@nextgis/geocoder 1.16.8 → 1.18.3

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,572 @@
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); }
126
- }
127
-
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
- }());
1
+ /** Bundle of @nextgis/geocoder; version: 1.18.3; author: NextGIS */
2
+ class CancelError extends Error {
3
+ constructor() {
4
+ super();
5
+ this.name = 'CancelError';
6
+ Object.setPrototypeOf(this, CancelError.prototype);
7
+ }
8
+ }
9
+
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);
529
- }
530
-
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
- }
549
- }
550
-
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;
597
- }
598
-
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;
610
- }
611
-
612
- function fixUrlStr(url) {
613
- // remove double slash
614
- return url.replace(/([^:]\/)\/+/g, '$1');
615
- }
616
-
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));
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
+ function getBoundsCoordinates(b) {
380
+ const westNorth = [b[0], b[1]];
381
+ const eastNorth = [b[2], b[1]];
382
+ const eastSouth = [b[2], b[3]];
383
+ const westSouth = [b[0], b[3]];
384
+ return [westNorth, eastNorth, eastSouth, westSouth, westNorth];
385
+ }
386
+
387
+ function degrees2meters(lng, lat) {
388
+ lat = lat > 85.06 ? 85.06 : lat < -85.06 ? -85.06 : lat;
389
+ const x = (lng * 20037508.34) / 180;
390
+ let y = Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) / (Math.PI / 180);
391
+ y = (y * 20037508.34) / 180;
392
+ return [x, y];
393
+ }
394
+ // export function degrees2meters2(lon: number, lat: number): [number, number] {
395
+ // const radius = 6378137.0;
396
+ // const x = (radius * lon * Math.PI) / 180.0;
397
+ // const y =
398
+ // radius * Math.log(Math.tan(Math.PI / 4.0 + (lat * Math.PI) / 360.0));
399
+ // return [x, y];
400
+ // }
401
+ // export function meters2degress2(x: number, y: number): LngLatArray {
402
+ // const radius = 6378137.0;
403
+ // const lon = (180 / Math.PI) * (x / radius);
404
+ // const lat = (360 / Math.PI) * (Math.atan(Math.exp(y / radius)) - Math.PI / 4);
405
+ // return [lon, lat];
406
+ // }
407
+ // const lon = -77.035974;
408
+ // const lat = 38.898717;
409
+ // console.log(degrees2meters(lon, lat), degrees2meters2(lon, lat));
410
+ // const x = -8575605.398443861;
411
+ // const y = 4707174.018280405;
412
+ // console.log(meters2degress(x, y), meters2degress2(x, y));
413
+
414
+ function isLngLatBoundsArray(array) {
415
+ return (Array.isArray(array) &&
416
+ array.length === 4 &&
417
+ array.every((x) => typeof x === 'number'));
418
+ }
419
+
420
+ /**
421
+ * Copy the values of all of the enumerable own properties from one or more source objects to a
422
+ * target object. Returns the target object.
423
+ * @param target - The target object to copy to.
424
+ * @param sources - One or more source objects from which to copy properties
425
+ */
426
+ function objectAssign(target, ...sources) {
427
+ for (const source of sources) {
428
+ for (const prop of Object.getOwnPropertyNames(source)) {
429
+ target[prop] = source[prop];
430
+ }
431
+ }
432
+ }
433
+
434
+ function isEqual(a, b, o, p) {
435
+ if (a instanceof Array) {
436
+ if (!(b instanceof Array))
437
+ return false;
438
+ //if (compareObjects(oVal, pVal === false) return false
439
+ //would work, too, and perhaps is a better fit, still, this is easy, too
440
+ return b.sort().join('') === a.sort().join('');
441
+ }
442
+ else if (a instanceof Date) {
443
+ if (!(b instanceof Date))
444
+ return false;
445
+ return '' + a === '' + b;
446
+ }
447
+ else if (a instanceof Function) {
448
+ if (!(b instanceof Function))
449
+ return false;
450
+ //ignore functions, or check them regardless?
451
+ }
452
+ else if (a instanceof Object) {
453
+ if (!(b instanceof Object))
454
+ return false;
455
+ if (a === o) {
456
+ return b === p;
457
+ }
458
+ else {
459
+ return objectDeepEqual(a, b);
460
+ }
461
+ }
462
+ return a === b;
463
+ }
464
+ // based on https://stackoverflow.com/a/13143059
465
+ function objectDeepEqual(o, p) {
466
+ const keysO = Object.keys(o).sort();
467
+ const keysP = Object.keys(p).sort();
468
+ if (keysO.length !== keysP.length)
469
+ return false;
470
+ if (keysO.join('') !== keysP.join(''))
471
+ return false;
472
+ for (let i = 0; i < keysO.length; i++) {
473
+ const oVal = o[keysO[i]];
474
+ const pVal = p[keysP[i]];
475
+ if (!isEqual(oVal, pVal, o, p)) {
476
+ return false;
477
+ }
478
+ }
479
+ return true;
480
+ }
481
+
482
+ function objectRemoveEmpty(obj) {
483
+ const newObj = {};
484
+ Object.keys(obj).forEach((key) => {
485
+ if (!(obj[key] instanceof Array) && obj[key] === Object(obj[key])) {
486
+ newObj[key] = objectRemoveEmpty(obj[key]);
487
+ }
488
+ else if (obj[key] !== undefined) {
489
+ newObj[key] = obj[key];
490
+ }
491
+ });
492
+ return newObj;
493
+ }
494
+
495
+ function round(val, toFixed) {
496
+ const n = toFixed ? Number('1e+' + toFixed) : 1;
497
+ return Math.round((val + Number.EPSILON) * n) / n;
498
+ }
499
+
500
+ function isObject$1(val) {
501
+ return Object.prototype.toString.call(val) === '[object Object]';
502
+ }
503
+ function isArray(val) {
504
+ return Object.prototype.toString.call(val) === '[object Array]';
505
+ }
506
+
507
+ function fixUrlStr(url) {
508
+ // remove double slash
509
+ return url.replace(/([^:]\/)\/+/g, '$1');
510
+ }
511
+
512
+ /**
513
+ * Represents the base class for a geocoder.
514
+ * This abstract class provides the basic methods that every geocoder should implement.
515
+ *
516
+ * @template O - The type of options that can be passed to the geocoder.
517
+ */
518
+ class BaseGeocoder {
519
+ constructor(options) {
520
+ if (options) {
521
+ objectAssign(this, options);
522
+ }
523
+ }
524
+ }
525
+
526
+ let ID$1 = 0;
527
+ class Geocoder extends BaseGeocoder {
528
+ constructor(options) {
529
+ super(options);
530
+ this.providers = [];
531
+ if (options && options.providers) {
532
+ this.providers = options.providers;
533
+ }
534
+ }
535
+ abort() {
536
+ this.providers.forEach((x) => {
537
+ if (x.abort) {
538
+ x.abort();
539
+ }
540
+ });
541
+ }
542
+ async *search(query) {
543
+ for (const provider of this.providers) {
544
+ try {
545
+ const results = provider.search(query);
546
+ for await (const r of results) {
547
+ yield { ...r, provider, _id: ID$1++ };
548
+ }
549
+ }
550
+ catch (er) {
551
+ //
552
+ }
553
+ }
554
+ }
555
+ result(item) {
556
+ if (item.provider) {
557
+ return item.provider.result(item);
558
+ }
559
+ return CancelablePromise.resolve(undefined);
560
+ }
561
+ }
562
+
563
+ /**
564
+ * Abstract base class representing a search provider.
565
+ * It builds upon the BaseGeocoder functionalities with provider-specific properties.
566
+ * @template O - Options type which extends BaseProviderOptions.
567
+ */
568
+ class BaseProvider extends BaseGeocoder {
569
+ }
720
570
 
721
571
  var events = {exports: {}};
722
572
 
@@ -1194,1455 +1044,1677 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
1194
1044
  }
1195
1045
  }
1196
1046
 
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
- */
1047
+ /**
1048
+ * @example
1049
+ * ```javascript
1050
+ * const cache1 = new Cache();
1051
+ * cache1.add('foo', 'value');
1052
+ *
1053
+ * const cache2 = new Cache();
1054
+ * cache2.match('foo'); // value
1055
+ *
1056
+ * const cache3 = new Cache({ namespace: 'foo' });
1057
+ * cache3.match('foo'); // undefined
1058
+ * ```
1059
+ *
1060
+ * @example
1061
+ * ```javascript
1062
+ * let COUNTER = 0;
1063
+ * const createPromise = () => new Promise((res) => {
1064
+ * COUNTER++
1065
+ * setTimeout(() => res('Ok'), 300)
1066
+ * });
1067
+ *
1068
+ * const cache = new Cache();
1069
+ * for (let i = 0; i < 10; i++) {
1070
+ * cache.add('foo', createPromise).then((data) => {
1071
+ * console.log(data); // 'Ok'
1072
+ * });
1073
+ * }
1074
+ * console.log(COUNTER); // 1
1075
+ * ```
1076
+ */
1077
+ class Cache$1 {
1078
+ constructor(options = {}) {
1079
+ var _a;
1080
+ this.cache = [];
1081
+ const namespace = (_a = options.namespace) !== null && _a !== void 0 ? _a : 'default';
1082
+ if (Cache$1.instance[namespace]) {
1083
+ return Cache$1.instance[namespace];
1084
+ }
1085
+ Cache$1.instance[namespace] = this;
1086
+ return this;
1087
+ }
1088
+ clean() {
1089
+ this.cache.length = 0;
1090
+ }
1091
+ all() {
1092
+ return this.cache;
1093
+ }
1094
+ /**
1095
+ * Caching only a non-empty value.
1096
+ *
1097
+ * Useful for get or create strategy
1098
+ * @example
1099
+ * ```javascript
1100
+ * const cache = new Cache();
1101
+ * const getItemFunc = () => fetch(url).then((data) => {
1102
+ * return data.json(); // undefined
1103
+ * });
1104
+ * const item = await cache.addFull('foo', getItemFunc);
1105
+ * if (!item) {
1106
+ * await createItem(); // 'New item'
1107
+ * }
1108
+ *
1109
+ * // somewhere else in the code
1110
+ * const item = await cache.addFull('foo', getItemFunc).then((resp) => {
1111
+ * console.log(resp); // 'New item'
1112
+ * })
1113
+ *
1114
+ * ```
1115
+ */
1116
+ addFull(key, valueToSet, props) {
1117
+ return this.add(key, valueToSet, props, true);
1118
+ }
1119
+ add(key, valueToSet, props, onlyFull) {
1120
+ const exist = this._find(key, props);
1121
+ if (!exist) {
1122
+ let value;
1123
+ if (valueToSet instanceof Function) {
1124
+ value = valueToSet();
1125
+ }
1126
+ else {
1127
+ value = valueToSet;
1128
+ }
1129
+ const props_ = props && JSON.parse(JSON.stringify(objectRemoveEmpty(props)));
1130
+ const cacheItem = {
1131
+ key,
1132
+ value,
1133
+ props: props_,
1134
+ // TODO: remove backward compatibility use only props
1135
+ options: props_,
1136
+ };
1137
+ if (onlyFull && !full(value)) {
1138
+ return value;
1139
+ }
1140
+ this.cache.push(cacheItem);
1141
+ if (value instanceof Promise) {
1142
+ value.catch((er) => {
1143
+ this.delete(key, props);
1144
+ throw er;
1145
+ });
1146
+ if (onlyFull) {
1147
+ value.then((x) => {
1148
+ if (!full(x)) {
1149
+ this.delete(key, props);
1150
+ }
1151
+ return x;
1152
+ });
1153
+ }
1154
+ return value;
1155
+ }
1156
+ return value;
1157
+ }
1158
+ else {
1159
+ return exist.value;
1160
+ }
1161
+ }
1162
+ match(key, props) {
1163
+ const cacheRecord = this._find(key, props);
1164
+ if (cacheRecord) {
1165
+ return cacheRecord.value;
1166
+ }
1167
+ }
1168
+ matchAll(key, props) {
1169
+ if (key) {
1170
+ return this.cache
1171
+ .filter((x) => this._filter(x, key, props))
1172
+ .map((x) => x.value);
1173
+ }
1174
+ return this.cache.map((x) => x.value);
1175
+ }
1176
+ delete(keyOrItem, props) {
1177
+ let exist = [];
1178
+ if (typeof keyOrItem === 'string') {
1179
+ exist = this.cache.filter((x) => this._filter(x, keyOrItem, props));
1180
+ }
1181
+ else {
1182
+ exist.push(keyOrItem);
1183
+ }
1184
+ for (const e of exist) {
1185
+ const index = this.cache.indexOf(e);
1186
+ this.cache.splice(index, 1);
1187
+ }
1188
+ }
1189
+ _find(key, props) {
1190
+ return this.cache.find((x) => this._filter(x, key, props));
1191
+ }
1192
+ _filter(item, key, props) {
1193
+ if (item.key === key) {
1194
+ if (props) {
1195
+ // TODO: remove backward compatibility
1196
+ const itemProps = item.props || item.options;
1197
+ return objectDeepEqual(itemProps || {}, objectRemoveEmpty(props));
1198
+ }
1199
+ return true;
1200
+ }
1201
+ return false;
1202
+ }
1203
+ }
1204
+ Cache$1.instance = {};
1205
+
1206
+ /**
1207
+ * Caching for asynchronous functions
1208
+ *
1209
+ * @packageDocumentation
1210
+ * @module cache
1211
+ */
1369
1212
  var Cache = Cache$1;
1370
1213
 
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]';
1403
- }
1404
-
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
- };
1514
- }
1515
-
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
- });
1529
- }
1530
-
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
- });
1588
- }
1589
-
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
- }
1644
- }
1645
-
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;
1679
- }
1680
-
1681
- function resourceCompare(res1, res2) {
1682
- return objectDeepEqual(res1, res2);
1683
- }
1684
-
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
- */
1214
+ /**
1215
+ * Thrown when...
1216
+ */
1217
+ class NetworkError extends Error {
1218
+ constructor(url) {
1219
+ super();
1220
+ this.name = 'NetworkError';
1221
+ Object.setPrototypeOf(this, NetworkError.prototype);
1222
+ this.message = `Unable to request ${url}.
1223
+ Possibly invalid NGW URL entered or CORS not configured to get request from ${location.origin}`; // /control-panel/cors
1224
+ }
1225
+ }
1226
+
1227
+ /**
1228
+ * Thrown when...
1229
+ */
1230
+ class NgwError extends Error {
1231
+ constructor(er) {
1232
+ super();
1233
+ this.name = 'NgwError';
1234
+ Object.assign(this, er);
1235
+ Object.setPrototypeOf(this, NgwError.prototype);
1236
+ }
1237
+ }
1238
+
1239
+ function isObject(val) {
1240
+ return Object.prototype.toString.call(val) === '[object Object]';
1241
+ }
1242
+
1243
+ let loadData;
1244
+ // @ts-ignore
1245
+ {
1246
+ loadData = (url, callback, options = {}, error, onCancel) => {
1247
+ options.method = options.method || 'GET';
1248
+ const xhr = new XMLHttpRequest();
1249
+ xhr.open(options.method || 'GET', url, true); // true for asynchronous
1250
+ if (options.responseType === 'blob') {
1251
+ xhr.responseType = options.responseType;
1252
+ }
1253
+ const getResponseText = () => {
1254
+ try {
1255
+ return JSON.parse(xhr.responseText);
1256
+ }
1257
+ catch (er) {
1258
+ return xhr.responseText;
1259
+ }
1260
+ };
1261
+ const processingResponse = (forError = false) => {
1262
+ const cb = forError ? error : callback;
1263
+ if (options.responseType === 'blob') {
1264
+ cb(xhr.response);
1265
+ }
1266
+ else {
1267
+ if (xhr.responseText) {
1268
+ cb(getResponseText());
1269
+ }
1270
+ else {
1271
+ error({ message: '' });
1272
+ }
1273
+ }
1274
+ };
1275
+ xhr.onload = () => {
1276
+ if ([401, 403, 404, 422, 500].indexOf(xhr.status) !== -1) {
1277
+ error(new NgwError(getResponseText()));
1278
+ }
1279
+ processingResponse();
1280
+ };
1281
+ // xhr.onreadystatechange = () => {
1282
+ // if (
1283
+ // (xhr.readyState === 4 && xhr.status === 200) ||
1284
+ // (xhr.readyState === 3 && xhr.status === 201)
1285
+ // ) {
1286
+ // processingResponse();
1287
+ // } else if (xhr.readyState === 3 && xhr.status === 400) {
1288
+ // processingResponse();
1289
+ // } else if (xhr.readyState === 4 && xhr.status === 500) {
1290
+ // processingResponse();
1291
+ // } else if (xhr.readyState === 4 && xhr.status === 401) {
1292
+ // error(xhr.statusText);
1293
+ // } else if (xhr.readyState === 4) {
1294
+ // error('request error');
1295
+ // }
1296
+ // };
1297
+ xhr.onerror = (er) => {
1298
+ if (xhr.status === 0) {
1299
+ error(new NetworkError(url));
1300
+ }
1301
+ else {
1302
+ error(er);
1303
+ }
1304
+ };
1305
+ xhr.upload.onprogress = function (e) {
1306
+ if (e.lengthComputable) {
1307
+ const percentComplete = (e.loaded / e.total) * 100;
1308
+ if (options.onProgress) {
1309
+ options.onProgress(percentComplete, e);
1310
+ }
1311
+ // console.log(percentComplete + '% uploaded');
1312
+ }
1313
+ };
1314
+ const headers = options.headers;
1315
+ if (headers) {
1316
+ for (const h in headers) {
1317
+ const header = headers[h];
1318
+ if (typeof header === 'string') {
1319
+ xhr.setRequestHeader(h, header);
1320
+ }
1321
+ }
1322
+ }
1323
+ if (options.withCredentials !== undefined) {
1324
+ xhr.withCredentials = options.withCredentials;
1325
+ }
1326
+ let data;
1327
+ if (options.file) {
1328
+ data = new FormData();
1329
+ data.append('file', options.file);
1330
+ if (options.data) {
1331
+ for (const d in options.data) {
1332
+ data.append(d, data[d]);
1333
+ }
1334
+ }
1335
+ }
1336
+ else {
1337
+ data = options.data
1338
+ ? typeof options.data === 'string'
1339
+ ? options.data
1340
+ : JSON.stringify(options.data)
1341
+ : null;
1342
+ }
1343
+ if (onCancel) {
1344
+ onCancel(() => {
1345
+ xhr.abort();
1346
+ });
1347
+ }
1348
+ xhr.send(data);
1349
+ };
1350
+ }
1351
+
1352
+ // https://github.com/Leaflet/Leaflet/blob/b507e21c510b53cd704fb8d3f89bb46ea925c8eb/src/core/Util.js#L165
1353
+ const templateRe = /\{ *([\w_-]+) *\}/g;
1354
+ function template(str, data) {
1355
+ return str.replace(templateRe, (s, key) => {
1356
+ let value = data[key];
1357
+ if (value === undefined) {
1358
+ throw new Error('No value provided for letiable ' + s);
1359
+ }
1360
+ else if (typeof value === 'function') {
1361
+ value = value(data);
1362
+ }
1363
+ return value;
1364
+ });
1365
+ }
1366
+
1367
+ function apiRequest(opt) {
1368
+ const params = opt.params;
1369
+ return new CancelablePromise((resolve, reject) => {
1370
+ opt.connector
1371
+ .connect()
1372
+ .then((apiItems) => {
1373
+ let apiItem = apiItems && apiItems[opt.name];
1374
+ if (apiItem) {
1375
+ apiItem = [...apiItem];
1376
+ let url = apiItem.shift();
1377
+ if (apiItem.length) {
1378
+ const replaceParams = {};
1379
+ for (let fry = 0; fry < apiItem.length; fry++) {
1380
+ const arg = apiItem[fry];
1381
+ replaceParams[fry] = '{' + arg + '}';
1382
+ if (params[arg] === undefined) {
1383
+ throw new Error('`' + arg + '`' + ' url api argument is not specified');
1384
+ }
1385
+ }
1386
+ if (url) {
1387
+ url = template(url, replaceParams);
1388
+ }
1389
+ }
1390
+ // Transfer part of the parameters from `params` to the URL string
1391
+ if (params) {
1392
+ const paramArray = [];
1393
+ const paramList = params.paramList;
1394
+ if (Array.isArray(paramList)) {
1395
+ delete params.paramList;
1396
+ paramList.forEach((x) => {
1397
+ paramArray.push(`${x[0]}=${x[1]}`);
1398
+ });
1399
+ }
1400
+ for (const p in params) {
1401
+ if (apiItem.indexOf(p) === -1) {
1402
+ paramArray.push(`${p}=${params[p]}`);
1403
+ }
1404
+ }
1405
+ if (paramArray.length) {
1406
+ url = url + '?' + paramArray.join('&');
1407
+ }
1408
+ }
1409
+ if (url) {
1410
+ resolve(opt.connector.makeQuery(url, params, opt.requestOptions));
1411
+ }
1412
+ else {
1413
+ reject(new Error('request url is not set'));
1414
+ }
1415
+ }
1416
+ else {
1417
+ resolve(undefined);
1418
+ }
1419
+ })
1420
+ .catch((er) => {
1421
+ reject(er);
1422
+ });
1423
+ });
1424
+ }
1425
+
1426
+ /**
1427
+ * Thrown when ...
1428
+ */
1429
+ class ResourceNotFoundError extends NgwError {
1430
+ constructor(obj) {
1431
+ super(obj);
1432
+ this.name = 'ResourceNotFoundError';
1433
+ this.exception = 'nextgisweb.resource.exception.ResourceNotFound';
1434
+ Object.setPrototypeOf(this, ResourceNotFoundError.prototype);
1435
+ }
1436
+ }
1437
+
1438
+ /**
1439
+ * Thrown when ...
1440
+ */
1441
+ class InsufficientPermissionsError extends NgwError {
1442
+ constructor(obj) {
1443
+ super(obj);
1444
+ this.name = 'InsufficientPermissionsError';
1445
+ this.exception = 'nextgisweb.core.exception.InsufficientPermissions';
1446
+ Object.setPrototypeOf(this, InsufficientPermissionsError.prototype);
1447
+ }
1448
+ }
1449
+
1450
+ const CONNECTORS = [];
1451
+ function addConnector(connector) {
1452
+ CONNECTORS.push(connector);
1453
+ }
1454
+ function findConnector(options) {
1455
+ return CONNECTORS.find((x) => {
1456
+ if (x.options.baseUrl === options.baseUrl) {
1457
+ if (options.auth) {
1458
+ if (x.options.auth) {
1459
+ return objectDeepEqual(x.options.auth, options.auth);
1460
+ }
1461
+ }
1462
+ else {
1463
+ // if auth not in find options; use first connector with same url
1464
+ return true;
1465
+ }
1466
+ }
1467
+ });
1468
+ }
1469
+ function removeConnector(connector) {
1470
+ const index = CONNECTORS.indexOf(connector);
1471
+ if (index !== -1) {
1472
+ CONNECTORS.splice(index, 1);
1473
+ }
1474
+ }
1475
+
1476
+ const exclude = ['description'];
1477
+ /**
1478
+ * @remarks
1479
+ * https://docs.nextgis.ru/docs_ngweb_dev/doc/developer/resource.html#search-resources
1480
+ *
1481
+ * ```
1482
+ * { keyname, owner_user: { id }} > { keyname, owner_user__id }
1483
+ * ```
1484
+ *
1485
+ * @param resource - Any property from NGW resource item
1486
+ */
1487
+ function resourceToQuery(resource, prefix = '') {
1488
+ prefix = prefix ? prefix + '__' : '';
1489
+ const query = {};
1490
+ for (const [key, value] of Object.entries(resource)) {
1491
+ if (exclude.indexOf(key) === -1) {
1492
+ if (isObject(value)) {
1493
+ if (key === 'owner_user') {
1494
+ const children = resourceToQuery(value, key);
1495
+ Object.assign(query, children);
1496
+ }
1497
+ else if (key === 'parent' && 'id' in value) {
1498
+ query.parent_id = value.id;
1499
+ }
1500
+ }
1501
+ else if (defined(value)) {
1502
+ query[prefix + key] = value;
1503
+ }
1504
+ }
1505
+ }
1506
+ return query;
1507
+ }
1508
+
1509
+ function resourceCompare(res1, res2) {
1510
+ return objectDeepEqual(res1, res2);
1511
+ }
1512
+
1513
+ class ResourcesControl {
1514
+ constructor(connector) {
1515
+ this.connector = connector;
1516
+ this.cache = new Cache();
1517
+ }
1518
+ // -------------------------------------------------------------------------
1519
+ // Resource Methods
1520
+ // -------------------------------------------------------------------------
1521
+ /**
1522
+ * Receive resource from NGW by id, keyname or search-object parameter.
1523
+ * @param resource - Resource id, keyname or search-object
1524
+ *
1525
+ * @remarks
1526
+ * Fetching resource would be cached to speed up next call
1527
+ */
1528
+ getOne(resource, requestOptions) {
1529
+ const cache = new Cache();
1530
+ const forCache = {};
1531
+ const opt = { ...requestOptions, cache: false };
1532
+ if (typeof resource === 'string') {
1533
+ forCache.keyname = resource;
1534
+ }
1535
+ else if (typeof resource === 'number') {
1536
+ forCache.id = resource;
1537
+ }
1538
+ else if (isObject(resource)) {
1539
+ if (resource.id !== undefined) {
1540
+ forCache.id = resource.id;
1541
+ }
1542
+ else if (resource.keyname) {
1543
+ forCache.keyname = resource.keyname;
1544
+ }
1545
+ }
1546
+ const makeRequest = () => {
1547
+ if (typeof resource === 'string') {
1548
+ return this._fetchResourceBy({ keyname: resource }, opt);
1549
+ }
1550
+ else if (typeof resource === 'number') {
1551
+ return this._fetchResourceById(resource, opt);
1552
+ }
1553
+ else if (isObject(resource)) {
1554
+ return this._fetchResourceBy(resource, opt);
1555
+ }
1556
+ return CancelablePromise.resolve(undefined);
1557
+ };
1558
+ return cache.addFull('resource', makeRequest, forCache);
1559
+ }
1560
+ getOneOrFail(resource, requestOptions) {
1561
+ return this.getOne(resource, requestOptions).then((res) => {
1562
+ if (res) {
1563
+ return res;
1564
+ }
1565
+ throw new ResourceNotFoundError();
1566
+ });
1567
+ }
1568
+ /**
1569
+ * A fast way to retrieve resource ID for any resource definition.
1570
+ * @param resource - Any available resource definition
1571
+ *
1572
+ * @remarks
1573
+ * There are situations when exactly the resource id is needed
1574
+ * (for example, to compose the correct request to the api)
1575
+ * then this method will come in handy to facilitate the extraction of the identifier
1576
+ * if the resource is specified through a keyname or other parameters.
1577
+ */
1578
+ getId(resource, requestOptions) {
1579
+ if (typeof resource === 'number') {
1580
+ return CancelablePromise.resolve(resource);
1581
+ }
1582
+ else if (typeof resource === 'string' || isObject(resource)) {
1583
+ return this.getOne(resource, requestOptions).then((res) => {
1584
+ if (res) {
1585
+ return res.resource.id;
1586
+ }
1587
+ });
1588
+ }
1589
+ return CancelablePromise.resolve(undefined);
1590
+ }
1591
+ /**
1592
+ * A fast way to retrieve resource ID for any resource definition.
1593
+ * @param resource - Any available resource definition
1594
+ *
1595
+ * @remarks
1596
+ * Similar with {@link NgwConnector.getResourceId | getResourceId} but rise error if resource is not exist.
1597
+ * To not make one more checks if the resource is definitely exists
1598
+ */
1599
+ getIdOrFail(resource, requestOptions) {
1600
+ return this.getId(resource, requestOptions).then((resp) => {
1601
+ if (resp === undefined) {
1602
+ throw new Error();
1603
+ }
1604
+ return resp;
1605
+ });
1606
+ }
1607
+ getMany(resource, requestOptions) {
1608
+ return this._resourceCacheFilter(resource).then((items) => {
1609
+ if (!items.length) {
1610
+ const query = {};
1611
+ if (resource.keyname) {
1612
+ query.keyname = resource.keyname;
1613
+ }
1614
+ else {
1615
+ Object.assign(query, resourceToQuery(resource));
1616
+ }
1617
+ return this.connector
1618
+ .get('resource.search', requestOptions, {
1619
+ serialization: 'full',
1620
+ ...query,
1621
+ })
1622
+ .then((resources) => {
1623
+ if (resources) {
1624
+ for (const x of resources) {
1625
+ this.cache.add('resource.item', CancelablePromise.resolve(x), {
1626
+ id: x.resource.id,
1627
+ });
1628
+ }
1629
+ }
1630
+ return resources;
1631
+ });
1632
+ }
1633
+ return items;
1634
+ });
1635
+ }
1636
+ getParent(resource, requestOptions) {
1637
+ return this.getOne(resource, requestOptions).then((child) => {
1638
+ if (child) {
1639
+ return this.getOne(child.resource.parent.id, requestOptions);
1640
+ }
1641
+ return CancelablePromise.resolve(undefined);
1642
+ });
1643
+ }
1644
+ getChildrenOf(resource, requestOptions) {
1645
+ return this.getIdOrFail(resource).then((parent) => this._getChildrenOf(parent, requestOptions));
1646
+ }
1647
+ update(resource, data) {
1648
+ return this.getId(resource).then((id) => {
1649
+ if (id !== undefined) {
1650
+ return this.connector.put('resource.item', { data }, { id });
1651
+ }
1652
+ });
1653
+ }
1654
+ /**
1655
+ * Fast way to delete resource from NGW and clean cache.
1656
+ * @param resource - Resource definition
1657
+ */
1658
+ delete(resource) {
1659
+ return this.getId(resource).then((id) => {
1660
+ if (id !== undefined) {
1661
+ return this.connector.delete('resource.item', null, { id }).then(() => {
1662
+ this._cleanResourceItemCache(id);
1663
+ return undefined;
1664
+ });
1665
+ }
1666
+ });
1667
+ }
1668
+ _getChildrenOf(parent, requestOptions, _items = []) {
1669
+ return this.connector
1670
+ .get('resource.collection', { cache: true, ...requestOptions }, {
1671
+ parent,
1672
+ })
1673
+ .then((items) => {
1674
+ const recursivePromises = [];
1675
+ for (const item of items) {
1676
+ this.cache.add('resource.item', CancelablePromise.resolve(item), {
1677
+ id: item.resource.id,
1678
+ });
1679
+ _items.push(item);
1680
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.recursive) && item.resource.children) {
1681
+ recursivePromises.push(this._getChildrenOf(item.resource.id, requestOptions, _items));
1682
+ }
1683
+ }
1684
+ if (recursivePromises.length) {
1685
+ return CancelablePromise.all(recursivePromises).then(() => {
1686
+ return _items;
1687
+ });
1688
+ }
1689
+ return _items;
1690
+ });
1691
+ }
1692
+ async _cleanResourceItemCache(id) {
1693
+ const all = this.cache.all();
1694
+ const toDelete = [];
1695
+ for (const c of all) {
1696
+ const cid = c.options && c.options.id;
1697
+ if (['resource.item', 'resource'].includes(c.key) && cid !== undefined) {
1698
+ if (typeof cid === 'number') {
1699
+ if (cid === id) {
1700
+ toDelete.push(c);
1701
+ }
1702
+ }
1703
+ else {
1704
+ const rid = await this.getId(cid);
1705
+ if (rid === id) {
1706
+ toDelete.push(c);
1707
+ }
1708
+ }
1709
+ }
1710
+ }
1711
+ for (const d of toDelete) {
1712
+ this.cache.delete(d);
1713
+ }
1714
+ }
1715
+ _fetchResourceById(id, requestOptions) {
1716
+ const promise = () => this.connector.get('resource.item', requestOptions, { id });
1717
+ return this.cache
1718
+ .add('resource.item', promise, {
1719
+ id,
1720
+ })
1721
+ .catch((er) => {
1722
+ if (!(er instanceof ResourceNotFoundError)) {
1723
+ throw er;
1724
+ }
1725
+ return undefined;
1726
+ });
1727
+ }
1728
+ _fetchResourceBy(resource, requestOptions) {
1729
+ return this.getMany(resource, requestOptions).then((resources) => {
1730
+ return resources[0];
1731
+ });
1732
+ }
1733
+ _resourceCacheFilter(resource) {
1734
+ return CancelablePromise.all(this.cache.matchAll('resource.item')).then((resources) => {
1735
+ const items = [];
1736
+ resources.filter((x) => {
1737
+ if (x) {
1738
+ // identical by uniq props
1739
+ if (resource.keyname && x.resource.keyname) {
1740
+ return resource.keyname === x.resource.keyname;
1741
+ }
1742
+ if (defined(resource.id) && defined(x.resource.id)) {
1743
+ return resource.id === x.resource.id;
1744
+ }
1745
+ return resourceCompare(resource, x.resource);
1746
+ }
1747
+ });
1748
+ return items;
1749
+ });
1750
+ }
1751
+ }
1752
+
1753
+ let ID = 0;
1754
+ class NgwConnector$1 {
1755
+ constructor(options) {
1756
+ this.options = options;
1757
+ this.id = ID++;
1758
+ this.emitter = new events.exports.EventEmitter();
1759
+ this.routeStr = '/api/component/pyramid/route';
1760
+ this.activeRequests = [];
1761
+ const exist = findConnector(options);
1762
+ if (exist) {
1763
+ return exist;
1764
+ }
1765
+ else {
1766
+ if (this.options.route) {
1767
+ this.routeStr = this.options.route;
1768
+ }
1769
+ if (this.options.requestTransform) {
1770
+ this.requestTransform = this.options.requestTransform;
1771
+ }
1772
+ this.resources = new ResourcesControl(this);
1773
+ addConnector(this);
1774
+ }
1775
+ }
1776
+ static create(options) {
1777
+ return new this(options);
1778
+ }
1779
+ setRequestTransform(requestTransform) {
1780
+ this.requestTransform = requestTransform;
1781
+ }
1782
+ /**
1783
+ * Fast way to specify the connection address to NextGIS Web.
1784
+ * The current connection will be severed.
1785
+ * @param baseUrl - NGW url
1786
+ */
1787
+ setNgw(baseUrl) {
1788
+ this.logout();
1789
+ this.options.baseUrl = baseUrl;
1790
+ addConnector(this);
1791
+ }
1792
+ /**
1793
+ * Establishing a connection with NextGIS Web to fulfill all other requests.
1794
+ * @remarks
1795
+ * This method need not be called manually as it is used when forming a request in {@link apiRequest | apiRequest}.
1796
+ * Can be used to check connection.
1797
+ * @example
1798
+ * ```javascript
1799
+ * const connector = new NgwConnector({baseUrl: 'https://demo.nextgis.com'});
1800
+ * connector.connect()
1801
+ * .then(() => console.log('Ok'))
1802
+ * .catch((er) => console.log('Connection problem', er));
1803
+ * ```
1804
+ */
1805
+ connect() {
1806
+ const cache = new Cache();
1807
+ const auth = this.options.auth;
1808
+ const makeConnect = () => new CancelablePromise((resolve, reject) => {
1809
+ const makeQuery = () => {
1810
+ return this.makeQuery(this.routeStr, {}, {})
1811
+ .then((route) => {
1812
+ resolve(route);
1813
+ })
1814
+ .catch((er) => {
1815
+ reject(er);
1816
+ });
1817
+ };
1818
+ if (auth) {
1819
+ const { login, password } = auth;
1820
+ if (login && password) {
1821
+ return this._login({ login, password })
1822
+ .then(() => {
1823
+ return makeQuery();
1824
+ })
1825
+ .catch((er) => reject(er));
1826
+ }
1827
+ }
1828
+ return makeQuery();
1829
+ });
1830
+ return cache.add('route', makeConnect, {
1831
+ id: this.id,
1832
+ auth,
1833
+ baseUrl: this.options.baseUrl,
1834
+ });
1835
+ }
1836
+ /**
1837
+ * Quick way to change NextGIS Web user.
1838
+ * @param credentials - New user credentials
1839
+ */
1840
+ login(credentials, options) {
1841
+ this.logout();
1842
+ addConnector(this);
1843
+ return this._login(credentials, options);
1844
+ }
1845
+ /**
1846
+ * Disconnecting a user. Aborting all current requests
1847
+ */
1848
+ logout() {
1849
+ this.abort();
1850
+ removeConnector(this);
1851
+ this.options.auth = undefined;
1852
+ this.user = undefined;
1853
+ this.emitter.emit('logout');
1854
+ this.resources.cache.clean();
1855
+ }
1856
+ getUserInfo(credentials, options) {
1857
+ if (this.user && this.user.id) {
1858
+ return CancelablePromise.resolve(this.user);
1859
+ }
1860
+ if (credentials) {
1861
+ this.options.auth = credentials;
1862
+ }
1863
+ const options_ = {
1864
+ headers: this.getAuthorizationHeaders(credentials),
1865
+ // withCredentials: true
1866
+ ...options,
1867
+ };
1868
+ // Do not use apiRequest('auth.current_user') to avoid circular-references
1869
+ return this.makeQuery('/api/component/auth/current_user', {}, options_);
1870
+ }
1871
+ /**
1872
+ * Obtaining the required Headers for authentication of requests in the NGW.
1873
+ */
1874
+ getAuthorizationHeaders(credentials) {
1875
+ const client = this.makeClientId(credentials);
1876
+ if (client) {
1877
+ return {
1878
+ Authorization: 'Basic ' + client,
1879
+ };
1880
+ }
1881
+ }
1882
+ makeClientId(credentials) {
1883
+ credentials = credentials || this.options.auth;
1884
+ if (credentials) {
1885
+ const { login, password } = credentials;
1886
+ const str = unescape(encodeURIComponent(`${login}:${password}`));
1887
+ // @ts-ignore
1888
+ {
1889
+ return window.btoa(str);
1890
+ }
1891
+ }
1892
+ }
1893
+ /** Stop all api requests */
1894
+ abort() {
1895
+ for (const req of this.activeRequests) {
1896
+ req.cancel();
1897
+ }
1898
+ this.activeRequests = [];
1899
+ }
1900
+ getActiveApiRequests() {
1901
+ return [...this.activeRequests];
1902
+ }
1903
+ /**
1904
+ * Send request to NGW api router.
1905
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1906
+ * @param params - Request item params or query params
1907
+ * @param requestOptions - Request options
1908
+ *
1909
+ * @example
1910
+ * ```javascript
1911
+ *
1912
+ * // there is such an NGW route item
1913
+ * // "feature_layer.feature.item": [
1914
+ * // "/api/resource/{0}/feature/{1}",
1915
+ * // "id",
1916
+ * // "fid"
1917
+ * // ],
1918
+ *
1919
+ * const connector = new NgwConnector({ baseUrl: 'https://example.nextgis.com' });
1920
+ * connector.apiRequest('feature_layer.feature.item', {
1921
+ * // request params for {0} and {1}
1922
+ * 'id': 2011,
1923
+ * 'fid': 101,
1924
+ * // query params
1925
+ * 'srs': 4326,
1926
+ * 'geom_format': 'geojson',
1927
+ * }, { method: 'GET' });
1928
+ * // send get-request to 'https://example.nextgis.com/api/resource/2011/feature/101?srs=4326&geom_format=geojson'
1929
+ *
1930
+ * ```
1931
+ */
1932
+ apiRequest(name, params_ = {}, requestOptions = {}) {
1933
+ var _a;
1934
+ const { method, headers, withCredentials, responseType } = requestOptions;
1935
+ const params = objectRemoveEmpty(params_);
1936
+ const makeApiRequest = () => apiRequest({ name, params, requestOptions, connector: this });
1937
+ if (requestOptions.cache && method === 'GET') {
1938
+ const cache = new Cache();
1939
+ return cache.add(name, makeApiRequest, {
1940
+ params,
1941
+ ...objectRemoveEmpty({
1942
+ headers,
1943
+ withCredentials,
1944
+ responseType,
1945
+ baseUrl: this.options.baseUrl,
1946
+ userId: (_a = this.user) === null || _a === void 0 ? void 0 : _a.id,
1947
+ }),
1948
+ });
1949
+ }
1950
+ return makeApiRequest();
1951
+ }
1952
+ /**
1953
+ * Shortcut method for send POST request to NGW.
1954
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1955
+ * @param options - Request options
1956
+ * @param params - Request item params or query params
1957
+ *
1958
+ * @example
1959
+ * ```javascript
1960
+ * connector.post('resource.collection', { data: POST_PAYLOAD })
1961
+ * .then((newResource) => console.log(newResource))
1962
+ * .catch((error) => console.warn(error));
1963
+ * ```
1964
+ */
1965
+ post(name, options, params) {
1966
+ options = options || {};
1967
+ options.method = 'POST';
1968
+ return this.apiRequest(name, params, options);
1969
+ }
1970
+ /**
1971
+ * Shortcut method for send GET request to NGW.
1972
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1973
+ * @param options - Request options
1974
+ * @param params - Request item params or query params
1975
+ */
1976
+ get(name, options, params) {
1977
+ options = options || {};
1978
+ options.method = 'GET';
1979
+ return this.apiRequest(name, params, options);
1980
+ }
1981
+ /**
1982
+ * Shortcut method for send PATCH request to NGW.
1983
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1984
+ * @param options - Request options
1985
+ * @param params - Request item params or query params
1986
+ */
1987
+ patch(name, options, params) {
1988
+ options = options || {};
1989
+ options.method = 'PATCH';
1990
+ return this.apiRequest(name, params, options);
1991
+ }
1992
+ /**
1993
+ * Shortcut method for send PUT request to NGW.
1994
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
1995
+ * @param options - Request options
1996
+ * @param params - Request item params or query params
1997
+ */
1998
+ put(name, options, params) {
1999
+ options = options || {};
2000
+ options.method = 'PUT';
2001
+ return this.apiRequest(name, params, options);
2002
+ }
2003
+ /**
2004
+ * Shortcut method for send DELETE request to NGW.
2005
+ * @param name - NGW route name from {@link https://docs.nextgis.com/docs_ngweb_dev/doc/developer/resource.html#routes | routes}
2006
+ * @param options - Request options
2007
+ * @param params - Request item params or query params
2008
+ */
2009
+ delete(name, options, params) {
2010
+ options = options || {};
2011
+ options.method = 'DELETE';
2012
+ return this.apiRequest(name, params, options);
2013
+ }
2014
+ /**
2015
+ * Send request to NGW.
2016
+ * @param url - URL address to NGW
2017
+ * @param params - Query params
2018
+ * @param options - Request options
2019
+ */
2020
+ makeQuery(url, params, options = {}) {
2021
+ url = (this.options.baseUrl ? this.options.baseUrl : '') + url;
2022
+ if (url) {
2023
+ if (params) {
2024
+ url = template(url, params);
2025
+ }
2026
+ url = encodeURI(fixUrlStr(url));
2027
+ return this._loadData(url, options);
2028
+ }
2029
+ else {
2030
+ throw new Error('Empty `url` not allowed');
2031
+ }
2032
+ }
2033
+ // -------------------------------------------------------------------------
2034
+ // Resource Methods
2035
+ // -------------------------------------------------------------------------
2036
+ /**
2037
+ * {@link ResourcesControl.getOne}
2038
+ */
2039
+ getResource(resource, requestOptions) {
2040
+ return this.resources.getOne(resource, requestOptions);
2041
+ }
2042
+ /**
2043
+ * {@link ResourcesControl.getOneOrFail}
2044
+ */
2045
+ getResourceOrFail(resource, requestOptions) {
2046
+ return this.resources.getOneOrFail(resource, requestOptions);
2047
+ }
2048
+ /**
2049
+ * @deprecated - use {@link getResource}
2050
+ */
2051
+ getResourceBy(resource) {
2052
+ return this.resources.getOne(resource);
2053
+ }
2054
+ /**
2055
+ * @deprecated - use {@link getResource}
2056
+ */
2057
+ getResourceByKeyname(keyname) {
2058
+ return this.resources.getOne(keyname);
2059
+ }
2060
+ /**
2061
+ * @deprecated - use {@link getResource}
2062
+ */
2063
+ getResourceById(id) {
2064
+ return this.resources.getOne(id);
2065
+ }
2066
+ /**
2067
+ * {@link ResourcesControl.getId}
2068
+ */
2069
+ getResourceId(resource, requestOptions) {
2070
+ return this.resources.getId(resource, requestOptions);
2071
+ }
2072
+ /**
2073
+ * {@link ResourcesControl.getIdOrFail}
2074
+ */
2075
+ getResourceIdOrFail(resource, requestOptions) {
2076
+ return this.resources.getIdOrFail(resource, requestOptions);
2077
+ }
2078
+ /**
2079
+ * {@link ResourcesControl.getMany}
2080
+ */
2081
+ getResourcesBy(resource, requestOptions) {
2082
+ return this.resources.getMany(resource, requestOptions);
2083
+ }
2084
+ /**
2085
+ * {@link ResourcesControl.getParent}
2086
+ */
2087
+ getResourceParent(resource, requestOptions) {
2088
+ return this.resources.getParent(resource, requestOptions);
2089
+ }
2090
+ /**
2091
+ * {@link ResourcesControl.getChildrenOf}
2092
+ */
2093
+ getResourceChildren(resource, requestOptions) {
2094
+ return this.resources.getChildrenOf(resource, requestOptions);
2095
+ }
2096
+ /**
2097
+ * {@link ResourcesControl.update}
2098
+ */
2099
+ updateResource(resource, data) {
2100
+ return this.resources.update(resource, data);
2101
+ }
2102
+ /**
2103
+ * {@link ResourcesControl.delete}
2104
+ */
2105
+ deleteResource(resource) {
2106
+ return this.resources.delete(resource);
2107
+ }
2108
+ /**
2109
+ * @internal
2110
+ */
2111
+ _loadData(url, options) {
2112
+ options.responseType = options.responseType || 'json';
2113
+ const request = new CancelablePromise((resolve, reject, onCancel) => {
2114
+ if (this.user) {
2115
+ options = options || {};
2116
+ // options.withCredentials = true;
2117
+ options.headers = {
2118
+ ...this.getAuthorizationHeaders(),
2119
+ ...options.headers,
2120
+ };
2121
+ }
2122
+ if (this.requestTransform) {
2123
+ const [transUrl, transOptions] = this.requestTransform(url, options);
2124
+ url = transUrl;
2125
+ options = transOptions;
2126
+ }
2127
+ loadData(url, resolve, options, reject, onCancel);
2128
+ })
2129
+ .then((resp) => {
2130
+ this._cleanActiveRequests(request);
2131
+ return resp;
2132
+ })
2133
+ .catch((httpError) => {
2134
+ this._cleanActiveRequests(request);
2135
+ if (httpError instanceof CancelablePromise.CancelError) ;
2136
+ else {
2137
+ // @ts-ignore
2138
+ {
2139
+ console.warn('DEV WARN', httpError);
2140
+ }
2141
+ const er = this._handleHttpError(httpError);
2142
+ if (er) {
2143
+ throw er;
2144
+ }
2145
+ }
2146
+ });
2147
+ if (options.signal &&
2148
+ typeof options.signal.addEventListener === 'function') {
2149
+ options.signal.addEventListener('abort', () => {
2150
+ request.cancel();
2151
+ this._cleanActiveRequests(request);
2152
+ });
2153
+ }
2154
+ this.activeRequests.push(request);
2155
+ return request;
2156
+ }
2157
+ _login(credentials, options) {
2158
+ return this.getUserInfo(credentials, options)
2159
+ .then((data) => {
2160
+ this.user = data;
2161
+ this.emitter.emit('login', data);
2162
+ return data;
2163
+ })
2164
+ .catch((er) => {
2165
+ this.emitter.emit('login:error', er);
2166
+ throw er;
2167
+ });
2168
+ }
2169
+ _cleanActiveRequests(request) {
2170
+ const activeRequestIndex = this.activeRequests.indexOf(request);
2171
+ if (activeRequestIndex !== -1) {
2172
+ this.activeRequests.splice(activeRequestIndex, 1);
2173
+ }
2174
+ }
2175
+ _handleHttpError(er) {
2176
+ if (er) {
2177
+ if (er instanceof NgwError) {
2178
+ if (er.exception === 'nextgisweb.resource.exception.ResourceNotFound') {
2179
+ throw new ResourceNotFoundError(er);
2180
+ }
2181
+ else if (er.exception === 'nextgisweb.core.exception.InsufficientPermissions') {
2182
+ throw new InsufficientPermissionsError(er);
2183
+ }
2184
+ }
2185
+ }
2186
+ return er;
2187
+ }
2188
+ }
2189
+ NgwConnector$1.errors = {
2190
+ NgwError,
2191
+ ResourceNotFoundError,
2192
+ };
2193
+
2194
+ /**
2195
+ * A lightweight HTTP client optimized for use with {@link http://docs.nextgis.ru/docs_ngweb_dev/doc/developer/toc.html | NextGIS Web} API
2196
+ *
2197
+ * @remarks
2198
+ * 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.
2199
+ *
2200
+ * @packageDocumentation
2201
+ * @module ngw-connector
2202
+ */
2408
2203
  var NgwConnector = NgwConnector$1;
2409
2204
 
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);
2205
+ function reEscape(s) {
2206
+ return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
2207
+ }
2208
+ function like(b, a, iLike) {
2209
+ a = String(a);
2210
+ b = String(b);
2211
+ if (a === b)
2212
+ return true;
2213
+ if (iLike && a.toUpperCase() === b.toUpperCase())
2214
+ return true;
2215
+ const re = `^${reEscape(a)}$`.replace(/%/g, '.*').replace('_', '.');
2216
+ return new RegExp(re, iLike ? 'i' : '').exec(b) !== null;
2217
+ }
2218
+ const operationsAliases = {
2219
+ // greater(>)
2220
+ gt: (a, b) => a > b,
2221
+ // lower(<)
2222
+ lt: (a, b) => a < b,
2223
+ // greater or equal(>=)
2224
+ ge: (a, b) => a >= b,
2225
+ // lower or equal(<=)
2226
+ le: (a, b) => a <= b,
2227
+ // equal(=)
2228
+ eq: (a, b) => a === b,
2229
+ // not equal(!=)
2230
+ ne: (a, b) => a !== b,
2231
+ in: (a, b) => b.indexOf(a) !== -1,
2232
+ notin: (a, b) => b.indexOf(a) === -1,
2233
+ // LIKE SQL statement(for strings compare)
2234
+ like: (a, b) => {
2235
+ return like(a, b);
2236
+ },
2237
+ // ILIKE SQL statement(for strings compare)
2238
+ ilike: (a, b) => {
2239
+ return like(a, b, true);
2240
+ },
2241
+ };
2242
+ function isPropertyFilter(filter) {
2243
+ const pf = filter;
2244
+ if (pf.length === 3 &&
2245
+ typeof pf[0] === 'string' &&
2246
+ typeof pf[1] === 'string') {
2247
+ return true;
2248
+ }
2249
+ return false;
2250
+ }
2251
+ function propertiesFilter(properties, filters) {
2252
+ const logic = typeof filters[0] === 'string' ? filters[0] : 'all';
2253
+ const filterFunction = (p) => {
2254
+ if (isPropertyFilter(p)) {
2255
+ const [field, operation, value] = p;
2256
+ const operationExec = operationsAliases[operation];
2257
+ if (operationExec) {
2258
+ if (operation === 'like' || operation === 'ilike') {
2259
+ if (typeof field === 'string') {
2260
+ let prop = '';
2261
+ const value_ = field.replace(/^%?(\w+)%?$/, (match, cleanField) => {
2262
+ prop = properties[cleanField];
2263
+ return field.replace(cleanField, value);
2264
+ });
2265
+ return operationExec(prop, value_);
2266
+ }
2267
+ }
2268
+ return operationExec(properties[field], value);
2269
+ }
2270
+ return false;
2271
+ }
2272
+ else {
2273
+ return propertiesFilter(properties, p);
2274
+ }
2275
+ };
2276
+ const filters_ = filters.filter((x) => Array.isArray(x));
2277
+ return logic === 'any'
2278
+ ? filters_.some(filterFunction)
2279
+ : filters_.every(filterFunction);
2280
+ }
2281
+
2282
+ const FEATURE_REQUEST_PARAMS = {
2283
+ srs: 4326,
2284
+ geom_format: 'geojson',
2285
+ };
2286
+ function updateItemRequestParam(params, options) {
2287
+ const { extensions, geom, fields, srs, ilike, like } = options;
2288
+ if (extensions) {
2289
+ params.extensions = extensions.join(',');
2290
+ }
2291
+ if (fields !== undefined) {
2292
+ params.fields = Array.isArray(fields) ? fields.join(',') : '';
2293
+ }
2294
+ if (geom !== undefined) {
2295
+ params.geom = geom ? 'yes' : 'no';
2296
+ if (!geom) {
2297
+ delete params.srs;
2298
+ delete params.geom_format;
2299
+ }
2300
+ }
2301
+ if (defined(ilike)) {
2302
+ params.ilike = ilike;
2303
+ }
2304
+ else if (defined(like)) {
2305
+ params.like = like;
2306
+ }
2307
+ if (defined(srs)) {
2308
+ params.srs = srs;
2309
+ }
2310
+ }
2311
+ // NGW REST API is not able to filtering by combined queries
2312
+ // therefore the filter is divided into several requests
2313
+ function createFeatureFieldFilterQueries(opt) {
2314
+ const queries = getQueries(opt);
2315
+ return CancelablePromise.all(queries).then((itemsParts) => {
2316
+ // this list of ids used for optimization
2317
+ const ids = [];
2318
+ const items = [];
2319
+ for (const part of itemsParts) {
2320
+ for (const item of part) {
2321
+ if (!ids.includes(item.id)) {
2322
+ items.push(item);
2323
+ ids.push(item.id);
2324
+ }
2325
+ }
2326
+ }
2327
+ const offset = opt.offset !== undefined ? opt.offset : 0;
2328
+ const limit = opt.limit !== undefined ? opt.limit : items.length;
2329
+ if (opt.offset || opt.limit) {
2330
+ return items.splice(offset, limit);
2331
+ }
2332
+ return items;
2333
+ });
2334
+ }
2335
+ function createParam(pf) {
2336
+ const [field, operation, value] = pf;
2337
+ const isFldStr = field !== 'id' ? 'fld_' : '';
2338
+ let vStart = '';
2339
+ let vEnd = '';
2340
+ const field_ = String(field)
2341
+ .trim()
2342
+ .replace(/^(%?)(.+?)(%?)$/, (m, a, b, c) => {
2343
+ vStart = a;
2344
+ vEnd = c;
2345
+ return b;
2346
+ });
2347
+ const v = vStart + value + vEnd;
2348
+ return [`${isFldStr}${field_}__${operation}`, v];
2349
+ }
2350
+ function getQueries(opt, _queries = [], _parentAllParams = []) {
2351
+ const { filters } = opt;
2352
+ const logic = typeof filters[0] === 'string' ? filters[0] : 'all';
2353
+ const filters_ = filters.filter((x) => Array.isArray(x));
2354
+ if (logic === 'any') {
2355
+ for (const f of filters_) {
2356
+ if (isPropertyFilter(f)) {
2357
+ _queries.push(fetchNgwLayerItemsRequest({
2358
+ ...opt,
2359
+ paramList: [..._parentAllParams, createParam(f)],
2360
+ }));
2361
+ }
2362
+ else {
2363
+ getQueries({
2364
+ ...opt,
2365
+ filters: f,
2366
+ }, _queries, [..._parentAllParams]);
2367
+ }
2368
+ }
2369
+ }
2370
+ else if (logic === 'all') {
2371
+ const filters = [];
2372
+ const propertiesFilterList = [];
2373
+ for (const f of filters_) {
2374
+ if (isPropertyFilter(f)) {
2375
+ filters.push(createParam(f));
2376
+ }
2377
+ else {
2378
+ propertiesFilterList.push(f);
2379
+ }
2380
+ }
2381
+ if (propertiesFilterList.length) {
2382
+ for (const x of propertiesFilterList) {
2383
+ getQueries({
2384
+ ...opt,
2385
+ filters: x,
2386
+ }, _queries, [..._parentAllParams, ...filters]);
2387
+ }
2388
+ }
2389
+ else {
2390
+ _queries.push(fetchNgwLayerItemsRequest({
2391
+ ...opt,
2392
+ paramList: [..._parentAllParams, ...filters],
2393
+ }));
2394
+ }
2395
+ }
2396
+ return _queries;
2397
+ }
2398
+ function createWktFromCoordArray(coord) {
2399
+ const polygon = coord.map(([lng, lat]) => {
2400
+ const [x, y] = degrees2meters(lng, lat).map((c) => round(c));
2401
+ return x + ' ' + y;
2402
+ });
2403
+ return `POLYGON((${polygon.join(', ')}))`;
2404
+ }
2405
+ function fetchNgwLayerItemsRequest(options) {
2406
+ const params = {
2407
+ ...FEATURE_REQUEST_PARAMS,
2408
+ };
2409
+ const { limit, cache, signal, offset, orderBy, paramList, connector, geomFormat, intersects, resourceId, } = options;
2410
+ if (limit) {
2411
+ if (limit !== Number.POSITIVE_INFINITY) {
2412
+ params.limit = limit;
2413
+ }
2414
+ }
2415
+ else {
2416
+ // Strict restriction on loading data from large layers
2417
+ params.limit = 7000;
2418
+ }
2419
+ if (offset) {
2420
+ params.offset = offset;
2421
+ }
2422
+ if (geomFormat) {
2423
+ params.geom_format = geomFormat;
2424
+ }
2425
+ updateItemRequestParam(params, options);
2426
+ if (orderBy) {
2427
+ params.order_by = orderBy.join(',');
2428
+ }
2429
+ if (Array.isArray(intersects)) {
2430
+ const coordinates = isLngLatBoundsArray(intersects)
2431
+ ? getBoundsCoordinates(intersects)
2432
+ : intersects;
2433
+ params.intersects = createWktFromCoordArray(coordinates);
2434
+ }
2435
+ else if (typeof intersects === 'string') {
2436
+ params.intersects = intersects;
2437
+ }
2438
+ if (paramList) {
2439
+ params.paramList = paramList;
2440
+ }
2441
+ const reqParams = {
2442
+ id: resourceId,
2443
+ ...params,
2444
+ };
2445
+ return connector.get('feature_layer.feature.collection', { cache, signal }, reqParams);
2446
+ }
2447
+
2448
+ function prepareNgwFieldsToPropertiesFilter(fields) {
2449
+ let f;
2450
+ for (f in fields) {
2451
+ const field = fields[f];
2452
+ if (isObject$1(field)) {
2453
+ const date = field;
2454
+ if (defined(date.year) && defined(date.month) && defined(date.day)) {
2455
+ const dt = [
2456
+ date.year,
2457
+ date.month - 1,
2458
+ date.day,
2459
+ ];
2460
+ if ('hour' in date) {
2461
+ [date.hour, date.minute, date.second].forEach((x) => {
2462
+ dt.push(x);
2463
+ });
2464
+ }
2465
+ fields[f] = new Date(...dt).toISOString();
2466
+ }
2467
+ }
2468
+ else if (f === 'id' && typeof field === 'string') {
2469
+ fields[f] = field.split(',').map(Number);
2470
+ }
2471
+ }
2472
+ return fields;
2473
+ }
2474
+
2475
+ function fetchNgwLayerItems(options) {
2476
+ const filters = options.filters;
2477
+ if (filters) {
2478
+ return createFeatureFieldFilterQueries({
2479
+ ...options,
2480
+ filters,
2481
+ }).then((data) => {
2482
+ var _a;
2483
+ const clientFilterValidate = (_a = options.clientFilterValidate) !== null && _a !== void 0 ? _a : isFilterWithAnyCase(filters);
2484
+ // Additional client-side filter check
2485
+ if (clientFilterValidate) {
2486
+ data = data.filter((y) => {
2487
+ const fields = prepareNgwFieldsToPropertiesFilter({
2488
+ ...y.fields,
2489
+ id: y.id,
2490
+ });
2491
+ const result = propertiesFilter(fields, filters);
2492
+ return result;
2493
+ });
2494
+ }
2495
+ return data;
2496
+ });
2497
+ }
2498
+ else {
2499
+ return fetchNgwLayerItemsRequest(options);
2500
+ }
2501
+ }
2502
+ function isFilterWithAnyCase(filters) {
2503
+ if (filters[0] === 'any') {
2504
+ return true;
2505
+ }
2506
+ for (let i = 1; i < filters.length; i++) {
2507
+ const p = filters[i];
2508
+ if (isArray(p)) {
2509
+ const deep = isFilterWithAnyCase(p);
2510
+ if (deep) {
2511
+ return true;
2512
+ }
2513
+ }
2514
+ }
2515
+ return false;
2516
+ }
2517
+
2518
+ class NgwProvider extends BaseProvider {
2519
+ constructor(options) {
2520
+ var _a;
2521
+ super(options);
2522
+ this.caseInsensitive = true;
2523
+ this.searchResources = [];
2524
+ this._abortControllers = [];
2525
+ if (!options.searchUrl && !((_a = options.connectorOptions) === null || _a === void 0 ? void 0 : _a.baseUrl)) {
2526
+ throw new Error('The `searchUrl` of `connectorOptions.baseUrl` are required');
2527
+ }
2528
+ this.connector =
2529
+ options.connector ||
2530
+ new NgwConnector({
2531
+ baseUrl: this.searchUrl,
2532
+ ...options.connectorOptions,
2533
+ });
2534
+ this.searchResources = options.searchResources;
2535
+ }
2536
+ abort() {
2537
+ this._abortControllers.forEach((a) => {
2538
+ a.abort();
2539
+ });
2540
+ this._abortControllers.length = 0;
2541
+ }
2542
+ async *search(query) {
2543
+ var _a, _b;
2544
+ const signal = this._makeSignal();
2545
+ for (const config of this.searchResources) {
2546
+ if (signal.aborted) {
2547
+ break;
2548
+ }
2549
+ const { searchMethod } = config;
2550
+ const limit = (_a = config.limit) !== null && _a !== void 0 ? _a : NgwProvider.limit;
2551
+ //
2552
+ const resourceId = (_b = config.id) !== null && _b !== void 0 ? _b : config.resourceId;
2553
+ try {
2554
+ const resource = await this.connector.getResourceOrFail(resourceId, {
2555
+ cache: true,
2556
+ });
2557
+ const options = {
2558
+ connector: this.connector,
2559
+ resourceId,
2560
+ signal,
2561
+ limit,
2562
+ };
2563
+ if (searchMethod === 'like') {
2564
+ options.like = query;
2565
+ }
2566
+ else {
2567
+ options.ilike = query;
2568
+ }
2569
+ const request = fetchNgwLayerItems(options);
2570
+ const entries = await request;
2571
+ for (const item of this._items({
2572
+ entries,
2573
+ query,
2574
+ config,
2575
+ resourceItem: resource,
2576
+ })) {
2577
+ item.result = () => this.result(item);
2578
+ yield item;
2579
+ }
2580
+ }
2581
+ catch (er) {
2582
+ if (er &&
2583
+ 'name' in er &&
2584
+ er.name !== 'CancelError') {
2585
+ console.warn(er);
2586
+ }
2587
+ }
2588
+ }
2589
+ }
2590
+ result(item) {
2591
+ const signal = this._makeSignal();
2592
+ const req = this.connector
2593
+ .get('feature_layer.feature.item_extent', { signal }, {
2594
+ id: item.resourceId,
2595
+ fid: item.featureId,
2596
+ })
2597
+ .then((x) => {
2598
+ const e = x.extent;
2599
+ return {
2600
+ text: item.text,
2601
+ extent: [e.minLon, e.minLat, e.maxLon, e.maxLat],
2602
+ };
2603
+ });
2604
+ return req;
2605
+ }
2606
+ _makeSignal() {
2607
+ const abortController = new AbortController();
2608
+ this._abortControllers.push(abortController);
2609
+ return abortController.signal;
2610
+ }
2611
+ _items({ entries, query, config, resourceItem, }) {
2612
+ var _a;
2613
+ const items = [];
2614
+ let labelField = undefined;
2615
+ if (resourceItem.feature_layer) {
2616
+ labelField = (_a = resourceItem.feature_layer.fields.find((f) => f.label_field)) === null || _a === void 0 ? void 0 : _a.keyname;
2617
+ }
2618
+ const meta = this.searchResources.find((x) => { var _a; return (_a = x.id) !== null && _a !== void 0 ? _a : x.resourceId === resourceItem.resource.id; });
2619
+ if (meta) {
2620
+ entries.forEach((entry) => {
2621
+ let text = labelField ? entry.fields[labelField] : entry.id;
2622
+ if (config.renderSearch) {
2623
+ text = config.renderSearch({
2624
+ item: entry,
2625
+ resourceItem,
2626
+ });
2627
+ }
2628
+ else if (labelField) {
2629
+ text = entry.fields[labelField];
2630
+ }
2631
+ items.push({
2632
+ query: query,
2633
+ text,
2634
+ featureId: entry.id,
2635
+ resourceId: resourceItem.resource.id,
2636
+ item: entry,
2637
+ resourceItem,
2638
+ });
2639
+ });
2640
+ }
2641
+ return items;
2642
+ }
2643
+ }
2644
+ NgwProvider.limit = 300;
2645
+
2646
+ class NominatimProvider extends BaseProvider {
2647
+ constructor(options) {
2648
+ super(options);
2649
+ this.searchUrl = 'https://nominatim.openstreetmap.org';
2650
+ this._requests = [];
2651
+ }
2652
+ abort() {
2653
+ this._requests.forEach((x) => x.cancel());
2654
+ this._requests = [];
2655
+ }
2656
+ async *search(val) {
2657
+ // RFC2616 accept - language string
2658
+ const url = fixUrlStr(
2659
+ // `${this.baseUrl}/search?format=geojson&polygon_geojson=1${window.locale === 'ru' ? '&accept-language=ru-RU,en-US' : ''}&q=${val}`
2660
+ `${this.searchUrl}/search?format=geojson&polygon_geojson=1&q=${val}`);
2661
+ const request = new CancelablePromise((resolve, reject, onCancel) => {
2662
+ const xhr = new XMLHttpRequest();
2663
+ xhr.open('GET', url, true);
2664
+ xhr.onload = () => {
2665
+ try {
2666
+ const geojson = JSON.parse(xhr.responseText);
2667
+ const features = geojson.features.map((x) => {
2668
+ return {
2669
+ geom: x,
2670
+ extent: x.bbox,
2671
+ text: x.properties && x.properties.display_name,
2672
+ query: val,
2673
+ };
2674
+ });
2675
+ resolve(features);
2676
+ }
2677
+ catch (er) {
2678
+ reject(er);
2679
+ }
2680
+ };
2681
+ xhr.onerror = (er) => {
2682
+ reject(er);
2683
+ };
2684
+ onCancel(() => {
2685
+ xhr.abort();
2686
+ });
2687
+ xhr.send();
2688
+ }).catch((er) => {
2689
+ if (er.name === 'CancelError') ;
2690
+ throw er;
2691
+ });
2692
+ this._requests.push(request);
2693
+ const items = await request;
2694
+ if (items) {
2695
+ for (const i of items) {
2696
+ i.result = () => this.result(i);
2697
+ yield i;
2698
+ }
2699
+ }
2700
+ }
2701
+ result(model) {
2702
+ return CancelablePromise.resolve({
2703
+ text: model.text,
2704
+ extent: model.extent || [],
2705
+ geom: model.geom,
2706
+ });
2707
+ }
2708
+ }
2709
+
2710
+ /**
2711
+ * Modern geocoder on async generators. May use different data providers.
2712
+ *
2713
+ * @packageDocumentation
2714
+ * @module geocoder
2715
+ */
2716
+ function create(options) {
2717
+ return new Geocoder(options);
2646
2718
  }
2647
2719
 
2648
2720
  export { BaseProvider, Geocoder, NgwProvider, NominatimProvider, create };