@commercetools/sdk-client-v2 0.1.0 → 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.
- package/CHANGELOG.md +24 -1
- package/README.md +196 -1
- package/dist/commercetools-sdk-client-v2.browser.cjs.js +901 -1234
- package/dist/commercetools-sdk-client-v2.browser.esm.js +901 -1233
- package/dist/commercetools-sdk-client-v2.cjs.dev.js +901 -1234
- package/dist/commercetools-sdk-client-v2.cjs.prod.js +901 -1234
- package/dist/commercetools-sdk-client-v2.esm.js +901 -1233
- package/dist/commercetools-sdk-client-v2.umd.js +2 -0
- package/dist/commercetools-sdk-client-v2.umd.js.LICENSE.txt +15 -0
- package/dist/declarations/src/client-builder/ClientBuilder.d.ts +26 -26
- package/dist/declarations/src/http-user-agent/create-user-agent.d.ts +2 -2
- package/dist/declarations/src/index.d.ts +14 -15
- package/dist/declarations/src/sdk-client/allowed-methods.d.ts +2 -2
- package/dist/declarations/src/sdk-client/client.d.ts +2 -2
- package/dist/declarations/src/sdk-client/errors.d.ts +10 -10
- package/dist/declarations/src/sdk-client/validate.d.ts +7 -7
- package/dist/declarations/src/sdk-middleware-auth/anonymous-session-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/base-auth-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/build-requests.d.ts +11 -11
- package/dist/declarations/src/sdk-middleware-auth/build-token-cache-key.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/client-credentials-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/existing-token.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/index.d.ts +5 -5
- package/dist/declarations/src/sdk-middleware-auth/password-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/refresh-token-flow.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-auth/utils.d.ts +4 -4
- package/dist/declarations/src/sdk-middleware-correlation-id/correlation-id.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-http/http.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-http/parse-headers.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-logger/logger.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-queue/queue.d.ts +2 -2
- package/dist/declarations/src/sdk-middleware-user-agent/user-agent.d.ts +2 -2
- package/package.json +8 -8
|
@@ -1,100 +1,5 @@
|
|
|
1
|
-
import qs from 'querystring';
|
|
2
1
|
import fetch$1 from 'node-fetch';
|
|
3
|
-
|
|
4
|
-
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
5
|
-
try {
|
|
6
|
-
var info = gen[key](arg);
|
|
7
|
-
var value = info.value;
|
|
8
|
-
} catch (error) {
|
|
9
|
-
reject(error);
|
|
10
|
-
return;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
if (info.done) {
|
|
14
|
-
resolve(value);
|
|
15
|
-
} else {
|
|
16
|
-
Promise.resolve(value).then(_next, _throw);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function _asyncToGenerator(fn) {
|
|
21
|
-
return function () {
|
|
22
|
-
var self = this,
|
|
23
|
-
args = arguments;
|
|
24
|
-
return new Promise(function (resolve, reject) {
|
|
25
|
-
var gen = fn.apply(self, args);
|
|
26
|
-
|
|
27
|
-
function _next(value) {
|
|
28
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function _throw(err) {
|
|
32
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
_next(undefined);
|
|
36
|
-
});
|
|
37
|
-
};
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function _arrayWithHoles(arr) {
|
|
41
|
-
if (Array.isArray(arr)) return arr;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function _iterableToArrayLimit(arr, i) {
|
|
45
|
-
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
|
|
46
|
-
|
|
47
|
-
if (_i == null) return;
|
|
48
|
-
var _arr = [];
|
|
49
|
-
var _n = true;
|
|
50
|
-
var _d = false;
|
|
51
|
-
|
|
52
|
-
var _s, _e;
|
|
53
|
-
|
|
54
|
-
try {
|
|
55
|
-
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
|
|
56
|
-
_arr.push(_s.value);
|
|
57
|
-
|
|
58
|
-
if (i && _arr.length === i) break;
|
|
59
|
-
}
|
|
60
|
-
} catch (err) {
|
|
61
|
-
_d = true;
|
|
62
|
-
_e = err;
|
|
63
|
-
} finally {
|
|
64
|
-
try {
|
|
65
|
-
if (!_n && _i["return"] != null) _i["return"]();
|
|
66
|
-
} finally {
|
|
67
|
-
if (_d) throw _e;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
return _arr;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function _arrayLikeToArray(arr, len) {
|
|
75
|
-
if (len == null || len > arr.length) len = arr.length;
|
|
76
|
-
|
|
77
|
-
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
|
|
78
|
-
|
|
79
|
-
return arr2;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function _unsupportedIterableToArray(o, minLen) {
|
|
83
|
-
if (!o) return;
|
|
84
|
-
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
|
|
85
|
-
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
86
|
-
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
87
|
-
if (n === "Map" || n === "Set") return Array.from(o);
|
|
88
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function _nonIterableRest() {
|
|
92
|
-
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function _slicedToArray(arr, i) {
|
|
96
|
-
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
|
|
97
|
-
}
|
|
2
|
+
import qs from 'querystring';
|
|
98
3
|
|
|
99
4
|
function _defineProperty(obj, key, value) {
|
|
100
5
|
if (key in obj) {
|
|
@@ -111,88 +16,24 @@ function _defineProperty(obj, key, value) {
|
|
|
111
16
|
return obj;
|
|
112
17
|
}
|
|
113
18
|
|
|
114
|
-
function ownKeys(object, enumerableOnly) {
|
|
115
|
-
var keys = Object.keys(object);
|
|
116
|
-
|
|
117
|
-
if (Object.getOwnPropertySymbols) {
|
|
118
|
-
var symbols = Object.getOwnPropertySymbols(object);
|
|
119
|
-
|
|
120
|
-
if (enumerableOnly) {
|
|
121
|
-
symbols = symbols.filter(function (sym) {
|
|
122
|
-
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
keys.push.apply(keys, symbols);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
return keys;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function _objectSpread2(target) {
|
|
133
|
-
for (var i = 1; i < arguments.length; i++) {
|
|
134
|
-
var source = arguments[i] != null ? arguments[i] : {};
|
|
135
|
-
|
|
136
|
-
if (i % 2) {
|
|
137
|
-
ownKeys(Object(source), true).forEach(function (key) {
|
|
138
|
-
_defineProperty(target, key, source[key]);
|
|
139
|
-
});
|
|
140
|
-
} else if (Object.getOwnPropertyDescriptors) {
|
|
141
|
-
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
|
|
142
|
-
} else {
|
|
143
|
-
ownKeys(Object(source)).forEach(function (key) {
|
|
144
|
-
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
return target;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function _arrayWithoutHoles(arr) {
|
|
153
|
-
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function _iterableToArray(iter) {
|
|
157
|
-
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function _nonIterableSpread() {
|
|
161
|
-
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
function _toConsumableArray(arr) {
|
|
165
|
-
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
|
|
166
|
-
}
|
|
167
|
-
|
|
168
19
|
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'];
|
|
169
20
|
|
|
170
21
|
/**
|
|
171
22
|
* @throws {Error}
|
|
172
23
|
*/
|
|
173
|
-
function validate(funcName, request) {
|
|
174
|
-
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
|
|
175
|
-
allowedMethods: METHODS
|
|
176
|
-
};
|
|
177
|
-
if (!request) throw new Error("The \"".concat(funcName, "\" function requires a \"Request\" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest"));
|
|
178
|
-
if (typeof request.uri !== 'string') throw new Error("The \"".concat(funcName, "\" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest"));
|
|
179
|
-
if (!options.allowedMethods.includes(request.method)) throw new Error("The \"".concat(funcName, "\" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest"));
|
|
180
|
-
}
|
|
181
24
|
|
|
182
|
-
function
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
}
|
|
25
|
+
function validate(funcName, request, options = {
|
|
26
|
+
allowedMethods: METHODS
|
|
27
|
+
}) {
|
|
28
|
+
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`);
|
|
29
|
+
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`);
|
|
30
|
+
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`);
|
|
31
|
+
}
|
|
186
32
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
});
|
|
33
|
+
function compose(...funcs) {
|
|
34
|
+
funcs = funcs.filter(func => typeof func === 'function');
|
|
190
35
|
if (funcs.length === 1) return funcs[0];
|
|
191
|
-
return funcs.reduce(
|
|
192
|
-
return function () {
|
|
193
|
-
return a(b.apply(void 0, arguments));
|
|
194
|
-
};
|
|
195
|
-
});
|
|
36
|
+
return funcs.reduce((a, b) => (...args) => a(b(...args)));
|
|
196
37
|
}
|
|
197
38
|
|
|
198
39
|
function createClient(options) {
|
|
@@ -203,16 +44,16 @@ function createClient(options) {
|
|
|
203
44
|
/**
|
|
204
45
|
* Given a request object,
|
|
205
46
|
*/
|
|
206
|
-
execute
|
|
47
|
+
execute(request) {
|
|
207
48
|
validate('exec', request);
|
|
208
|
-
return new Promise(
|
|
209
|
-
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const resolver = (rq, rs) => {
|
|
210
51
|
// Note: pick the promise `resolve` and `reject` function from
|
|
211
52
|
// the response object. This is not necessary the same function
|
|
212
53
|
// given from the `new Promise` constructor, as middlewares could
|
|
213
54
|
// override those functions for custom behaviours.
|
|
214
55
|
if (rs.error) rs.reject(rs.error);else {
|
|
215
|
-
|
|
56
|
+
const resObj = {
|
|
216
57
|
body: rs.body || {},
|
|
217
58
|
statusCode: rs.statusCode
|
|
218
59
|
};
|
|
@@ -222,280 +63,109 @@ function createClient(options) {
|
|
|
222
63
|
}
|
|
223
64
|
};
|
|
224
65
|
|
|
225
|
-
|
|
66
|
+
const dispatch = compose(...options.middlewares)(resolver);
|
|
226
67
|
dispatch(request, // Initial response shape
|
|
227
68
|
{
|
|
228
|
-
resolve
|
|
229
|
-
reject
|
|
69
|
+
resolve,
|
|
70
|
+
reject,
|
|
230
71
|
body: undefined,
|
|
231
72
|
error: undefined
|
|
232
73
|
});
|
|
233
74
|
});
|
|
234
75
|
},
|
|
235
|
-
process: function process(request, fn, processOpt) {
|
|
236
|
-
var _this = this;
|
|
237
76
|
|
|
77
|
+
process(request, fn, processOpt) {
|
|
238
78
|
validate('process', request, {
|
|
239
79
|
allowedMethods: ['GET']
|
|
240
80
|
});
|
|
241
81
|
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
|
|
242
82
|
|
|
243
|
-
|
|
83
|
+
const opt = {
|
|
244
84
|
total: Number.POSITIVE_INFINITY,
|
|
245
|
-
accumulate: true
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
return new Promise(
|
|
249
|
-
|
|
85
|
+
accumulate: true,
|
|
86
|
+
...processOpt
|
|
87
|
+
};
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
let _path,
|
|
250
90
|
_queryString = '';
|
|
251
91
|
|
|
252
92
|
if (request && request.uri) {
|
|
253
|
-
|
|
254
|
-
_request$uri$split2 = _slicedToArray(_request$uri$split, 2),
|
|
255
|
-
path = _request$uri$split2[0],
|
|
256
|
-
queryString = _request$uri$split2[1];
|
|
257
|
-
|
|
93
|
+
const [path, queryString] = request.uri.split('?');
|
|
258
94
|
_path = path;
|
|
259
95
|
_queryString = queryString;
|
|
260
96
|
}
|
|
261
97
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
98
|
+
const requestQuery = { ...qs.parse(_queryString)
|
|
99
|
+
};
|
|
100
|
+
const query = {
|
|
265
101
|
// defaults
|
|
266
|
-
limit: 20
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
return regeneratorRuntime.wrap(function _callee$(_context) {
|
|
291
|
-
while (1) {
|
|
292
|
-
switch (_context.prev = _context.next) {
|
|
293
|
-
case 0:
|
|
294
|
-
acc = _args.length > 1 && _args[1] !== undefined ? _args[1] : [];
|
|
295
|
-
// Use the lesser value between limit and itemsToGet in query
|
|
296
|
-
limit = query.limit < itemsToGet ? query.limit : itemsToGet;
|
|
297
|
-
originalQueryString = qs.stringify(_objectSpread2(_objectSpread2({}, query), {}, {
|
|
298
|
-
limit: limit
|
|
299
|
-
}));
|
|
300
|
-
enhancedQuery = _objectSpread2({
|
|
301
|
-
sort: 'id asc',
|
|
302
|
-
withTotal: false
|
|
303
|
-
}, lastId ? {
|
|
304
|
-
where: "id > \"".concat(lastId, "\"")
|
|
305
|
-
} : {});
|
|
306
|
-
enhancedQueryString = qs.stringify(enhancedQuery);
|
|
307
|
-
enhancedRequest = _objectSpread2(_objectSpread2({}, request), {}, {
|
|
308
|
-
uri: "".concat(_path, "?").concat(enhancedQueryString, "&").concat(originalQueryString)
|
|
309
|
-
});
|
|
310
|
-
_context.prev = 6;
|
|
311
|
-
_context.next = 9;
|
|
312
|
-
return _this.execute(enhancedRequest);
|
|
313
|
-
|
|
314
|
-
case 9:
|
|
315
|
-
payload = _context.sent;
|
|
316
|
-
_payload$body = payload.body, results = _payload$body.results, resultsLength = _payload$body.count;
|
|
317
|
-
|
|
318
|
-
if (!(!resultsLength && hasFirstPageBeenProcessed)) {
|
|
319
|
-
_context.next = 13;
|
|
320
|
-
break;
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
return _context.abrupt("return", resolve(acc || []));
|
|
324
|
-
|
|
325
|
-
case 13:
|
|
326
|
-
_context.next = 15;
|
|
327
|
-
return Promise.resolve(fn(payload));
|
|
328
|
-
|
|
329
|
-
case 15:
|
|
330
|
-
result = _context.sent;
|
|
331
|
-
hasFirstPageBeenProcessed = true;
|
|
332
|
-
if (opt.accumulate) accumulated = acc.concat(result || []);
|
|
333
|
-
itemsToGet -= resultsLength; // If there are no more items to get, it means the total number
|
|
334
|
-
// of items in the original request have been fetched so we
|
|
335
|
-
// resolve the promise.
|
|
336
|
-
// Also, if we get less results in a page then the limit set it
|
|
337
|
-
// means that there are no more pages and that we can finally
|
|
338
|
-
// resolve the promise.
|
|
339
|
-
|
|
340
|
-
if (!(resultsLength < query.limit || !itemsToGet)) {
|
|
341
|
-
_context.next = 21;
|
|
342
|
-
break;
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
return _context.abrupt("return", resolve(accumulated || []));
|
|
346
|
-
|
|
347
|
-
case 21:
|
|
348
|
-
last = results[resultsLength - 1];
|
|
349
|
-
newLastId = last && last.id;
|
|
350
|
-
processPage(newLastId, accumulated);
|
|
351
|
-
_context.next = 29;
|
|
352
|
-
break;
|
|
353
|
-
|
|
354
|
-
case 26:
|
|
355
|
-
_context.prev = 26;
|
|
356
|
-
_context.t0 = _context["catch"](6);
|
|
357
|
-
reject(_context.t0);
|
|
358
|
-
|
|
359
|
-
case 29:
|
|
360
|
-
case "end":
|
|
361
|
-
return _context.stop();
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
}, _callee, null, [[6, 26]]);
|
|
365
|
-
}));
|
|
366
|
-
|
|
367
|
-
return function processPage(_x) {
|
|
368
|
-
return _ref.apply(this, arguments);
|
|
102
|
+
limit: 20,
|
|
103
|
+
// merge given query params
|
|
104
|
+
...requestQuery
|
|
105
|
+
};
|
|
106
|
+
let hasFirstPageBeenProcessed = false;
|
|
107
|
+
let itemsToGet = opt.total;
|
|
108
|
+
|
|
109
|
+
const processPage = async (lastId, acc = []) => {
|
|
110
|
+
// Use the lesser value between limit and itemsToGet in query
|
|
111
|
+
const limit = query.limit < itemsToGet ? query.limit : itemsToGet;
|
|
112
|
+
const originalQueryString = qs.stringify({ ...query,
|
|
113
|
+
limit
|
|
114
|
+
});
|
|
115
|
+
const enhancedQuery = {
|
|
116
|
+
sort: 'id asc',
|
|
117
|
+
withTotal: false,
|
|
118
|
+
...(lastId ? {
|
|
119
|
+
where: `id > "${lastId}"`
|
|
120
|
+
} : {})
|
|
121
|
+
};
|
|
122
|
+
const enhancedQueryString = qs.stringify(enhancedQuery);
|
|
123
|
+
const enhancedRequest = { ...request,
|
|
124
|
+
uri: `${_path}?${enhancedQueryString}&${originalQueryString}`
|
|
369
125
|
};
|
|
370
|
-
}(); // Start iterating through pages
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
processPage();
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
};
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
function defineError(statusCode, message) {
|
|
380
|
-
var meta = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
|
|
381
|
-
this.status = this.statusCode = this.code = statusCode;
|
|
382
|
-
this.message = message;
|
|
383
|
-
Object.assign(this, meta);
|
|
384
|
-
this.name = this.constructor.name;
|
|
385
|
-
this.constructor.prototype.__proto__ = Error.prototype;
|
|
386
|
-
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
function NetworkError() {
|
|
390
|
-
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
|
391
|
-
args[_key] = arguments[_key];
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
defineError.call.apply(defineError, [this, 0
|
|
395
|
-
/* special code to indicate network errors */
|
|
396
|
-
].concat(args));
|
|
397
|
-
}
|
|
398
|
-
function HttpError() {
|
|
399
|
-
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
|
400
|
-
args[_key2] = arguments[_key2];
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
defineError.call.apply(defineError, [this].concat(args));
|
|
404
|
-
}
|
|
405
|
-
function BadRequest() {
|
|
406
|
-
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
|
|
407
|
-
args[_key3] = arguments[_key3];
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
defineError.call.apply(defineError, [this, 400].concat(args));
|
|
411
|
-
}
|
|
412
|
-
function Unauthorized() {
|
|
413
|
-
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
|
|
414
|
-
args[_key4] = arguments[_key4];
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
defineError.call.apply(defineError, [this, 401].concat(args));
|
|
418
|
-
}
|
|
419
|
-
function Forbidden() {
|
|
420
|
-
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
|
|
421
|
-
args[_key5] = arguments[_key5];
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
defineError.call.apply(defineError, [this, 403].concat(args));
|
|
425
|
-
}
|
|
426
|
-
function NotFound() {
|
|
427
|
-
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
|
|
428
|
-
args[_key6] = arguments[_key6];
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
defineError.call.apply(defineError, [this, 404].concat(args));
|
|
432
|
-
}
|
|
433
|
-
function ConcurrentModification() {
|
|
434
|
-
for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
|
|
435
|
-
args[_key7] = arguments[_key7];
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
defineError.call.apply(defineError, [this, 409].concat(args));
|
|
439
|
-
}
|
|
440
|
-
function InternalServerError() {
|
|
441
|
-
for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
|
|
442
|
-
args[_key8] = arguments[_key8];
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
defineError.call.apply(defineError, [this, 500].concat(args));
|
|
446
|
-
}
|
|
447
|
-
function ServiceUnavailable() {
|
|
448
|
-
for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
|
|
449
|
-
args[_key9] = arguments[_key9];
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
defineError.call.apply(defineError, [this, 503].concat(args));
|
|
453
|
-
}
|
|
454
|
-
function getErrorByCode(code) {
|
|
455
|
-
switch (code) {
|
|
456
|
-
case 0:
|
|
457
|
-
return NetworkError;
|
|
458
|
-
|
|
459
|
-
case 400:
|
|
460
|
-
return BadRequest;
|
|
461
126
|
|
|
462
|
-
|
|
463
|
-
|
|
127
|
+
try {
|
|
128
|
+
const payload = await this.execute(enhancedRequest);
|
|
129
|
+
const {
|
|
130
|
+
results,
|
|
131
|
+
count: resultsLength
|
|
132
|
+
} = payload.body;
|
|
464
133
|
|
|
465
|
-
|
|
466
|
-
|
|
134
|
+
if (!resultsLength && hasFirstPageBeenProcessed) {
|
|
135
|
+
return resolve(acc || []);
|
|
136
|
+
}
|
|
467
137
|
|
|
468
|
-
|
|
469
|
-
|
|
138
|
+
const result = await Promise.resolve(fn(payload));
|
|
139
|
+
let accumulated;
|
|
140
|
+
hasFirstPageBeenProcessed = true;
|
|
141
|
+
if (opt.accumulate) accumulated = acc.concat(result || []);
|
|
142
|
+
itemsToGet -= resultsLength; // If there are no more items to get, it means the total number
|
|
143
|
+
// of items in the original request have been fetched so we
|
|
144
|
+
// resolve the promise.
|
|
145
|
+
// Also, if we get less results in a page then the limit set it
|
|
146
|
+
// means that there are no more pages and that we can finally
|
|
147
|
+
// resolve the promise.
|
|
148
|
+
|
|
149
|
+
if (resultsLength < query.limit || !itemsToGet) {
|
|
150
|
+
return resolve(accumulated || []);
|
|
151
|
+
}
|
|
470
152
|
|
|
471
|
-
|
|
472
|
-
|
|
153
|
+
const last = results[resultsLength - 1];
|
|
154
|
+
const newLastId = last && last.id;
|
|
155
|
+
processPage(newLastId, accumulated);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
reject(error);
|
|
158
|
+
}
|
|
159
|
+
}; // Start iterating through pages
|
|
473
160
|
|
|
474
|
-
case 500:
|
|
475
|
-
return InternalServerError;
|
|
476
161
|
|
|
477
|
-
|
|
478
|
-
|
|
162
|
+
processPage();
|
|
163
|
+
});
|
|
164
|
+
}
|
|
479
165
|
|
|
480
|
-
|
|
481
|
-
return undefined;
|
|
482
|
-
}
|
|
166
|
+
};
|
|
483
167
|
}
|
|
484
168
|
|
|
485
|
-
var errors = /*#__PURE__*/Object.freeze({
|
|
486
|
-
__proto__: null,
|
|
487
|
-
NetworkError: NetworkError,
|
|
488
|
-
HttpError: HttpError,
|
|
489
|
-
BadRequest: BadRequest,
|
|
490
|
-
Unauthorized: Unauthorized,
|
|
491
|
-
Forbidden: Forbidden,
|
|
492
|
-
NotFound: NotFound,
|
|
493
|
-
ConcurrentModification: ConcurrentModification,
|
|
494
|
-
InternalServerError: InternalServerError,
|
|
495
|
-
ServiceUnavailable: ServiceUnavailable,
|
|
496
|
-
'default': getErrorByCode
|
|
497
|
-
});
|
|
498
|
-
|
|
499
169
|
// POST https://{host}/oauth/token?grant_type=client_credentials&scope={scope}
|
|
500
170
|
// Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
|
|
501
171
|
function buildRequestForClientCredentialsFlow(options) {
|
|
@@ -503,21 +173,22 @@ function buildRequestForClientCredentialsFlow(options) {
|
|
|
503
173
|
if (!options.host) throw new Error('Missing required option (host)');
|
|
504
174
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
505
175
|
if (!options.credentials) throw new Error('Missing required option (credentials)');
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
176
|
+
const {
|
|
177
|
+
clientId,
|
|
178
|
+
clientSecret
|
|
179
|
+
} = options.credentials;
|
|
509
180
|
if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
|
|
510
|
-
|
|
511
|
-
|
|
181
|
+
const scope = options.scopes ? options.scopes.join(' ') : undefined;
|
|
182
|
+
const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
|
|
512
183
|
// other oauth endpoints.
|
|
513
184
|
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
185
|
+
const oauthUri = options.oauthUri || '/oauth/token';
|
|
186
|
+
const url = options.host.replace(/\/$/, '') + oauthUri;
|
|
187
|
+
const body = `grant_type=client_credentials${scope ? `&scope=${scope}` : ''}`;
|
|
517
188
|
return {
|
|
518
|
-
basicAuth
|
|
519
|
-
url
|
|
520
|
-
body
|
|
189
|
+
basicAuth,
|
|
190
|
+
url,
|
|
191
|
+
body
|
|
521
192
|
};
|
|
522
193
|
}
|
|
523
194
|
function buildRequestForPasswordFlow(options) {
|
|
@@ -525,31 +196,34 @@ function buildRequestForPasswordFlow(options) {
|
|
|
525
196
|
if (!options.host) throw new Error('Missing required option (host)');
|
|
526
197
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
527
198
|
if (!options.credentials) throw new Error('Missing required option (credentials)');
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
199
|
+
const {
|
|
200
|
+
clientId,
|
|
201
|
+
clientSecret,
|
|
202
|
+
user
|
|
203
|
+
} = options.credentials;
|
|
204
|
+
const pKey = options.projectKey;
|
|
533
205
|
if (!(clientId && clientSecret && user)) throw new Error('Missing required credentials (clientId, clientSecret, user)');
|
|
534
|
-
|
|
535
|
-
|
|
206
|
+
const {
|
|
207
|
+
username,
|
|
208
|
+
password
|
|
209
|
+
} = user;
|
|
536
210
|
if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
211
|
+
const scope = (options.scopes || []).join(' ');
|
|
212
|
+
const scopeStr = scope ? `&scope=${scope}` : '';
|
|
213
|
+
const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
|
|
540
214
|
/**
|
|
541
215
|
* This is mostly useful for internal testing purposes to be able to check
|
|
542
216
|
* other oauth endpoints.
|
|
543
217
|
*/
|
|
544
218
|
|
|
545
|
-
|
|
546
|
-
|
|
219
|
+
const oauthUri = options.oauthUri || `/oauth/${pKey}/customers/token`;
|
|
220
|
+
const url = options.host.replace(/\/$/, '') + oauthUri; // encode username and password as requested by platform
|
|
547
221
|
|
|
548
|
-
|
|
222
|
+
const body = `grant_type=password&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}${scopeStr}`;
|
|
549
223
|
return {
|
|
550
|
-
basicAuth
|
|
551
|
-
url
|
|
552
|
-
body
|
|
224
|
+
basicAuth,
|
|
225
|
+
url,
|
|
226
|
+
body
|
|
553
227
|
};
|
|
554
228
|
}
|
|
555
229
|
function buildRequestForRefreshTokenFlow(options) {
|
|
@@ -558,46 +232,40 @@ function buildRequestForRefreshTokenFlow(options) {
|
|
|
558
232
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
559
233
|
if (!options.credentials) throw new Error('Missing required option (credentials)');
|
|
560
234
|
if (!options.refreshToken) throw new Error('Missing required option (refreshToken)');
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
235
|
+
const {
|
|
236
|
+
clientId,
|
|
237
|
+
clientSecret
|
|
238
|
+
} = options.credentials;
|
|
564
239
|
if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
|
|
565
|
-
|
|
240
|
+
const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
|
|
566
241
|
// other oauth endpoints.
|
|
567
242
|
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
243
|
+
const oauthUri = options.oauthUri || '/oauth/token';
|
|
244
|
+
const url = options.host.replace(/\/$/, '') + oauthUri;
|
|
245
|
+
const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
|
|
571
246
|
return {
|
|
572
|
-
basicAuth
|
|
573
|
-
url
|
|
574
|
-
body
|
|
247
|
+
basicAuth,
|
|
248
|
+
url,
|
|
249
|
+
body
|
|
575
250
|
};
|
|
576
251
|
}
|
|
577
252
|
function buildRequestForAnonymousSessionFlow(options) {
|
|
578
253
|
if (!options) throw new Error('Missing required options');
|
|
579
254
|
if (!options.projectKey) throw new Error('Missing required option (projectKey)');
|
|
580
|
-
|
|
581
|
-
options.oauthUri = options.oauthUri ||
|
|
582
|
-
|
|
583
|
-
if (options.credentials.anonymousId) result.body +=
|
|
584
|
-
return
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
function buildTokenCacheKey(options) {
|
|
588
|
-
return {
|
|
589
|
-
clientId: options.credentials.clientId,
|
|
590
|
-
host: options.host,
|
|
591
|
-
projectKey: options.projectKey
|
|
255
|
+
const pKey = options.projectKey;
|
|
256
|
+
options.oauthUri = options.oauthUri || `/oauth/${pKey}/anonymous/token`;
|
|
257
|
+
const result = buildRequestForClientCredentialsFlow(options);
|
|
258
|
+
if (options.credentials.anonymousId) result.body += `&anonymous_id=${options.credentials.anonymousId}`;
|
|
259
|
+
return { ...result
|
|
592
260
|
};
|
|
593
261
|
}
|
|
594
262
|
|
|
595
263
|
function mergeAuthHeader(token, req) {
|
|
596
|
-
return
|
|
597
|
-
headers:
|
|
598
|
-
Authorization:
|
|
599
|
-
}
|
|
600
|
-
}
|
|
264
|
+
return { ...req,
|
|
265
|
+
headers: { ...req.headers,
|
|
266
|
+
Authorization: `Bearer ${token}`
|
|
267
|
+
}
|
|
268
|
+
};
|
|
601
269
|
}
|
|
602
270
|
|
|
603
271
|
function calculateExpirationTime(expiresIn) {
|
|
@@ -605,136 +273,108 @@ function calculateExpirationTime(expiresIn) {
|
|
|
605
273
|
expiresIn * 1000 - 2 * 60 * 60 * 1000;
|
|
606
274
|
}
|
|
607
275
|
|
|
608
|
-
function executeRequest(
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
},
|
|
630
|
-
body: body
|
|
631
|
-
});
|
|
276
|
+
async function executeRequest({
|
|
277
|
+
fetcher,
|
|
278
|
+
url,
|
|
279
|
+
basicAuth,
|
|
280
|
+
body,
|
|
281
|
+
tokenCache,
|
|
282
|
+
requestState,
|
|
283
|
+
pendingTasks,
|
|
284
|
+
response,
|
|
285
|
+
tokenCacheKey
|
|
286
|
+
}) {
|
|
287
|
+
try {
|
|
288
|
+
const _res = await fetcher(url, {
|
|
289
|
+
method: 'POST',
|
|
290
|
+
headers: {
|
|
291
|
+
Authorization: `Basic ${basicAuth}`,
|
|
292
|
+
'Content-Length': Buffer.byteLength(body).toString(),
|
|
293
|
+
'Content-Type': 'application/x-www-form-urlencoded'
|
|
294
|
+
},
|
|
295
|
+
body
|
|
296
|
+
});
|
|
632
297
|
|
|
633
|
-
|
|
634
|
-
|
|
298
|
+
if (_res.ok) {
|
|
299
|
+
const {
|
|
300
|
+
access_token: token,
|
|
301
|
+
expires_in: expiresIn,
|
|
302
|
+
refresh_token: refreshToken
|
|
303
|
+
} = await _res.json();
|
|
304
|
+
const expirationTime = calculateExpirationTime(expiresIn); // cache new generated token
|
|
305
|
+
|
|
306
|
+
tokenCache.set({
|
|
307
|
+
token,
|
|
308
|
+
expirationTime,
|
|
309
|
+
refreshToken
|
|
310
|
+
}, tokenCacheKey); // Dispatch all pending requests
|
|
311
|
+
|
|
312
|
+
requestState.set(false);
|
|
313
|
+
/**
|
|
314
|
+
* Freeze and copy pending queue, reset original one for accepting
|
|
315
|
+
* new pending tasks
|
|
316
|
+
*/
|
|
635
317
|
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
318
|
+
const executionQueue = pendingTasks.slice();
|
|
319
|
+
pendingTasks = [];
|
|
320
|
+
executionQueue.forEach(task => {
|
|
321
|
+
// Assign the new token in the request header
|
|
322
|
+
const requestWithAuth = mergeAuthHeader(token, task.request);
|
|
323
|
+
/**
|
|
324
|
+
* console.log('test', cache, pendingTasks)
|
|
325
|
+
* Continue by calling the task's own next function
|
|
326
|
+
*/
|
|
327
|
+
|
|
328
|
+
task.next(requestWithAuth, task.response);
|
|
329
|
+
});
|
|
330
|
+
return;
|
|
331
|
+
} // Handle error response
|
|
640
332
|
|
|
641
|
-
_context.next = 8;
|
|
642
|
-
return _res.json();
|
|
643
|
-
|
|
644
|
-
case 8:
|
|
645
|
-
_yield$_res$json = _context.sent;
|
|
646
|
-
token = _yield$_res$json.access_token;
|
|
647
|
-
expiresIn = _yield$_res$json.expires_in;
|
|
648
|
-
refreshToken = _yield$_res$json.refresh_token;
|
|
649
|
-
expirationTime = calculateExpirationTime(expiresIn); // cache new generated token
|
|
650
|
-
|
|
651
|
-
tokenCache.set({
|
|
652
|
-
token: token,
|
|
653
|
-
expirationTime: expirationTime,
|
|
654
|
-
refreshToken: refreshToken
|
|
655
|
-
}, tokenCacheKey); // Dispatch all pending requests
|
|
656
|
-
|
|
657
|
-
requestState.set(false);
|
|
658
|
-
/**
|
|
659
|
-
* Freeze and copy pending queue, reset original one for accepting
|
|
660
|
-
* new pending tasks
|
|
661
|
-
*/
|
|
662
|
-
|
|
663
|
-
executionQueue = pendingTasks.slice();
|
|
664
|
-
pendingTasks = [];
|
|
665
|
-
executionQueue.forEach(function (task) {
|
|
666
|
-
// Assign the new token in the request header
|
|
667
|
-
var requestWithAuth = mergeAuthHeader(token, task.request);
|
|
668
|
-
/**
|
|
669
|
-
* console.log('test', cache, pendingTasks)
|
|
670
|
-
* Continue by calling the task's own next function
|
|
671
|
-
*/
|
|
672
|
-
|
|
673
|
-
task.next(requestWithAuth, task.response);
|
|
674
|
-
});
|
|
675
|
-
return _context.abrupt("return");
|
|
676
333
|
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
return _res.text();
|
|
334
|
+
let parsed;
|
|
335
|
+
const text = await _res.text();
|
|
680
336
|
|
|
681
|
-
|
|
682
|
-
|
|
337
|
+
try {
|
|
338
|
+
parsed = JSON.parse(text);
|
|
339
|
+
} catch (error) {
|
|
340
|
+
/* noop */
|
|
341
|
+
}
|
|
683
342
|
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
343
|
+
const error = new Error(parsed ? parsed.message : text);
|
|
344
|
+
if (parsed) error.body = parsed;
|
|
345
|
+
/**
|
|
346
|
+
* to notify that token is either fetched or failed
|
|
347
|
+
* in the below case token failed to be fetched
|
|
348
|
+
* and reset requestState to false
|
|
349
|
+
* so requestState could be shared between multi authMiddlewareBase functions
|
|
350
|
+
*/
|
|
689
351
|
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
break;
|
|
703
|
-
|
|
704
|
-
case 29:
|
|
705
|
-
_context.prev = 29;
|
|
706
|
-
_context.t0 = _context["catch"](1);
|
|
707
|
-
|
|
708
|
-
/**
|
|
709
|
-
* to notify that token is either fetched or failed
|
|
710
|
-
* in the below case token failed to be fetched
|
|
711
|
-
* and reset requestState to false
|
|
712
|
-
* so requestState could be shared between multi authMiddlewareBase functions
|
|
713
|
-
*/
|
|
714
|
-
requestState.set(false);
|
|
715
|
-
if (response && typeof response.reject === 'function') response.reject(_context.t0);
|
|
716
|
-
|
|
717
|
-
case 33:
|
|
718
|
-
case "end":
|
|
719
|
-
return _context.stop();
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
}, _callee, null, [[1, 29]]);
|
|
723
|
-
}));
|
|
724
|
-
return _executeRequest.apply(this, arguments);
|
|
352
|
+
requestState.set(false);
|
|
353
|
+
response.reject(error);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
/**
|
|
356
|
+
* to notify that token is either fetched or failed
|
|
357
|
+
* in the below case token failed to be fetched
|
|
358
|
+
* and reset requestState to false
|
|
359
|
+
* so requestState could be shared between multi authMiddlewareBase functions
|
|
360
|
+
*/
|
|
361
|
+
requestState.set(false);
|
|
362
|
+
if (response && typeof response.reject === 'function') response.reject(error);
|
|
363
|
+
}
|
|
725
364
|
}
|
|
726
365
|
|
|
727
|
-
function authMiddlewareBase(
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
366
|
+
function authMiddlewareBase({
|
|
367
|
+
request,
|
|
368
|
+
response,
|
|
369
|
+
url,
|
|
370
|
+
basicAuth,
|
|
371
|
+
body,
|
|
372
|
+
pendingTasks,
|
|
373
|
+
requestState,
|
|
374
|
+
tokenCache,
|
|
375
|
+
tokenCacheKey,
|
|
376
|
+
fetch: fetcher
|
|
377
|
+
}, next, userOptions) {
|
|
738
378
|
if (!fetcher && typeof fetch === 'undefined') throw new Error('`fetch` is not available. Please pass in `fetch` as an option or have it globally available.');
|
|
739
379
|
if (!fetcher) fetcher = fetch; // Check if there is already a `Authorization` header in the request.
|
|
740
380
|
// If so, then go directly to the next middleware.
|
|
@@ -746,10 +386,10 @@ function authMiddlewareBase(_ref2, next, userOptions) {
|
|
|
746
386
|
// the token in the `Authorization` header.
|
|
747
387
|
|
|
748
388
|
|
|
749
|
-
|
|
389
|
+
const tokenObj = tokenCache.get(tokenCacheKey);
|
|
750
390
|
|
|
751
391
|
if (tokenObj && tokenObj.token && Date.now() < tokenObj.expirationTime) {
|
|
752
|
-
|
|
392
|
+
const requestWithAuth = mergeAuthHeader(tokenObj.token, request);
|
|
753
393
|
next(requestWithAuth, response);
|
|
754
394
|
return;
|
|
755
395
|
}
|
|
@@ -762,9 +402,9 @@ function authMiddlewareBase(_ref2, next, userOptions) {
|
|
|
762
402
|
|
|
763
403
|
|
|
764
404
|
pendingTasks.push({
|
|
765
|
-
request
|
|
766
|
-
response
|
|
767
|
-
next
|
|
405
|
+
request,
|
|
406
|
+
response,
|
|
407
|
+
next
|
|
768
408
|
}); // If a token is currently being fetched, just wait ;)
|
|
769
409
|
|
|
770
410
|
if (requestState.get()) return; // Mark that a token is being fetched
|
|
@@ -777,373 +417,268 @@ function authMiddlewareBase(_ref2, next, userOptions) {
|
|
|
777
417
|
|
|
778
418
|
if (tokenObj && tokenObj.refreshToken && (!tokenObj.token || tokenObj.token && Date.now() > tokenObj.expirationTime)) {
|
|
779
419
|
if (!userOptions) throw new Error('Missing required options');
|
|
780
|
-
executeRequest(
|
|
781
|
-
fetcher
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
tokenCacheKey
|
|
786
|
-
tokenCache
|
|
787
|
-
requestState
|
|
788
|
-
pendingTasks
|
|
789
|
-
response
|
|
790
|
-
})
|
|
420
|
+
executeRequest({
|
|
421
|
+
fetcher,
|
|
422
|
+
...buildRequestForRefreshTokenFlow({ ...userOptions,
|
|
423
|
+
refreshToken: tokenObj.refreshToken
|
|
424
|
+
}),
|
|
425
|
+
tokenCacheKey,
|
|
426
|
+
tokenCache,
|
|
427
|
+
requestState,
|
|
428
|
+
pendingTasks,
|
|
429
|
+
response
|
|
430
|
+
});
|
|
791
431
|
return;
|
|
792
432
|
} // Token and refreshToken are not present or invalid. Request a new token...
|
|
793
433
|
|
|
794
434
|
|
|
795
435
|
executeRequest({
|
|
796
|
-
fetcher
|
|
797
|
-
url
|
|
798
|
-
basicAuth
|
|
799
|
-
body
|
|
800
|
-
tokenCacheKey
|
|
801
|
-
tokenCache
|
|
802
|
-
requestState
|
|
803
|
-
pendingTasks
|
|
804
|
-
response
|
|
436
|
+
fetcher,
|
|
437
|
+
url,
|
|
438
|
+
basicAuth,
|
|
439
|
+
body,
|
|
440
|
+
tokenCacheKey,
|
|
441
|
+
tokenCache,
|
|
442
|
+
requestState,
|
|
443
|
+
pendingTasks,
|
|
444
|
+
response
|
|
805
445
|
});
|
|
806
446
|
}
|
|
807
447
|
|
|
808
448
|
function store(initVal) {
|
|
809
|
-
|
|
449
|
+
let value = initVal;
|
|
810
450
|
return {
|
|
811
|
-
get:
|
|
812
|
-
|
|
813
|
-
},
|
|
814
|
-
set: function set(val) {
|
|
451
|
+
get: () => value,
|
|
452
|
+
set: val => {
|
|
815
453
|
value = val;
|
|
816
454
|
return value;
|
|
817
455
|
}
|
|
818
456
|
};
|
|
819
457
|
}
|
|
820
458
|
|
|
821
|
-
function
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
833
|
-
next(request, response);
|
|
834
|
-
return;
|
|
835
|
-
}
|
|
836
|
-
|
|
837
|
-
var params = _objectSpread2(_objectSpread2({
|
|
838
|
-
request: request,
|
|
839
|
-
response: response
|
|
840
|
-
}, buildRequestForClientCredentialsFlow(options)), {}, {
|
|
841
|
-
pendingTasks: pendingTasks,
|
|
842
|
-
requestState: requestState,
|
|
843
|
-
tokenCache: tokenCache,
|
|
844
|
-
tokenCacheKey: buildTokenCacheKey(options),
|
|
845
|
-
fetch: options.fetch
|
|
846
|
-
});
|
|
459
|
+
function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
|
|
460
|
+
const tokenCache = store({});
|
|
461
|
+
const pendingTasks = [];
|
|
462
|
+
const requestState = store(false);
|
|
463
|
+
return next => (request, response) => {
|
|
464
|
+
// Check if there is already a `Authorization` header in the request.
|
|
465
|
+
// If so, then go directly to the next middleware.
|
|
466
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
467
|
+
next(request, response);
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
847
470
|
|
|
848
|
-
|
|
471
|
+
const params = {
|
|
472
|
+
request,
|
|
473
|
+
response,
|
|
474
|
+
...buildRequestForAnonymousSessionFlow(options),
|
|
475
|
+
pendingTasks,
|
|
476
|
+
requestState,
|
|
477
|
+
tokenCache,
|
|
478
|
+
fetch: options.fetch
|
|
849
479
|
};
|
|
480
|
+
authMiddlewareBase(params, next, options);
|
|
850
481
|
};
|
|
851
482
|
}
|
|
852
483
|
|
|
853
|
-
function
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
return function (request, response) {
|
|
859
|
-
// Check if there is already a `Authorization` header in the request.
|
|
860
|
-
// If so, then go directly to the next middleware.
|
|
861
|
-
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
862
|
-
next(request, response);
|
|
863
|
-
return;
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
var params = _objectSpread2(_objectSpread2({
|
|
867
|
-
request: request,
|
|
868
|
-
response: response
|
|
869
|
-
}, buildRequestForPasswordFlow(options)), {}, {
|
|
870
|
-
pendingTasks: pendingTasks,
|
|
871
|
-
requestState: requestState,
|
|
872
|
-
tokenCache: tokenCache,
|
|
873
|
-
fetch: options.fetch
|
|
874
|
-
});
|
|
875
|
-
|
|
876
|
-
authMiddlewareBase(params, next, options);
|
|
877
|
-
};
|
|
484
|
+
function buildTokenCacheKey(options) {
|
|
485
|
+
return {
|
|
486
|
+
clientId: options.credentials.clientId,
|
|
487
|
+
host: options.host,
|
|
488
|
+
projectKey: options.projectKey
|
|
878
489
|
};
|
|
879
490
|
}
|
|
880
491
|
|
|
881
|
-
function
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
request: request,
|
|
896
|
-
response: response
|
|
897
|
-
}, buildRequestForRefreshTokenFlow(options)), {}, {
|
|
898
|
-
pendingTasks: pendingTasks,
|
|
899
|
-
requestState: requestState,
|
|
900
|
-
tokenCache: tokenCache,
|
|
901
|
-
fetch: options.fetch
|
|
902
|
-
});
|
|
492
|
+
function createAuthMiddlewareForClientCredentialsFlow$1(options) {
|
|
493
|
+
const tokenCache = options.tokenCache || store({
|
|
494
|
+
token: '',
|
|
495
|
+
expirationTime: -1
|
|
496
|
+
});
|
|
497
|
+
const requestState = store(false);
|
|
498
|
+
const pendingTasks = [];
|
|
499
|
+
return next => (request, response) => {
|
|
500
|
+
// Check if there is already a `Authorization` header in the request.
|
|
501
|
+
// If so, then go directly to the next middleware.
|
|
502
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
503
|
+
next(request, response);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
903
506
|
|
|
904
|
-
|
|
507
|
+
const params = {
|
|
508
|
+
request,
|
|
509
|
+
response,
|
|
510
|
+
...buildRequestForClientCredentialsFlow(options),
|
|
511
|
+
pendingTasks,
|
|
512
|
+
requestState,
|
|
513
|
+
tokenCache,
|
|
514
|
+
tokenCacheKey: buildTokenCacheKey(options),
|
|
515
|
+
fetch: options.fetch
|
|
905
516
|
};
|
|
517
|
+
authMiddlewareBase(params, next);
|
|
906
518
|
};
|
|
907
519
|
}
|
|
908
520
|
|
|
909
|
-
function
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
918
|
-
next(request, response);
|
|
919
|
-
return;
|
|
920
|
-
}
|
|
521
|
+
function createAuthMiddlewareWithExistingToken$1(authorization = '', options = {}) {
|
|
522
|
+
return next => (request, response) => {
|
|
523
|
+
if (typeof authorization !== 'string') throw new Error('authorization must be a string');
|
|
524
|
+
const force = options.force === undefined ? true : options.force;
|
|
525
|
+
/** The request will not be modified if:
|
|
526
|
+
* 1. no argument is passed
|
|
527
|
+
* 2. force is false and authorization header exists
|
|
528
|
+
*/
|
|
921
529
|
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
}, buildRequestForAnonymousSessionFlow(options)), {}, {
|
|
926
|
-
pendingTasks: pendingTasks,
|
|
927
|
-
requestState: requestState,
|
|
928
|
-
tokenCache: tokenCache,
|
|
929
|
-
fetch: options.fetch
|
|
930
|
-
});
|
|
530
|
+
if (!authorization || (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) && force === false) {
|
|
531
|
+
return next(request, response);
|
|
532
|
+
}
|
|
931
533
|
|
|
932
|
-
|
|
534
|
+
const requestWithAuth = { ...request,
|
|
535
|
+
headers: { ...request.headers,
|
|
536
|
+
Authorization: authorization
|
|
537
|
+
}
|
|
933
538
|
};
|
|
539
|
+
return next(requestWithAuth, response);
|
|
934
540
|
};
|
|
935
541
|
}
|
|
936
542
|
|
|
937
|
-
function
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
if (!authorization || (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) && force === false) {
|
|
950
|
-
return next(request, response);
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
var requestWithAuth = _objectSpread2(_objectSpread2({}, request), {}, {
|
|
954
|
-
headers: _objectSpread2(_objectSpread2({}, request.headers), {}, {
|
|
955
|
-
Authorization: authorization
|
|
956
|
-
})
|
|
957
|
-
});
|
|
543
|
+
function createAuthMiddlewareForPasswordFlow$1(options) {
|
|
544
|
+
const tokenCache = store({});
|
|
545
|
+
const pendingTasks = [];
|
|
546
|
+
const requestState = store(false);
|
|
547
|
+
return next => (request, response) => {
|
|
548
|
+
// Check if there is already a `Authorization` header in the request.
|
|
549
|
+
// If so, then go directly to the next middleware.
|
|
550
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
551
|
+
next(request, response);
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
958
554
|
|
|
959
|
-
|
|
555
|
+
const params = {
|
|
556
|
+
request,
|
|
557
|
+
response,
|
|
558
|
+
...buildRequestForPasswordFlow(options),
|
|
559
|
+
pendingTasks,
|
|
560
|
+
requestState,
|
|
561
|
+
tokenCache,
|
|
562
|
+
fetch: options.fetch
|
|
960
563
|
};
|
|
564
|
+
authMiddlewareBase(params, next, options);
|
|
961
565
|
};
|
|
962
566
|
}
|
|
963
567
|
|
|
964
|
-
function
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
568
|
+
function createAuthMiddlewareForRefreshTokenFlow$1(options) {
|
|
569
|
+
const tokenCache = store({});
|
|
570
|
+
const pendingTasks = [];
|
|
571
|
+
const requestState = store(false);
|
|
572
|
+
return next => (request, response) => {
|
|
573
|
+
// Check if there is already a `Authorization` header in the request.
|
|
574
|
+
// If so, then go directly to the next middleware.
|
|
575
|
+
if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
|
|
576
|
+
next(request, response);
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
972
579
|
|
|
973
|
-
|
|
580
|
+
const params = {
|
|
581
|
+
request,
|
|
582
|
+
response,
|
|
583
|
+
...buildRequestForRefreshTokenFlow(options),
|
|
584
|
+
pendingTasks,
|
|
585
|
+
requestState,
|
|
586
|
+
tokenCache,
|
|
587
|
+
fetch: options.fetch
|
|
974
588
|
};
|
|
589
|
+
authMiddlewareBase(params, next);
|
|
975
590
|
};
|
|
976
591
|
}
|
|
977
592
|
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
593
|
+
var authMiddlewares = /*#__PURE__*/Object.freeze({
|
|
594
|
+
__proto__: null,
|
|
595
|
+
createAuthMiddlewareForAnonymousSessionFlow: createAuthMiddlewareForAnonymousSessionFlow$1,
|
|
596
|
+
createAuthMiddlewareForClientCredentialsFlow: createAuthMiddlewareForClientCredentialsFlow$1,
|
|
597
|
+
createAuthMiddlewareWithExistingToken: createAuthMiddlewareWithExistingToken$1,
|
|
598
|
+
createAuthMiddlewareForPasswordFlow: createAuthMiddlewareForPasswordFlow$1,
|
|
599
|
+
createAuthMiddlewareForRefreshTokenFlow: createAuthMiddlewareForRefreshTokenFlow$1
|
|
600
|
+
});
|
|
601
|
+
|
|
602
|
+
function createCorrelationIdMiddleware(options) {
|
|
603
|
+
return next => (request, response) => {
|
|
604
|
+
const nextRequest = { ...request,
|
|
605
|
+
headers: { ...request.headers,
|
|
606
|
+
'X-Correlation-ID': options.generate()
|
|
607
|
+
}
|
|
991
608
|
};
|
|
609
|
+
next(nextRequest, response);
|
|
992
610
|
};
|
|
993
611
|
}
|
|
994
612
|
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
*/
|
|
1003
|
-
var isBrowser = function isBrowser() {
|
|
1004
|
-
return window.document && window.document.nodeType === 9;
|
|
1005
|
-
};
|
|
1006
|
-
|
|
1007
|
-
function getSystemInfo() {
|
|
1008
|
-
if (isBrowser()) return window.navigator.userAgent;
|
|
1009
|
-
var nodeVersion = process.version.slice(1); // const platformInfo = `(${process.platform}; ${process.arch})`
|
|
1010
|
-
// return `Node.js/${nodeVersion} ${platformInfo}`
|
|
1011
|
-
|
|
1012
|
-
return "node.js/".concat(nodeVersion);
|
|
613
|
+
function defineError(statusCode, message, meta = {}) {
|
|
614
|
+
this.status = this.statusCode = this.code = statusCode;
|
|
615
|
+
this.message = message;
|
|
616
|
+
Object.assign(this, meta);
|
|
617
|
+
this.name = this.constructor.name;
|
|
618
|
+
this.constructor.prototype.__proto__ = Error.prototype;
|
|
619
|
+
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
1013
620
|
}
|
|
1014
621
|
|
|
1015
|
-
function
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
var libraryInfo = null;
|
|
1021
|
-
if (options.libraryName && !options.libraryVersion) libraryInfo = options.libraryName;else if (options.libraryName && options.libraryVersion) libraryInfo = "".concat(options.libraryName, "/").concat(options.libraryVersion); // Contact info
|
|
1022
|
-
|
|
1023
|
-
var contactInfo = null;
|
|
1024
|
-
if (options.contactUrl && !options.contactEmail) contactInfo = "(+".concat(options.contactUrl, ")");else if (!options.contactUrl && options.contactEmail) contactInfo = "(+".concat(options.contactEmail, ")");else if (options.contactUrl && options.contactEmail) contactInfo = "(+".concat(options.contactUrl, "; +").concat(options.contactEmail, ")"); // System info
|
|
1025
|
-
|
|
1026
|
-
var systemInfo = getSystemInfo();
|
|
1027
|
-
return [baseInfo, systemInfo, libraryInfo, contactInfo].filter(Boolean).join(' ');
|
|
622
|
+
function NetworkError(...args) {
|
|
623
|
+
defineError.call(this, 0
|
|
624
|
+
/* special code to indicate network errors */
|
|
625
|
+
, ...args);
|
|
1028
626
|
}
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
function createUserAgentMiddleware() {
|
|
1034
|
-
var userAgent = createUserAgent({
|
|
1035
|
-
name: "commercetools-sdk-javascript-v2/".concat(version)
|
|
1036
|
-
});
|
|
1037
|
-
return function (next) {
|
|
1038
|
-
return function (request, response) {
|
|
1039
|
-
var requestWithUserAgent = _objectSpread2(_objectSpread2({}, request), {}, {
|
|
1040
|
-
headers: _objectSpread2(_objectSpread2({}, request.headers), {}, {
|
|
1041
|
-
'User-Agent': userAgent
|
|
1042
|
-
})
|
|
1043
|
-
});
|
|
1044
|
-
|
|
1045
|
-
next(requestWithUserAgent, response);
|
|
1046
|
-
};
|
|
1047
|
-
};
|
|
627
|
+
function HttpError(...args) {
|
|
628
|
+
defineError.call(this,
|
|
629
|
+
/* code will be passed as arg */
|
|
630
|
+
...args);
|
|
1048
631
|
}
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
var _ref$concurrency = _ref.concurrency,
|
|
1052
|
-
concurrency = _ref$concurrency === void 0 ? 20 : _ref$concurrency;
|
|
1053
|
-
var queue = [];
|
|
1054
|
-
var runningCount = 0;
|
|
1055
|
-
|
|
1056
|
-
var dequeue = function dequeue(next) {
|
|
1057
|
-
// We assume here that this task has been completed
|
|
1058
|
-
runningCount -= 1; // Check if there are any other pending tasks and execute them
|
|
1059
|
-
|
|
1060
|
-
if (queue.length && runningCount <= concurrency) {
|
|
1061
|
-
var nextTask = queue.shift();
|
|
1062
|
-
runningCount += 1;
|
|
1063
|
-
next(nextTask.request, nextTask.response);
|
|
1064
|
-
}
|
|
1065
|
-
};
|
|
1066
|
-
|
|
1067
|
-
return function (next) {
|
|
1068
|
-
return function (request, response) {
|
|
1069
|
-
// Override response `resolve` and `reject` to know when the request has
|
|
1070
|
-
// been completed and therefore trigger a pending task in the queue.
|
|
1071
|
-
var patchedResponse = _objectSpread2(_objectSpread2({}, response), {}, {
|
|
1072
|
-
resolve: function resolve(data) {
|
|
1073
|
-
// Resolve original promise
|
|
1074
|
-
response.resolve(data);
|
|
1075
|
-
dequeue(next);
|
|
1076
|
-
},
|
|
1077
|
-
reject: function reject(error) {
|
|
1078
|
-
// Reject original promise
|
|
1079
|
-
response.reject(error);
|
|
1080
|
-
dequeue(next);
|
|
1081
|
-
}
|
|
1082
|
-
}); // Add task to the queue
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
queue.push({
|
|
1086
|
-
request: request,
|
|
1087
|
-
response: patchedResponse
|
|
1088
|
-
}); // If possible, run the task straight away
|
|
1089
|
-
|
|
1090
|
-
if (runningCount < concurrency) {
|
|
1091
|
-
var nextTask = queue.shift();
|
|
1092
|
-
runningCount += 1;
|
|
1093
|
-
next(nextTask.request, nextTask.response);
|
|
1094
|
-
}
|
|
1095
|
-
};
|
|
1096
|
-
};
|
|
632
|
+
function BadRequest(...args) {
|
|
633
|
+
defineError.call(this, 400, ...args);
|
|
1097
634
|
}
|
|
635
|
+
function Unauthorized(...args) {
|
|
636
|
+
defineError.call(this, 401, ...args);
|
|
637
|
+
}
|
|
638
|
+
function Forbidden(...args) {
|
|
639
|
+
defineError.call(this, 403, ...args);
|
|
640
|
+
}
|
|
641
|
+
function NotFound(...args) {
|
|
642
|
+
defineError.call(this, 404, ...args);
|
|
643
|
+
}
|
|
644
|
+
function ConcurrentModification(...args) {
|
|
645
|
+
defineError.call(this, 409, ...args);
|
|
646
|
+
}
|
|
647
|
+
function InternalServerError(...args) {
|
|
648
|
+
defineError.call(this, 500, ...args);
|
|
649
|
+
}
|
|
650
|
+
function ServiceUnavailable(...args) {
|
|
651
|
+
defineError.call(this, 503, ...args);
|
|
652
|
+
}
|
|
653
|
+
function getErrorByCode(code) {
|
|
654
|
+
switch (code) {
|
|
655
|
+
case 0:
|
|
656
|
+
return NetworkError;
|
|
1098
657
|
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
|
|
1103
|
-
_typeof = function (obj) {
|
|
1104
|
-
return typeof obj;
|
|
1105
|
-
};
|
|
1106
|
-
} else {
|
|
1107
|
-
_typeof = function (obj) {
|
|
1108
|
-
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
|
|
1109
|
-
};
|
|
1110
|
-
}
|
|
658
|
+
case 400:
|
|
659
|
+
return BadRequest;
|
|
1111
660
|
|
|
1112
|
-
|
|
1113
|
-
|
|
661
|
+
case 401:
|
|
662
|
+
return Unauthorized;
|
|
1114
663
|
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
var target = {};
|
|
1118
|
-
var sourceKeys = Object.keys(source);
|
|
1119
|
-
var key, i;
|
|
664
|
+
case 403:
|
|
665
|
+
return Forbidden;
|
|
1120
666
|
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
if (excluded.indexOf(key) >= 0) continue;
|
|
1124
|
-
target[key] = source[key];
|
|
1125
|
-
}
|
|
667
|
+
case 404:
|
|
668
|
+
return NotFound;
|
|
1126
669
|
|
|
1127
|
-
|
|
1128
|
-
|
|
670
|
+
case 409:
|
|
671
|
+
return ConcurrentModification;
|
|
1129
672
|
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
var target = _objectWithoutPropertiesLoose(source, excluded);
|
|
1133
|
-
var key, i;
|
|
673
|
+
case 500:
|
|
674
|
+
return InternalServerError;
|
|
1134
675
|
|
|
1135
|
-
|
|
1136
|
-
|
|
676
|
+
case 503:
|
|
677
|
+
return ServiceUnavailable;
|
|
1137
678
|
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
if (excluded.indexOf(key) >= 0) continue;
|
|
1141
|
-
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
|
|
1142
|
-
target[key] = source[key];
|
|
1143
|
-
}
|
|
679
|
+
default:
|
|
680
|
+
return undefined;
|
|
1144
681
|
}
|
|
1145
|
-
|
|
1146
|
-
return target;
|
|
1147
682
|
}
|
|
1148
683
|
|
|
1149
684
|
function parseHeaders(headers) {
|
|
@@ -1152,23 +687,21 @@ function parseHeaders(headers) {
|
|
|
1152
687
|
|
|
1153
688
|
if (!headers.forEach) return {}; // whatwg-fetch
|
|
1154
689
|
|
|
1155
|
-
|
|
1156
|
-
headers.forEach(
|
|
690
|
+
const map = {};
|
|
691
|
+
headers.forEach((value, name) => {
|
|
1157
692
|
map[name] = value;
|
|
1158
693
|
});
|
|
1159
694
|
return map;
|
|
1160
695
|
}
|
|
1161
696
|
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
if (statusCode === 404) errorMessage = "URI not found: ".concat(rest.originalRequest.uri);
|
|
1171
|
-
var ResponseError = getErrorByCode(statusCode);
|
|
697
|
+
function createError({
|
|
698
|
+
statusCode,
|
|
699
|
+
message,
|
|
700
|
+
...rest
|
|
701
|
+
}) {
|
|
702
|
+
let errorMessage = message || 'Unexpected non-JSON error response';
|
|
703
|
+
if (statusCode === 404) errorMessage = `URI not found: ${rest.originalRequest.uri}`;
|
|
704
|
+
const ResponseError = getErrorByCode(statusCode);
|
|
1172
705
|
if (ResponseError) return new ResponseError(errorMessage, rest);
|
|
1173
706
|
return new HttpError(statusCode, errorMessage, rest);
|
|
1174
707
|
} // calculates the delay duration exponentially
|
|
@@ -1177,7 +710,7 @@ function createError(_ref) {
|
|
|
1177
710
|
|
|
1178
711
|
function calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay) {
|
|
1179
712
|
if (backoff) return retryCount !== 0 // do not increase if it's the first retry
|
|
1180
|
-
? Math.min(Math.round((Math.random() + 1) * retryDelay *
|
|
713
|
+
? Math.min(Math.round((Math.random() + 1) * retryDelay * 2 ** retryCount), maxDelay) : retryDelay;
|
|
1181
714
|
return retryDelay;
|
|
1182
715
|
}
|
|
1183
716
|
|
|
@@ -1188,30 +721,27 @@ function maskAuthData(request, maskSensitiveHeaderData) {
|
|
|
1188
721
|
}
|
|
1189
722
|
}
|
|
1190
723
|
|
|
1191
|
-
function createHttpMiddleware(
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
maxDelay = _ref2$retryConfig$max2 === void 0 ? Infinity : _ref2$retryConfig$max2,
|
|
1210
|
-
fetcher = _ref2.fetch,
|
|
1211
|
-
getAbortController = _ref2.getAbortController;
|
|
724
|
+
function createHttpMiddleware({
|
|
725
|
+
host,
|
|
726
|
+
credentialsMode,
|
|
727
|
+
includeResponseHeaders,
|
|
728
|
+
includeOriginalRequest,
|
|
729
|
+
maskSensitiveHeaderData = true,
|
|
730
|
+
enableRetry,
|
|
731
|
+
timeout,
|
|
732
|
+
retryConfig: {
|
|
733
|
+
// encourage exponential backoff to prevent spamming the server if down
|
|
734
|
+
maxRetries = 10,
|
|
735
|
+
backoff = true,
|
|
736
|
+
retryDelay = 200,
|
|
737
|
+
maxDelay = Infinity
|
|
738
|
+
} = {},
|
|
739
|
+
fetch: fetcher,
|
|
740
|
+
getAbortController
|
|
741
|
+
}) {
|
|
1212
742
|
if (!fetcher && typeof fetch === 'undefined') throw new Error('`fetch` is not available. Please pass in `fetch` as an option or have it globally available.');
|
|
1213
743
|
if (timeout && !getAbortController && typeof AbortController === 'undefined') throw new Error('`AbortController` is not available. Please pass in `getAbortController` as an option or have AbortController globally available when using timeout.');
|
|
1214
|
-
|
|
744
|
+
let fetchFunction;
|
|
1215
745
|
|
|
1216
746
|
if (fetcher) {
|
|
1217
747
|
fetchFunction = fetcher;
|
|
@@ -1222,187 +752,335 @@ function createHttpMiddleware(_ref2) {
|
|
|
1222
752
|
fetchFunction = fetch;
|
|
1223
753
|
}
|
|
1224
754
|
|
|
1225
|
-
return
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
var requestHeader = _objectSpread2({}, request.headers);
|
|
1234
|
-
|
|
1235
|
-
if (!Object.prototype.hasOwnProperty.call(requestHeader, 'Content-Type')) {
|
|
1236
|
-
requestHeader['Content-Type'] = 'application/json';
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
if (body) {
|
|
1240
|
-
requestHeader['Content-Length'] = Buffer.byteLength(body).toString();
|
|
1241
|
-
}
|
|
1242
|
-
|
|
1243
|
-
var fetchOptions = {
|
|
1244
|
-
method: request.method,
|
|
1245
|
-
headers: requestHeader
|
|
1246
|
-
};
|
|
1247
|
-
|
|
1248
|
-
if (credentialsMode) {
|
|
1249
|
-
fetchOptions.credentialsMode = credentialsMode;
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
if (abortController) {
|
|
1253
|
-
fetchOptions.signal = abortController.signal;
|
|
1254
|
-
}
|
|
1255
|
-
|
|
1256
|
-
if (body) {
|
|
1257
|
-
fetchOptions.body = body;
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
var retryCount = 0; // wrap in a fn so we can retry if error occur
|
|
1261
|
-
|
|
1262
|
-
function executeFetch() {
|
|
1263
|
-
// Kick off timer for abortController directly before fetch.
|
|
1264
|
-
var timer;
|
|
1265
|
-
if (timeout) timer = setTimeout(function () {
|
|
1266
|
-
abortController.abort();
|
|
1267
|
-
}, timeout);
|
|
1268
|
-
fetchFunction(url, fetchOptions).then(function (res) {
|
|
1269
|
-
if (res.ok) {
|
|
1270
|
-
if (fetchOptions.method === 'HEAD') {
|
|
1271
|
-
next(request, _objectSpread2(_objectSpread2({}, response), {}, {
|
|
1272
|
-
statusCode: res.status
|
|
1273
|
-
}));
|
|
1274
|
-
return;
|
|
1275
|
-
}
|
|
755
|
+
return next => (request, response) => {
|
|
756
|
+
let abortController;
|
|
757
|
+
if (timeout || getAbortController) abortController = (getAbortController ? getAbortController() : null) || new AbortController();
|
|
758
|
+
const url = host.replace(/\/$/, '') + request.uri;
|
|
759
|
+
const body = typeof request.body === 'string' || Buffer.isBuffer(request.body) ? request.body : // NOTE: `stringify` of `null` gives the String('null')
|
|
760
|
+
JSON.stringify(request.body || undefined);
|
|
761
|
+
const requestHeader = { ...request.headers
|
|
762
|
+
};
|
|
1276
763
|
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
764
|
+
if (!Object.prototype.hasOwnProperty.call(requestHeader, 'Content-Type')) {
|
|
765
|
+
requestHeader['Content-Type'] = 'application/json';
|
|
766
|
+
}
|
|
1280
767
|
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
if (enableRetry && retryCount < maxRetries) {
|
|
1285
|
-
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
1286
|
-
retryCount += 1;
|
|
1287
|
-
return;
|
|
1288
|
-
}
|
|
768
|
+
if (body) {
|
|
769
|
+
requestHeader['Content-Length'] = Buffer.byteLength(body).toString();
|
|
770
|
+
}
|
|
1289
771
|
|
|
1290
|
-
|
|
1291
|
-
|
|
772
|
+
const fetchOptions = {
|
|
773
|
+
method: request.method,
|
|
774
|
+
headers: requestHeader
|
|
775
|
+
};
|
|
1292
776
|
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
});
|
|
777
|
+
if (credentialsMode) {
|
|
778
|
+
fetchOptions.credentialsMode = credentialsMode;
|
|
779
|
+
}
|
|
1297
780
|
|
|
1298
|
-
|
|
781
|
+
if (abortController) {
|
|
782
|
+
fetchOptions.signal = abortController.signal;
|
|
783
|
+
}
|
|
1299
784
|
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
}
|
|
785
|
+
if (body) {
|
|
786
|
+
fetchOptions.body = body;
|
|
787
|
+
}
|
|
1304
788
|
|
|
1305
|
-
|
|
789
|
+
let retryCount = 0; // wrap in a fn so we can retry if error occur
|
|
790
|
+
|
|
791
|
+
function executeFetch() {
|
|
792
|
+
// Kick off timer for abortController directly before fetch.
|
|
793
|
+
let timer;
|
|
794
|
+
if (timeout) timer = setTimeout(() => {
|
|
795
|
+
abortController.abort();
|
|
796
|
+
}, timeout);
|
|
797
|
+
fetchFunction(url, fetchOptions).then(res => {
|
|
798
|
+
if (res.ok) {
|
|
799
|
+
if (fetchOptions.method === 'HEAD') {
|
|
800
|
+
next(request, { ...response,
|
|
801
|
+
statusCode: res.status
|
|
1306
802
|
});
|
|
1307
803
|
return;
|
|
1308
804
|
}
|
|
1309
805
|
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
return;
|
|
1314
|
-
} // Server responded with an error. Try to parse it as JSON, then
|
|
1315
|
-
// return a proper error type with all necessary meta information.
|
|
1316
|
-
|
|
1317
|
-
res.text().then(function (text) {
|
|
1318
|
-
// Try to parse the error response as JSON
|
|
1319
|
-
var parsed;
|
|
806
|
+
res.text().then(result => {
|
|
807
|
+
// Try to parse the response as JSON
|
|
808
|
+
let parsed;
|
|
1320
809
|
|
|
1321
810
|
try {
|
|
1322
|
-
parsed = JSON.parse(
|
|
1323
|
-
} catch (
|
|
1324
|
-
|
|
1325
|
-
|
|
811
|
+
parsed = result.length > 0 ? JSON.parse(result) : {};
|
|
812
|
+
} catch (err) {
|
|
813
|
+
if (enableRetry && retryCount < maxRetries) {
|
|
814
|
+
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
815
|
+
retryCount += 1;
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
1326
818
|
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
originalRequest: request,
|
|
1330
|
-
retryCount: retryCount,
|
|
1331
|
-
headers: parseHeaders(res.headers)
|
|
1332
|
-
}, _typeof(parsed) === 'object' ? {
|
|
1333
|
-
message: parsed.message,
|
|
1334
|
-
body: parsed
|
|
1335
|
-
} : {
|
|
1336
|
-
message: parsed,
|
|
1337
|
-
body: parsed
|
|
1338
|
-
}));
|
|
1339
|
-
maskAuthData(error.originalRequest, maskSensitiveHeaderData); // Let the final resolver to reject the promise
|
|
819
|
+
parsed = result;
|
|
820
|
+
}
|
|
1340
821
|
|
|
1341
|
-
|
|
1342
|
-
|
|
822
|
+
const parsedResponse = { ...response,
|
|
823
|
+
body: parsed,
|
|
1343
824
|
statusCode: res.status
|
|
1344
|
-
}
|
|
825
|
+
};
|
|
826
|
+
if (includeResponseHeaders) parsedResponse.headers = parseHeaders(res.headers);
|
|
827
|
+
|
|
828
|
+
if (includeOriginalRequest) {
|
|
829
|
+
parsedResponse.request = { ...fetchOptions
|
|
830
|
+
};
|
|
831
|
+
maskAuthData(parsedResponse.request, maskSensitiveHeaderData);
|
|
832
|
+
}
|
|
1345
833
|
|
|
1346
834
|
next(request, parsedResponse);
|
|
1347
835
|
});
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
if (res.status === 503 && enableRetry) if (retryCount < maxRetries) {
|
|
840
|
+
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
841
|
+
retryCount += 1;
|
|
842
|
+
return;
|
|
843
|
+
} // Server responded with an error. Try to parse it as JSON, then
|
|
844
|
+
// return a proper error type with all necessary meta information.
|
|
845
|
+
|
|
846
|
+
res.text().then(text => {
|
|
847
|
+
// Try to parse the error response as JSON
|
|
848
|
+
let parsed;
|
|
849
|
+
|
|
850
|
+
try {
|
|
851
|
+
parsed = JSON.parse(text);
|
|
852
|
+
} catch (error) {
|
|
853
|
+
parsed = text;
|
|
1354
854
|
}
|
|
1355
|
-
|
|
855
|
+
|
|
856
|
+
const error = createError({
|
|
857
|
+
statusCode: res.status,
|
|
1356
858
|
originalRequest: request,
|
|
1357
|
-
retryCount
|
|
859
|
+
retryCount,
|
|
860
|
+
headers: parseHeaders(res.headers),
|
|
861
|
+
...(typeof parsed === 'object' ? {
|
|
862
|
+
message: parsed.message,
|
|
863
|
+
body: parsed
|
|
864
|
+
} : {
|
|
865
|
+
message: parsed,
|
|
866
|
+
body: parsed
|
|
867
|
+
})
|
|
1358
868
|
});
|
|
1359
|
-
maskAuthData(error.originalRequest, maskSensitiveHeaderData);
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
869
|
+
maskAuthData(error.originalRequest, maskSensitiveHeaderData); // Let the final resolver to reject the promise
|
|
870
|
+
|
|
871
|
+
const parsedResponse = { ...response,
|
|
872
|
+
error,
|
|
873
|
+
statusCode: res.status
|
|
874
|
+
};
|
|
875
|
+
next(request, parsedResponse);
|
|
1366
876
|
});
|
|
1367
|
-
}
|
|
877
|
+
}, // We know that this is a "network" error thrown by the `fetch` library
|
|
878
|
+
e => {
|
|
879
|
+
if (enableRetry) if (retryCount < maxRetries) {
|
|
880
|
+
setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
|
|
881
|
+
retryCount += 1;
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
const error = new NetworkError(e.message, {
|
|
885
|
+
originalRequest: request,
|
|
886
|
+
retryCount
|
|
887
|
+
});
|
|
888
|
+
maskAuthData(error.originalRequest, maskSensitiveHeaderData);
|
|
889
|
+
next(request, { ...response,
|
|
890
|
+
error,
|
|
891
|
+
statusCode: 0
|
|
892
|
+
});
|
|
893
|
+
}).finally(() => {
|
|
894
|
+
clearTimeout(timer);
|
|
895
|
+
});
|
|
896
|
+
}
|
|
1368
897
|
|
|
1369
|
-
|
|
1370
|
-
};
|
|
898
|
+
executeFetch();
|
|
1371
899
|
};
|
|
1372
900
|
}
|
|
1373
901
|
|
|
1374
|
-
function
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
902
|
+
function createLoggerMiddleware() {
|
|
903
|
+
return next => (request, response) => {
|
|
904
|
+
const {
|
|
905
|
+
error,
|
|
906
|
+
body,
|
|
907
|
+
statusCode
|
|
908
|
+
} = response;
|
|
909
|
+
console.log('Request: ', request);
|
|
910
|
+
console.log('Response: ', {
|
|
911
|
+
error,
|
|
912
|
+
body,
|
|
913
|
+
statusCode
|
|
914
|
+
});
|
|
915
|
+
next(request, response);
|
|
916
|
+
};
|
|
1378
917
|
}
|
|
1379
918
|
|
|
1380
|
-
function
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
919
|
+
function createQueueMiddleware({
|
|
920
|
+
concurrency = 20
|
|
921
|
+
}) {
|
|
922
|
+
const queue = [];
|
|
923
|
+
let runningCount = 0;
|
|
924
|
+
|
|
925
|
+
const dequeue = next => {
|
|
926
|
+
// We assume here that this task has been completed
|
|
927
|
+
runningCount -= 1; // Check if there are any other pending tasks and execute them
|
|
928
|
+
|
|
929
|
+
if (queue.length && runningCount <= concurrency) {
|
|
930
|
+
const nextTask = queue.shift();
|
|
931
|
+
runningCount += 1;
|
|
932
|
+
next(nextTask.request, nextTask.response);
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
|
|
936
|
+
return next => (request, response) => {
|
|
937
|
+
// Override response `resolve` and `reject` to know when the request has
|
|
938
|
+
// been completed and therefore trigger a pending task in the queue.
|
|
939
|
+
const patchedResponse = { ...response,
|
|
940
|
+
|
|
941
|
+
resolve(data) {
|
|
942
|
+
// Resolve original promise
|
|
943
|
+
response.resolve(data);
|
|
944
|
+
dequeue(next);
|
|
945
|
+
},
|
|
946
|
+
|
|
947
|
+
reject(error) {
|
|
948
|
+
// Reject original promise
|
|
949
|
+
response.reject(error);
|
|
950
|
+
dequeue(next);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
}; // Add task to the queue
|
|
954
|
+
|
|
955
|
+
queue.push({
|
|
956
|
+
request,
|
|
957
|
+
response: patchedResponse
|
|
958
|
+
}); // If possible, run the task straight away
|
|
959
|
+
|
|
960
|
+
if (runningCount < concurrency) {
|
|
961
|
+
const nextTask = queue.shift();
|
|
962
|
+
runningCount += 1;
|
|
963
|
+
next(nextTask.request, nextTask.response);
|
|
964
|
+
}
|
|
965
|
+
};
|
|
1388
966
|
}
|
|
1389
967
|
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
968
|
+
var packageJson = {
|
|
969
|
+
name: "@commercetools/sdk-client-v2",
|
|
970
|
+
version: "1.0.0",
|
|
971
|
+
description: "commercetools TypeScript SDK client.",
|
|
972
|
+
keywords: [
|
|
973
|
+
"commercetools",
|
|
974
|
+
"sdk",
|
|
975
|
+
"typescript",
|
|
976
|
+
"client",
|
|
977
|
+
"middleware",
|
|
978
|
+
"http",
|
|
979
|
+
"oauth",
|
|
980
|
+
"auth"
|
|
981
|
+
],
|
|
982
|
+
homepage: "https://github.com/commercetools/commercetools-sdk-typescript",
|
|
983
|
+
license: "MIT",
|
|
984
|
+
directories: {
|
|
985
|
+
lib: "lib",
|
|
986
|
+
test: "test"
|
|
987
|
+
},
|
|
988
|
+
publishConfig: {
|
|
989
|
+
access: "public"
|
|
990
|
+
},
|
|
991
|
+
repository: {
|
|
992
|
+
type: "git",
|
|
993
|
+
url: "git+https://github.com/commercetools/commercetools-sdk-typescript.git"
|
|
994
|
+
},
|
|
995
|
+
bugs: {
|
|
996
|
+
url: "https://github.com/commercetools/commercetools-sdk-typescript/issues"
|
|
997
|
+
},
|
|
998
|
+
dependencies: {
|
|
999
|
+
"node-fetch": "^2.6.1",
|
|
1000
|
+
querystring: "^0.2.1"
|
|
1001
|
+
},
|
|
1002
|
+
files: [
|
|
1003
|
+
"dist",
|
|
1004
|
+
"CHANGELOG.md"
|
|
1005
|
+
],
|
|
1006
|
+
author: "Chukwuemeka Ajima <meeky.ae@gmail.com>",
|
|
1007
|
+
main: "dist/commercetools-sdk-client-v2.cjs.js",
|
|
1008
|
+
module: "dist/commercetools-sdk-client-v2.esm.js",
|
|
1009
|
+
browser: {
|
|
1010
|
+
"./dist/commercetools-sdk-client-v2.cjs.js": "./dist/commercetools-sdk-client-v2.browser.cjs.js",
|
|
1011
|
+
"./dist/commercetools-sdk-client-v2.esm.js": "./dist/commercetools-sdk-client-v2.browser.esm.js"
|
|
1012
|
+
},
|
|
1013
|
+
devDependencies: {
|
|
1014
|
+
"abort-controller": "3.0.0",
|
|
1015
|
+
"common-tags": "1.8.2",
|
|
1016
|
+
dotenv: "10.0.0",
|
|
1017
|
+
jest: "27.3.1",
|
|
1018
|
+
nock: "12.0.3",
|
|
1019
|
+
"organize-imports-cli": "0.8.0"
|
|
1020
|
+
},
|
|
1021
|
+
scripts: {
|
|
1022
|
+
organize_imports: "find src -type f -name '*.ts' | xargs organize-imports-cli",
|
|
1023
|
+
postbuild: "yarn organize_imports",
|
|
1024
|
+
post_process_generate: "yarn organize_imports"
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
|
|
1028
|
+
/*
|
|
1029
|
+
This is the easiest way, for this use case, to detect if we're running in
|
|
1030
|
+
Node.js or in a browser environment. In other cases, this won't be even a
|
|
1031
|
+
problem as Rollup will provide the correct polyfill in the bundle.
|
|
1032
|
+
The main advantage by doing it this way is that it allows to easily test
|
|
1033
|
+
the code running in both environments, by overriding `global.window` in
|
|
1034
|
+
the specific test.
|
|
1035
|
+
*/
|
|
1036
|
+
const isBrowser = () => window.document && window.document.nodeType === 9;
|
|
1037
|
+
|
|
1038
|
+
function getSystemInfo() {
|
|
1039
|
+
if (isBrowser()) return window.navigator.userAgent;
|
|
1040
|
+
const nodeVersion = process.version.slice(1); // const platformInfo = `(${process.platform}; ${process.arch})`
|
|
1041
|
+
// return `Node.js/${nodeVersion} ${platformInfo}`
|
|
1042
|
+
|
|
1043
|
+
return `node.js/${nodeVersion}`;
|
|
1394
1044
|
}
|
|
1395
1045
|
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
createAuthMiddlewareWithExistingToken = createAuthMiddlewareWithExistingToken$1;
|
|
1046
|
+
function createUserAgent(options) {
|
|
1047
|
+
if (!options || Object.keys(options).length === 0 || !{}.hasOwnProperty.call(options, 'name')) throw new Error('Missing required option `name`'); // Main info
|
|
1048
|
+
|
|
1049
|
+
const baseInfo = options.version ? `${options.name}/${options.version}` : options.name; // Library info
|
|
1401
1050
|
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1051
|
+
let libraryInfo = null;
|
|
1052
|
+
if (options.libraryName && !options.libraryVersion) libraryInfo = options.libraryName;else if (options.libraryName && options.libraryVersion) libraryInfo = `${options.libraryName}/${options.libraryVersion}`; // Contact info
|
|
1053
|
+
|
|
1054
|
+
let contactInfo = null;
|
|
1055
|
+
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
|
|
1056
|
+
|
|
1057
|
+
const systemInfo = getSystemInfo();
|
|
1058
|
+
return [baseInfo, systemInfo, libraryInfo, contactInfo].filter(Boolean).join(' ');
|
|
1059
|
+
}
|
|
1405
1060
|
|
|
1061
|
+
function createUserAgentMiddleware() {
|
|
1062
|
+
const userAgent = createUserAgent({
|
|
1063
|
+
name: `commercetools-sdk-javascript-v2/${packageJson.version}`
|
|
1064
|
+
});
|
|
1065
|
+
return next => (request, response) => {
|
|
1066
|
+
const requestWithUserAgent = { ...request,
|
|
1067
|
+
headers: { ...request.headers,
|
|
1068
|
+
'User-Agent': userAgent
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
next(requestWithUserAgent, response);
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
const {
|
|
1076
|
+
createAuthMiddlewareForPasswordFlow,
|
|
1077
|
+
createAuthMiddlewareForAnonymousSessionFlow,
|
|
1078
|
+
createAuthMiddlewareForClientCredentialsFlow,
|
|
1079
|
+
createAuthMiddlewareForRefreshTokenFlow,
|
|
1080
|
+
createAuthMiddlewareWithExistingToken
|
|
1081
|
+
} = authMiddlewares;
|
|
1082
|
+
class ClientBuilder {
|
|
1083
|
+
constructor() {
|
|
1406
1084
|
_defineProperty(this, "projectKey", void 0);
|
|
1407
1085
|
|
|
1408
1086
|
_defineProperty(this, "authMiddleware", void 0);
|
|
@@ -1420,157 +1098,147 @@ var ClientBuilder = /*#__PURE__*/function () {
|
|
|
1420
1098
|
_defineProperty(this, "middlewares", []);
|
|
1421
1099
|
}
|
|
1422
1100
|
|
|
1423
|
-
|
|
1424
|
-
key
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
}
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
}
|
|
1550
|
-
key: "withCorrelationIdMiddleware",
|
|
1551
|
-
value: function withCorrelationIdMiddleware(options) {
|
|
1552
|
-
this.correlationIdMiddleware = createCorrelationIdMiddleware(_objectSpread2({
|
|
1553
|
-
generate: options.generate || null
|
|
1554
|
-
}, options));
|
|
1555
|
-
return this;
|
|
1556
|
-
}
|
|
1557
|
-
}, {
|
|
1558
|
-
key: "build",
|
|
1559
|
-
value: function build() {
|
|
1560
|
-
var middlewares = this.middlewares.slice();
|
|
1561
|
-
if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
|
|
1562
|
-
if (this.userAgentMiddleware) middlewares.push(this.userAgentMiddleware);
|
|
1563
|
-
if (this.authMiddleware) middlewares.push(this.authMiddleware);
|
|
1564
|
-
if (this.loggerMiddleware) middlewares.push(this.loggerMiddleware);
|
|
1565
|
-
if (this.queueMiddleware) middlewares.push(this.queueMiddleware);
|
|
1566
|
-
if (this.httpMiddleware) middlewares.push(this.httpMiddleware);
|
|
1567
|
-
return createClient({
|
|
1568
|
-
middlewares: middlewares
|
|
1569
|
-
});
|
|
1570
|
-
}
|
|
1571
|
-
}]);
|
|
1101
|
+
withProjectKey(key) {
|
|
1102
|
+
this.projectKey = key;
|
|
1103
|
+
return this;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
defaultClient(baseUri, credentials, oauthUri, projectKey) {
|
|
1107
|
+
return this.withClientCredentialsFlow({
|
|
1108
|
+
host: oauthUri,
|
|
1109
|
+
projectKey: projectKey || this.projectKey,
|
|
1110
|
+
credentials
|
|
1111
|
+
}).withHttpMiddleware({
|
|
1112
|
+
host: baseUri,
|
|
1113
|
+
fetch: fetch$1
|
|
1114
|
+
}).withLoggerMiddleware();
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
withAuthMiddleware(authMiddleware) {
|
|
1118
|
+
this.authMiddleware = authMiddleware;
|
|
1119
|
+
return this;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
withMiddleware(middleware) {
|
|
1123
|
+
this.middlewares.push(middleware);
|
|
1124
|
+
return this;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
withClientCredentialsFlow(options) {
|
|
1128
|
+
return this.withAuthMiddleware(createAuthMiddlewareForClientCredentialsFlow({
|
|
1129
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1130
|
+
projectKey: options.projectKey || this.projectKey,
|
|
1131
|
+
credentials: {
|
|
1132
|
+
clientId: options.credentials.clientId || '',
|
|
1133
|
+
clientSecret: options.credentials.clientSecret || ''
|
|
1134
|
+
},
|
|
1135
|
+
oauthUri: options.oauthUri || '',
|
|
1136
|
+
scopes: options.scopes,
|
|
1137
|
+
fetch: options.fetch || fetch$1,
|
|
1138
|
+
...options
|
|
1139
|
+
}));
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
withPasswordFlow(options) {
|
|
1143
|
+
return this.withAuthMiddleware(createAuthMiddlewareForPasswordFlow({
|
|
1144
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1145
|
+
projectKey: options.projectKey || this.projectKey,
|
|
1146
|
+
credentials: {
|
|
1147
|
+
clientId: process.env.myClientId,
|
|
1148
|
+
clientSecret: process.env.myClientSecret,
|
|
1149
|
+
user: {
|
|
1150
|
+
username: options.credentials.user.username || '',
|
|
1151
|
+
password: options.credentials.user.password || ''
|
|
1152
|
+
}
|
|
1153
|
+
},
|
|
1154
|
+
fetch: options.fetch || fetch$1,
|
|
1155
|
+
...options
|
|
1156
|
+
}));
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
withAnonymousSessionFlow(options) {
|
|
1160
|
+
return this.withAuthMiddleware(createAuthMiddlewareForAnonymousSessionFlow({
|
|
1161
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1162
|
+
projectKey: this.projectKey || options.projectKey,
|
|
1163
|
+
credentials: {
|
|
1164
|
+
clientId: options.credentials.clientId || '',
|
|
1165
|
+
clientSecret: options.credentials.clientSecret || '',
|
|
1166
|
+
anonymousId: options.credentials.anonymousId || ''
|
|
1167
|
+
},
|
|
1168
|
+
fetch: options.fetch || fetch$1,
|
|
1169
|
+
...options
|
|
1170
|
+
}));
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
withRefreshTokenFlow(options) {
|
|
1174
|
+
return this.withAuthMiddleware(createAuthMiddlewareForRefreshTokenFlow({
|
|
1175
|
+
host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
|
|
1176
|
+
projectKey: this.projectKey || options.projectKey,
|
|
1177
|
+
credentials: {
|
|
1178
|
+
clientId: options.credentials.clientId || '',
|
|
1179
|
+
clientSecret: options.credentials.clientSecret || ''
|
|
1180
|
+
},
|
|
1181
|
+
fetch: options.fetch || fetch$1,
|
|
1182
|
+
refreshToken: options.refreshToken || '',
|
|
1183
|
+
...options
|
|
1184
|
+
}));
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
withExistingTokenFlow(authorization, options) {
|
|
1188
|
+
return this.withAuthMiddleware(createAuthMiddlewareWithExistingToken(authorization, {
|
|
1189
|
+
force: options.force || true,
|
|
1190
|
+
...options
|
|
1191
|
+
}));
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
withHttpMiddleware(options) {
|
|
1195
|
+
this.httpMiddleware = createHttpMiddleware({
|
|
1196
|
+
host: options.host || 'https://api.europe-west1.gcp.commercetools.com',
|
|
1197
|
+
fetch: options.fetch || fetch$1,
|
|
1198
|
+
...options
|
|
1199
|
+
});
|
|
1200
|
+
return this;
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
withUserAgentMiddleware() {
|
|
1204
|
+
this.userAgentMiddleware = createUserAgentMiddleware();
|
|
1205
|
+
return this;
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
withQueueMiddleware(options) {
|
|
1209
|
+
this.queueMiddleware = createQueueMiddleware({
|
|
1210
|
+
concurrency: options.concurrency || 20,
|
|
1211
|
+
...options
|
|
1212
|
+
});
|
|
1213
|
+
return this;
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
withLoggerMiddleware() {
|
|
1217
|
+
this.loggerMiddleware = createLoggerMiddleware();
|
|
1218
|
+
return this;
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
withCorrelationIdMiddleware(options) {
|
|
1222
|
+
this.correlationIdMiddleware = createCorrelationIdMiddleware({
|
|
1223
|
+
generate: options.generate || null,
|
|
1224
|
+
...options
|
|
1225
|
+
});
|
|
1226
|
+
return this;
|
|
1227
|
+
}
|
|
1572
1228
|
|
|
1573
|
-
|
|
1574
|
-
|
|
1229
|
+
build() {
|
|
1230
|
+
const middlewares = this.middlewares.slice();
|
|
1231
|
+
if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
|
|
1232
|
+
if (this.userAgentMiddleware) middlewares.push(this.userAgentMiddleware);
|
|
1233
|
+
if (this.authMiddleware) middlewares.push(this.authMiddleware);
|
|
1234
|
+
if (this.loggerMiddleware) middlewares.push(this.loggerMiddleware);
|
|
1235
|
+
if (this.queueMiddleware) middlewares.push(this.queueMiddleware);
|
|
1236
|
+
if (this.httpMiddleware) middlewares.push(this.httpMiddleware);
|
|
1237
|
+
return createClient({
|
|
1238
|
+
middlewares
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
}
|
|
1575
1243
|
|
|
1576
|
-
export { ClientBuilder, 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,
|
|
1244
|
+
export { ClientBuilder, 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 };
|