@opengeoweb/api 4.21.0 → 4.22.1

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/index.js ADDED
@@ -0,0 +1,831 @@
1
+ import * as React from 'react';
2
+ import axios from 'axios';
3
+ import { useIsMounted } from '@opengeoweb/shared';
4
+
5
+ function _iterableToArrayLimit(arr, i) {
6
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
7
+ if (null != _i) {
8
+ var _s,
9
+ _e,
10
+ _x,
11
+ _r,
12
+ _arr = [],
13
+ _n = !0,
14
+ _d = !1;
15
+ try {
16
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
17
+ if (Object(_i) !== _i) return;
18
+ _n = !1;
19
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
20
+ } catch (err) {
21
+ _d = !0, _e = err;
22
+ } finally {
23
+ try {
24
+ if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
25
+ } finally {
26
+ if (_d) throw _e;
27
+ }
28
+ }
29
+ return _arr;
30
+ }
31
+ }
32
+ function _regeneratorRuntime() {
33
+ _regeneratorRuntime = function () {
34
+ return exports;
35
+ };
36
+ var exports = {},
37
+ Op = Object.prototype,
38
+ hasOwn = Op.hasOwnProperty,
39
+ defineProperty = Object.defineProperty || function (obj, key, desc) {
40
+ obj[key] = desc.value;
41
+ },
42
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
43
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
44
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
45
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
46
+ function define(obj, key, value) {
47
+ return Object.defineProperty(obj, key, {
48
+ value: value,
49
+ enumerable: !0,
50
+ configurable: !0,
51
+ writable: !0
52
+ }), obj[key];
53
+ }
54
+ try {
55
+ define({}, "");
56
+ } catch (err) {
57
+ define = function (obj, key, value) {
58
+ return obj[key] = value;
59
+ };
60
+ }
61
+ function wrap(innerFn, outerFn, self, tryLocsList) {
62
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
63
+ generator = Object.create(protoGenerator.prototype),
64
+ context = new Context(tryLocsList || []);
65
+ return defineProperty(generator, "_invoke", {
66
+ value: makeInvokeMethod(innerFn, self, context)
67
+ }), generator;
68
+ }
69
+ function tryCatch(fn, obj, arg) {
70
+ try {
71
+ return {
72
+ type: "normal",
73
+ arg: fn.call(obj, arg)
74
+ };
75
+ } catch (err) {
76
+ return {
77
+ type: "throw",
78
+ arg: err
79
+ };
80
+ }
81
+ }
82
+ exports.wrap = wrap;
83
+ var ContinueSentinel = {};
84
+ function Generator() {}
85
+ function GeneratorFunction() {}
86
+ function GeneratorFunctionPrototype() {}
87
+ var IteratorPrototype = {};
88
+ define(IteratorPrototype, iteratorSymbol, function () {
89
+ return this;
90
+ });
91
+ var getProto = Object.getPrototypeOf,
92
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
93
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
94
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
95
+ function defineIteratorMethods(prototype) {
96
+ ["next", "throw", "return"].forEach(function (method) {
97
+ define(prototype, method, function (arg) {
98
+ return this._invoke(method, arg);
99
+ });
100
+ });
101
+ }
102
+ function AsyncIterator(generator, PromiseImpl) {
103
+ function invoke(method, arg, resolve, reject) {
104
+ var record = tryCatch(generator[method], generator, arg);
105
+ if ("throw" !== record.type) {
106
+ var result = record.arg,
107
+ value = result.value;
108
+ return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
109
+ invoke("next", value, resolve, reject);
110
+ }, function (err) {
111
+ invoke("throw", err, resolve, reject);
112
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
113
+ result.value = unwrapped, resolve(result);
114
+ }, function (error) {
115
+ return invoke("throw", error, resolve, reject);
116
+ });
117
+ }
118
+ reject(record.arg);
119
+ }
120
+ var previousPromise;
121
+ defineProperty(this, "_invoke", {
122
+ value: function (method, arg) {
123
+ function callInvokeWithMethodAndArg() {
124
+ return new PromiseImpl(function (resolve, reject) {
125
+ invoke(method, arg, resolve, reject);
126
+ });
127
+ }
128
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
129
+ }
130
+ });
131
+ }
132
+ function makeInvokeMethod(innerFn, self, context) {
133
+ var state = "suspendedStart";
134
+ return function (method, arg) {
135
+ if ("executing" === state) throw new Error("Generator is already running");
136
+ if ("completed" === state) {
137
+ if ("throw" === method) throw arg;
138
+ return doneResult();
139
+ }
140
+ for (context.method = method, context.arg = arg;;) {
141
+ var delegate = context.delegate;
142
+ if (delegate) {
143
+ var delegateResult = maybeInvokeDelegate(delegate, context);
144
+ if (delegateResult) {
145
+ if (delegateResult === ContinueSentinel) continue;
146
+ return delegateResult;
147
+ }
148
+ }
149
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
150
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
151
+ context.dispatchException(context.arg);
152
+ } else "return" === context.method && context.abrupt("return", context.arg);
153
+ state = "executing";
154
+ var record = tryCatch(innerFn, self, context);
155
+ if ("normal" === record.type) {
156
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
157
+ return {
158
+ value: record.arg,
159
+ done: context.done
160
+ };
161
+ }
162
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
163
+ }
164
+ };
165
+ }
166
+ function maybeInvokeDelegate(delegate, context) {
167
+ var methodName = context.method,
168
+ method = delegate.iterator[methodName];
169
+ if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
170
+ var record = tryCatch(method, delegate.iterator, context.arg);
171
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
172
+ var info = record.arg;
173
+ return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
174
+ }
175
+ function pushTryEntry(locs) {
176
+ var entry = {
177
+ tryLoc: locs[0]
178
+ };
179
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
180
+ }
181
+ function resetTryEntry(entry) {
182
+ var record = entry.completion || {};
183
+ record.type = "normal", delete record.arg, entry.completion = record;
184
+ }
185
+ function Context(tryLocsList) {
186
+ this.tryEntries = [{
187
+ tryLoc: "root"
188
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
189
+ }
190
+ function values(iterable) {
191
+ if (iterable) {
192
+ var iteratorMethod = iterable[iteratorSymbol];
193
+ if (iteratorMethod) return iteratorMethod.call(iterable);
194
+ if ("function" == typeof iterable.next) return iterable;
195
+ if (!isNaN(iterable.length)) {
196
+ var i = -1,
197
+ next = function next() {
198
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
199
+ return next.value = undefined, next.done = !0, next;
200
+ };
201
+ return next.next = next;
202
+ }
203
+ }
204
+ return {
205
+ next: doneResult
206
+ };
207
+ }
208
+ function doneResult() {
209
+ return {
210
+ value: undefined,
211
+ done: !0
212
+ };
213
+ }
214
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
215
+ value: GeneratorFunctionPrototype,
216
+ configurable: !0
217
+ }), defineProperty(GeneratorFunctionPrototype, "constructor", {
218
+ value: GeneratorFunction,
219
+ configurable: !0
220
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
221
+ var ctor = "function" == typeof genFun && genFun.constructor;
222
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
223
+ }, exports.mark = function (genFun) {
224
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
225
+ }, exports.awrap = function (arg) {
226
+ return {
227
+ __await: arg
228
+ };
229
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
230
+ return this;
231
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
232
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
233
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
234
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
235
+ return result.done ? result.value : iter.next();
236
+ });
237
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
238
+ return this;
239
+ }), define(Gp, "toString", function () {
240
+ return "[object Generator]";
241
+ }), exports.keys = function (val) {
242
+ var object = Object(val),
243
+ keys = [];
244
+ for (var key in object) keys.push(key);
245
+ return keys.reverse(), function next() {
246
+ for (; keys.length;) {
247
+ var key = keys.pop();
248
+ if (key in object) return next.value = key, next.done = !1, next;
249
+ }
250
+ return next.done = !0, next;
251
+ };
252
+ }, exports.values = values, Context.prototype = {
253
+ constructor: Context,
254
+ reset: function (skipTempReset) {
255
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
256
+ },
257
+ stop: function () {
258
+ this.done = !0;
259
+ var rootRecord = this.tryEntries[0].completion;
260
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
261
+ return this.rval;
262
+ },
263
+ dispatchException: function (exception) {
264
+ if (this.done) throw exception;
265
+ var context = this;
266
+ function handle(loc, caught) {
267
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
268
+ }
269
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
270
+ var entry = this.tryEntries[i],
271
+ record = entry.completion;
272
+ if ("root" === entry.tryLoc) return handle("end");
273
+ if (entry.tryLoc <= this.prev) {
274
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
275
+ hasFinally = hasOwn.call(entry, "finallyLoc");
276
+ if (hasCatch && hasFinally) {
277
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
278
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
279
+ } else if (hasCatch) {
280
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
281
+ } else {
282
+ if (!hasFinally) throw new Error("try statement without catch or finally");
283
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
284
+ }
285
+ }
286
+ }
287
+ },
288
+ abrupt: function (type, arg) {
289
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
290
+ var entry = this.tryEntries[i];
291
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
292
+ var finallyEntry = entry;
293
+ break;
294
+ }
295
+ }
296
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
297
+ var record = finallyEntry ? finallyEntry.completion : {};
298
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
299
+ },
300
+ complete: function (record, afterLoc) {
301
+ if ("throw" === record.type) throw record.arg;
302
+ return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
303
+ },
304
+ finish: function (finallyLoc) {
305
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
306
+ var entry = this.tryEntries[i];
307
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
308
+ }
309
+ },
310
+ catch: function (tryLoc) {
311
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
312
+ var entry = this.tryEntries[i];
313
+ if (entry.tryLoc === tryLoc) {
314
+ var record = entry.completion;
315
+ if ("throw" === record.type) {
316
+ var thrown = record.arg;
317
+ resetTryEntry(entry);
318
+ }
319
+ return thrown;
320
+ }
321
+ }
322
+ throw new Error("illegal catch attempt");
323
+ },
324
+ delegateYield: function (iterable, resultName, nextLoc) {
325
+ return this.delegate = {
326
+ iterator: values(iterable),
327
+ resultName: resultName,
328
+ nextLoc: nextLoc
329
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
330
+ }
331
+ }, exports;
332
+ }
333
+ function _slicedToArray(arr, i) {
334
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
335
+ }
336
+ function _arrayWithHoles(arr) {
337
+ if (Array.isArray(arr)) return arr;
338
+ }
339
+ function _unsupportedIterableToArray(o, minLen) {
340
+ if (!o) return;
341
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
342
+ var n = Object.prototype.toString.call(o).slice(8, -1);
343
+ if (n === "Object" && o.constructor) n = o.constructor.name;
344
+ if (n === "Map" || n === "Set") return Array.from(o);
345
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
346
+ }
347
+ function _arrayLikeToArray(arr, len) {
348
+ if (len == null || len > arr.length) len = arr.length;
349
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
350
+ return arr2;
351
+ }
352
+ function _nonIterableRest() {
353
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
354
+ }
355
+
356
+ /*
357
+ Accepts a value and timeout and will debounce
358
+
359
+ @param {string} value: value of element
360
+ @param {timeout} number: timer
361
+ @return {value: string}
362
+
363
+ @example:
364
+ const debouncedName = useDebounce('testing', 2000)
365
+ */
366
+ var useDebounce = function useDebounce(value, timeout) {
367
+ var _React$useState = React.useState(value),
368
+ _React$useState2 = _slicedToArray(_React$useState, 2),
369
+ state = _React$useState2[0],
370
+ setState = _React$useState2[1];
371
+ React.useEffect(function () {
372
+ var handler = setTimeout(function () {
373
+ return setState(value);
374
+ }, timeout);
375
+ return function () {
376
+ return clearTimeout(handler);
377
+ };
378
+ }, [value, timeout]);
379
+ return state;
380
+ };
381
+
382
+ /******************************************************************************
383
+ Copyright (c) Microsoft Corporation.
384
+
385
+ Permission to use, copy, modify, and/or distribute this software for any
386
+ purpose with or without fee is hereby granted.
387
+
388
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
389
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
390
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
391
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
392
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
393
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
394
+ PERFORMANCE OF THIS SOFTWARE.
395
+ ***************************************************************************** */
396
+
397
+ function __rest(s, e) {
398
+ var t = {};
399
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
400
+ t[p] = s[p];
401
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
402
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
403
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
404
+ t[p[i]] = s[p[i]];
405
+ }
406
+ return t;
407
+ }
408
+
409
+ function __awaiter(thisArg, _arguments, P, generator) {
410
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
411
+ return new (P || (P = Promise))(function (resolve, reject) {
412
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
413
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
414
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
415
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
416
+ });
417
+ }
418
+
419
+ var generateRandomId = function generateRandomId() {
420
+ return "-".concat(Math.random().toString(36).substr(2, 9));
421
+ };
422
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
423
+ var useApi = function useApi(apiCall) {
424
+ var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
425
+ var _useIsMounted = useIsMounted(),
426
+ isMounted = _useIsMounted.isMounted;
427
+ var _React$useState = React.useState(generateRandomId()),
428
+ _React$useState2 = _slicedToArray(_React$useState, 1),
429
+ id = _React$useState2[0];
430
+ var _React$useState3 = React.useState(true),
431
+ _React$useState4 = _slicedToArray(_React$useState3, 2),
432
+ isLoading = _React$useState4[0],
433
+ setIsloading = _React$useState4[1];
434
+ var _React$useState5 = React.useState(null),
435
+ _React$useState6 = _slicedToArray(_React$useState5, 2),
436
+ error = _React$useState6[0],
437
+ setError = _React$useState6[1];
438
+ var _React$useState7 = React.useState(null),
439
+ _React$useState8 = _slicedToArray(_React$useState7, 2),
440
+ result = _React$useState8[0],
441
+ setResult = _React$useState8[1];
442
+ var debouncedParams = useDebounce(JSON.stringify(params), 300);
443
+ var fetchApiData = function fetchApiData() {
444
+ var _params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
445
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
446
+ var response;
447
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
448
+ while (1) switch (_context.prev = _context.next) {
449
+ case 0:
450
+ _context.prev = 0;
451
+ setIsloading(true);
452
+ setError(null);
453
+ _context.next = 5;
454
+ return apiCall(_params, id);
455
+ case 5:
456
+ response = _context.sent;
457
+ if (isMounted.current) {
458
+ setResult(Array.isArray(response) ? response.map(function (d) {
459
+ return d.data;
460
+ }) : response.data);
461
+ setIsloading(false);
462
+ setError(null);
463
+ }
464
+ _context.next = 12;
465
+ break;
466
+ case 9:
467
+ _context.prev = 9;
468
+ _context.t0 = _context["catch"](0);
469
+ if (isMounted.current) {
470
+ if (axios.isCancel(_context.t0)) {
471
+ setIsloading(false);
472
+ } else {
473
+ setError(_context.t0);
474
+ setIsloading(false);
475
+ }
476
+ }
477
+ case 12:
478
+ case "end":
479
+ return _context.stop();
480
+ }
481
+ }, _callee, null, [[0, 9]]);
482
+ }));
483
+ };
484
+ React.useEffect(function () {
485
+ fetchApiData(params);
486
+ },
487
+ // eslint-disable-next-line react-hooks/exhaustive-deps
488
+ [debouncedParams]);
489
+ var clearResults = function clearResults() {
490
+ setIsloading(true);
491
+ setResult(null);
492
+ };
493
+ return {
494
+ isLoading: isLoading,
495
+ error: error,
496
+ result: result,
497
+ clearResults: clearResults,
498
+ fetchApiData: fetchApiData
499
+ };
500
+ };
501
+
502
+ var ApiContext = /*#__PURE__*/React.createContext({
503
+ api: null
504
+ });
505
+ var registeredApis = new Map();
506
+ function registerApi(name, api) {
507
+ registeredApis.set(name, api);
508
+ }
509
+ function getApi(name) {
510
+ return registeredApis.get(name);
511
+ }
512
+ var ApiProvider = function ApiProvider(_a) {
513
+ var children = _a.children,
514
+ createApi = _a.createApi,
515
+ name = _a.name,
516
+ apiModuleProps = __rest(_a, ["children", "createApi", "name"]);
517
+ var handleNewApi = React.useCallback(function () {
518
+ var newApi = createApi(apiModuleProps);
519
+ if (name) {
520
+ registerApi(name, newApi);
521
+ }
522
+ return newApi;
523
+ // eslint-disable-next-line react-hooks/exhaustive-deps
524
+ }, [createApi, name]);
525
+ var _React$useState = React.useState(handleNewApi),
526
+ _React$useState2 = _slicedToArray(_React$useState, 2),
527
+ api = _React$useState2[0],
528
+ setApi = _React$useState2[1];
529
+ React.useEffect(function () {
530
+ setApi(handleNewApi);
531
+ return function () {
532
+ };
533
+ }, [handleNewApi, name]);
534
+ return /*#__PURE__*/React.createElement(ApiContext.Provider, {
535
+ value: {
536
+ api: api
537
+ }
538
+ }, children);
539
+ };
540
+ function useApiContext() {
541
+ return React.useContext(ApiContext);
542
+ }
543
+
544
+ var DEFAULT_TIMEOUT = 15000;
545
+ var KEEP_ALIVE_IN_SECONDS = 60; // Number of seconds in between intervals to check with the token request if connection is stil intact
546
+ var KEEP_ALIVE_POLLER_IN_SECONDS = 10; // Number of milliseconds to check if connection is restored or to check if KEEP_ALIVE_IN_SECONDS has passed
547
+ var REFRESH_TOKEN_WHEN_PCT_EXPIRED = 75; // Refresh token when 75% expired. Set to (10 / 3600) * 100 = 0.2777778% to test with 10 second interval.
548
+ var DEFAULT_TOKEN_EXPIRES_IN = 3600; // Number of seconds a token expires by default
549
+ var MILLISECOND_TO_SECOND = 1 / 1000;
550
+ /**
551
+ * Creates a Credentials object based on the axios response from the token service.
552
+ *
553
+ * It will calculate the expires_at attribute based on the expires_in property found in the JWT.
554
+ *
555
+ * @param tokenResponse Response of the tokenservice as axios response object.
556
+ * @returns Credentials object.
557
+ */
558
+ var makeCredentialsFromTokenResponse = function makeCredentialsFromTokenResponse(tokenResponse) {
559
+ var token = tokenResponse.data.body || tokenResponse.data;
560
+ // eslint-disable-next-line @typescript-eslint/naming-convention
561
+ var access_token = token.access_token,
562
+ refresh_token = token.refresh_token,
563
+ id_token = token.id_token,
564
+ expires_in = token.expires_in;
565
+ if (!access_token || !id_token) {
566
+ throw new Error('Login failed');
567
+ }
568
+ var userInfoString = atob(
569
+ // convert base64url specific characters before parsing as base64
570
+ id_token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'));
571
+ var userInfo = JSON.parse(userInfoString);
572
+ var tokenExpirationInSeconds = expires_in && expires_in > 0 ? expires_in : DEFAULT_TOKEN_EXPIRES_IN; // If not set or zero in the token, assume valid for 1 hour.
573
+ var pctTokenExpirationInSeconds = tokenExpirationInSeconds * (REFRESH_TOKEN_WHEN_PCT_EXPIRED / 100);
574
+ var epochTimeTokenExpirationInSeconds = pctTokenExpirationInSeconds + getCurrentTimeInSeconds();
575
+ var isAuthCognito = userInfo.iss.includes('cognito');
576
+ var newAuth = {
577
+ username: isAuthCognito ? userInfo['cognito:username'] : userInfo.email,
578
+ token: access_token,
579
+ refresh_token: refresh_token || '',
580
+ expires_at: epochTimeTokenExpirationInSeconds,
581
+ keep_session_alive_at: getCurrentTimeInSeconds() + KEEP_ALIVE_IN_SECONDS,
582
+ has_connection_issue: false
583
+ };
584
+ return newAuth;
585
+ };
586
+ var refreshAccessToken = function refreshAccessToken(_ref) {
587
+ var auth = _ref.auth,
588
+ _ref$config = _ref.config,
589
+ _ref$config2 = _ref$config === void 0 ? {} : _ref$config,
590
+ authTokenURL = _ref$config2.authTokenURL,
591
+ authClientId = _ref$config2.authClientId,
592
+ appURL = _ref$config2.appURL,
593
+ _ref$timeout = _ref.timeout,
594
+ timeout = _ref$timeout === void 0 ? DEFAULT_TIMEOUT : _ref$timeout;
595
+ // Refresh token request with a new axios instance
596
+ // without request interceptor
597
+ var tokenAxiosInstance = axios.create({
598
+ headers: {},
599
+ timeout: timeout
600
+ });
601
+ var refreshPayload = {
602
+ refresh_token: auth.refresh_token,
603
+ redirect_uri: "".concat(appURL, "/code"),
604
+ grant_type: 'refresh_token',
605
+ client_id: authClientId
606
+ };
607
+ /* Send data in the "application/x-www-form-urlencoded" format.
608
+ If only JSON is supported, use Axios' default content type ("application/x-www-form-urlencoded"). */
609
+ var useDefaultContentType = authTokenURL.includes('amazonaws.com');
610
+ var data = useDefaultContentType ? refreshPayload : new URLSearchParams(refreshPayload);
611
+ var axiosConfig = {
612
+ headers: {
613
+ 'Content-Type': useDefaultContentType ? 'application/json' : 'application/x-www-form-urlencoded'
614
+ }
615
+ };
616
+ return tokenAxiosInstance.post(authTokenURL, data, axiosConfig);
617
+ };
618
+ var refreshAccessTokenAndSetAuthContext = function refreshAccessTokenAndSetAuthContext(_ref2) {
619
+ var auth = _ref2.auth,
620
+ onSetAuth = _ref2.onSetAuth,
621
+ config = _ref2.config,
622
+ _ref2$timeout = _ref2.timeout,
623
+ timeout = _ref2$timeout === void 0 ? DEFAULT_TIMEOUT : _ref2$timeout;
624
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
625
+ var refreshedToken, newAuth;
626
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
627
+ while (1) switch (_context.prev = _context.next) {
628
+ case 0:
629
+ _context.prev = 0;
630
+ _context.next = 3;
631
+ return refreshAccessToken({
632
+ auth: auth,
633
+ config: config,
634
+ timeout: timeout
635
+ });
636
+ case 3:
637
+ refreshedToken = _context.sent;
638
+ newAuth = makeCredentialsFromTokenResponse(refreshedToken); // Cognito does not send a new refresh token, but gitlab does. Set it here into the auth context.
639
+ if (!newAuth.refresh_token || newAuth.refresh_token.length === 0) {
640
+ newAuth.refresh_token = auth.refresh_token;
641
+ }
642
+ onSetAuth(newAuth);
643
+ _context.next = 12;
644
+ break;
645
+ case 9:
646
+ _context.prev = 9;
647
+ _context.t0 = _context["catch"](0);
648
+ onSetAuth(Object.assign(Object.assign({}, auth), {
649
+ has_connection_issue: true
650
+ }));
651
+ case 12:
652
+ case "end":
653
+ return _context.stop();
654
+ }
655
+ }, _callee, null, [[0, 9]]);
656
+ }));
657
+ };
658
+ var createApiInstance = function createApiInstance(_ref3) {
659
+ var auth = _ref3.auth,
660
+ onSetAuth = _ref3.onSetAuth,
661
+ _ref3$config = _ref3.config,
662
+ _ref3$config2 = _ref3$config === void 0 ? {} : _ref3$config,
663
+ baseURL = _ref3$config2.baseURL,
664
+ authTokenURL = _ref3$config2.authTokenURL,
665
+ authClientId = _ref3$config2.authClientId,
666
+ appURL = _ref3$config2.appURL,
667
+ _ref3$timeout = _ref3.timeout,
668
+ timeout = _ref3$timeout === void 0 ? DEFAULT_TIMEOUT : _ref3$timeout;
669
+ var axiosInstance = axios.create({
670
+ baseURL: baseURL,
671
+ headers: {},
672
+ timeout: timeout
673
+ });
674
+ // Request interceptor for API calls done BEFORE the request is made.
675
+ axiosInstance.interceptors.request.use(function (axiosConfig) {
676
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
677
+ var timeInSecondsLeftBeforeExpiration, newConfig;
678
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
679
+ while (1) switch (_context2.prev = _context2.next) {
680
+ case 0:
681
+ timeInSecondsLeftBeforeExpiration = auth && auth.expires_at ? auth.expires_at - getCurrentTimeInSeconds() : 0; // If expires_at is not set, don't do anything. (set timeInSecondsLeftBeforeExpiration = 0 will skip refresh)
682
+ if (!(timeInSecondsLeftBeforeExpiration < 0)) {
683
+ _context2.next = 4;
684
+ break;
685
+ }
686
+ _context2.next = 4;
687
+ return refreshAccessTokenAndSetAuthContext({
688
+ auth: auth,
689
+ onSetAuth: onSetAuth,
690
+ config: {
691
+ baseURL: baseURL,
692
+ authTokenURL: authTokenURL,
693
+ authClientId: authClientId,
694
+ appURL: appURL
695
+ },
696
+ timeout: timeout
697
+ });
698
+ case 4:
699
+ newConfig = Object.assign(Object.assign({}, axiosConfig), {
700
+ headers: Object.assign({
701
+ 'Content-Type': 'application/json',
702
+ Authorization: "Bearer ".concat(auth.token),
703
+ Accept: 'application/json'
704
+ }, axiosConfig.headers)
705
+ });
706
+ return _context2.abrupt("return", newConfig);
707
+ case 6:
708
+ case "end":
709
+ return _context2.stop();
710
+ }
711
+ }, _callee2);
712
+ }));
713
+ }, function (error) {
714
+ Promise.reject(error);
715
+ });
716
+ // Response interceptor for API calls done AFTER the request is made.
717
+ axiosInstance.interceptors.response.use(function (response) {
718
+ return response;
719
+ }, function (error) {
720
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
721
+ var originalRequest;
722
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
723
+ while (1) switch (_context3.prev = _context3.next) {
724
+ case 0:
725
+ originalRequest = error.config;
726
+ if (!(error.response && error.response.status && (error.response.status === 401 || error.response.status === 403) && !originalRequest.inRetry)) {
727
+ _context3.next = 6;
728
+ break;
729
+ }
730
+ originalRequest.inRetry = true;
731
+ _context3.next = 5;
732
+ return refreshAccessTokenAndSetAuthContext({
733
+ auth: auth,
734
+ onSetAuth: onSetAuth,
735
+ config: {
736
+ baseURL: baseURL,
737
+ authTokenURL: authTokenURL,
738
+ authClientId: authClientId,
739
+ appURL: appURL
740
+ },
741
+ timeout: timeout
742
+ });
743
+ case 5:
744
+ return _context3.abrupt("return", axiosInstance(originalRequest));
745
+ case 6:
746
+ return _context3.abrupt("return", Promise.reject(error));
747
+ case 7:
748
+ case "end":
749
+ return _context3.stop();
750
+ }
751
+ }, _callee3);
752
+ }));
753
+ });
754
+ return axiosInstance;
755
+ };
756
+ var createNonAuthApiInstance = function createNonAuthApiInstance(_ref4) {
757
+ var _ref4$config = _ref4.config,
758
+ _ref4$config2 = _ref4$config === void 0 ? {} : _ref4$config,
759
+ baseURL = _ref4$config2.baseURL,
760
+ _ref4$timeout = _ref4.timeout,
761
+ timeout = _ref4$timeout === void 0 ? DEFAULT_TIMEOUT : _ref4$timeout;
762
+ var axiosInstance = axios.create({
763
+ baseURL: baseURL,
764
+ headers: {},
765
+ timeout: timeout
766
+ });
767
+ // Request interceptor for API calls
768
+ axiosInstance.interceptors.request.use(function (config) {
769
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
770
+ var newConfig;
771
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
772
+ while (1) switch (_context4.prev = _context4.next) {
773
+ case 0:
774
+ newConfig = Object.assign(Object.assign({}, config), {
775
+ headers: Object.assign({
776
+ 'Content-Type': 'application/json',
777
+ Accept: 'application/json'
778
+ }, config.headers)
779
+ });
780
+ return _context4.abrupt("return", newConfig);
781
+ case 2:
782
+ case "end":
783
+ return _context4.stop();
784
+ }
785
+ }, _callee4);
786
+ }));
787
+ }, function (error) {
788
+ Promise.reject(error);
789
+ });
790
+ return axiosInstance;
791
+ };
792
+ var fakeApiRequest = function fakeApiRequest(signal) {
793
+ return new Promise(function (resolve, reject) {
794
+ var timer = setTimeout(function () {
795
+ resolve();
796
+ }, 300);
797
+ signal === null || signal === void 0 ? void 0 : signal.signal.addEventListener('abort', function () {
798
+ clearTimeout(timer);
799
+ reject(new Error('canceled'));
800
+ });
801
+ });
802
+ };
803
+ var createFakeApiInstance = function createFakeApiInstance() {
804
+ return {
805
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars,
806
+ get: function get(_url, _params) {
807
+ return fakeApiRequest();
808
+ },
809
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars,
810
+ put: function put(_url, _params) {
811
+ return fakeApiRequest();
812
+ },
813
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars,
814
+ post: function post(_url, _params) {
815
+ return fakeApiRequest();
816
+ },
817
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
818
+ "delete": function _delete(_url, _params) {
819
+ return fakeApiRequest();
820
+ },
821
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars, @typescript-eslint/explicit-module-boundary-types
822
+ patch: function patch(_url, _params, _signal) {
823
+ return fakeApiRequest(_signal);
824
+ }
825
+ };
826
+ };
827
+ var getCurrentTimeInSeconds = function getCurrentTimeInSeconds() {
828
+ return Date.now() * MILLISECOND_TO_SECOND;
829
+ };
830
+
831
+ export { ApiProvider, KEEP_ALIVE_IN_SECONDS, KEEP_ALIVE_POLLER_IN_SECONDS, MILLISECOND_TO_SECOND, REFRESH_TOKEN_WHEN_PCT_EXPIRED, createApiInstance, createFakeApiInstance, createNonAuthApiInstance, fakeApiRequest, getApi, getCurrentTimeInSeconds, makeCredentialsFromTokenResponse, refreshAccessToken, refreshAccessTokenAndSetAuthContext, useApi, useApiContext, useDebounce };