@nextgis/geocoder 1.16.8 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,722 +1,508 @@
1
- /** Bundle of @nextgis/geocoder; version: 1.16.8; author: NextGIS */
2
- /******************************************************************************
3
- Copyright (c) Microsoft Corporation.
4
-
5
- Permission to use, copy, modify, and/or distribute this software for any
6
- purpose with or without fee is hereby granted.
7
-
8
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
9
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
11
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
- PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */
16
- /* global Reflect, Promise */
17
-
18
- var extendStatics = function(d, b) {
19
- extendStatics = Object.setPrototypeOf ||
20
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
21
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
22
- return extendStatics(d, b);
23
- };
24
-
25
- function __extends(d, b) {
26
- if (typeof b !== "function" && b !== null)
27
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
28
- extendStatics(d, b);
29
- function __() { this.constructor = d; }
30
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
31
- }
32
-
33
- var __assign = function() {
34
- __assign = Object.assign || function __assign(t) {
35
- for (var s, i = 1, n = arguments.length; i < n; i++) {
36
- s = arguments[i];
37
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
38
- }
39
- return t;
40
- };
41
- return __assign.apply(this, arguments);
42
- };
43
-
44
- function __awaiter(thisArg, _arguments, P, generator) {
45
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
46
- return new (P || (P = Promise))(function (resolve, reject) {
47
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
48
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
49
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
50
- step((generator = generator.apply(thisArg, _arguments || [])).next());
51
- });
52
- }
53
-
54
- function __generator(thisArg, body) {
55
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
56
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
57
- function verb(n) { return function (v) { return step([n, v]); }; }
58
- function step(op) {
59
- if (f) throw new TypeError("Generator is already executing.");
60
- while (_) try {
61
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
62
- if (y = 0, t) op = [op[0] & 2, t.value];
63
- switch (op[0]) {
64
- case 0: case 1: t = op; break;
65
- case 4: _.label++; return { value: op[1], done: false };
66
- case 5: _.label++; y = op[1]; op = [0]; continue;
67
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
68
- default:
69
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
70
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
71
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
72
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
73
- if (t[2]) _.ops.pop();
74
- _.trys.pop(); continue;
75
- }
76
- op = body.call(thisArg, _);
77
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
78
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
79
- }
80
- }
81
-
82
- function __values(o) {
83
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
84
- if (m) return m.call(o);
85
- if (o && typeof o.length === "number") return {
86
- next: function () {
87
- if (o && i >= o.length) o = void 0;
88
- return { value: o && o[i++], done: !o };
89
- }
90
- };
91
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
92
- }
93
-
94
- function __spreadArray(to, from, pack) {
95
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
96
- if (ar || !(i in from)) {
97
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
98
- ar[i] = from[i];
99
- }
100
- }
101
- return to.concat(ar || Array.prototype.slice.call(from));
102
- }
103
-
104
- function __await(v) {
105
- return this instanceof __await ? (this.v = v, this) : new __await(v);
106
- }
107
-
108
- function __asyncGenerator(thisArg, _arguments, generator) {
109
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
110
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
111
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
112
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
113
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
114
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
115
- function fulfill(value) { resume("next", value); }
116
- function reject(value) { resume("throw", value); }
117
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
118
- }
119
-
120
- function __asyncValues(o) {
121
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
122
- var m = o[Symbol.asyncIterator], i;
123
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
124
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
125
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
1
+ /** Bundle of @nextgis/geocoder; version: 1.17.0; author: NextGIS */
2
+ class CancelError extends Error {
3
+ constructor() {
4
+ super();
5
+ this.name = 'CancelError';
6
+ Object.setPrototypeOf(this, CancelError.prototype);
7
+ }
126
8
  }
127
9
 
128
- var CancelError = /** @class */ (function (_super) {
129
- __extends(CancelError, _super);
130
- function CancelError() {
131
- var _this = _super.call(this) || this;
132
- _this.name = 'CancelError';
133
- Object.setPrototypeOf(_this, CancelError.prototype);
134
- return _this;
135
- }
136
- return CancelError;
137
- }(Error));
138
-
139
- var PromiseControl = /** @class */ (function () {
140
- function PromiseControl(options) {
141
- if (options === void 0) { options = {}; }
142
- this.options = options;
143
- this._promises = new Map();
144
- }
145
- Object.defineProperty(PromiseControl.prototype, "isLoaded", {
146
- get: function () {
147
- return this._promises.size > 0;
148
- },
149
- enumerable: false,
150
- configurable: true
151
- });
152
- PromiseControl.prototype.remove = function (promise) {
153
- if (this._promises.has(promise)) {
154
- this._promises.delete(promise);
155
- this._onStop();
156
- }
157
- };
158
- PromiseControl.prototype.get = function (promise) {
159
- return this._promises.get(promise);
160
- };
161
- PromiseControl.prototype.add = function (promise, name) {
162
- var _this = this;
163
- var key = name ? name : promise;
164
- var exist = this._promises.get(key);
165
- if (this.options.onStart && !this.isLoaded) {
166
- this.options.onStart();
167
- }
168
- if (exist) {
169
- return exist;
170
- }
171
- this._promises.set(key, promise);
172
- promise.finally(function () {
173
- _this.remove(key);
174
- });
175
- return promise;
176
- };
177
- PromiseControl.prototype.abort = function () {
178
- if (this.isLoaded) {
179
- this._promises.forEach(function (x) {
180
- if (x.cancel) {
181
- x.cancel();
182
- }
183
- });
184
- this._promises.clear();
185
- this._onStop();
186
- }
187
- };
188
- PromiseControl.prototype.waitFunc = function (func, name) {
189
- if (name === void 0) { name = ''; }
190
- name = name || func.name;
191
- var exist = this.get(name);
192
- if (exist) {
193
- return exist;
194
- }
195
- return this.add(func(), name);
196
- };
197
- PromiseControl.prototype.WaitForMe = function (name) {
198
- if (name === void 0) { name = ''; }
199
- var get = this.get.bind(this);
200
- var add = this.add.bind(this);
201
- return function (target, key, descriptor) {
202
- var originalMethod = descriptor.value;
203
- name = name || key;
204
- descriptor.value = function () {
205
- var args = [];
206
- for (var _i = 0; _i < arguments.length; _i++) {
207
- args[_i] = arguments[_i];
208
- }
209
- var exist = get(name);
210
- if (exist) {
211
- return exist;
212
- }
213
- var result = add(originalMethod.apply(this, args), name);
214
- return result;
215
- };
216
- return descriptor;
217
- };
218
- };
219
- /** @deprecated use {@link PromiseControl.WaitForMe } instead */
220
- PromiseControl.prototype.GetOrCreateDecorator = function (name) {
221
- if (name === void 0) { name = ''; }
222
- return this.WaitForMe(name);
223
- };
224
- PromiseControl.prototype._onStop = function () {
225
- if (this.options.onStop && !this.isLoaded) {
226
- this.options.onStop();
227
- }
228
- };
229
- return PromiseControl;
230
- }());
231
-
232
- var TimeoutError = /** @class */ (function (_super) {
233
- __extends(TimeoutError, _super);
234
- function TimeoutError() {
235
- var _this = _super.call(this) || this;
236
- _this.name = 'TimeoutError';
237
- Object.setPrototypeOf(_this, TimeoutError.prototype);
238
- return _this;
239
- }
240
- return TimeoutError;
241
- }(Error));
242
-
243
- var handleCallback = function (resolve, reject, callback, r) {
244
- try {
245
- resolve(callback(r));
246
- }
247
- catch (e) {
248
- reject(e);
249
- }
250
- };
251
- var ID$2 = 0;
252
- /**
253
- * Promise that can be canceled
254
- *
255
- * @example
256
- * Catch `CancelError`
257
- * ```javascript
258
- * import CancelablePromise from "@nextgis/cancelable-promise";
259
- *
260
- * const promise = new CancelablePromise((resolve, reject) => {
261
- * setTimeout(() => resolve(), 100);
262
- * }).catch((er) => {
263
- * if (er.name === "CancelError") {
264
- * // handle cancel error
265
- * }
266
- * throw er;
267
- * });
268
- *
269
- * promise.cancel();
270
- * ```
271
- * @example
272
- * Handle `onCancel` callback
273
- * ```javascript
274
- * import CancelablePromise from "@nextgis/cancelable-promise";
275
- *
276
- * const promise = new CancelablePromise((resolve, reject, onCancel) => {
277
- * const xhr = new XMLHttpRequest();
278
- * xhr.open("GET", url, true);
279
- * xhr.onload = () => {
280
- * resolve(xhr.responseText);
281
- * };
282
- * xhr.onerror = (er) => {
283
- * reject(er);
284
- * };
285
- *
286
- * onCancel(() => {
287
- * xhr.abort();
288
- * });
289
- *
290
- * xhr.send();
291
- * });
292
- *
293
- * promise.cancel();
294
- * ```
295
- */
296
- var CancelablePromise$1 = /** @class */ (function () {
297
- function CancelablePromise(executor, timeout) {
298
- var _this = this;
299
- this.id = ID$2++;
300
- this._isCanceled = false;
301
- this._isPending = true;
302
- this._cancelHandlers = [];
303
- this._children = [];
304
- this._cancelPromise = new Promise(function (resolve_, reject_) {
305
- _this._setCanceledCallback = function (er) { return resolve_(er || new CancelError()); };
306
- });
307
- var promises = [
308
- this._cancelPromise,
309
- new Promise(function (resolve, reject) {
310
- var onResolve = function (value) {
311
- if (value instanceof CancelablePromise) {
312
- _this.attach(value);
313
- }
314
- else {
315
- _this._isPending = false;
316
- }
317
- // TODO: fix types, `undefined` not allowed since 19.12.2020
318
- resolve(value);
319
- };
320
- var onReject = function (error) {
321
- _this._isPending = false;
322
- reject(error);
323
- };
324
- var onCancel = function (handler) {
325
- if (!_this._isPending) {
326
- throw new Error('The `onCancel` handler was attached after the promise settled.');
327
- }
328
- _this._cancelHandlers.push(handler);
329
- };
330
- return executor(onResolve, onReject, onCancel);
331
- }),
332
- ];
333
- if (timeout) {
334
- promises.push(new Promise(function (resolve, reject) {
335
- setTimeout(function () {
336
- if (_this._isPending) {
337
- try {
338
- _this.cancel();
339
- }
340
- finally {
341
- reject(new TimeoutError());
342
- }
343
- }
344
- }, timeout);
345
- }));
346
- }
347
- this._promise = Promise.race(promises);
348
- }
349
- CancelablePromise.createControl = function (opt) {
350
- return new PromiseControl(opt);
351
- };
352
- CancelablePromise.resolve = function (value) {
353
- return new CancelablePromise(function (resolve) { return resolve(value); });
354
- };
355
- CancelablePromise.reject = function (value) {
356
- return new CancelablePromise(function (resolve, reject) { return reject(value); });
357
- };
358
- CancelablePromise.all = function (values) {
359
- var _this = this;
360
- return new CancelablePromise(function (resolve, reject) {
361
- Promise.all(values).then(resolve).catch(reject);
362
- }).catch(function (er) {
363
- if (er instanceof _this.CancelError) {
364
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
365
- var v = values_1[_i];
366
- var v_ = v;
367
- if ('cancel' in v_) {
368
- v_.cancel();
369
- }
370
- }
371
- }
372
- throw er;
373
- });
374
- };
375
- CancelablePromise.prototype.attach = function (p) {
376
- if (this._isCanceled) {
377
- p.cancel();
378
- }
379
- else {
380
- this._children.push(p);
381
- }
382
- };
383
- CancelablePromise.prototype.then = function (onfulfilled, onrejected) {
384
- var _this = this;
385
- var p = new CancelablePromise(function (resolve, reject) {
386
- if (_this._promise) {
387
- var reject_1 = function (r) {
388
- if (onrejected) {
389
- handleCallback(resolve, reject, onrejected, r);
390
- }
391
- else {
392
- reject(r);
393
- }
394
- };
395
- _this._promise.then(function (r) {
396
- if (_this._isCanceled) {
397
- reject_1(r);
398
- }
399
- else {
400
- if (onfulfilled) {
401
- handleCallback(resolve, reject, onfulfilled, r);
402
- }
403
- else {
404
- resolve(r);
405
- }
406
- }
407
- }, reject_1);
408
- }
409
- });
410
- p._parentPromise = this;
411
- this._children.push(p);
412
- return p;
413
- };
414
- CancelablePromise.prototype.catch = function (onrejected) {
415
- if (this._isCanceled && onrejected) {
416
- onrejected(new CancelError());
417
- }
418
- return this.then(undefined, onrejected);
419
- };
420
- CancelablePromise.prototype.finally = function (onfinally) {
421
- if (this._promise) {
422
- return this._promise.finally(onfinally);
423
- }
424
- if (this._isCanceled) {
425
- return Promise.reject(new CancelError());
426
- }
427
- return Promise.reject(onfinally);
428
- };
429
- CancelablePromise.prototype.cancel = function () {
430
- // No reason to run cancel action if promise is already complete
431
- if (this._isCanceled || !this._isPending) {
432
- return this;
433
- }
434
- this._isCanceled = true;
435
- var parent = this._getTopParent();
436
- if (parent) {
437
- parent.cancel();
438
- }
439
- if (this._children) {
440
- this._children.forEach(function (x) { return x.cancel(); });
441
- }
442
- if (this._isPending) {
443
- if (this._cancelHandlers.length) {
444
- try {
445
- for (var _i = 0, _a = this._cancelHandlers; _i < _a.length; _i++) {
446
- var handler = _a[_i];
447
- handler();
448
- }
449
- }
450
- catch (error) {
451
- // this._setCanceledCallback(error);
452
- }
453
- }
454
- if (this._setCanceledCallback) {
455
- this._setCanceledCallback();
456
- }
457
- }
458
- this._destroy();
459
- return this;
460
- };
461
- CancelablePromise.prototype._getTopParent = function () {
462
- var parent = this._parentPromise;
463
- var hasParent = !!parent;
464
- while (hasParent) {
465
- if (parent && parent._parentPromise) {
466
- parent = parent._parentPromise;
467
- hasParent = !!parent;
468
- }
469
- else {
470
- hasParent = false;
471
- }
472
- }
473
- return parent;
474
- };
475
- CancelablePromise.prototype._destroy = function () {
476
- this._setCanceledCallback = undefined;
477
- this._cancelPromise = undefined;
478
- this._promise = undefined;
479
- };
480
- CancelablePromise.CancelError = CancelError;
481
- CancelablePromise.TimeoutError = TimeoutError;
482
- CancelablePromise.PromiseControl = PromiseControl;
483
- return CancelablePromise;
484
- }());
10
+ class PromiseControl {
11
+ constructor(options = {}) {
12
+ this.options = options;
13
+ this._promises = new Map();
14
+ }
15
+ get isLoaded() {
16
+ return this._promises.size > 0;
17
+ }
18
+ remove(promise) {
19
+ if (this._promises.has(promise)) {
20
+ this._promises.delete(promise);
21
+ this._onStop();
22
+ }
23
+ }
24
+ get(promise) {
25
+ return this._promises.get(promise);
26
+ }
27
+ add(promise, name) {
28
+ const key = name ? name : promise;
29
+ const exist = this._promises.get(key);
30
+ if (this.options.onStart && !this.isLoaded) {
31
+ this.options.onStart();
32
+ }
33
+ if (exist) {
34
+ return exist;
35
+ }
36
+ this._promises.set(key, promise);
37
+ promise.finally(() => {
38
+ this.remove(key);
39
+ });
40
+ return promise;
41
+ }
42
+ abort() {
43
+ if (this.isLoaded) {
44
+ this._promises.forEach((x) => {
45
+ if (x.cancel) {
46
+ x.cancel();
47
+ }
48
+ });
49
+ this._promises.clear();
50
+ this._onStop();
51
+ }
52
+ }
53
+ waitFunc(func, name = '') {
54
+ name = name || func.name;
55
+ const exist = this.get(name);
56
+ if (exist) {
57
+ return exist;
58
+ }
59
+ return this.add(func(), name);
60
+ }
61
+ WaitForMe(name = '') {
62
+ const get = this.get.bind(this);
63
+ const add = this.add.bind(this);
64
+ return function (target, key, descriptor) {
65
+ const originalMethod = descriptor.value;
66
+ name = name || key;
67
+ descriptor.value = function (...args) {
68
+ const exist = get(name);
69
+ if (exist) {
70
+ return exist;
71
+ }
72
+ const result = add(originalMethod.apply(this, args), name);
73
+ return result;
74
+ };
75
+ return descriptor;
76
+ };
77
+ }
78
+ /** @deprecated use {@link PromiseControl.WaitForMe } instead */
79
+ GetOrCreateDecorator(name = '') {
80
+ return this.WaitForMe(name);
81
+ }
82
+ _onStop() {
83
+ if (this.options.onStop && !this.isLoaded) {
84
+ this.options.onStop();
85
+ }
86
+ }
87
+ }
88
+
89
+ class TimeoutError extends Error {
90
+ constructor() {
91
+ super();
92
+ this.name = 'TimeoutError';
93
+ Object.setPrototypeOf(this, TimeoutError.prototype);
94
+ }
95
+ }
96
+
97
+ const handleCallback = (resolve, reject, callback, r) => {
98
+ try {
99
+ resolve(callback(r));
100
+ }
101
+ catch (e) {
102
+ reject(e);
103
+ }
104
+ };
105
+ let ID$2 = 0;
106
+ /**
107
+ * Promise that can be canceled
108
+ *
109
+ * @example
110
+ * Catch `CancelError`
111
+ * ```javascript
112
+ * import CancelablePromise from "@nextgis/cancelable-promise";
113
+ *
114
+ * const promise = new CancelablePromise((resolve, reject) => {
115
+ * setTimeout(() => resolve(), 100);
116
+ * }).catch((er) => {
117
+ * if (er.name === "CancelError") {
118
+ * // handle cancel error
119
+ * }
120
+ * throw er;
121
+ * });
122
+ *
123
+ * promise.cancel();
124
+ * ```
125
+ * @example
126
+ * Handle `onCancel` callback
127
+ * ```javascript
128
+ * import CancelablePromise from "@nextgis/cancelable-promise";
129
+ *
130
+ * const promise = new CancelablePromise((resolve, reject, onCancel) => {
131
+ * const xhr = new XMLHttpRequest();
132
+ * xhr.open("GET", url, true);
133
+ * xhr.onload = () => {
134
+ * resolve(xhr.responseText);
135
+ * };
136
+ * xhr.onerror = (er) => {
137
+ * reject(er);
138
+ * };
139
+ *
140
+ * onCancel(() => {
141
+ * xhr.abort();
142
+ * });
143
+ *
144
+ * xhr.send();
145
+ * });
146
+ *
147
+ * promise.cancel();
148
+ * ```
149
+ */
150
+ class CancelablePromise$1 {
151
+ constructor(executor, timeout) {
152
+ this.id = ID$2++;
153
+ this._isCanceled = false;
154
+ this._isPending = true;
155
+ this._cancelHandlers = [];
156
+ this._children = [];
157
+ this._cancelPromise = new Promise((resolve_, reject_) => {
158
+ this._setCanceledCallback = (er) => resolve_(er || new CancelError());
159
+ });
160
+ const promises = [
161
+ this._cancelPromise,
162
+ new Promise((resolve, reject) => {
163
+ const onResolve = (value) => {
164
+ if (value instanceof CancelablePromise$1) {
165
+ this.attach(value);
166
+ }
167
+ else {
168
+ this._isPending = false;
169
+ }
170
+ // TODO: fix types, `undefined` not allowed since 19.12.2020
171
+ resolve(value);
172
+ };
173
+ const onReject = (error) => {
174
+ this._isPending = false;
175
+ reject(error);
176
+ };
177
+ const onCancel = (handler) => {
178
+ if (!this._isPending) {
179
+ throw new Error('The `onCancel` handler was attached after the promise settled.');
180
+ }
181
+ this._cancelHandlers.push(handler);
182
+ };
183
+ return executor(onResolve, onReject, onCancel);
184
+ }),
185
+ ];
186
+ if (timeout) {
187
+ promises.push(new Promise((resolve, reject) => {
188
+ setTimeout(() => {
189
+ if (this._isPending) {
190
+ try {
191
+ this.cancel();
192
+ }
193
+ finally {
194
+ reject(new TimeoutError());
195
+ }
196
+ }
197
+ }, timeout);
198
+ }));
199
+ }
200
+ this._promise = Promise.race(promises);
201
+ }
202
+ static createControl(opt) {
203
+ return new PromiseControl(opt);
204
+ }
205
+ static resolve(value) {
206
+ return new CancelablePromise$1((resolve) => resolve(value));
207
+ }
208
+ static reject(value) {
209
+ return new CancelablePromise$1((resolve, reject) => reject(value));
210
+ }
211
+ static all(values) {
212
+ return new CancelablePromise$1((resolve, reject) => {
213
+ Promise.all(values).then(resolve).catch(reject);
214
+ }).catch((er) => {
215
+ if (er instanceof this.CancelError) {
216
+ for (const v of values) {
217
+ const v_ = v;
218
+ if ('cancel' in v_) {
219
+ v_.cancel();
220
+ }
221
+ }
222
+ }
223
+ throw er;
224
+ });
225
+ }
226
+ attach(p) {
227
+ if (this._isCanceled) {
228
+ p.cancel();
229
+ }
230
+ else {
231
+ this._children.push(p);
232
+ }
233
+ }
234
+ then(onfulfilled, onrejected) {
235
+ const p = new CancelablePromise$1((resolve, reject) => {
236
+ if (this._promise) {
237
+ const reject_ = (r) => {
238
+ if (onrejected) {
239
+ handleCallback(resolve, reject, onrejected, r);
240
+ }
241
+ else {
242
+ reject(r);
243
+ }
244
+ };
245
+ this._promise.then((r) => {
246
+ if (this._isCanceled) {
247
+ reject_(r);
248
+ }
249
+ else {
250
+ if (onfulfilled) {
251
+ handleCallback(resolve, reject, onfulfilled, r);
252
+ }
253
+ else {
254
+ resolve(r);
255
+ }
256
+ }
257
+ }, reject_);
258
+ }
259
+ });
260
+ p._parentPromise = this;
261
+ this._children.push(p);
262
+ return p;
263
+ }
264
+ catch(onrejected) {
265
+ if (this._isCanceled && onrejected) {
266
+ onrejected(new CancelError());
267
+ }
268
+ return this.then(undefined, onrejected);
269
+ }
270
+ finally(onfinally) {
271
+ if (this._promise) {
272
+ return this._promise.finally(onfinally);
273
+ }
274
+ if (this._isCanceled) {
275
+ return Promise.reject(new CancelError());
276
+ }
277
+ return Promise.reject(onfinally);
278
+ }
279
+ cancel() {
280
+ // No reason to run cancel action if promise is already complete
281
+ if (this._isCanceled || !this._isPending) {
282
+ return this;
283
+ }
284
+ this._isCanceled = true;
285
+ const parent = this._getTopParent();
286
+ if (parent) {
287
+ parent.cancel();
288
+ }
289
+ if (this._children) {
290
+ this._children.forEach((x) => x.cancel());
291
+ }
292
+ if (this._isPending) {
293
+ if (this._cancelHandlers.length) {
294
+ try {
295
+ for (const handler of this._cancelHandlers) {
296
+ handler();
297
+ }
298
+ }
299
+ catch (error) {
300
+ // this._setCanceledCallback(error);
301
+ }
302
+ }
303
+ if (this._setCanceledCallback) {
304
+ this._setCanceledCallback();
305
+ }
306
+ }
307
+ this._destroy();
308
+ return this;
309
+ }
310
+ _getTopParent() {
311
+ let parent = this._parentPromise;
312
+ let hasParent = !!parent;
313
+ while (hasParent) {
314
+ if (parent && parent._parentPromise) {
315
+ parent = parent._parentPromise;
316
+ hasParent = !!parent;
317
+ }
318
+ else {
319
+ hasParent = false;
320
+ }
321
+ }
322
+ return parent;
323
+ }
324
+ _destroy() {
325
+ this._setCanceledCallback = undefined;
326
+ this._cancelPromise = undefined;
327
+ this._promise = undefined;
328
+ }
329
+ }
330
+ CancelablePromise$1.CancelError = CancelError;
331
+ CancelablePromise$1.TimeoutError = TimeoutError;
332
+ CancelablePromise$1.PromiseControl = PromiseControl;
485
333
  Object.setPrototypeOf(CancelablePromise$1.prototype, Promise.prototype);
486
334
 
487
- /**
488
- * A promise you can stop
489
- *
490
- * @packageDocumentation
491
- * @module cancelable-promise
492
- */
335
+ /**
336
+ * A promise you can stop
337
+ *
338
+ * @packageDocumentation
339
+ * @module cancelable-promise
340
+ */
493
341
  var CancelablePromise = CancelablePromise$1;
494
342
 
495
- /**
496
- * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
497
- *
498
- * @param val - The object.
499
- * @returns Returns true if the object is defined, returns false otherwise.
500
- *
501
- * @example
502
- * ```javascript
503
- * if (defined(positions)) {
504
- * doSomething();
505
- * } else {
506
- * doSomethingElse();
507
- * }
508
- * ```
509
- */
510
- function defined(val) {
511
- return val !== undefined && val !== null;
512
- }
513
- /**
514
- * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
515
- *
516
- * @param val - The object.
517
- * @returns Returns true if the object is defined and not empty string, returns false otherwise.
518
- *
519
- * @example
520
- * ```javascript
521
- * full('foo') // true
522
- * full('') // false
523
- * full(undefined) // false
524
- * full(0) // true
525
- * ```
526
- */
527
- function full(val) {
528
- return typeof val === 'string' ? !!val : defined(val);
343
+ /**
344
+ * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
345
+ *
346
+ * @param val - The object.
347
+ * @returns Returns true if the object is defined, returns false otherwise.
348
+ *
349
+ * @example
350
+ * ```javascript
351
+ * if (defined(positions)) {
352
+ * doSomething();
353
+ * } else {
354
+ * doSomethingElse();
355
+ * }
356
+ * ```
357
+ */
358
+ function defined(val) {
359
+ return val !== undefined && val !== null;
360
+ }
361
+ /**
362
+ * from https://github.com/CesiumGS/cesium/blob/master/Source/Core/defined.js
363
+ *
364
+ * @param val - The object.
365
+ * @returns Returns true if the object is defined and not empty string, returns false otherwise.
366
+ *
367
+ * @example
368
+ * ```javascript
369
+ * full('foo') // true
370
+ * full('') // false
371
+ * full(undefined) // false
372
+ * full(0) // true
373
+ * ```
374
+ */
375
+ function full(val) {
376
+ return typeof val === 'string' ? !!val : defined(val);
377
+ }
378
+
379
+ /**
380
+ * Copy the values of all of the enumerable own properties from one or more source objects to a
381
+ * target object. Returns the target object.
382
+ * @param target - The target object to copy to.
383
+ * @param sources - One or more source objects from which to copy properties
384
+ */
385
+ function objectAssign(target, ...sources) {
386
+ for (const source of sources) {
387
+ for (const prop of Object.getOwnPropertyNames(source)) {
388
+ target[prop] = source[prop];
389
+ }
390
+ }
391
+ }
392
+
393
+ function isEqual(a, b, o, p) {
394
+ if (a instanceof Array) {
395
+ if (!(b instanceof Array))
396
+ return false;
397
+ //if (compareObjects(oVal, pVal === false) return false
398
+ //would work, too, and perhaps is a better fit, still, this is easy, too
399
+ return b.sort().join('') === a.sort().join('');
400
+ }
401
+ else if (a instanceof Date) {
402
+ if (!(b instanceof Date))
403
+ return false;
404
+ return '' + a === '' + b;
405
+ }
406
+ else if (a instanceof Function) {
407
+ if (!(b instanceof Function))
408
+ return false;
409
+ //ignore functions, or check them regardless?
410
+ }
411
+ else if (a instanceof Object) {
412
+ if (!(b instanceof Object))
413
+ return false;
414
+ if (a === o) {
415
+ return b === p;
416
+ }
417
+ else {
418
+ return objectDeepEqual(a, b);
419
+ }
420
+ }
421
+ return a === b;
422
+ }
423
+ // based on https://stackoverflow.com/a/13143059
424
+ function objectDeepEqual(o, p) {
425
+ const keysO = Object.keys(o).sort();
426
+ const keysP = Object.keys(p).sort();
427
+ if (keysO.length !== keysP.length)
428
+ return false;
429
+ if (keysO.join('') !== keysP.join(''))
430
+ return false;
431
+ for (let i = 0; i < keysO.length; i++) {
432
+ const oVal = o[keysO[i]];
433
+ const pVal = p[keysP[i]];
434
+ if (!isEqual(oVal, pVal, o, p)) {
435
+ return false;
436
+ }
437
+ }
438
+ return true;
529
439
  }
530
440
 
531
- /**
532
- * Copy the values of all of the enumerable own properties from one or more source objects to a
533
- * target object. Returns the target object.
534
- * @param target - The target object to copy to.
535
- * @param sources - One or more source objects from which to copy properties
536
- */
537
- function objectAssign(target) {
538
- var sources = [];
539
- for (var _i = 1; _i < arguments.length; _i++) {
540
- sources[_i - 1] = arguments[_i];
541
- }
542
- for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
543
- var source = sources_1[_a];
544
- for (var _b = 0, _c = Object.getOwnPropertyNames(source); _b < _c.length; _b++) {
545
- var prop = _c[_b];
546
- target[prop] = source[prop];
547
- }
548
- }
441
+ function objectRemoveEmpty(obj) {
442
+ const newObj = {};
443
+ Object.keys(obj).forEach((key) => {
444
+ if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
445
+ newObj[key] = objectRemoveEmpty(obj[key]);
446
+ }
447
+ else if (obj[key] !== undefined) {
448
+ newObj[key] = obj[key];
449
+ }
450
+ });
451
+ return newObj;
549
452
  }
550
453
 
551
- function isEqual(a, b, o, p) {
552
- if (a instanceof Array) {
553
- if (!(b instanceof Array))
554
- return false;
555
- //if (compareObjects(oVal, pVal === false) return false
556
- //would work, too, and perhaps is a better fit, still, this is easy, too
557
- return b.sort().join('') === a.sort().join('');
558
- }
559
- else if (a instanceof Date) {
560
- if (!(b instanceof Date))
561
- return false;
562
- return '' + a === '' + b;
563
- }
564
- else if (a instanceof Function) {
565
- if (!(b instanceof Function))
566
- return false;
567
- //ignore functions, or check them regardless?
568
- }
569
- else if (a instanceof Object) {
570
- if (!(b instanceof Object))
571
- return false;
572
- if (a === o) {
573
- return b === p;
574
- }
575
- else {
576
- return objectDeepEqual(a, b);
577
- }
578
- }
579
- return a === b;
580
- }
581
- // based on https://stackoverflow.com/a/13143059
582
- function objectDeepEqual(o, p) {
583
- var keysO = Object.keys(o).sort();
584
- var keysP = Object.keys(p).sort();
585
- if (keysO.length !== keysP.length)
586
- return false;
587
- if (keysO.join('') !== keysP.join(''))
588
- return false;
589
- for (var i = 0; i < keysO.length; i++) {
590
- var oVal = o[keysO[i]];
591
- var pVal = p[keysP[i]];
592
- if (!isEqual(oVal, pVal, o, p)) {
593
- return false;
594
- }
595
- }
596
- return true;
454
+ function fixUrlStr(url) {
455
+ // remove double slash
456
+ return url.replace(/([^:]\/)\/+/g, '$1');
597
457
  }
598
458
 
599
- function objectRemoveEmpty(obj) {
600
- var newObj = {};
601
- Object.keys(obj).forEach(function (key) {
602
- if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
603
- newObj[key] = objectRemoveEmpty(obj[key]);
604
- }
605
- else if (obj[key] !== undefined) {
606
- newObj[key] = obj[key];
607
- }
608
- });
609
- return newObj;
459
+ class BaseGeocoder {
460
+ constructor(options) {
461
+ if (options) {
462
+ objectAssign(this, options);
463
+ }
464
+ }
610
465
  }
611
466
 
612
- function fixUrlStr(url) {
613
- // remove double slash
614
- return url.replace(/([^:]\/)\/+/g, '$1');
467
+ let ID$1 = 0;
468
+ class Geocoder extends BaseGeocoder {
469
+ constructor(options) {
470
+ super(options);
471
+ this.providers = [];
472
+ if (options && options.providers) {
473
+ this.providers = options.providers;
474
+ }
475
+ }
476
+ abort() {
477
+ this.providers.forEach((x) => {
478
+ if (x.abort) {
479
+ x.abort();
480
+ }
481
+ });
482
+ }
483
+ async *search(query) {
484
+ for (const provider of this.providers) {
485
+ try {
486
+ const results = provider.search(query);
487
+ for await (const r of results) {
488
+ yield { ...r, provider, _id: ID$1++ };
489
+ }
490
+ }
491
+ catch (er) {
492
+ //
493
+ }
494
+ }
495
+ }
496
+ result(item) {
497
+ if (item.provider) {
498
+ return item.provider.result(item);
499
+ }
500
+ return CancelablePromise.resolve(undefined);
501
+ }
615
502
  }
616
503
 
617
- var BaseGeocoder = /** @class */ (function () {
618
- function BaseGeocoder(options) {
619
- if (options) {
620
- objectAssign(this, options);
621
- }
622
- }
623
- return BaseGeocoder;
624
- }());
625
-
626
- var ID$1 = 0;
627
- var Geocoder = /** @class */ (function (_super) {
628
- __extends(Geocoder, _super);
629
- function Geocoder(options) {
630
- var _this = _super.call(this, options) || this;
631
- _this.providers = [];
632
- if (options && options.providers) {
633
- _this.providers = options.providers;
634
- }
635
- return _this;
636
- }
637
- Geocoder.prototype.abort = function () {
638
- this.providers.forEach(function (x) {
639
- if (x.abort) {
640
- x.abort();
641
- }
642
- });
643
- };
644
- Geocoder.prototype.search = function (query) {
645
- return __asyncGenerator(this, arguments, function search_1() {
646
- var _i, _a, provider, results, results_1, results_1_1, r, e_1_1;
647
- var e_1, _b;
648
- return __generator(this, function (_c) {
649
- switch (_c.label) {
650
- case 0:
651
- _i = 0, _a = this.providers;
652
- _c.label = 1;
653
- case 1:
654
- if (!(_i < _a.length)) return [3 /*break*/, 19];
655
- provider = _a[_i];
656
- _c.label = 2;
657
- case 2:
658
- _c.trys.push([2, 17, , 18]);
659
- results = provider.search(query);
660
- _c.label = 3;
661
- case 3:
662
- _c.trys.push([3, 10, 11, 16]);
663
- results_1 = (e_1 = void 0, __asyncValues(results));
664
- _c.label = 4;
665
- case 4: return [4 /*yield*/, __await(results_1.next())];
666
- case 5:
667
- if (!(results_1_1 = _c.sent(), !results_1_1.done)) return [3 /*break*/, 9];
668
- r = results_1_1.value;
669
- return [4 /*yield*/, __await(__assign(__assign({}, r), { provider: provider, _id: ID$1++ }))];
670
- case 6: return [4 /*yield*/, _c.sent()];
671
- case 7:
672
- _c.sent();
673
- _c.label = 8;
674
- case 8: return [3 /*break*/, 4];
675
- case 9: return [3 /*break*/, 16];
676
- case 10:
677
- e_1_1 = _c.sent();
678
- e_1 = { error: e_1_1 };
679
- return [3 /*break*/, 16];
680
- case 11:
681
- _c.trys.push([11, , 14, 15]);
682
- if (!(results_1_1 && !results_1_1.done && (_b = results_1.return))) return [3 /*break*/, 13];
683
- return [4 /*yield*/, __await(_b.call(results_1))];
684
- case 12:
685
- _c.sent();
686
- _c.label = 13;
687
- case 13: return [3 /*break*/, 15];
688
- case 14:
689
- if (e_1) throw e_1.error;
690
- return [7 /*endfinally*/];
691
- case 15: return [7 /*endfinally*/];
692
- case 16: return [3 /*break*/, 18];
693
- case 17:
694
- _c.sent();
695
- return [3 /*break*/, 18];
696
- case 18:
697
- _i++;
698
- return [3 /*break*/, 1];
699
- case 19: return [2 /*return*/];
700
- }
701
- });
702
- });
703
- };
704
- Geocoder.prototype.result = function (item) {
705
- if (item.provider) {
706
- return item.provider.result(item);
707
- }
708
- return CancelablePromise.resolve(undefined);
709
- };
710
- return Geocoder;
711
- }(BaseGeocoder));
712
-
713
- var BaseProvider = /** @class */ (function (_super) {
714
- __extends(BaseProvider, _super);
715
- function BaseProvider() {
716
- return _super !== null && _super.apply(this, arguments) || this;
717
- }
718
- return BaseProvider;
719
- }(BaseGeocoder));
504
+ class BaseProvider extends BaseGeocoder {
505
+ }
720
506
 
721
507
  var events = {exports: {}};
722
508
 
@@ -1194,1455 +980,1313 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
1194
980
  }
1195
981
  }
1196
982
 
1197
- /**
1198
- * @example
1199
- * ```javascript
1200
- * const cache1 = new Cache();
1201
- * cache1.add('foo', 'value');
1202
- *
1203
- * const cache2 = new Cache();
1204
- * cache2.match('foo'); // value
1205
- *
1206
- * const cache3 = new Cache({ namespace: 'foo' });
1207
- * cache3.match('foo'); // undefined
1208
- * ```
1209
- *
1210
- * @example
1211
- * ```javascript
1212
- * let COUNTER = 0;
1213
- * const createPromise = () => new Promise((res) => {
1214
- * COUNTER++
1215
- * setTimeout(() => res('Ok'), 300)
1216
- * });
1217
- *
1218
- * const cache = new Cache();
1219
- * for (let i = 0; i < 10; i++) {
1220
- * cache.add('foo', createPromise).then((data) => {
1221
- * console.log(data); // 'Ok'
1222
- * });
1223
- * }
1224
- * console.log(COUNTER); // 1
1225
- * ```
1226
- */
1227
- var Cache$1 = /** @class */ (function () {
1228
- function Cache(options) {
1229
- if (options === void 0) { options = {}; }
1230
- var _a;
1231
- this.cache = [];
1232
- var namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
1233
- if (Cache.instance[namespace]) {
1234
- return Cache.instance[namespace];
1235
- }
1236
- Cache.instance[namespace] = this;
1237
- return this;
1238
- }
1239
- Cache.prototype.clean = function () {
1240
- this.cache.length = 0;
1241
- };
1242
- Cache.prototype.all = function () {
1243
- return this.cache;
1244
- };
1245
- /**
1246
- * Caching only a non-empty value.
1247
- *
1248
- * Useful for get or create strategy
1249
- * @example
1250
- * ```javascript
1251
- * const cache = new Cache();
1252
- * const getItemFunc = () => fetch(url).then((data) => {
1253
- * return data.json(); // undefined
1254
- * });
1255
- * const item = await cache.addFull('foo', getItemFunc);
1256
- * if (!item) {
1257
- * await createItem(); // 'New item'
1258
- * }
1259
- *
1260
- * // somewhere else in the code
1261
- * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
1262
- * console.log(resp); // 'New item'
1263
- * })
1264
- *
1265
- * ```
1266
- */
1267
- Cache.prototype.addFull = function (key, valueToSet, props) {
1268
- return this.add(key, valueToSet, props, true);
1269
- };
1270
- Cache.prototype.add = function (key, valueToSet, props, onlyFull) {
1271
- var _this = this;
1272
- var exist = this._find(key, props);
1273
- if (!exist) {
1274
- var value = void 0;
1275
- if (valueToSet instanceof Function) {
1276
- value = valueToSet();
1277
- }
1278
- else {
1279
- value = valueToSet;
1280
- }
1281
- var props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
1282
- var cacheItem = {
1283
- key: key,
1284
- value: value,
1285
- props: props_,
1286
- // TODO: remove backward compatibility use only props
1287
- options: props_,
1288
- };
1289
- if (onlyFull && !full(value)) {
1290
- return value;
1291
- }
1292
- this.cache.push(cacheItem);
1293
- if (value instanceof Promise) {
1294
- value.catch(function (er) {
1295
- _this.delete(key, props);
1296
- throw er;
1297
- });
1298
- if (onlyFull) {
1299
- value.then(function (x) {
1300
- if (!full(x)) {
1301
- _this.delete(key, props);
1302
- }
1303
- return x;
1304
- });
1305
- }
1306
- return value;
1307
- }
1308
- return value;
1309
- }
1310
- else {
1311
- return exist.value;
1312
- }
1313
- };
1314
- Cache.prototype.match = function (key, props) {
1315
- var cacheRecord = this._find(key, props);
1316
- if (cacheRecord) {
1317
- return cacheRecord.value;
1318
- }
1319
- };
1320
- Cache.prototype.matchAll = function (key, props) {
1321
- var _this = this;
1322
- if (key) {
1323
- return this.cache
1324
- .filter(function (x) { return _this._filter(x, key, props); })
1325
- .map(function (x) { return x.value; });
1326
- }
1327
- return this.cache.map(function (x) { return x.value; });
1328
- };
1329
- Cache.prototype.delete = function (keyOrItem, props) {
1330
- var _this = this;
1331
- var exist = [];
1332
- if (typeof keyOrItem === 'string') {
1333
- exist = this.cache.filter(function (x) { return _this._filter(x, keyOrItem, props); });
1334
- }
1335
- else {
1336
- exist.push(keyOrItem);
1337
- }
1338
- for (var _i = 0, exist_1 = exist; _i < exist_1.length; _i++) {
1339
- var e = exist_1[_i];
1340
- var index = this.cache.indexOf(e);
1341
- this.cache.splice(index, 1);
1342
- }
1343
- };
1344
- Cache.prototype._find = function (key, props) {
1345
- var _this = this;
1346
- return this.cache.find(function (x) { return _this._filter(x, key, props); });
1347
- };
1348
- Cache.prototype._filter = function (item, key, props) {
1349
- if (item.key === key) {
1350
- if (props) {
1351
- // TODO: remove backward compatibility
1352
- var itemProps = item.props || item.options;
1353
- return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
1354
- }
1355
- return true;
1356
- }
1357
- return false;
1358
- };
1359
- Cache.instance = {};
1360
- return Cache;
1361
- }());
1362
-
1363
- /**
1364
- * Caching for asynchronous functions
1365
- *
1366
- * @packageDocumentation
1367
- * @module cache
1368
- */
983
+ /**
984
+ * @example
985
+ * ```javascript
986
+ * const cache1 = new Cache();
987
+ * cache1.add('foo', 'value');
988
+ *
989
+ * const cache2 = new Cache();
990
+ * cache2.match('foo'); // value
991
+ *
992
+ * const cache3 = new Cache({ namespace: 'foo' });
993
+ * cache3.match('foo'); // undefined
994
+ * ```
995
+ *
996
+ * @example
997
+ * ```javascript
998
+ * let COUNTER = 0;
999
+ * const createPromise = () => new Promise((res) => {
1000
+ * COUNTER++
1001
+ * setTimeout(() => res('Ok'), 300)
1002
+ * });
1003
+ *
1004
+ * const cache = new Cache();
1005
+ * for (let i = 0; i < 10; i++) {
1006
+ * cache.add('foo', createPromise).then((data) => {
1007
+ * console.log(data); // 'Ok'
1008
+ * });
1009
+ * }
1010
+ * console.log(COUNTER); // 1
1011
+ * ```
1012
+ */
1013
+ class Cache$1 {
1014
+ constructor(options = {}) {
1015
+ var _a;
1016
+ this.cache = [];
1017
+ const namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
1018
+ if (Cache$1.instance[namespace]) {
1019
+ return Cache$1.instance[namespace];
1020
+ }
1021
+ Cache$1.instance[namespace] = this;
1022
+ return this;
1023
+ }
1024
+ clean() {
1025
+ this.cache.length = 0;
1026
+ }
1027
+ all() {
1028
+ return this.cache;
1029
+ }
1030
+ /**
1031
+ * Caching only a non-empty value.
1032
+ *
1033
+ * Useful for get or create strategy
1034
+ * @example
1035
+ * ```javascript
1036
+ * const cache = new Cache();
1037
+ * const getItemFunc = () => fetch(url).then((data) => {
1038
+ * return data.json(); // undefined
1039
+ * });
1040
+ * const item = await cache.addFull('foo', getItemFunc);
1041
+ * if (!item) {
1042
+ * await createItem(); // 'New item'
1043
+ * }
1044
+ *
1045
+ * // somewhere else in the code
1046
+ * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
1047
+ * console.log(resp); // 'New item'
1048
+ * })
1049
+ *
1050
+ * ```
1051
+ */
1052
+ addFull(key, valueToSet, props) {
1053
+ return this.add(key, valueToSet, props, true);
1054
+ }
1055
+ add(key, valueToSet, props, onlyFull) {
1056
+ const exist = this._find(key, props);
1057
+ if (!exist) {
1058
+ let value;
1059
+ if (valueToSet instanceof Function) {
1060
+ value = valueToSet();
1061
+ }
1062
+ else {
1063
+ value = valueToSet;
1064
+ }
1065
+ const props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
1066
+ const cacheItem = {
1067
+ key,
1068
+ value,
1069
+ props: props_,
1070
+ // TODO: remove backward compatibility use only props
1071
+ options: props_,
1072
+ };
1073
+ if (onlyFull && !full(value)) {
1074
+ return value;
1075
+ }
1076
+ this.cache.push(cacheItem);
1077
+ if (value instanceof Promise) {
1078
+ value.catch((er) => {
1079
+ this.delete(key, props);
1080
+ throw er;
1081
+ });
1082
+ if (onlyFull) {
1083
+ value.then((x) => {
1084
+ if (!full(x)) {
1085
+ this.delete(key, props);
1086
+ }
1087
+ return x;
1088
+ });
1089
+ }
1090
+ return value;
1091
+ }
1092
+ return value;
1093
+ }
1094
+ else {
1095
+ return exist.value;
1096
+ }
1097
+ }
1098
+ match(key, props) {
1099
+ const cacheRecord = this._find(key, props);
1100
+ if (cacheRecord) {
1101
+ return cacheRecord.value;
1102
+ }
1103
+ }
1104
+ matchAll(key, props) {
1105
+ if (key) {
1106
+ return this.cache
1107
+ .filter((x) => this._filter(x, key, props))
1108
+ .map((x) => x.value);
1109
+ }
1110
+ return this.cache.map((x) => x.value);
1111
+ }
1112
+ delete(keyOrItem, props) {
1113
+ let exist = [];
1114
+ if (typeof keyOrItem === 'string') {
1115
+ exist = this.cache.filter((x) => this._filter(x, keyOrItem, props));
1116
+ }
1117
+ else {
1118
+ exist.push(keyOrItem);
1119
+ }
1120
+ for (const e of exist) {
1121
+ const index = this.cache.indexOf(e);
1122
+ this.cache.splice(index, 1);
1123
+ }
1124
+ }
1125
+ _find(key, props) {
1126
+ return this.cache.find((x) => this._filter(x, key, props));
1127
+ }
1128
+ _filter(item, key, props) {
1129
+ if (item.key === key) {
1130
+ if (props) {
1131
+ // TODO: remove backward compatibility
1132
+ const itemProps = item.props || item.options;
1133
+ return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
1134
+ }
1135
+ return true;
1136
+ }
1137
+ return false;
1138
+ }
1139
+ }
1140
+ Cache$1.instance = {};
1141
+
1142
+ /**
1143
+ * Caching for asynchronous functions
1144
+ *
1145
+ * @packageDocumentation
1146
+ * @module cache
1147
+ */
1369
1148
  var Cache = Cache$1;
1370
1149
 
1371
- /**
1372
- * Thrown when...
1373
- */
1374
- var NetworkError = /** @class */ (function (_super) {
1375
- __extends(NetworkError, _super);
1376
- function NetworkError(url) {
1377
- var _this = _super.call(this) || this;
1378
- _this.name = 'NetworkError';
1379
- Object.setPrototypeOf(_this, NetworkError.prototype);
1380
- _this.message = "Unable to request ".concat(url, ".\n Possibly invalid NGW URL entered or CORS not configured to get request from ").concat(location.origin); // /control-panel/cors
1381
- return _this;
1382
- }
1383
- return NetworkError;
1384
- }(Error));
1385
-
1386
- /**
1387
- * Thrown when...
1388
- */
1389
- var NgwError = /** @class */ (function (_super) {
1390
- __extends(NgwError, _super);
1391
- function NgwError(er) {
1392
- var _this = _super.call(this) || this;
1393
- _this.name = 'NgwError';
1394
- Object.assign(_this, er);
1395
- Object.setPrototypeOf(_this, NgwError.prototype);
1396
- return _this;
1397
- }
1398
- return NgwError;
1399
- }(Error));
1400
-
1401
- function isObject(val) {
1402
- return Object.prototype.toString.call(val) === '[object Object]';
1150
+ /**
1151
+ * Thrown when...
1152
+ */
1153
+ class NetworkError extends Error {
1154
+ constructor(url) {
1155
+ super();
1156
+ this.name = 'NetworkError';
1157
+ Object.setPrototypeOf(this, NetworkError.prototype);
1158
+ this.message = `Unable to request ${url}.
1159
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`; // /control-panel/cors
1160
+ }
1403
1161
  }
1404
1162
 
1405
- var loadData;
1406
- // @ts-ignore
1407
- {
1408
- loadData = function (url, callback, options, error, onCancel) {
1409
- if (options === void 0) { options = {}; }
1410
- options.method = options.method || 'GET';
1411
- var xhr = new XMLHttpRequest();
1412
- xhr.open(options.method || 'GET', url, true); // true for asynchronous
1413
- if (options.responseType === 'blob') {
1414
- xhr.responseType = options.responseType;
1415
- }
1416
- var getResponseText = function () {
1417
- try {
1418
- return JSON.parse(xhr.responseText);
1419
- }
1420
- catch (er) {
1421
- return xhr.responseText;
1422
- }
1423
- };
1424
- var processingResponse = function (forError) {
1425
- if (forError === void 0) { forError = false; }
1426
- var cb = forError ? error : callback;
1427
- if (options.responseType === 'blob') {
1428
- cb(xhr.response);
1429
- }
1430
- else {
1431
- if (xhr.responseText) {
1432
- cb(getResponseText());
1433
- }
1434
- else {
1435
- error({ message: '' });
1436
- }
1437
- }
1438
- };
1439
- xhr.onload = function () {
1440
- if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1441
- error(new NgwError(getResponseText()));
1442
- }
1443
- processingResponse();
1444
- };
1445
- // xhr.onreadystatechange = () => {
1446
- // if (
1447
- // (xhr.readyState === 4 && xhr.status === 200) ||
1448
- // (xhr.readyState === 3 && xhr.status === 201)
1449
- // ) {
1450
- // processingResponse();
1451
- // } else if (xhr.readyState === 3 && xhr.status === 400) {
1452
- // processingResponse();
1453
- // } else if (xhr.readyState === 4 && xhr.status === 500) {
1454
- // processingResponse();
1455
- // } else if (xhr.readyState === 4 && xhr.status === 401) {
1456
- // error(xhr.statusText);
1457
- // } else if (xhr.readyState === 4) {
1458
- // error('request error');
1459
- // }
1460
- // };
1461
- xhr.onerror = function (er) {
1462
- if (xhr.status === 0) {
1463
- error(new NetworkError(url));
1464
- }
1465
- else {
1466
- error(er);
1467
- }
1468
- };
1469
- xhr.upload.onprogress = function (e) {
1470
- if (e.lengthComputable) {
1471
- var percentComplete = (e.loaded / e.total) * 100;
1472
- if (options.onProgress) {
1473
- options.onProgress(percentComplete, e);
1474
- }
1475
- // console.log(percentComplete + '% uploaded');
1476
- }
1477
- };
1478
- var headers = options.headers;
1479
- if (headers) {
1480
- for (var h in headers) {
1481
- var header = headers[h];
1482
- if (typeof header === 'string') {
1483
- xhr.setRequestHeader(h, header);
1484
- }
1485
- }
1486
- }
1487
- if (options.withCredentials !== undefined) {
1488
- xhr.withCredentials = options.withCredentials;
1489
- }
1490
- var data;
1491
- if (options.file) {
1492
- data = new FormData();
1493
- data.append('file', options.file);
1494
- if (options.data) {
1495
- for (var d in options.data) {
1496
- data.append(d, data[d]);
1497
- }
1498
- }
1499
- }
1500
- else {
1501
- data = options.data
1502
- ? typeof options.data === 'string'
1503
- ? options.data
1504
- : JSON.stringify(options.data)
1505
- : null;
1506
- }
1507
- if (onCancel) {
1508
- onCancel(function () {
1509
- xhr.abort();
1510
- });
1511
- }
1512
- xhr.send(data);
1513
- };
1163
+ /**
1164
+ * Thrown when...
1165
+ */
1166
+ class NgwError extends Error {
1167
+ constructor(er) {
1168
+ super();
1169
+ this.name = 'NgwError';
1170
+ Object.assign(this, er);
1171
+ Object.setPrototypeOf(this, NgwError.prototype);
1172
+ }
1514
1173
  }
1515
1174
 
1516
- // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
1517
- var templateRe = /\{ *([\w_-]+) *\}/g;
1518
- function template(str, data) {
1519
- return str.replace(templateRe, function (s, key) {
1520
- var value = data[key];
1521
- if (value === undefined) {
1522
- throw new Error('No value provided for letiable ' + s);
1523
- }
1524
- else if (typeof value === 'function') {
1525
- value = value(data);
1526
- }
1527
- return value;
1528
- });
1175
+ function isObject(val) {
1176
+ return Object.prototype.toString.call(val) === '[object Object]';
1529
1177
  }
1530
1178
 
1531
- function apiRequest(opt) {
1532
- var params = opt.params;
1533
- return new CancelablePromise(function (resolve, reject) {
1534
- opt.connector
1535
- .connect()
1536
- .then(function (apiItems) {
1537
- var apiItem = apiItems && apiItems[opt.name];
1538
- if (apiItem) {
1539
- apiItem = __spreadArray([], apiItem, true);
1540
- var url = apiItem.shift();
1541
- if (apiItem.length) {
1542
- var replaceParams = {};
1543
- for (var fry = 0; fry < apiItem.length; fry++) {
1544
- var arg = apiItem[fry];
1545
- replaceParams[fry] = '{' + arg + '}';
1546
- if (params[arg] === undefined) {
1547
- throw new Error('`' + arg + '`' + ' url api argument is not specified');
1548
- }
1549
- }
1550
- if (url) {
1551
- url = template(url, replaceParams);
1552
- }
1553
- }
1554
- // Transfer part of the parameters from `params` to the URL string
1555
- if (params) {
1556
- var paramArray_1 = [];
1557
- var paramList = params.paramList;
1558
- if (Array.isArray(paramList)) {
1559
- delete params.paramList;
1560
- paramList.forEach(function (x) {
1561
- paramArray_1.push("".concat(x[0], "=").concat(x[1]));
1562
- });
1563
- }
1564
- for (var p in params) {
1565
- if (apiItem.indexOf(p) === -1) {
1566
- paramArray_1.push("".concat(p, "=").concat(params[p]));
1567
- }
1568
- }
1569
- if (paramArray_1.length) {
1570
- url = url + '?' + paramArray_1.join('&');
1571
- }
1572
- }
1573
- if (url) {
1574
- resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
1575
- }
1576
- else {
1577
- reject(new Error('request url is not set'));
1578
- }
1579
- }
1580
- else {
1581
- resolve(undefined);
1582
- }
1583
- })
1584
- .catch(function (er) {
1585
- reject(er);
1586
- });
1587
- });
1179
+ let loadData;
1180
+ // @ts-ignore
1181
+ {
1182
+ loadData = (url, callback, options = {}, error, onCancel) => {
1183
+ options.method = options.method || 'GET';
1184
+ const xhr = new XMLHttpRequest();
1185
+ xhr.open(options.method || 'GET', url, true); // true for asynchronous
1186
+ if (options.responseType === 'blob') {
1187
+ xhr.responseType = options.responseType;
1188
+ }
1189
+ const getResponseText = () => {
1190
+ try {
1191
+ return JSON.parse(xhr.responseText);
1192
+ }
1193
+ catch (er) {
1194
+ return xhr.responseText;
1195
+ }
1196
+ };
1197
+ const processingResponse = (forError = false) => {
1198
+ const cb = forError ? error : callback;
1199
+ if (options.responseType === 'blob') {
1200
+ cb(xhr.response);
1201
+ }
1202
+ else {
1203
+ if (xhr.responseText) {
1204
+ cb(getResponseText());
1205
+ }
1206
+ else {
1207
+ error({ message: '' });
1208
+ }
1209
+ }
1210
+ };
1211
+ xhr.onload = () => {
1212
+ if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1213
+ error(new NgwError(getResponseText()));
1214
+ }
1215
+ processingResponse();
1216
+ };
1217
+ // xhr.onreadystatechange = () => {
1218
+ // if (
1219
+ // (xhr.readyState === 4 && xhr.status === 200) ||
1220
+ // (xhr.readyState === 3 && xhr.status === 201)
1221
+ // ) {
1222
+ // processingResponse();
1223
+ // } else if (xhr.readyState === 3 && xhr.status === 400) {
1224
+ // processingResponse();
1225
+ // } else if (xhr.readyState === 4 && xhr.status === 500) {
1226
+ // processingResponse();
1227
+ // } else if (xhr.readyState === 4 && xhr.status === 401) {
1228
+ // error(xhr.statusText);
1229
+ // } else if (xhr.readyState === 4) {
1230
+ // error('request error');
1231
+ // }
1232
+ // };
1233
+ xhr.onerror = (er) => {
1234
+ if (xhr.status === 0) {
1235
+ error(new NetworkError(url));
1236
+ }
1237
+ else {
1238
+ error(er);
1239
+ }
1240
+ };
1241
+ xhr.upload.onprogress = function (e) {
1242
+ if (e.lengthComputable) {
1243
+ const percentComplete = (e.loaded / e.total) * 100;
1244
+ if (options.onProgress) {
1245
+ options.onProgress(percentComplete, e);
1246
+ }
1247
+ // console.log(percentComplete + '% uploaded');
1248
+ }
1249
+ };
1250
+ const headers = options.headers;
1251
+ if (headers) {
1252
+ for (const h in headers) {
1253
+ const header = headers[h];
1254
+ if (typeof header === 'string') {
1255
+ xhr.setRequestHeader(h, header);
1256
+ }
1257
+ }
1258
+ }
1259
+ if (options.withCredentials !== undefined) {
1260
+ xhr.withCredentials = options.withCredentials;
1261
+ }
1262
+ let data;
1263
+ if (options.file) {
1264
+ data = new FormData();
1265
+ data.append('file', options.file);
1266
+ if (options.data) {
1267
+ for (const d in options.data) {
1268
+ data.append(d, data[d]);
1269
+ }
1270
+ }
1271
+ }
1272
+ else {
1273
+ data = options.data
1274
+ ? typeof options.data === 'string'
1275
+ ? options.data
1276
+ : JSON.stringify(options.data)
1277
+ : null;
1278
+ }
1279
+ if (onCancel) {
1280
+ onCancel(() => {
1281
+ xhr.abort();
1282
+ });
1283
+ }
1284
+ xhr.send(data);
1285
+ };
1588
1286
  }
1589
1287
 
1590
- /**
1591
- * Thrown when ...
1592
- */
1593
- var ResourceNotFoundError = /** @class */ (function (_super) {
1594
- __extends(ResourceNotFoundError, _super);
1595
- function ResourceNotFoundError(obj) {
1596
- var _this = _super.call(this, obj) || this;
1597
- _this.name = 'ResourceNotFoundError';
1598
- _this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
1599
- Object.setPrototypeOf(_this, ResourceNotFoundError.prototype);
1600
- return _this;
1601
- }
1602
- return ResourceNotFoundError;
1603
- }(NgwError));
1604
-
1605
- /**
1606
- * Thrown when ...
1607
- */
1608
- var InsufficientPermissionsError = /** @class */ (function (_super) {
1609
- __extends(InsufficientPermissionsError, _super);
1610
- function InsufficientPermissionsError(obj) {
1611
- var _this = _super.call(this, obj) || this;
1612
- _this.name = 'InsufficientPermissionsError';
1613
- _this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
1614
- Object.setPrototypeOf(_this, InsufficientPermissionsError.prototype);
1615
- return _this;
1616
- }
1617
- return InsufficientPermissionsError;
1618
- }(NgwError));
1619
-
1620
- var CONNECTORS = [];
1621
- function addConnector(connector) {
1622
- CONNECTORS.push(connector);
1623
- }
1624
- function findConnector(options) {
1625
- return CONNECTORS.find(function (x) {
1626
- if (x.options.baseUrl === options.baseUrl) {
1627
- if (options.auth) {
1628
- if (x.options.auth) {
1629
- return objectDeepEqual(x.options.auth, options.auth);
1630
- }
1631
- }
1632
- else {
1633
- // if auth not in find options; use first connector with same url
1634
- return true;
1635
- }
1636
- }
1637
- });
1638
- }
1639
- function removeConnector(connector) {
1640
- var index = CONNECTORS.indexOf(connector);
1641
- if (index !== -1) {
1642
- CONNECTORS.splice(index, 1);
1643
- }
1288
+ // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
1289
+ const templateRe = /\{ *([\w_-]+) *\}/g;
1290
+ function template(str, data) {
1291
+ return str.replace(templateRe, (s, key) => {
1292
+ let value = data[key];
1293
+ if (value === undefined) {
1294
+ throw new Error('No value provided for letiable ' + s);
1295
+ }
1296
+ else if (typeof value === 'function') {
1297
+ value = value(data);
1298
+ }
1299
+ return value;
1300
+ });
1301
+ }
1302
+
1303
+ function apiRequest(opt) {
1304
+ const params = opt.params;
1305
+ return new CancelablePromise((resolve, reject) => {
1306
+ opt.connector
1307
+ .connect()
1308
+ .then((apiItems) => {
1309
+ let apiItem = apiItems && apiItems[opt.name];
1310
+ if (apiItem) {
1311
+ apiItem = [...apiItem];
1312
+ let url = apiItem.shift();
1313
+ if (apiItem.length) {
1314
+ const replaceParams = {};
1315
+ for (let fry = 0; fry < apiItem.length; fry++) {
1316
+ const arg = apiItem[fry];
1317
+ replaceParams[fry] = '{' + arg + '}';
1318
+ if (params[arg] === undefined) {
1319
+ throw new Error('`' + arg + '`' + ' url api argument is not specified');
1320
+ }
1321
+ }
1322
+ if (url) {
1323
+ url = template(url, replaceParams);
1324
+ }
1325
+ }
1326
+ // Transfer part of the parameters from `params` to the URL string
1327
+ if (params) {
1328
+ const paramArray = [];
1329
+ const paramList = params.paramList;
1330
+ if (Array.isArray(paramList)) {
1331
+ delete params.paramList;
1332
+ paramList.forEach((x) => {
1333
+ paramArray.push(`${x[0]}=${x[1]}`);
1334
+ });
1335
+ }
1336
+ for (const p in params) {
1337
+ if (apiItem.indexOf(p) === -1) {
1338
+ paramArray.push(`${p}=${params[p]}`);
1339
+ }
1340
+ }
1341
+ if (paramArray.length) {
1342
+ url = url + '?' + paramArray.join('&');
1343
+ }
1344
+ }
1345
+ if (url) {
1346
+ resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
1347
+ }
1348
+ else {
1349
+ reject(new Error('request url is not set'));
1350
+ }
1351
+ }
1352
+ else {
1353
+ resolve(undefined);
1354
+ }
1355
+ })
1356
+ .catch((er) => {
1357
+ reject(er);
1358
+ });
1359
+ });
1644
1360
  }
1645
1361
 
1646
- var exclude = ['description'];
1647
- /**
1648
- * @remarks
1649
- * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
1650
- *
1651
- * ```
1652
- * { keyname, owner_user: { id }} > { keyname, owner_user__id }
1653
- * ```
1654
- *
1655
- * @param resource - Any property from NGW resource item
1656
- */
1657
- function resourceToQuery(resource, prefix) {
1658
- if (prefix === void 0) { prefix = ''; }
1659
- prefix = prefix ? prefix + '__' : '';
1660
- var query = {};
1661
- for (var _i = 0, _a = Object.entries(resource); _i < _a.length; _i++) {
1662
- var _b = _a[_i], key = _b[0], value = _b[1];
1663
- if (exclude.indexOf(key) === -1) {
1664
- if (isObject(value)) {
1665
- if (key === 'owner_user') {
1666
- var children = resourceToQuery(value, key);
1667
- Object.assign(query, children);
1668
- }
1669
- else if (key === 'parent' && 'id' in value) {
1670
- query.parent_id = value.id;
1671
- }
1672
- }
1673
- else if (defined(value)) {
1674
- query[prefix + key] = value;
1675
- }
1676
- }
1677
- }
1678
- return query;
1362
+ /**
1363
+ * Thrown when ...
1364
+ */
1365
+ class ResourceNotFoundError extends NgwError {
1366
+ constructor(obj) {
1367
+ super(obj);
1368
+ this.name = 'ResourceNotFoundError';
1369
+ this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
1370
+ Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
1371
+ }
1679
1372
  }
1680
1373
 
1681
- function resourceCompare(res1, res2) {
1682
- return objectDeepEqual(res1, res2);
1374
+ /**
1375
+ * Thrown when ...
1376
+ */
1377
+ class InsufficientPermissionsError extends NgwError {
1378
+ constructor(obj) {
1379
+ super(obj);
1380
+ this.name = 'InsufficientPermissionsError';
1381
+ this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
1382
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1383
+ }
1384
+ }
1385
+
1386
+ const CONNECTORS = [];
1387
+ function addConnector(connector) {
1388
+ CONNECTORS.push(connector);
1389
+ }
1390
+ function findConnector(options) {
1391
+ return CONNECTORS.find((x) => {
1392
+ if (x.options.baseUrl === options.baseUrl) {
1393
+ if (options.auth) {
1394
+ if (x.options.auth) {
1395
+ return objectDeepEqual(x.options.auth, options.auth);
1396
+ }
1397
+ }
1398
+ else {
1399
+ // if auth not in find options; use first connector with same url
1400
+ return true;
1401
+ }
1402
+ }
1403
+ });
1404
+ }
1405
+ function removeConnector(connector) {
1406
+ const index = CONNECTORS.indexOf(connector);
1407
+ if (index !== -1) {
1408
+ CONNECTORS.splice(index, 1);
1409
+ }
1683
1410
  }
1684
1411
 
1685
- var ResourcesControl = /** @class */ (function () {
1686
- function ResourcesControl(connector) {
1687
- this.connector = connector;
1688
- this.cache = new Cache();
1689
- }
1690
- // -------------------------------------------------------------------------
1691
- // Resource Methods
1692
- // -------------------------------------------------------------------------
1693
- /**
1694
- * Receive resource from NGW by id, keyname or search-object parameter.
1695
- * @param resource - Resource id, keyname or search-object
1696
- *
1697
- * @remarks
1698
- * Fetching resource would be cached to speed up next call
1699
- */
1700
- ResourcesControl.prototype.getOne = function (resource, requestOptions) {
1701
- var _this = this;
1702
- var cache = new Cache();
1703
- var forCache = {};
1704
- var opt = __assign(__assign({}, requestOptions), { cache: false });
1705
- if (typeof resource === 'string') {
1706
- forCache.keyname = resource;
1707
- }
1708
- else if (typeof resource === 'number') {
1709
- forCache.id = resource;
1710
- }
1711
- else if (isObject(resource)) {
1712
- if (resource.id !== undefined) {
1713
- forCache.id = resource.id;
1714
- }
1715
- else if (resource.keyname) {
1716
- forCache.keyname = resource.keyname;
1717
- }
1718
- }
1719
- var makeRequest = function () {
1720
- if (typeof resource === 'string') {
1721
- return _this._fetchResourceBy({ keyname: resource }, opt);
1722
- }
1723
- else if (typeof resource === 'number') {
1724
- return _this._fetchResourceById(resource, opt);
1725
- }
1726
- else if (isObject(resource)) {
1727
- return _this._fetchResourceBy(resource, opt);
1728
- }
1729
- return CancelablePromise.resolve(undefined);
1730
- };
1731
- return cache.addFull('resource', makeRequest, forCache);
1732
- };
1733
- ResourcesControl.prototype.getOneOrFail = function (resource, requestOptions) {
1734
- return this.getOne(resource, requestOptions).then(function (res) {
1735
- if (res) {
1736
- return res;
1737
- }
1738
- throw new ResourceNotFoundError();
1739
- });
1740
- };
1741
- /**
1742
- * A fast way to retrieve resource ID for any resource definition.
1743
- * @param resource - Any available resource definition
1744
- *
1745
- * @remarks
1746
- * There are situations when exactly the resource id is needed
1747
- * (for example, to compose the correct request to the api)
1748
- * then this method will come in handy to facilitate the extraction of the identifier
1749
- * if the resource is specified through a keyname or other parameters.
1750
- */
1751
- ResourcesControl.prototype.getId = function (resource, requestOptions) {
1752
- if (typeof resource === 'number') {
1753
- return CancelablePromise.resolve(resource);
1754
- }
1755
- else if (typeof resource === 'string' || isObject(resource)) {
1756
- return this.getOne(resource, requestOptions).then(function (res) {
1757
- if (res) {
1758
- return res.resource.id;
1759
- }
1760
- });
1761
- }
1762
- return CancelablePromise.resolve(undefined);
1763
- };
1764
- /**
1765
- * A fast way to retrieve resource ID for any resource definition.
1766
- * @param resource - Any available resource definition
1767
- *
1768
- * @remarks
1769
- * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1770
- * To not make one more checks if the resource is definitely exists
1771
- */
1772
- ResourcesControl.prototype.getIdOrFail = function (resource, requestOptions) {
1773
- return this.getId(resource, requestOptions).then(function (resp) {
1774
- if (resp === undefined) {
1775
- throw new Error();
1776
- }
1777
- return resp;
1778
- });
1779
- };
1780
- ResourcesControl.prototype.getMany = function (resource, requestOptions) {
1781
- var _this = this;
1782
- return this._resourceCacheFilter(resource).then(function (items) {
1783
- if (!items.length) {
1784
- var query = {};
1785
- if (resource.keyname) {
1786
- query.keyname = resource.keyname;
1787
- }
1788
- else {
1789
- Object.assign(query, resourceToQuery(resource));
1790
- }
1791
- return _this.connector
1792
- .get('resource.search', requestOptions, __assign({ serialization: 'full' }, query))
1793
- .then(function (resources) {
1794
- if (resources) {
1795
- for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) {
1796
- var x = resources_1[_i];
1797
- _this.cache.add('resource.item', CancelablePromise.resolve(x), {
1798
- id: x.resource.id,
1799
- });
1800
- }
1801
- }
1802
- return resources;
1803
- });
1804
- }
1805
- return items;
1806
- });
1807
- };
1808
- ResourcesControl.prototype.getParent = function (resource, requestOptions) {
1809
- var _this = this;
1810
- return this.getOne(resource, requestOptions).then(function (child) {
1811
- if (child) {
1812
- return _this.getOne(child.resource.parent.id, requestOptions);
1813
- }
1814
- return CancelablePromise.resolve(undefined);
1815
- });
1816
- };
1817
- ResourcesControl.prototype.getChildrenOf = function (resource, requestOptions) {
1818
- var _this = this;
1819
- return this.getIdOrFail(resource).then(function (parent) {
1820
- return _this._getChildrenOf(parent, requestOptions);
1821
- });
1822
- };
1823
- ResourcesControl.prototype.update = function (resource, data) {
1824
- var _this = this;
1825
- return this.getId(resource).then(function (id) {
1826
- if (id !== undefined) {
1827
- return _this.connector.put('resource.item', { data: data }, { id: id });
1828
- }
1829
- });
1830
- };
1831
- /**
1832
- * Fast way to delete resource from NGW and clean cache.
1833
- * @param resource - Resource definition
1834
- */
1835
- ResourcesControl.prototype.delete = function (resource) {
1836
- var _this = this;
1837
- return this.getId(resource).then(function (id) {
1838
- if (id !== undefined) {
1839
- return _this.connector.delete('resource.item', null, { id: id }).then(function () {
1840
- _this._cleanResourceItemCache(id);
1841
- return undefined;
1842
- });
1843
- }
1844
- });
1845
- };
1846
- ResourcesControl.prototype._getChildrenOf = function (parent, requestOptions, _items) {
1847
- var _this = this;
1848
- if (_items === void 0) { _items = []; }
1849
- return this.connector
1850
- .get('resource.collection', __assign({ cache: true }, requestOptions), {
1851
- parent: parent,
1852
- })
1853
- .then(function (items) {
1854
- var recursivePromises = [];
1855
- for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
1856
- var item = items_1[_i];
1857
- _this.cache.add('resource.item', CancelablePromise.resolve(item), {
1858
- id: item.resource.id,
1859
- });
1860
- _items.push(item);
1861
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
1862
- recursivePromises.push(_this._getChildrenOf(item.resource.id, requestOptions, _items));
1863
- }
1864
- }
1865
- if (recursivePromises.length) {
1866
- return CancelablePromise.all(recursivePromises).then(function () {
1867
- return _items;
1868
- });
1869
- }
1870
- return _items;
1871
- });
1872
- };
1873
- ResourcesControl.prototype._cleanResourceItemCache = function (id) {
1874
- return __awaiter(this, void 0, void 0, function () {
1875
- var all, toDelete, _i, all_1, c, cid, rid, _a, toDelete_1, d;
1876
- return __generator(this, function (_b) {
1877
- switch (_b.label) {
1878
- case 0:
1879
- all = this.cache.all();
1880
- toDelete = [];
1881
- _i = 0, all_1 = all;
1882
- _b.label = 1;
1883
- case 1:
1884
- if (!(_i < all_1.length)) return [3 /*break*/, 5];
1885
- c = all_1[_i];
1886
- cid = c.options && c.options.id;
1887
- if (!(['resource.item', 'resource'].includes(c.key) && cid !== undefined)) return [3 /*break*/, 4];
1888
- if (!(typeof cid === 'number')) return [3 /*break*/, 2];
1889
- if (cid === id) {
1890
- toDelete.push(c);
1891
- }
1892
- return [3 /*break*/, 4];
1893
- case 2: return [4 /*yield*/, this.getId(cid)];
1894
- case 3:
1895
- rid = _b.sent();
1896
- if (rid === id) {
1897
- toDelete.push(c);
1898
- }
1899
- _b.label = 4;
1900
- case 4:
1901
- _i++;
1902
- return [3 /*break*/, 1];
1903
- case 5:
1904
- for (_a = 0, toDelete_1 = toDelete; _a < toDelete_1.length; _a++) {
1905
- d = toDelete_1[_a];
1906
- this.cache.delete(d);
1907
- }
1908
- return [2 /*return*/];
1909
- }
1910
- });
1911
- });
1912
- };
1913
- ResourcesControl.prototype._fetchResourceById = function (id, requestOptions) {
1914
- var _this = this;
1915
- var promise = function () {
1916
- return _this.connector.get('resource.item', requestOptions, { id: id });
1917
- };
1918
- return this.cache
1919
- .add('resource.item', promise, {
1920
- id: id,
1921
- })
1922
- .catch(function (er) {
1923
- if (!(er instanceof ResourceNotFoundError)) {
1924
- throw er;
1925
- }
1926
- return undefined;
1927
- });
1928
- };
1929
- ResourcesControl.prototype._fetchResourceBy = function (resource, requestOptions) {
1930
- return this.getMany(resource, requestOptions).then(function (resources) {
1931
- return resources[0];
1932
- });
1933
- };
1934
- ResourcesControl.prototype._resourceCacheFilter = function (resource) {
1935
- return CancelablePromise.all(this.cache.matchAll('resource.item')).then(function (resources) {
1936
- var items = [];
1937
- resources.filter(function (x) {
1938
- if (x) {
1939
- // identical by uniq props
1940
- if (resource.keyname && x.resource.keyname) {
1941
- return resource.keyname === x.resource.keyname;
1942
- }
1943
- if (defined(resource.id) && defined(x.resource.id)) {
1944
- return resource.id === x.resource.id;
1945
- }
1946
- return resourceCompare(resource, x.resource);
1947
- }
1948
- });
1949
- return items;
1950
- });
1951
- };
1952
- return ResourcesControl;
1953
- }());
1954
-
1955
- var ID = 0;
1956
- var NgwConnector$1 = /** @class */ (function () {
1957
- function NgwConnector(options) {
1958
- this.options = options;
1959
- this.id = ID++;
1960
- this.emitter = new events.exports.EventEmitter();
1961
- this.routeStr = '/api/component/pyramid/route';
1962
- this.activeRequests = [];
1963
- var exist = findConnector(options);
1964
- if (exist) {
1965
- return exist;
1966
- }
1967
- else {
1968
- if (this.options.route) {
1969
- this.routeStr = this.options.route;
1970
- }
1971
- if (this.options.requestTransform) {
1972
- this.requestTransform = this.options.requestTransform;
1973
- }
1974
- this.resources = new ResourcesControl(this);
1975
- addConnector(this);
1976
- }
1977
- }
1978
- NgwConnector.create = function (options) {
1979
- return new this(options);
1980
- };
1981
- NgwConnector.prototype.setRequestTransform = function (requestTransform) {
1982
- this.requestTransform = requestTransform;
1983
- };
1984
- /**
1985
- * Fast way to specify the connection address to NextGIS Web.
1986
- * The current connection will be severed.
1987
- * @param baseUrl - NGW url
1988
- */
1989
- NgwConnector.prototype.setNgw = function (baseUrl) {
1990
- this.logout();
1991
- this.options.baseUrl = baseUrl;
1992
- addConnector(this);
1993
- };
1994
- /**
1995
- * Establishing a connection with NextGIS Web to fulfill all other requests.
1996
- * @remarks
1997
- * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1998
- * Can be used to check connection.
1999
- * @example
2000
- * ```javascript
2001
- * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
2002
- * connector.connect()
2003
- * .then(() => console.log('Ok'))
2004
- * .catch((er) => console.log('Connection problem', er));
2005
- * ```
2006
- */
2007
- NgwConnector.prototype.connect = function () {
2008
- var _this = this;
2009
- var cache = new Cache();
2010
- var auth = this.options.auth;
2011
- var makeConnect = function () {
2012
- return new CancelablePromise(function (resolve, reject) {
2013
- var makeQuery = function () {
2014
- return _this.makeQuery(_this.routeStr, {}, {})
2015
- .then(function (route) {
2016
- resolve(route);
2017
- })
2018
- .catch(function (er) {
2019
- reject(er);
2020
- });
2021
- };
2022
- if (auth) {
2023
- var login = auth.login, password = auth.password;
2024
- if (login && password) {
2025
- return _this._login({ login: login, password: password })
2026
- .then(function () {
2027
- return makeQuery();
2028
- })
2029
- .catch(function (er) { return reject(er); });
2030
- }
2031
- }
2032
- return makeQuery();
2033
- });
2034
- };
2035
- return cache.add('route', makeConnect, {
2036
- id: this.id,
2037
- auth: auth,
2038
- baseUrl: this.options.baseUrl,
2039
- });
2040
- };
2041
- /**
2042
- * Quick way to change NextGIS Web user.
2043
- * @param credentials - New user credentials
2044
- */
2045
- NgwConnector.prototype.login = function (credentials, options) {
2046
- this.logout();
2047
- addConnector(this);
2048
- return this._login(credentials, options);
2049
- };
2050
- /**
2051
- * Disconnecting a user. Aborting all current requests
2052
- */
2053
- NgwConnector.prototype.logout = function () {
2054
- this.abort();
2055
- removeConnector(this);
2056
- this.options.auth = undefined;
2057
- this.user = undefined;
2058
- this.emitter.emit('logout');
2059
- this.resources.cache.clean();
2060
- };
2061
- NgwConnector.prototype.getUserInfo = function (credentials, options) {
2062
- if (this.user && this.user.id) {
2063
- return CancelablePromise.resolve(this.user);
2064
- }
2065
- if (credentials) {
2066
- this.options.auth = credentials;
2067
- }
2068
- var options_ = __assign({ headers: this.getAuthorizationHeaders(credentials) }, options);
2069
- // Do not use apiRequest('auth.current_user') to avoid circular-references
2070
- return this.makeQuery('/api/component/auth/current_user', {}, options_);
2071
- };
2072
- /**
2073
- * Obtaining the required Headers for authentication of requests in the NGW.
2074
- */
2075
- NgwConnector.prototype.getAuthorizationHeaders = function (credentials) {
2076
- var client = this.makeClientId(credentials);
2077
- if (client) {
2078
- return {
2079
- Authorization: 'Basic ' + client,
2080
- };
2081
- }
2082
- };
2083
- NgwConnector.prototype.makeClientId = function (credentials) {
2084
- credentials = credentials || this.options.auth;
2085
- if (credentials) {
2086
- var login = credentials.login, password = credentials.password;
2087
- var str = unescape(encodeURIComponent("".concat(login, ":").concat(password)));
2088
- // @ts-ignore
2089
- {
2090
- return window.btoa(str);
2091
- }
2092
- }
2093
- };
2094
- /** Stop all api requests */
2095
- NgwConnector.prototype.abort = function () {
2096
- for (var _i = 0, _a = this.activeRequests; _i < _a.length; _i++) {
2097
- var req = _a[_i];
2098
- req.cancel();
2099
- }
2100
- this.activeRequests = [];
2101
- };
2102
- NgwConnector.prototype.getActiveApiRequests = function () {
2103
- return __spreadArray([], this.activeRequests, true);
2104
- };
2105
- /**
2106
- * Send request to NGW api router.
2107
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2108
- * @param params - Request item params or query params
2109
- * @param requestOptions - Request options
2110
- *
2111
- * @example
2112
- * ```javascript
2113
- *
2114
- * // there is such an NGW route item
2115
- * // "feature_layer.feature.item": [
2116
- * // "/api/resource/{0}/feature/{1}",
2117
- * // "id",
2118
- * // "fid"
2119
- * // ],
2120
- *
2121
- * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
2122
- * connector.apiRequest('feature_layer.feature.item', {
2123
- * // request params for {0} and {1}
2124
- * 'id': 2011,
2125
- * 'fid': 101,
2126
- * // query params
2127
- * 'srs': 4326,
2128
- * 'geom_format': 'geojson',
2129
- * }, { method: 'GET' });
2130
- * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
2131
- *
2132
- * ```
2133
- */
2134
- NgwConnector.prototype.apiRequest = function (name, params_, requestOptions) {
2135
- var _this = this;
2136
- var _a;
2137
- if (params_ === void 0) { params_ = {}; }
2138
- if (requestOptions === void 0) { requestOptions = {}; }
2139
- var method = requestOptions.method, headers = requestOptions.headers, withCredentials = requestOptions.withCredentials, responseType = requestOptions.responseType;
2140
- var params = objectRemoveEmpty(params_);
2141
- var makeApiRequest = function () {
2142
- return apiRequest({ name: name, params: params, requestOptions: requestOptions, connector: _this });
2143
- };
2144
- if (requestOptions.cache && method === 'GET') {
2145
- var cache = new Cache();
2146
- return cache.add(name, makeApiRequest, __assign({ params: params }, objectRemoveEmpty({
2147
- headers: headers,
2148
- withCredentials: withCredentials,
2149
- responseType: responseType,
2150
- baseUrl: this.options.baseUrl,
2151
- userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
2152
- })));
2153
- }
2154
- return makeApiRequest();
2155
- };
2156
- /**
2157
- * Shortcut method for send POST request to NGW.
2158
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2159
- * @param options - Request options
2160
- * @param params - Request item params or query params
2161
- *
2162
- * @example
2163
- * ```javascript
2164
- * connector.post('resource.collection', { data: POST_PAYLOAD })
2165
- * .then((newResource) => console.log(newResource))
2166
- * .catch((error) => console.warn(error));
2167
- * ```
2168
- */
2169
- NgwConnector.prototype.post = function (name, options, params) {
2170
- options = options || {};
2171
- options.method = 'POST';
2172
- return this.apiRequest(name, params, options);
2173
- };
2174
- /**
2175
- * Shortcut method for send GET request to NGW.
2176
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2177
- * @param options - Request options
2178
- * @param params - Request item params or query params
2179
- */
2180
- NgwConnector.prototype.get = function (name, options, params) {
2181
- options = options || {};
2182
- options.method = 'GET';
2183
- return this.apiRequest(name, params, options);
2184
- };
2185
- /**
2186
- * Shortcut method for send PATCH request to NGW.
2187
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2188
- * @param options - Request options
2189
- * @param params - Request item params or query params
2190
- */
2191
- NgwConnector.prototype.patch = function (name, options, params) {
2192
- options = options || {};
2193
- options.method = 'PATCH';
2194
- return this.apiRequest(name, params, options);
2195
- };
2196
- /**
2197
- * Shortcut method for send PUT request to NGW.
2198
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2199
- * @param options - Request options
2200
- * @param params - Request item params or query params
2201
- */
2202
- NgwConnector.prototype.put = function (name, options, params) {
2203
- options = options || {};
2204
- options.method = 'PUT';
2205
- return this.apiRequest(name, params, options);
2206
- };
2207
- /**
2208
- * Shortcut method for send DELETE request to NGW.
2209
- * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2210
- * @param options - Request options
2211
- * @param params - Request item params or query params
2212
- */
2213
- NgwConnector.prototype.delete = function (name, options, params) {
2214
- options = options || {};
2215
- options.method = 'DELETE';
2216
- return this.apiRequest(name, params, options);
2217
- };
2218
- /**
2219
- * Send request to NGW.
2220
- * @param url - URL address to NGW
2221
- * @param params - Query params
2222
- * @param options - Request options
2223
- */
2224
- NgwConnector.prototype.makeQuery = function (url, params, options) {
2225
- if (options === void 0) { options = {}; }
2226
- url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
2227
- if (url) {
2228
- if (params) {
2229
- url = template(url, params);
2230
- }
2231
- url = encodeURI(fixUrlStr(url));
2232
- return this._loadData(url, options);
2233
- }
2234
- else {
2235
- throw new Error('Empty `url` not allowed');
2236
- }
2237
- };
2238
- // -------------------------------------------------------------------------
2239
- // Resource Methods
2240
- // -------------------------------------------------------------------------
2241
- /**
2242
- * {@link ResourcesControl.getOne}
2243
- */
2244
- NgwConnector.prototype.getResource = function (resource, requestOptions) {
2245
- return this.resources.getOne(resource, requestOptions);
2246
- };
2247
- /**
2248
- * {@link ResourcesControl.getOneOrFail}
2249
- */
2250
- NgwConnector.prototype.getResourceOrFail = function (resource, requestOptions) {
2251
- return this.resources.getOneOrFail(resource, requestOptions);
2252
- };
2253
- /**
2254
- * @deprecated - use {@link getResource}
2255
- */
2256
- NgwConnector.prototype.getResourceBy = function (resource) {
2257
- return this.resources.getOne(resource);
2258
- };
2259
- /**
2260
- * @deprecated - use {@link getResource}
2261
- */
2262
- NgwConnector.prototype.getResourceByKeyname = function (keyname) {
2263
- return this.resources.getOne(keyname);
2264
- };
2265
- /**
2266
- * @deprecated - use {@link getResource}
2267
- */
2268
- NgwConnector.prototype.getResourceById = function (id) {
2269
- return this.resources.getOne(id);
2270
- };
2271
- /**
2272
- * {@link ResourcesControl.getId}
2273
- */
2274
- NgwConnector.prototype.getResourceId = function (resource, requestOptions) {
2275
- return this.resources.getId(resource, requestOptions);
2276
- };
2277
- /**
2278
- * {@link ResourcesControl.getIdOrFail}
2279
- */
2280
- NgwConnector.prototype.getResourceIdOrFail = function (resource, requestOptions) {
2281
- return this.resources.getIdOrFail(resource, requestOptions);
2282
- };
2283
- /**
2284
- * {@link ResourcesControl.getMany}
2285
- */
2286
- NgwConnector.prototype.getResourcesBy = function (resource, requestOptions) {
2287
- return this.resources.getMany(resource, requestOptions);
2288
- };
2289
- /**
2290
- * {@link ResourcesControl.getParent}
2291
- */
2292
- NgwConnector.prototype.getResourceParent = function (resource, requestOptions) {
2293
- return this.resources.getParent(resource, requestOptions);
2294
- };
2295
- /**
2296
- * {@link ResourcesControl.getChildrenOf}
2297
- */
2298
- NgwConnector.prototype.getResourceChildren = function (resource, requestOptions) {
2299
- return this.resources.getChildrenOf(resource, requestOptions);
2300
- };
2301
- /**
2302
- * {@link ResourcesControl.update}
2303
- */
2304
- NgwConnector.prototype.updateResource = function (resource, data) {
2305
- return this.resources.update(resource, data);
2306
- };
2307
- /**
2308
- * {@link ResourcesControl.delete}
2309
- */
2310
- NgwConnector.prototype.deleteResource = function (resource) {
2311
- return this.resources.delete(resource);
2312
- };
2313
- /**
2314
- * @internal
2315
- */
2316
- NgwConnector.prototype._loadData = function (url, options) {
2317
- var _this = this;
2318
- options.responseType = options.responseType || 'json';
2319
- var request = new CancelablePromise(function (resolve, reject, onCancel) {
2320
- if (_this.user) {
2321
- options = options || {};
2322
- // options.withCredentials = true;
2323
- options.headers = __assign(__assign({}, _this.getAuthorizationHeaders()), options.headers);
2324
- }
2325
- if (_this.requestTransform) {
2326
- var _a = _this.requestTransform(url, options), transUrl = _a[0], transOptions = _a[1];
2327
- url = transUrl;
2328
- options = transOptions;
2329
- }
2330
- loadData(url, resolve, options, reject, onCancel);
2331
- })
2332
- .then(function (resp) {
2333
- _this._cleanActiveRequests(request);
2334
- return resp;
2335
- })
2336
- .catch(function (httpError) {
2337
- _this._cleanActiveRequests(request);
2338
- if (httpError instanceof CancelablePromise.CancelError) ;
2339
- else {
2340
- // @ts-ignore
2341
- {
2342
- console.warn('DEV WARN', httpError);
2343
- }
2344
- var er = _this._handleHttpError(httpError);
2345
- if (er) {
2346
- throw er;
2347
- }
2348
- }
2349
- });
2350
- if (options.signal &&
2351
- typeof options.signal.addEventListener === 'function') {
2352
- options.signal.addEventListener('abort', function () {
2353
- request.cancel();
2354
- _this._cleanActiveRequests(request);
2355
- });
2356
- }
2357
- this.activeRequests.push(request);
2358
- return request;
2359
- };
2360
- NgwConnector.prototype._login = function (credentials, options) {
2361
- var _this = this;
2362
- return this.getUserInfo(credentials, options)
2363
- .then(function (data) {
2364
- _this.user = data;
2365
- _this.emitter.emit('login', data);
2366
- return data;
2367
- })
2368
- .catch(function (er) {
2369
- _this.emitter.emit('login:error', er);
2370
- throw er;
2371
- });
2372
- };
2373
- NgwConnector.prototype._cleanActiveRequests = function (request) {
2374
- var activeRequestIndex = this.activeRequests.indexOf(request);
2375
- if (activeRequestIndex !== -1) {
2376
- this.activeRequests.splice(activeRequestIndex, 1);
2377
- }
2378
- };
2379
- NgwConnector.prototype._handleHttpError = function (er) {
2380
- if (er) {
2381
- if (er instanceof NgwError) {
2382
- if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
2383
- throw new ResourceNotFoundError(er);
2384
- }
2385
- else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
2386
- throw new InsufficientPermissionsError(er);
2387
- }
2388
- }
2389
- }
2390
- return er;
2391
- };
2392
- NgwConnector.errors = {
2393
- NgwError: NgwError,
2394
- ResourceNotFoundError: ResourceNotFoundError,
2395
- };
2396
- return NgwConnector;
2397
- }());
2398
-
2399
- /**
2400
- * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
2401
- *
2402
- * @remarks
2403
- * Make sure CORS is registered in the {@link https://docs.nextgis.com/docs_ngcom/source/CORS.html | NextGIS Web settings } to be able to send requests.
2404
- *
2405
- * @packageDocumentation
2406
- * @module ngw-connector
2407
- */
1412
+ const exclude = ['description'];
1413
+ /**
1414
+ * @remarks
1415
+ * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
1416
+ *
1417
+ * ```
1418
+ * { keyname, owner_user: { id }} > { keyname, owner_user__id }
1419
+ * ```
1420
+ *
1421
+ * @param resource - Any property from NGW resource item
1422
+ */
1423
+ function resourceToQuery(resource, prefix = '') {
1424
+ prefix = prefix ? prefix + '__' : '';
1425
+ const query = {};
1426
+ for (const [key, value] of Object.entries(resource)) {
1427
+ if (exclude.indexOf(key) === -1) {
1428
+ if (isObject(value)) {
1429
+ if (key === 'owner_user') {
1430
+ const children = resourceToQuery(value, key);
1431
+ Object.assign(query, children);
1432
+ }
1433
+ else if (key === 'parent' && 'id' in value) {
1434
+ query.parent_id = value.id;
1435
+ }
1436
+ }
1437
+ else if (defined(value)) {
1438
+ query[prefix + key] = value;
1439
+ }
1440
+ }
1441
+ }
1442
+ return query;
1443
+ }
1444
+
1445
+ function resourceCompare(res1, res2) {
1446
+ return objectDeepEqual(res1, res2);
1447
+ }
1448
+
1449
+ class ResourcesControl {
1450
+ constructor(connector) {
1451
+ this.connector = connector;
1452
+ this.cache = new Cache();
1453
+ }
1454
+ // -------------------------------------------------------------------------
1455
+ // Resource Methods
1456
+ // -------------------------------------------------------------------------
1457
+ /**
1458
+ * Receive resource from NGW by id, keyname or search-object parameter.
1459
+ * @param resource - Resource id, keyname or search-object
1460
+ *
1461
+ * @remarks
1462
+ * Fetching resource would be cached to speed up next call
1463
+ */
1464
+ getOne(resource, requestOptions) {
1465
+ const cache = new Cache();
1466
+ const forCache = {};
1467
+ const opt = { ...requestOptions, cache: false };
1468
+ if (typeof resource === 'string') {
1469
+ forCache.keyname = resource;
1470
+ }
1471
+ else if (typeof resource === 'number') {
1472
+ forCache.id = resource;
1473
+ }
1474
+ else if (isObject(resource)) {
1475
+ if (resource.id !== undefined) {
1476
+ forCache.id = resource.id;
1477
+ }
1478
+ else if (resource.keyname) {
1479
+ forCache.keyname = resource.keyname;
1480
+ }
1481
+ }
1482
+ const makeRequest = () => {
1483
+ if (typeof resource === 'string') {
1484
+ return this._fetchResourceBy({ keyname: resource }, opt);
1485
+ }
1486
+ else if (typeof resource === 'number') {
1487
+ return this._fetchResourceById(resource, opt);
1488
+ }
1489
+ else if (isObject(resource)) {
1490
+ return this._fetchResourceBy(resource, opt);
1491
+ }
1492
+ return CancelablePromise.resolve(undefined);
1493
+ };
1494
+ return cache.addFull('resource', makeRequest, forCache);
1495
+ }
1496
+ getOneOrFail(resource, requestOptions) {
1497
+ return this.getOne(resource, requestOptions).then((res) => {
1498
+ if (res) {
1499
+ return res;
1500
+ }
1501
+ throw new ResourceNotFoundError();
1502
+ });
1503
+ }
1504
+ /**
1505
+ * A fast way to retrieve resource ID for any resource definition.
1506
+ * @param resource - Any available resource definition
1507
+ *
1508
+ * @remarks
1509
+ * There are situations when exactly the resource id is needed
1510
+ * (for example, to compose the correct request to the api)
1511
+ * then this method will come in handy to facilitate the extraction of the identifier
1512
+ * if the resource is specified through a keyname or other parameters.
1513
+ */
1514
+ getId(resource, requestOptions) {
1515
+ if (typeof resource === 'number') {
1516
+ return CancelablePromise.resolve(resource);
1517
+ }
1518
+ else if (typeof resource === 'string' || isObject(resource)) {
1519
+ return this.getOne(resource, requestOptions).then((res) => {
1520
+ if (res) {
1521
+ return res.resource.id;
1522
+ }
1523
+ });
1524
+ }
1525
+ return CancelablePromise.resolve(undefined);
1526
+ }
1527
+ /**
1528
+ * A fast way to retrieve resource ID for any resource definition.
1529
+ * @param resource - Any available resource definition
1530
+ *
1531
+ * @remarks
1532
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1533
+ * To not make one more checks if the resource is definitely exists
1534
+ */
1535
+ getIdOrFail(resource, requestOptions) {
1536
+ return this.getId(resource, requestOptions).then((resp) => {
1537
+ if (resp === undefined) {
1538
+ throw new Error();
1539
+ }
1540
+ return resp;
1541
+ });
1542
+ }
1543
+ getMany(resource, requestOptions) {
1544
+ return this._resourceCacheFilter(resource).then((items) => {
1545
+ if (!items.length) {
1546
+ const query = {};
1547
+ if (resource.keyname) {
1548
+ query.keyname = resource.keyname;
1549
+ }
1550
+ else {
1551
+ Object.assign(query, resourceToQuery(resource));
1552
+ }
1553
+ return this.connector
1554
+ .get('resource.search', requestOptions, {
1555
+ serialization: 'full',
1556
+ ...query,
1557
+ })
1558
+ .then((resources) => {
1559
+ if (resources) {
1560
+ for (const x of resources) {
1561
+ this.cache.add('resource.item', CancelablePromise.resolve(x), {
1562
+ id: x.resource.id,
1563
+ });
1564
+ }
1565
+ }
1566
+ return resources;
1567
+ });
1568
+ }
1569
+ return items;
1570
+ });
1571
+ }
1572
+ getParent(resource, requestOptions) {
1573
+ return this.getOne(resource, requestOptions).then((child) => {
1574
+ if (child) {
1575
+ return this.getOne(child.resource.parent.id, requestOptions);
1576
+ }
1577
+ return CancelablePromise.resolve(undefined);
1578
+ });
1579
+ }
1580
+ getChildrenOf(resource, requestOptions) {
1581
+ return this.getIdOrFail(resource).then((parent) => this._getChildrenOf(parent, requestOptions));
1582
+ }
1583
+ update(resource, data) {
1584
+ return this.getId(resource).then((id) => {
1585
+ if (id !== undefined) {
1586
+ return this.connector.put('resource.item', { data }, { id });
1587
+ }
1588
+ });
1589
+ }
1590
+ /**
1591
+ * Fast way to delete resource from NGW and clean cache.
1592
+ * @param resource - Resource definition
1593
+ */
1594
+ delete(resource) {
1595
+ return this.getId(resource).then((id) => {
1596
+ if (id !== undefined) {
1597
+ return this.connector.delete('resource.item', null, { id }).then(() => {
1598
+ this._cleanResourceItemCache(id);
1599
+ return undefined;
1600
+ });
1601
+ }
1602
+ });
1603
+ }
1604
+ _getChildrenOf(parent, requestOptions, _items = []) {
1605
+ return this.connector
1606
+ .get('resource.collection', { cache: true, ...requestOptions }, {
1607
+ parent,
1608
+ })
1609
+ .then((items) => {
1610
+ const recursivePromises = [];
1611
+ for (const item of items) {
1612
+ this.cache.add('resource.item', CancelablePromise.resolve(item), {
1613
+ id: item.resource.id,
1614
+ });
1615
+ _items.push(item);
1616
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
1617
+ recursivePromises.push(this._getChildrenOf(item.resource.id, requestOptions, _items));
1618
+ }
1619
+ }
1620
+ if (recursivePromises.length) {
1621
+ return CancelablePromise.all(recursivePromises).then(() => {
1622
+ return _items;
1623
+ });
1624
+ }
1625
+ return _items;
1626
+ });
1627
+ }
1628
+ async _cleanResourceItemCache(id) {
1629
+ const all = this.cache.all();
1630
+ const toDelete = [];
1631
+ for (const c of all) {
1632
+ const cid = c.options && c.options.id;
1633
+ if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {
1634
+ if (typeof cid === 'number') {
1635
+ if (cid === id) {
1636
+ toDelete.push(c);
1637
+ }
1638
+ }
1639
+ else {
1640
+ const rid = await this.getId(cid);
1641
+ if (rid === id) {
1642
+ toDelete.push(c);
1643
+ }
1644
+ }
1645
+ }
1646
+ }
1647
+ for (const d of toDelete) {
1648
+ this.cache.delete(d);
1649
+ }
1650
+ }
1651
+ _fetchResourceById(id, requestOptions) {
1652
+ const promise = () => this.connector.get('resource.item', requestOptions, { id });
1653
+ return this.cache
1654
+ .add('resource.item', promise, {
1655
+ id,
1656
+ })
1657
+ .catch((er) => {
1658
+ if (!(er instanceof ResourceNotFoundError)) {
1659
+ throw er;
1660
+ }
1661
+ return undefined;
1662
+ });
1663
+ }
1664
+ _fetchResourceBy(resource, requestOptions) {
1665
+ return this.getMany(resource, requestOptions).then((resources) => {
1666
+ return resources[0];
1667
+ });
1668
+ }
1669
+ _resourceCacheFilter(resource) {
1670
+ return CancelablePromise.all(this.cache.matchAll('resource.item')).then((resources) => {
1671
+ const items = [];
1672
+ resources.filter((x) => {
1673
+ if (x) {
1674
+ // identical by uniq props
1675
+ if (resource.keyname && x.resource.keyname) {
1676
+ return resource.keyname === x.resource.keyname;
1677
+ }
1678
+ if (defined(resource.id) && defined(x.resource.id)) {
1679
+ return resource.id === x.resource.id;
1680
+ }
1681
+ return resourceCompare(resource, x.resource);
1682
+ }
1683
+ });
1684
+ return items;
1685
+ });
1686
+ }
1687
+ }
1688
+
1689
+ let ID = 0;
1690
+ class NgwConnector$1 {
1691
+ constructor(options) {
1692
+ this.options = options;
1693
+ this.id = ID++;
1694
+ this.emitter = new events.exports.EventEmitter();
1695
+ this.routeStr = '/api/component/pyramid/route';
1696
+ this.activeRequests = [];
1697
+ const exist = findConnector(options);
1698
+ if (exist) {
1699
+ return exist;
1700
+ }
1701
+ else {
1702
+ if (this.options.route) {
1703
+ this.routeStr = this.options.route;
1704
+ }
1705
+ if (this.options.requestTransform) {
1706
+ this.requestTransform = this.options.requestTransform;
1707
+ }
1708
+ this.resources = new ResourcesControl(this);
1709
+ addConnector(this);
1710
+ }
1711
+ }
1712
+ static create(options) {
1713
+ return new this(options);
1714
+ }
1715
+ setRequestTransform(requestTransform) {
1716
+ this.requestTransform = requestTransform;
1717
+ }
1718
+ /**
1719
+ * Fast way to specify the connection address to NextGIS Web.
1720
+ * The current connection will be severed.
1721
+ * @param baseUrl - NGW url
1722
+ */
1723
+ setNgw(baseUrl) {
1724
+ this.logout();
1725
+ this.options.baseUrl = baseUrl;
1726
+ addConnector(this);
1727
+ }
1728
+ /**
1729
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
1730
+ * @remarks
1731
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1732
+ * Can be used to check connection.
1733
+ * @example
1734
+ * ```javascript
1735
+ * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1736
+ * connector.connect()
1737
+ * .then(() => console.log('Ok'))
1738
+ * .catch((er) => console.log('Connection problem', er));
1739
+ * ```
1740
+ */
1741
+ connect() {
1742
+ const cache = new Cache();
1743
+ const auth = this.options.auth;
1744
+ const makeConnect = () => new CancelablePromise((resolve, reject) => {
1745
+ const makeQuery = () => {
1746
+ return this.makeQuery(this.routeStr, {}, {})
1747
+ .then((route) => {
1748
+ resolve(route);
1749
+ })
1750
+ .catch((er) => {
1751
+ reject(er);
1752
+ });
1753
+ };
1754
+ if (auth) {
1755
+ const { login, password } = auth;
1756
+ if (login && password) {
1757
+ return this._login({ login, password })
1758
+ .then(() => {
1759
+ return makeQuery();
1760
+ })
1761
+ .catch((er) => reject(er));
1762
+ }
1763
+ }
1764
+ return makeQuery();
1765
+ });
1766
+ return cache.add('route', makeConnect, {
1767
+ id: this.id,
1768
+ auth,
1769
+ baseUrl: this.options.baseUrl,
1770
+ });
1771
+ }
1772
+ /**
1773
+ * Quick way to change NextGIS Web user.
1774
+ * @param credentials - New user credentials
1775
+ */
1776
+ login(credentials, options) {
1777
+ this.logout();
1778
+ addConnector(this);
1779
+ return this._login(credentials, options);
1780
+ }
1781
+ /**
1782
+ * Disconnecting a user. Aborting all current requests
1783
+ */
1784
+ logout() {
1785
+ this.abort();
1786
+ removeConnector(this);
1787
+ this.options.auth = undefined;
1788
+ this.user = undefined;
1789
+ this.emitter.emit('logout');
1790
+ this.resources.cache.clean();
1791
+ }
1792
+ getUserInfo(credentials, options) {
1793
+ if (this.user && this.user.id) {
1794
+ return CancelablePromise.resolve(this.user);
1795
+ }
1796
+ if (credentials) {
1797
+ this.options.auth = credentials;
1798
+ }
1799
+ const options_ = {
1800
+ headers: this.getAuthorizationHeaders(credentials),
1801
+ // withCredentials: true
1802
+ ...options,
1803
+ };
1804
+ // Do not use apiRequest('auth.current_user') to avoid circular-references
1805
+ return this.makeQuery('/api/component/auth/current_user', {}, options_);
1806
+ }
1807
+ /**
1808
+ * Obtaining the required Headers for authentication of requests in the NGW.
1809
+ */
1810
+ getAuthorizationHeaders(credentials) {
1811
+ const client = this.makeClientId(credentials);
1812
+ if (client) {
1813
+ return {
1814
+ Authorization: 'Basic ' + client,
1815
+ };
1816
+ }
1817
+ }
1818
+ makeClientId(credentials) {
1819
+ credentials = credentials || this.options.auth;
1820
+ if (credentials) {
1821
+ const { login, password } = credentials;
1822
+ const str = unescape(encodeURIComponent(`${login}:${password}`));
1823
+ // @ts-ignore
1824
+ {
1825
+ return window.btoa(str);
1826
+ }
1827
+ }
1828
+ }
1829
+ /** Stop all api requests */
1830
+ abort() {
1831
+ for (const req of this.activeRequests) {
1832
+ req.cancel();
1833
+ }
1834
+ this.activeRequests = [];
1835
+ }
1836
+ getActiveApiRequests() {
1837
+ return [...this.activeRequests];
1838
+ }
1839
+ /**
1840
+ * Send request to NGW api router.
1841
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1842
+ * @param params - Request item params or query params
1843
+ * @param requestOptions - Request options
1844
+ *
1845
+ * @example
1846
+ * ```javascript
1847
+ *
1848
+ * // there is such an NGW route item
1849
+ * // "feature_layer.feature.item": [
1850
+ * // "/api/resource/{0}/feature/{1}",
1851
+ * // "id",
1852
+ * // "fid"
1853
+ * // ],
1854
+ *
1855
+ * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
1856
+ * connector.apiRequest('feature_layer.feature.item', {
1857
+ * // request params for {0} and {1}
1858
+ * 'id': 2011,
1859
+ * 'fid': 101,
1860
+ * // query params
1861
+ * 'srs': 4326,
1862
+ * 'geom_format': 'geojson',
1863
+ * }, { method: 'GET' });
1864
+ * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
1865
+ *
1866
+ * ```
1867
+ */
1868
+ apiRequest(name, params_ = {}, requestOptions = {}) {
1869
+ var _a;
1870
+ const { method, headers, withCredentials, responseType } = requestOptions;
1871
+ const params = objectRemoveEmpty(params_);
1872
+ const makeApiRequest = () => apiRequest({ name, params, requestOptions, connector: this });
1873
+ if (requestOptions.cache && method === 'GET') {
1874
+ const cache = new Cache();
1875
+ return cache.add(name, makeApiRequest, {
1876
+ params,
1877
+ ...objectRemoveEmpty({
1878
+ headers,
1879
+ withCredentials,
1880
+ responseType,
1881
+ baseUrl: this.options.baseUrl,
1882
+ userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
1883
+ }),
1884
+ });
1885
+ }
1886
+ return makeApiRequest();
1887
+ }
1888
+ /**
1889
+ * Shortcut method for send POST request to NGW.
1890
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1891
+ * @param options - Request options
1892
+ * @param params - Request item params or query params
1893
+ *
1894
+ * @example
1895
+ * ```javascript
1896
+ * connector.post('resource.collection', { data: POST_PAYLOAD })
1897
+ * .then((newResource) => console.log(newResource))
1898
+ * .catch((error) => console.warn(error));
1899
+ * ```
1900
+ */
1901
+ post(name, options, params) {
1902
+ options = options || {};
1903
+ options.method = 'POST';
1904
+ return this.apiRequest(name, params, options);
1905
+ }
1906
+ /**
1907
+ * Shortcut method for send GET request to NGW.
1908
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1909
+ * @param options - Request options
1910
+ * @param params - Request item params or query params
1911
+ */
1912
+ get(name, options, params) {
1913
+ options = options || {};
1914
+ options.method = 'GET';
1915
+ return this.apiRequest(name, params, options);
1916
+ }
1917
+ /**
1918
+ * Shortcut method for send PATCH request to NGW.
1919
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1920
+ * @param options - Request options
1921
+ * @param params - Request item params or query params
1922
+ */
1923
+ patch(name, options, params) {
1924
+ options = options || {};
1925
+ options.method = 'PATCH';
1926
+ return this.apiRequest(name, params, options);
1927
+ }
1928
+ /**
1929
+ * Shortcut method for send PUT request to NGW.
1930
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1931
+ * @param options - Request options
1932
+ * @param params - Request item params or query params
1933
+ */
1934
+ put(name, options, params) {
1935
+ options = options || {};
1936
+ options.method = 'PUT';
1937
+ return this.apiRequest(name, params, options);
1938
+ }
1939
+ /**
1940
+ * Shortcut method for send DELETE request to NGW.
1941
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1942
+ * @param options - Request options
1943
+ * @param params - Request item params or query params
1944
+ */
1945
+ delete(name, options, params) {
1946
+ options = options || {};
1947
+ options.method = 'DELETE';
1948
+ return this.apiRequest(name, params, options);
1949
+ }
1950
+ /**
1951
+ * Send request to NGW.
1952
+ * @param url - URL address to NGW
1953
+ * @param params - Query params
1954
+ * @param options - Request options
1955
+ */
1956
+ makeQuery(url, params, options = {}) {
1957
+ url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
1958
+ if (url) {
1959
+ if (params) {
1960
+ url = template(url, params);
1961
+ }
1962
+ url = encodeURI(fixUrlStr(url));
1963
+ return this._loadData(url, options);
1964
+ }
1965
+ else {
1966
+ throw new Error('Empty `url` not allowed');
1967
+ }
1968
+ }
1969
+ // -------------------------------------------------------------------------
1970
+ // Resource Methods
1971
+ // -------------------------------------------------------------------------
1972
+ /**
1973
+ * {@link ResourcesControl.getOne}
1974
+ */
1975
+ getResource(resource, requestOptions) {
1976
+ return this.resources.getOne(resource, requestOptions);
1977
+ }
1978
+ /**
1979
+ * {@link ResourcesControl.getOneOrFail}
1980
+ */
1981
+ getResourceOrFail(resource, requestOptions) {
1982
+ return this.resources.getOneOrFail(resource, requestOptions);
1983
+ }
1984
+ /**
1985
+ * @deprecated - use {@link getResource}
1986
+ */
1987
+ getResourceBy(resource) {
1988
+ return this.resources.getOne(resource);
1989
+ }
1990
+ /**
1991
+ * @deprecated - use {@link getResource}
1992
+ */
1993
+ getResourceByKeyname(keyname) {
1994
+ return this.resources.getOne(keyname);
1995
+ }
1996
+ /**
1997
+ * @deprecated - use {@link getResource}
1998
+ */
1999
+ getResourceById(id) {
2000
+ return this.resources.getOne(id);
2001
+ }
2002
+ /**
2003
+ * {@link ResourcesControl.getId}
2004
+ */
2005
+ getResourceId(resource, requestOptions) {
2006
+ return this.resources.getId(resource, requestOptions);
2007
+ }
2008
+ /**
2009
+ * {@link ResourcesControl.getIdOrFail}
2010
+ */
2011
+ getResourceIdOrFail(resource, requestOptions) {
2012
+ return this.resources.getIdOrFail(resource, requestOptions);
2013
+ }
2014
+ /**
2015
+ * {@link ResourcesControl.getMany}
2016
+ */
2017
+ getResourcesBy(resource, requestOptions) {
2018
+ return this.resources.getMany(resource, requestOptions);
2019
+ }
2020
+ /**
2021
+ * {@link ResourcesControl.getParent}
2022
+ */
2023
+ getResourceParent(resource, requestOptions) {
2024
+ return this.resources.getParent(resource, requestOptions);
2025
+ }
2026
+ /**
2027
+ * {@link ResourcesControl.getChildrenOf}
2028
+ */
2029
+ getResourceChildren(resource, requestOptions) {
2030
+ return this.resources.getChildrenOf(resource, requestOptions);
2031
+ }
2032
+ /**
2033
+ * {@link ResourcesControl.update}
2034
+ */
2035
+ updateResource(resource, data) {
2036
+ return this.resources.update(resource, data);
2037
+ }
2038
+ /**
2039
+ * {@link ResourcesControl.delete}
2040
+ */
2041
+ deleteResource(resource) {
2042
+ return this.resources.delete(resource);
2043
+ }
2044
+ /**
2045
+ * @internal
2046
+ */
2047
+ _loadData(url, options) {
2048
+ options.responseType = options.responseType || 'json';
2049
+ const request = new CancelablePromise((resolve, reject, onCancel) => {
2050
+ if (this.user) {
2051
+ options = options || {};
2052
+ // options.withCredentials = true;
2053
+ options.headers = {
2054
+ ...this.getAuthorizationHeaders(),
2055
+ ...options.headers,
2056
+ };
2057
+ }
2058
+ if (this.requestTransform) {
2059
+ const [transUrl, transOptions] = this.requestTransform(url, options);
2060
+ url = transUrl;
2061
+ options = transOptions;
2062
+ }
2063
+ loadData(url, resolve, options, reject, onCancel);
2064
+ })
2065
+ .then((resp) => {
2066
+ this._cleanActiveRequests(request);
2067
+ return resp;
2068
+ })
2069
+ .catch((httpError) => {
2070
+ this._cleanActiveRequests(request);
2071
+ if (httpError instanceof CancelablePromise.CancelError) ;
2072
+ else {
2073
+ // @ts-ignore
2074
+ {
2075
+ console.warn('DEV WARN', httpError);
2076
+ }
2077
+ const er = this._handleHttpError(httpError);
2078
+ if (er) {
2079
+ throw er;
2080
+ }
2081
+ }
2082
+ });
2083
+ if (options.signal &&
2084
+ typeof options.signal.addEventListener === 'function') {
2085
+ options.signal.addEventListener('abort', () => {
2086
+ request.cancel();
2087
+ this._cleanActiveRequests(request);
2088
+ });
2089
+ }
2090
+ this.activeRequests.push(request);
2091
+ return request;
2092
+ }
2093
+ _login(credentials, options) {
2094
+ return this.getUserInfo(credentials, options)
2095
+ .then((data) => {
2096
+ this.user = data;
2097
+ this.emitter.emit('login', data);
2098
+ return data;
2099
+ })
2100
+ .catch((er) => {
2101
+ this.emitter.emit('login:error', er);
2102
+ throw er;
2103
+ });
2104
+ }
2105
+ _cleanActiveRequests(request) {
2106
+ const activeRequestIndex = this.activeRequests.indexOf(request);
2107
+ if (activeRequestIndex !== -1) {
2108
+ this.activeRequests.splice(activeRequestIndex, 1);
2109
+ }
2110
+ }
2111
+ _handleHttpError(er) {
2112
+ if (er) {
2113
+ if (er instanceof NgwError) {
2114
+ if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
2115
+ throw new ResourceNotFoundError(er);
2116
+ }
2117
+ else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
2118
+ throw new InsufficientPermissionsError(er);
2119
+ }
2120
+ }
2121
+ }
2122
+ return er;
2123
+ }
2124
+ }
2125
+ NgwConnector$1.errors = {
2126
+ NgwError,
2127
+ ResourceNotFoundError,
2128
+ };
2129
+
2130
+ /**
2131
+ * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
2132
+ *
2133
+ * @remarks
2134
+ * Make sure CORS is registered in the {@link https://docs.nextgis.com/docs_ngcom/source/CORS.html | NextGIS Web settings } to be able to send requests.
2135
+ *
2136
+ * @packageDocumentation
2137
+ * @module ngw-connector
2138
+ */
2408
2139
  var NgwConnector = NgwConnector$1;
2409
2140
 
2410
- var NgwProvider = /** @class */ (function (_super) {
2411
- __extends(NgwProvider, _super);
2412
- function NgwProvider(options) {
2413
- var _this = _super.call(this, options) || this;
2414
- _this.caseInsensitive = true;
2415
- _this.searchUrl = 'https://maxim.nextgis.com';
2416
- _this.searchResources = [];
2417
- _this.requests = [];
2418
- _this.connector =
2419
- options.connector ||
2420
- new NgwConnector({
2421
- baseUrl: _this.searchUrl,
2422
- });
2423
- _this.searchResources = options.searchResources;
2424
- return _this;
2425
- }
2426
- NgwProvider.prototype.abort = function () {
2427
- this.requests.forEach(function (x) {
2428
- x.cancel();
2429
- });
2430
- this.requests = [];
2431
- };
2432
- NgwProvider.prototype.search = function (like) {
2433
- return __asyncGenerator(this, arguments, function search_1() {
2434
- var _loop_1, this_1, _i, _a, resource;
2435
- var _this = this;
2436
- return __generator(this, function (_b) {
2437
- switch (_b.label) {
2438
- case 0:
2439
- _loop_1 = function (resource) {
2440
- var limit, request, resp, entries, _loop_2, _c, _d, item;
2441
- return __generator(this, function (_e) {
2442
- switch (_e.label) {
2443
- case 0:
2444
- limit = resource.limit || 300;
2445
- request = this_1.connector.get('feature_layer.store', {
2446
- headers: { RANGE: "items=0-".concat(limit) },
2447
- }, {
2448
- id: resource.id,
2449
- like: like,
2450
- });
2451
- this_1.requests.push(request);
2452
- request.catch(function (er) {
2453
- console.warn(er);
2454
- });
2455
- return [4 /*yield*/, __await(request)];
2456
- case 1:
2457
- resp = _e.sent();
2458
- entries = [];
2459
- if (resp) {
2460
- resp.forEach(function (x) {
2461
- entries.push(__assign({ query: like, resourceId: resource.id }, x));
2462
- });
2463
- }
2464
- _loop_2 = function (item) {
2465
- return __generator(this, function (_f) {
2466
- switch (_f.label) {
2467
- case 0:
2468
- item.result = function () { return _this.result(item); };
2469
- return [4 /*yield*/, __await(item)];
2470
- case 1: return [4 /*yield*/, _f.sent()];
2471
- case 2:
2472
- _f.sent();
2473
- return [2 /*return*/];
2474
- }
2475
- });
2476
- };
2477
- _c = 0, _d = this_1._items(entries);
2478
- _e.label = 2;
2479
- case 2:
2480
- if (!(_c < _d.length)) return [3 /*break*/, 5];
2481
- item = _d[_c];
2482
- return [5 /*yield**/, _loop_2(item)];
2483
- case 3:
2484
- _e.sent();
2485
- _e.label = 4;
2486
- case 4:
2487
- _c++;
2488
- return [3 /*break*/, 2];
2489
- case 5: return [2 /*return*/];
2490
- }
2491
- });
2492
- };
2493
- this_1 = this;
2494
- _i = 0, _a = this.searchResources;
2495
- _b.label = 1;
2496
- case 1:
2497
- if (!(_i < _a.length)) return [3 /*break*/, 4];
2498
- resource = _a[_i];
2499
- return [5 /*yield**/, _loop_1(resource)];
2500
- case 2:
2501
- _b.sent();
2502
- _b.label = 3;
2503
- case 3:
2504
- _i++;
2505
- return [3 /*break*/, 1];
2506
- case 4: return [2 /*return*/];
2507
- }
2508
- });
2509
- });
2510
- };
2511
- NgwProvider.prototype.result = function (item) {
2512
- var req = this.connector
2513
- .get('feature_layer.feature.item_extent', null, {
2514
- id: item.resourceId,
2515
- fid: item.featureId,
2516
- })
2517
- .then(function (x) {
2518
- var e = x.extent;
2519
- return {
2520
- text: item.text,
2521
- extent: [e.minLon, e.minLat, e.maxLon, e.maxLat],
2522
- };
2523
- });
2524
- this.requests.push(req);
2525
- return req;
2526
- };
2527
- NgwProvider.prototype._items = function (entries) {
2528
- var _this = this;
2529
- var items = [];
2530
- entries.forEach(function (entry) {
2531
- var meta = _this.searchResources.find(function (x) { return x.id === entry.resourceId; });
2532
- if (meta) {
2533
- items.push({
2534
- query: entry.query,
2535
- text: entry.label,
2536
- featureId: entry.id,
2537
- resourceId: entry.resourceId,
2538
- });
2539
- }
2540
- });
2541
- return items;
2542
- };
2543
- return NgwProvider;
2544
- }(BaseProvider));
2545
-
2546
- var NominatimProvider = /** @class */ (function (_super) {
2547
- __extends(NominatimProvider, _super);
2548
- function NominatimProvider(options) {
2549
- var _this = _super.call(this, options) || this;
2550
- _this.searchUrl = 'https://nominatim.openstreetmap.org';
2551
- _this._requests = [];
2552
- return _this;
2553
- }
2554
- NominatimProvider.prototype.abort = function () {
2555
- this._requests.forEach(function (x) { return x.cancel(); });
2556
- this._requests = [];
2557
- };
2558
- NominatimProvider.prototype.search = function (val) {
2559
- return __asyncGenerator(this, arguments, function search_1() {
2560
- var url, request, items, _loop_1, _i, items_1, i;
2561
- var _this = this;
2562
- return __generator(this, function (_a) {
2563
- switch (_a.label) {
2564
- case 0:
2565
- url = fixUrlStr(
2566
- // `${this.baseUrl}/search?format=geojson&polygon_geojson=1${window.locale === 'ru' ? '&accept-language=ru-RU,en-US' : ''}&q=${val}`
2567
- "".concat(this.searchUrl, "/search?format=geojson&polygon_geojson=1&q=").concat(val));
2568
- request = new CancelablePromise(function (resolve, reject, onCancel) {
2569
- var xhr = new XMLHttpRequest();
2570
- xhr.open('GET', url, true);
2571
- xhr.onload = function () {
2572
- try {
2573
- var geojson = JSON.parse(xhr.responseText);
2574
- var features = geojson.features.map(function (x) {
2575
- return {
2576
- geom: x,
2577
- extent: x.bbox,
2578
- text: x.properties && x.properties.display_name,
2579
- query: val,
2580
- };
2581
- });
2582
- resolve(features);
2583
- }
2584
- catch (er) {
2585
- reject(er);
2586
- }
2587
- };
2588
- xhr.onerror = function (er) {
2589
- reject(er);
2590
- };
2591
- onCancel(function () {
2592
- xhr.abort();
2593
- });
2594
- xhr.send();
2595
- }).catch(function (er) {
2596
- if (er.name === 'CancelError') ;
2597
- throw er;
2598
- });
2599
- this._requests.push(request);
2600
- return [4 /*yield*/, __await(request)];
2601
- case 1:
2602
- items = _a.sent();
2603
- if (!items) return [3 /*break*/, 5];
2604
- _loop_1 = function (i) {
2605
- return __generator(this, function (_b) {
2606
- switch (_b.label) {
2607
- case 0:
2608
- i.result = function () { return _this.result(i); };
2609
- return [4 /*yield*/, __await(i)];
2610
- case 1: return [4 /*yield*/, _b.sent()];
2611
- case 2:
2612
- _b.sent();
2613
- return [2 /*return*/];
2614
- }
2615
- });
2616
- };
2617
- _i = 0, items_1 = items;
2618
- _a.label = 2;
2619
- case 2:
2620
- if (!(_i < items_1.length)) return [3 /*break*/, 5];
2621
- i = items_1[_i];
2622
- return [5 /*yield**/, _loop_1(i)];
2623
- case 3:
2624
- _a.sent();
2625
- _a.label = 4;
2626
- case 4:
2627
- _i++;
2628
- return [3 /*break*/, 2];
2629
- case 5: return [2 /*return*/];
2630
- }
2631
- });
2632
- });
2633
- };
2634
- NominatimProvider.prototype.result = function (model) {
2635
- return CancelablePromise.resolve({
2636
- text: model.text,
2637
- extent: model.extent || [],
2638
- geom: model.geom,
2639
- });
2640
- };
2641
- return NominatimProvider;
2642
- }(BaseProvider));
2643
-
2644
- function create(options) {
2645
- return new Geocoder(options);
2141
+ class NgwProvider extends BaseProvider {
2142
+ constructor(options) {
2143
+ super(options);
2144
+ this.caseInsensitive = true;
2145
+ this.searchUrl = 'https://maxim.nextgis.com';
2146
+ this.searchResources = [];
2147
+ this.requests = [];
2148
+ this.connector =
2149
+ options.connector ||
2150
+ new NgwConnector({
2151
+ baseUrl: this.searchUrl,
2152
+ });
2153
+ this.searchResources = options.searchResources;
2154
+ }
2155
+ abort() {
2156
+ this.requests.forEach((x) => {
2157
+ x.cancel();
2158
+ });
2159
+ this.requests = [];
2160
+ }
2161
+ async *search(like) {
2162
+ for (const resource of this.searchResources) {
2163
+ const limit = resource.limit || 300;
2164
+ const request = this.connector.get('feature_layer.store', {
2165
+ headers: { RANGE: `items=0-${limit}` },
2166
+ }, {
2167
+ id: resource.id,
2168
+ like,
2169
+ });
2170
+ this.requests.push(request);
2171
+ request.catch((er) => {
2172
+ console.warn(er);
2173
+ });
2174
+ const resp = await request;
2175
+ const entries = [];
2176
+ if (resp) {
2177
+ resp.forEach((x) => {
2178
+ entries.push({
2179
+ query: like,
2180
+ resourceId: resource.id,
2181
+ ...x,
2182
+ });
2183
+ });
2184
+ }
2185
+ for (const item of this._items(entries)) {
2186
+ item.result = () => this.result(item);
2187
+ yield item;
2188
+ }
2189
+ }
2190
+ }
2191
+ result(item) {
2192
+ const req = this.connector
2193
+ .get('feature_layer.feature.item_extent', null, {
2194
+ id: item.resourceId,
2195
+ fid: item.featureId,
2196
+ })
2197
+ .then((x) => {
2198
+ const e = x.extent;
2199
+ return {
2200
+ text: item.text,
2201
+ extent: [e.minLon, e.minLat, e.maxLon, e.maxLat],
2202
+ };
2203
+ });
2204
+ this.requests.push(req);
2205
+ return req;
2206
+ }
2207
+ _items(entries) {
2208
+ const items = [];
2209
+ entries.forEach((entry) => {
2210
+ const meta = this.searchResources.find((x) => x.id === entry.resourceId);
2211
+ if (meta) {
2212
+ items.push({
2213
+ query: entry.query,
2214
+ text: entry.label,
2215
+ featureId: entry.id,
2216
+ resourceId: entry.resourceId,
2217
+ });
2218
+ }
2219
+ });
2220
+ return items;
2221
+ }
2222
+ }
2223
+
2224
+ class NominatimProvider extends BaseProvider {
2225
+ constructor(options) {
2226
+ super(options);
2227
+ this.searchUrl = 'https://nominatim.openstreetmap.org';
2228
+ this._requests = [];
2229
+ }
2230
+ abort() {
2231
+ this._requests.forEach((x) => x.cancel());
2232
+ this._requests = [];
2233
+ }
2234
+ async *search(val) {
2235
+ // RFC2616 accept - language string
2236
+ const url = fixUrlStr(
2237
+ // `${this.baseUrl}/search?format=geojson&polygon_geojson=1${window.locale === 'ru' ? '&accept-language=ru-RU,en-US' : ''}&q=${val}`
2238
+ `${this.searchUrl}/search?format=geojson&polygon_geojson=1&q=${val}`);
2239
+ const request = new CancelablePromise((resolve, reject, onCancel) => {
2240
+ const xhr = new XMLHttpRequest();
2241
+ xhr.open('GET', url, true);
2242
+ xhr.onload = () => {
2243
+ try {
2244
+ const geojson = JSON.parse(xhr.responseText);
2245
+ const features = geojson.features.map((x) => {
2246
+ return {
2247
+ geom: x,
2248
+ extent: x.bbox,
2249
+ text: x.properties && x.properties.display_name,
2250
+ query: val,
2251
+ };
2252
+ });
2253
+ resolve(features);
2254
+ }
2255
+ catch (er) {
2256
+ reject(er);
2257
+ }
2258
+ };
2259
+ xhr.onerror = (er) => {
2260
+ reject(er);
2261
+ };
2262
+ onCancel(() => {
2263
+ xhr.abort();
2264
+ });
2265
+ xhr.send();
2266
+ }).catch((er) => {
2267
+ if (er.name === 'CancelError') ;
2268
+ throw er;
2269
+ });
2270
+ this._requests.push(request);
2271
+ const items = await request;
2272
+ if (items) {
2273
+ for (const i of items) {
2274
+ i.result = () => this.result(i);
2275
+ yield i;
2276
+ }
2277
+ }
2278
+ }
2279
+ result(model) {
2280
+ return CancelablePromise.resolve({
2281
+ text: model.text,
2282
+ extent: model.extent || [],
2283
+ geom: model.geom,
2284
+ });
2285
+ }
2286
+ }
2287
+
2288
+ function create(options) {
2289
+ return new Geocoder(options);
2646
2290
  }
2647
2291
 
2648
2292
  export { BaseProvider, Geocoder, NgwProvider, NominatimProvider, create };