szdl-utils-kit 0.3.14 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
- var _t = Object.defineProperty;
2
- var Et = (_, r, e) => r in _ ? _t(_, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : _[r] = e;
3
- var I = (_, r, e) => (Et(_, typeof r != "symbol" ? r + "" : r, e), e), ct = (_, r, e) => {
4
- if (!r.has(_))
1
+ var zt = Object.defineProperty;
2
+ var Zt = (S, r, e) => r in S ? zt(S, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : S[r] = e;
3
+ var w = (S, r, e) => (Zt(S, typeof r != "symbol" ? r + "" : r, e), e), Bt = (S, r, e) => {
4
+ if (!r.has(S))
5
5
  throw TypeError("Cannot " + e);
6
6
  };
7
- var T = (_, r, e) => (ct(_, r, "read from private field"), e ? e.call(_) : r.get(_)), U = (_, r, e) => {
8
- if (r.has(_))
7
+ var R = (S, r, e) => (Bt(S, r, "read from private field"), e ? e.call(S) : r.get(S)), I = (S, r, e) => {
8
+ if (r.has(S))
9
9
  throw TypeError("Cannot add the same private member more than once");
10
- r instanceof WeakSet ? r.add(_) : r.set(_, e);
11
- }, X = (_, r, e, i) => (ct(_, r, "write to private field"), i ? i.call(_, e) : r.set(_, e), e);
12
- var J = (_, r, e) => (ct(_, r, "access private method"), e);
13
- var Tt = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
14
- function Rt(_) {
15
- return _ && _.__esModule && Object.prototype.hasOwnProperty.call(_, "default") ? _.default : _;
10
+ r instanceof WeakSet ? r.add(S) : r.set(S, e);
11
+ }, J = (S, r, e, s) => (Bt(S, r, "write to private field"), s ? s.call(S, e) : r.set(S, e), e);
12
+ var E = (S, r, e) => (Bt(S, r, "access private method"), e);
13
+ var Vt = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
14
+ function $t(S) {
15
+ return S && S.__esModule && Object.prototype.hasOwnProperty.call(S, "default") ? S.default : S;
16
16
  }
17
- var lt = { exports: {} };
18
- (function(_, r) {
17
+ var Ct = { exports: {} };
18
+ (function(S, r) {
19
19
  (function(e) {
20
20
  Array.prototype.indexOf || (Array.prototype.indexOf = function(t, a) {
21
21
  var d, g;
@@ -24,31 +24,31 @@ var lt = { exports: {} };
24
24
  return d;
25
25
  return -1;
26
26
  });
27
- var i = this, n = function(t, a) {
27
+ var s = this, n = function(t, a) {
28
28
  for (var d = t.toString(); d.length < a; )
29
29
  d = "0" + d;
30
30
  return d;
31
31
  }, o = function(t, a) {
32
32
  return a !== e ? (t.year(a.year() || a.year), t.month(a.month() || a.month), t.day(a.day() || a.day), t.hours(a.hours() || a.hours), t.minutes(a.minutes() || a.minutes), t.seconds(a.seconds() || a.seconds), t.milliseconds(a.milliseconds() || a.milliseconds), t) : e;
33
- }, l = function(t, a) {
33
+ }, h = function(t, a) {
34
34
  var d, g = "";
35
35
  return d = t.slice(a, a + 1), d !== "" && !isNaN(Number(d)) && (g += "%H"), d = t.charAt(a + 2), d !== "" && d === ":" && (g += d), d = t.slice(a + 3, a + 4), d !== "" && !isNaN(Number(d)) && (g += "%M"), d = t.charAt(a + 5), d !== "" && d === ":" && (g += d), d = t.slice(a + 6, a + 7), d !== "" && !isNaN(Number(d)) && (g += "%S"), g;
36
- }, c = function(t, a) {
36
+ }, A = function(t, a) {
37
37
  var d, g = [
38
38
  t.slice(a, a + 1),
39
39
  t.charAt(a + 2),
40
40
  t.slice(a + 3, a + 4),
41
41
  t.charAt(a + 5),
42
42
  t.slice(a + 6, a + 9)
43
- ], k;
44
- return !isNaN(Number(g[0])) && !isNaN(Number(g[2])) && !isNaN(Number(g[4])) ? (g[1] === "." && g[3] === "." ? d = "%d.%m.%Y" : g[1] === "-" && g[3] === "-" ? d = "%m-%d-%Y" : g[1] === "/" && g[3] === "/" && (d = "%m/%d/%Y"), d) : (k = [
43
+ ], D;
44
+ return !isNaN(Number(g[0])) && !isNaN(Number(g[2])) && !isNaN(Number(g[4])) ? (g[1] === "." && g[3] === "." ? d = "%d.%m.%Y" : g[1] === "-" && g[3] === "-" ? d = "%m-%d-%Y" : g[1] === "/" && g[3] === "/" && (d = "%m/%d/%Y"), d) : (D = [
45
45
  t.slice(a, a + 3),
46
46
  t.charAt(a + 4),
47
47
  t.slice(a + 5, a + 6),
48
48
  t.charAt(a + 7),
49
49
  t.slice(a + 8, a + 9)
50
- ], !isNaN(Number(k[0])) && !isNaN(Number(k[2])) && !isNaN(Number(k[4])) ? (k[1] === "-" && k[3] === "-" && (d = "%Y-%m-%d"), d) : "");
51
- }, h = i.tempus, s, f, m = i.navigator || {}, A = "en", u = {
50
+ ], !isNaN(Number(D[0])) && !isNaN(Number(D[2])) && !isNaN(Number(D[4])) ? (D[1] === "-" && D[3] === "-" && (d = "%Y-%m-%d"), d) : "");
51
+ }, l = s.tempus, i, u, y = s.navigator || {}, c = "en", f = {
52
52
  en: {
53
53
  JANUARY_SHORT: "Jan",
54
54
  FEBRUARY_SHORT: "Feb",
@@ -209,66 +209,66 @@ var lt = { exports: {} };
209
209
  FRIDAY_LONG: "Freitag",
210
210
  SATURDAY_LONG: "Samstag"
211
211
  }
212
- }, N = function() {
212
+ }, O = function() {
213
213
  return [
214
- u[A].JANUARY_LONG,
215
- u[A].FEBRUARY_LONG,
216
- u[A].MARCH_LONG,
217
- u[A].APRIL_LONG,
218
- u[A].MAY_LONG,
219
- u[A].JUNE_LONG,
220
- u[A].JULY_LONG,
221
- u[A].AUGUST_LONG,
222
- u[A].SEPTEMBER_LONG,
223
- u[A].OCTOBER_LONG,
224
- u[A].NOVEMBER_LONG,
225
- u[A].DECEMBER_LONG
214
+ f[c].JANUARY_LONG,
215
+ f[c].FEBRUARY_LONG,
216
+ f[c].MARCH_LONG,
217
+ f[c].APRIL_LONG,
218
+ f[c].MAY_LONG,
219
+ f[c].JUNE_LONG,
220
+ f[c].JULY_LONG,
221
+ f[c].AUGUST_LONG,
222
+ f[c].SEPTEMBER_LONG,
223
+ f[c].OCTOBER_LONG,
224
+ f[c].NOVEMBER_LONG,
225
+ f[c].DECEMBER_LONG
226
226
  ];
227
- }, y = function() {
227
+ }, _ = function() {
228
228
  return [
229
- u[A].JANUARY_SHORT,
230
- u[A].FEBRUARY_SHORT,
231
- u[A].MARCH_SHORT,
232
- u[A].APRIL_SHORT,
233
- u[A].MAY_SHORT,
234
- u[A].JUNE_SHORT,
235
- u[A].JULY_SHORT,
236
- u[A].AUGUST_SHORT,
237
- u[A].SEPTEMBER_SHORT,
238
- u[A].OCTOBER_SHORT,
239
- u[A].NOVEMBER_SHORT,
240
- u[A].DECEMBER_SHORT
229
+ f[c].JANUARY_SHORT,
230
+ f[c].FEBRUARY_SHORT,
231
+ f[c].MARCH_SHORT,
232
+ f[c].APRIL_SHORT,
233
+ f[c].MAY_SHORT,
234
+ f[c].JUNE_SHORT,
235
+ f[c].JULY_SHORT,
236
+ f[c].AUGUST_SHORT,
237
+ f[c].SEPTEMBER_SHORT,
238
+ f[c].OCTOBER_SHORT,
239
+ f[c].NOVEMBER_SHORT,
240
+ f[c].DECEMBER_SHORT
241
241
  ];
242
- }, p = function() {
242
+ }, m = function() {
243
243
  return [
244
- u[A].SUNDAY_LONG,
245
- u[A].MONDAY_LONG,
246
- u[A].TUESDAY_LONG,
247
- u[A].WEDNESDAY_LONG,
248
- u[A].THURSDAY_LONG,
249
- u[A].FRIDAY_LONG,
250
- u[A].SATURDAY_LONG
244
+ f[c].SUNDAY_LONG,
245
+ f[c].MONDAY_LONG,
246
+ f[c].TUESDAY_LONG,
247
+ f[c].WEDNESDAY_LONG,
248
+ f[c].THURSDAY_LONG,
249
+ f[c].FRIDAY_LONG,
250
+ f[c].SATURDAY_LONG
251
251
  ];
252
- }, R = function() {
252
+ }, N = function() {
253
253
  return [
254
- u[A].SUNDAY_SHORT,
255
- u[A].MONDAY_SHORT,
256
- u[A].TUESDAY_SHORT,
257
- u[A].WEDNESDAY_SHORT,
258
- u[A].THURSDAY_SHORT,
259
- u[A].FRIDAY_SHORT,
260
- u[A].SATURDAY_SHORT
254
+ f[c].SUNDAY_SHORT,
255
+ f[c].MONDAY_SHORT,
256
+ f[c].TUESDAY_SHORT,
257
+ f[c].WEDNESDAY_SHORT,
258
+ f[c].THURSDAY_SHORT,
259
+ f[c].FRIDAY_SHORT,
260
+ f[c].SATURDAY_SHORT
261
261
  ];
262
- }, b, M, D, B, F = function(t, a, d) {
262
+ }, p, T, k, C, U = function(t, a, d) {
263
263
  var g;
264
- i.XMLHttpRequest ? g = new XMLHttpRequest() : g = new ActiveXObject("Microsoft.XMLHTTP"), g.onreadystatechange = function() {
265
- g.readyState === 4 && (g.status === 200 ? a && (i.JSON === e ? alert(`Please, include json2 into your project if you want use old browsers!
264
+ s.XMLHttpRequest ? g = new XMLHttpRequest() : g = new ActiveXObject("Microsoft.XMLHTTP"), g.onreadystatechange = function() {
265
+ g.readyState === 4 && (g.status === 200 ? a && (s.JSON === e ? alert(`Please, include json2 into your project if you want use old browsers!
266
266
  https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.parse(g.responseText))) : d && d(g));
267
267
  }, g.open("GET", t, !1), g.send();
268
- }, S = {
268
+ }, M = {
269
269
  "%d": {
270
270
  format: function(t) {
271
- return n(t.day() || s.MIN_DAY, 2);
271
+ return n(t.day() || i.MIN_DAY, 2);
272
272
  },
273
273
  parse: function(t) {
274
274
  var a = Number(t);
@@ -280,7 +280,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
280
280
  },
281
281
  "%m": {
282
282
  format: function(t) {
283
- return n(t.month() || s.MIN_MONTH, 2);
283
+ return n(t.month() || i.MIN_MONTH, 2);
284
284
  },
285
285
  parse: function(t) {
286
286
  var a = Number(t);
@@ -292,7 +292,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
292
292
  },
293
293
  "%Y": {
294
294
  format: function(t) {
295
- return n(t.year() || s.MIN_YEAR, 4);
295
+ return n(t.year() || i.MIN_YEAR, 4);
296
296
  },
297
297
  parse: function(t) {
298
298
  var a = Number(t);
@@ -304,7 +304,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
304
304
  },
305
305
  "%w": {
306
306
  format: function(t) {
307
- return t.dayOfWeek() || s.MIN_DAY_OF_WEEK;
307
+ return t.dayOfWeek() || i.MIN_DAY_OF_WEEK;
308
308
  },
309
309
  parse: function() {
310
310
  return {};
@@ -316,7 +316,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
316
316
  "%a": {
317
317
  format: function(t) {
318
318
  var a = t.dayOfWeek();
319
- return B[a !== e ? a : s.MIN_DAY_OF_WEEK];
319
+ return C[a !== e ? a : i.MIN_DAY_OF_WEEK];
320
320
  },
321
321
  parse: function() {
322
322
  return {};
@@ -328,7 +328,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
328
328
  "%A": {
329
329
  format: function(t) {
330
330
  var a = t.dayOfWeek();
331
- return D[a !== e ? a : s.MIN_DAY_OF_WEEK];
331
+ return k[a !== e ? a : i.MIN_DAY_OF_WEEK];
332
332
  },
333
333
  parse: function() {
334
334
  return {};
@@ -339,11 +339,11 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
339
339
  },
340
340
  "%b": {
341
341
  format: function(t) {
342
- var a = s.options("monthFromZero") ? t.month() : t.month() - 1;
343
- return M[a !== e ? a : s.MIN_MONTH];
342
+ var a = i.options("monthFromZero") ? t.month() : t.month() - 1;
343
+ return T[a !== e ? a : i.MIN_MONTH];
344
344
  },
345
345
  parse: function(t) {
346
- var a = s.monthNames().indexOf(t) + (s.options("monthFromZero") ? 0 : 1);
346
+ var a = i.monthNames().indexOf(t) + (i.options("monthFromZero") ? 0 : 1);
347
347
  return { month: a !== -1 ? a : e };
348
348
  },
349
349
  minLength: 1,
@@ -352,11 +352,11 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
352
352
  },
353
353
  "%B": {
354
354
  format: function(t) {
355
- var a = s.options("monthFromZero") ? t.month() : t.month() - 1;
356
- return b[a !== e ? a : s.MIN_MONTH];
355
+ var a = i.options("monthFromZero") ? t.month() : t.month() - 1;
356
+ return p[a !== e ? a : i.MIN_MONTH];
357
357
  },
358
358
  parse: function(t) {
359
- var a = s.monthNames(!0).indexOf(t) + (s.options("monthFromZero") ? 0 : 1);
359
+ var a = i.monthNames(!0).indexOf(t) + (i.options("monthFromZero") ? 0 : 1);
360
360
  return { month: a !== -1 ? a : e };
361
361
  },
362
362
  minLength: 1,
@@ -365,7 +365,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
365
365
  },
366
366
  "%H": {
367
367
  format: function(t) {
368
- return n(t.hours() || s.MIN_HOURS, 2);
368
+ return n(t.hours() || i.MIN_HOURS, 2);
369
369
  },
370
370
  parse: function(t) {
371
371
  var a = Number(t);
@@ -377,7 +377,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
377
377
  },
378
378
  "%M": {
379
379
  format: function(t) {
380
- return n(t.minutes() || s.MIN_MINUTES, 2);
380
+ return n(t.minutes() || i.MIN_MINUTES, 2);
381
381
  },
382
382
  parse: function(t) {
383
383
  var a = Number(t);
@@ -389,7 +389,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
389
389
  },
390
390
  "%S": {
391
391
  format: function(t) {
392
- return n(t.seconds() || s.MIN_SECONDS, 2);
392
+ return n(t.seconds() || i.MIN_SECONDS, 2);
393
393
  },
394
394
  parse: function(t) {
395
395
  var a = Number(t);
@@ -404,7 +404,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
404
404
  return t.timestamp();
405
405
  },
406
406
  parse: function(t) {
407
- return isNaN(Number(t)) ? {} : s(Number(t)).get();
407
+ return isNaN(Number(t)) ? {} : i(Number(t)).get();
408
408
  },
409
409
  minLength: 1,
410
410
  maxLength: 20,
@@ -412,7 +412,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
412
412
  },
413
413
  "%F": {
414
414
  format: function(t) {
415
- return n(t.year() || s.MIN_YEAR, 4) + "-" + n(t.month() || s.MIN_MONTH, 2) + "-" + n(t.day() || s.MIN_DAY, 2);
415
+ return n(t.year() || i.MIN_YEAR, 4) + "-" + n(t.month() || i.MIN_MONTH, 2) + "-" + n(t.day() || i.MIN_DAY, 2);
416
416
  },
417
417
  parse: function(t) {
418
418
  var a = Number(t.slice(0, 4)), d = Number(t.slice(5, 7)), g = Number(t.slice(8, 10));
@@ -428,7 +428,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
428
428
  },
429
429
  "%D": {
430
430
  format: function(t) {
431
- return n(t.month() || s.MIN_MONTH, 2) + "/" + n(t.day() || s.MIN_DAY, 2) + "/" + n(t.year() || s.MIN_YEAR, 4);
431
+ return n(t.month() || i.MIN_MONTH, 2) + "/" + n(t.day() || i.MIN_DAY, 2) + "/" + n(t.year() || i.MIN_YEAR, 4);
432
432
  },
433
433
  parse: function(t) {
434
434
  var a = Number(t.slice(0, 2)), d = Number(t.slice(3, 5)), g = Number(t.slice(6, 10));
@@ -442,11 +442,11 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
442
442
  maxLength: 10,
443
443
  type: "string"
444
444
  }
445
- }, W = {
445
+ }, H = {
446
446
  useMilliseconds: !1,
447
447
  monthFromZero: !1
448
- }, O;
449
- O = function(t, a, d) {
448
+ }, b;
449
+ b = function(t, a, d) {
450
450
  return this._d = /* @__PURE__ */ new Date(), this._i = {
451
451
  year: !1,
452
452
  month: !1,
@@ -456,55 +456,55 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
456
456
  seconds: !1,
457
457
  milliseconds: !1
458
458
  }, t !== e && this.set(t, a, d), this;
459
- }, O.fn = O.prototype, O.fn.dayCount = function() {
460
- var t = this.month(), a = s.MAX_DAY_IN_MONTHS[t - (s.options("monthFromZero") ? 0 : 1)];
461
- return this.leapYear() && t === (s.options("monthFromZero") ? 1 : 2) && (a += 1), a;
462
- }, O.fn.year = function(t) {
459
+ }, b.fn = b.prototype, b.fn.dayCount = function() {
460
+ var t = this.month(), a = i.MAX_DAY_IN_MONTHS[t - (i.options("monthFromZero") ? 0 : 1)];
461
+ return this.leapYear() && t === (i.options("monthFromZero") ? 1 : 2) && (a += 1), a;
462
+ }, b.fn.year = function(t) {
463
463
  if (arguments.length !== 0)
464
- (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= s.MIN_YEAR && Number(t) <= s.MAX_YEAR ? (this._d.setFullYear(Number(t)), this._i.year = !1) : this._i.year = Number(t) : (this._d.setFullYear(s.MIN_YEAR), this._i.year = !1);
464
+ (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= i.MIN_YEAR && Number(t) <= i.MAX_YEAR ? (this._d.setFullYear(Number(t)), this._i.year = !1) : this._i.year = Number(t) : (this._d.setFullYear(i.MIN_YEAR), this._i.year = !1);
465
465
  else
466
466
  return this._i.year === !1 ? this._d.getFullYear() : this._i.year;
467
467
  return this;
468
- }, O.fn.month = function(t) {
468
+ }, b.fn.month = function(t) {
469
469
  if (arguments.length !== 0)
470
- (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= s.MIN_MONTH && Number(t) <= s.MAX_MONTH ? (this._d.setMonth(s.options("monthFromZero") ? Number(t) : Number(t) - 1), this._i.month = !1) : this._i.month = Number(t) : (this._d.setMonth(s.options("monthFromZero") ? s.MIN_MONTH : s.MIN_MONTH - 1), this._i.month = !1);
470
+ (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= i.MIN_MONTH && Number(t) <= i.MAX_MONTH ? (this._d.setMonth(i.options("monthFromZero") ? Number(t) : Number(t) - 1), this._i.month = !1) : this._i.month = Number(t) : (this._d.setMonth(i.options("monthFromZero") ? i.MIN_MONTH : i.MIN_MONTH - 1), this._i.month = !1);
471
471
  else
472
- return this._i.month === !1 ? s.options("monthFromZero") ? this._d.getMonth() : this._d.getMonth() + 1 : this._i.month;
472
+ return this._i.month === !1 ? i.options("monthFromZero") ? this._d.getMonth() : this._d.getMonth() + 1 : this._i.month;
473
473
  return this;
474
- }, O.fn.day = function(t) {
474
+ }, b.fn.day = function(t) {
475
475
  if (arguments.length !== 0)
476
- (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= s.MIN_DAY && Number(t) <= this.dayCount() ? (this._d.setDate(Number(t)), this._i.day = !1) : this._i.day = Number(t) : (this._d.setDate(s.MIN_DAY), this._i.day = !1);
476
+ (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= i.MIN_DAY && Number(t) <= this.dayCount() ? (this._d.setDate(Number(t)), this._i.day = !1) : this._i.day = Number(t) : (this._d.setDate(i.MIN_DAY), this._i.day = !1);
477
477
  else
478
478
  return this._i.day === !1 ? this._d.getDate() : this._i.day;
479
479
  return this;
480
- }, O.fn.hours = function(t) {
480
+ }, b.fn.hours = function(t) {
481
481
  if (arguments.length !== 0)
482
- (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= s.MIN_HOURS && Number(t) <= s.MAX_HOURS ? (this._d.setHours(Number(t)), this._i.hours = !1) : this._i.hours = Number(t) : (this._d.setHours(s.MIN_HOURS), this._i.hours = !1);
482
+ (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= i.MIN_HOURS && Number(t) <= i.MAX_HOURS ? (this._d.setHours(Number(t)), this._i.hours = !1) : this._i.hours = Number(t) : (this._d.setHours(i.MIN_HOURS), this._i.hours = !1);
483
483
  else
484
484
  return this._i.hours === !1 ? this._d.getHours() : this._i.hours;
485
485
  return this;
486
- }, O.fn.minutes = function(t) {
486
+ }, b.fn.minutes = function(t) {
487
487
  if (arguments.length !== 0)
488
- (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= s.MIN_MINUTES && Number(t) <= s.MAX_MINUTES ? (this._d.setMinutes(Number(t)), this._i.minutes = !1) : this._i.minutes = Number(t) : (this._d.setMinutes(s.MIN_MINUTES), this._i.minutes = !1);
488
+ (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= i.MIN_MINUTES && Number(t) <= i.MAX_MINUTES ? (this._d.setMinutes(Number(t)), this._i.minutes = !1) : this._i.minutes = Number(t) : (this._d.setMinutes(i.MIN_MINUTES), this._i.minutes = !1);
489
489
  else
490
490
  return this._i.minutes === !1 ? this._d.getMinutes() : this._i.minutes;
491
491
  return this;
492
- }, O.fn.seconds = function(t) {
492
+ }, b.fn.seconds = function(t) {
493
493
  if (arguments.length !== 0)
494
- (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= s.MIN_SECONDS && Number(t) <= s.MAX_SECONDS ? (this._d.setSeconds(Number(t)), this._i.seconds = !1) : this._i.seconds = Number(t) : (this._d.setSeconds(s.MIN_SECONDS), this._i.seconds = !1);
494
+ (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= i.MIN_SECONDS && Number(t) <= i.MAX_SECONDS ? (this._d.setSeconds(Number(t)), this._i.seconds = !1) : this._i.seconds = Number(t) : (this._d.setSeconds(i.MIN_SECONDS), this._i.seconds = !1);
495
495
  else
496
496
  return this._i.seconds === !1 ? this._d.getSeconds() : this._i.seconds;
497
497
  return this;
498
- }, O.fn.milliseconds = function(t) {
498
+ }, b.fn.milliseconds = function(t) {
499
499
  if (arguments.length !== 0)
500
- (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= s.MIN_MILLISECONDS && Number(t) <= s.MAX_MILLISECONDS ? (this._d.setMilliseconds(Number(t)), this._i.milliseconds = !1) : this._i.milliseconds = Number(t) : (this._d.setMilliseconds(s.MIN_MILLISECONDS), this._i.milliseconds = !1);
500
+ (typeof t == "number" || typeof t == "string") && !isNaN(Number(t)) ? Number(t) >= i.MIN_MILLISECONDS && Number(t) <= i.MAX_MILLISECONDS ? (this._d.setMilliseconds(Number(t)), this._i.milliseconds = !1) : this._i.milliseconds = Number(t) : (this._d.setMilliseconds(i.MIN_MILLISECONDS), this._i.milliseconds = !1);
501
501
  else
502
502
  return this._i.milliseconds === !1 ? this._d.getMilliseconds() : this._i.milliseconds;
503
503
  return this;
504
- }, O.fn.week = function() {
505
- var t = new Date(this.year(), 0, 1), a = s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc() * 1e3;
504
+ }, b.fn.week = function() {
505
+ var t = new Date(this.year(), 0, 1), a = i(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc() * 1e3;
506
506
  return Math.ceil(((a - t.getTime()) / 864e5 + t.getDay() + 1) / 7);
507
- }, O.fn.set = function(t, a, d) {
507
+ }, b.fn.set = function(t, a, d) {
508
508
  if (this._i = {
509
509
  year: !1,
510
510
  month: !1,
@@ -518,11 +518,11 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
518
518
  if (t instanceof Date)
519
519
  return this._d = t, this;
520
520
  if (typeof t == "number")
521
- return this._d = new Date(t * (s.options("useMilliseconds") ? 1 : 1e3)), this;
522
- if (typeof t == "object" && (t instanceof Array ? (this.day(s.MIN_DAY), this.year(t[0]), this.month(t[1]), this.day(t[2]), this.hours(t[3]), this.minutes(t[4]), this.seconds(t[5]), this.milliseconds(t[6])) : (this.day(s.MIN_DAY), this.year(t.year), this.month(t.month), this.day(t.day), this.hours(t.hours), this.minutes(t.minutes), this.seconds(t.seconds), this.milliseconds(t.milliseconds))), typeof t == "string") {
523
- var g, k = [], E, L, v = [], Y = 0, G = 0, C, x, w = {}, H;
521
+ return this._d = new Date(t * (i.options("useMilliseconds") ? 1 : 1e3)), this;
522
+ if (typeof t == "object" && (t instanceof Array ? (this.day(i.MIN_DAY), this.year(t[0]), this.month(t[1]), this.day(t[2]), this.hours(t[3]), this.minutes(t[4]), this.seconds(t[5]), this.milliseconds(t[6])) : (this.day(i.MIN_DAY), this.year(t.year), this.month(t.month), this.day(t.day), this.hours(t.hours), this.minutes(t.minutes), this.seconds(t.seconds), this.milliseconds(t.milliseconds))), typeof t == "string") {
523
+ var g, D = [], L, B, Q = [], W = 0, x = 0, P, X, Y = {}, G;
524
524
  if (t === e)
525
- return E = o(this, d), E === e && (this._i = {
525
+ return L = o(this, d), L === e && (this._i = {
526
526
  year: -1,
527
527
  month: -1,
528
528
  day: -1,
@@ -530,26 +530,26 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
530
530
  minutes: -1,
531
531
  seconds: -1,
532
532
  milliseconds: -1
533
- }), E;
534
- for (a === e && (a = s.detectFormat(t)); Y < a.length; ) {
535
- if (a.charAt(Y) === "%") {
536
- if (L = a.charAt(Y) + a.charAt(Y + 1), S[L] !== e) {
537
- switch (C = 0, x = "", S[L].type) {
533
+ }), L;
534
+ for (a === e && (a = i.detectFormat(t)); W < a.length; ) {
535
+ if (a.charAt(W) === "%") {
536
+ if (B = a.charAt(W) + a.charAt(W + 1), M[B] !== e) {
537
+ switch (P = 0, X = "", M[B].type) {
538
538
  case "number":
539
- for (; C < S[L].maxLength && G + C < t.length && !isNaN(Number(t.charAt(G + C))); )
540
- x += t.charAt(G + C), C += 1;
539
+ for (; P < M[B].maxLength && x + P < t.length && !isNaN(Number(t.charAt(x + P))); )
540
+ X += t.charAt(x + P), P += 1;
541
541
  break;
542
542
  case "word":
543
- for (; C < S[L].maxLength && G + C < t.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(G + C)); )
544
- x += t.charAt(G + C), C += 1;
543
+ for (; P < M[B].maxLength && x + P < t.length && /^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(x + P)); )
544
+ X += t.charAt(x + P), P += 1;
545
545
  break;
546
546
  case "string":
547
- for (; C < S[L].maxLength && G + C < t.length; )
548
- x += t.charAt(G + C), C += 1;
547
+ for (; P < M[B].maxLength && x + P < t.length; )
548
+ X += t.charAt(x + P), P += 1;
549
549
  break;
550
550
  }
551
- if (C < S[L].minLength)
552
- return E = o(this, d), E === e && (this._i = {
551
+ if (P < M[B].minLength)
552
+ return L = o(this, d), L === e && (this._i = {
553
553
  year: -1,
554
554
  month: -1,
555
555
  day: -1,
@@ -557,11 +557,11 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
557
557
  minutes: -1,
558
558
  seconds: -1,
559
559
  milliseconds: -1
560
- }), E;
561
- k.push(L), v.push(x), C -= 1, G += C, Y += 1;
560
+ }), L;
561
+ D.push(B), Q.push(X), P -= 1, x += P, W += 1;
562
562
  }
563
- } else if (t.charAt(G) !== a.charAt(Y))
564
- return E = o(this, d), E === e && (this._i = {
563
+ } else if (t.charAt(x) !== a.charAt(W))
564
+ return L = o(this, d), L === e && (this._i = {
565
565
  year: -1,
566
566
  month: -1,
567
567
  day: -1,
@@ -569,33 +569,33 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
569
569
  minutes: -1,
570
570
  seconds: -1,
571
571
  milliseconds: -1
572
- }), E;
573
- Y += 1, G += 1;
572
+ }), L;
573
+ W += 1, x += 1;
574
574
  }
575
- for (g in k)
576
- k.hasOwnProperty(g) && S.hasOwnProperty(k[g]) && (H = S[k[g]].parse(v[g]), w = {
577
- year: H.year !== e ? H.year : w.year,
578
- month: H.month !== e ? H.month : w.month,
579
- day: H.day !== e ? H.day : w.day,
580
- hours: H.hours !== e ? H.hours : w.hours,
581
- minutes: H.minutes !== e ? H.minutes : w.minutes,
582
- seconds: H.seconds !== e ? H.seconds : w.seconds
575
+ for (g in D)
576
+ D.hasOwnProperty(g) && M.hasOwnProperty(D[g]) && (G = M[D[g]].parse(Q[g]), Y = {
577
+ year: G.year !== e ? G.year : Y.year,
578
+ month: G.month !== e ? G.month : Y.month,
579
+ day: G.day !== e ? G.day : Y.day,
580
+ hours: G.hours !== e ? G.hours : Y.hours,
581
+ minutes: G.minutes !== e ? G.minutes : Y.minutes,
582
+ seconds: G.seconds !== e ? G.seconds : Y.seconds
583
583
  });
584
- this.day(s.MIN_DAY), this.year(w.year), this.month(w.month), this.day(w.day), this.hours(w.hours), this.minutes(w.minutes), this.seconds(w.seconds), this.milliseconds(w.milliseconds);
584
+ this.day(i.MIN_DAY), this.year(Y.year), this.month(Y.month), this.day(Y.day), this.hours(Y.hours), this.minutes(Y.minutes), this.seconds(Y.seconds), this.milliseconds(Y.milliseconds);
585
585
  }
586
586
  return this;
587
- }, O.fn.leapYear = function() {
587
+ }, b.fn.leapYear = function() {
588
588
  var t = this.year();
589
589
  return t % 4 === 0 ? t % 100 === 0 ? t % 400 === 0 : !0 : !1;
590
- }, O.fn.timestamp = function(t) {
591
- return arguments.length !== 0 ? (this._d = new Date(Number(t) * (s.options("useMilliseconds") ? 1 : 1e3) + this._d.getTimezoneOffset() * 6e4), this) : s.options("useMilliseconds") ? this._d.getTime() - this._d.getTimezoneOffset() * 6e4 : Math.floor(this._d.getTime() / 1e3) - this._d.getTimezoneOffset() * 60;
592
- }, O.fn.utc = function(t) {
593
- return arguments.length !== 0 ? (this._d = new Date(Number(t) * (s.options("useMilliseconds") ? 1 : 1e3)), this) : s.options("useMilliseconds") ? this._d.getTime() : Math.floor(this._d.getTime() / 1e3);
594
- }, O.fn.dayOfWeek = function(t) {
590
+ }, b.fn.timestamp = function(t) {
591
+ return arguments.length !== 0 ? (this._d = new Date(Number(t) * (i.options("useMilliseconds") ? 1 : 1e3) + this._d.getTimezoneOffset() * 6e4), this) : i.options("useMilliseconds") ? this._d.getTime() - this._d.getTimezoneOffset() * 6e4 : Math.floor(this._d.getTime() / 1e3) - this._d.getTimezoneOffset() * 60;
592
+ }, b.fn.utc = function(t) {
593
+ return arguments.length !== 0 ? (this._d = new Date(Number(t) * (i.options("useMilliseconds") ? 1 : 1e3)), this) : i.options("useMilliseconds") ? this._d.getTime() : Math.floor(this._d.getTime() / 1e3);
594
+ }, b.fn.dayOfWeek = function(t) {
595
595
  if (t === "long")
596
- return D[this._d.getDay()];
596
+ return k[this._d.getDay()];
597
597
  if (t === "short")
598
- return B[this._d.getDay()];
598
+ return C[this._d.getDay()];
599
599
  if (t === e)
600
600
  return this._d.getDay();
601
601
  if (t === 0 || t === "Sunday")
@@ -612,7 +612,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
612
612
  return this.calc({ day: (this.dayOfWeek() === 0 ? -2 : 5) - this.dayOfWeek() });
613
613
  if (t === 6 || t === "Saturday")
614
614
  return this.calc({ day: (this.dayOfWeek() === 0 ? -1 : 6) - this.dayOfWeek() });
615
- }, O.fn.timezone = function(t) {
615
+ }, b.fn.timezone = function(t) {
616
616
  switch (t) {
617
617
  case "hours":
618
618
  return Math.floor(this._d.getTimezoneOffset() / 60);
@@ -621,12 +621,12 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
621
621
  default:
622
622
  return this._d.getTimezoneOffset() * 60;
623
623
  }
624
- }, O.fn.get = function(t) {
624
+ }, b.fn.get = function(t) {
625
625
  switch (t) {
626
626
  case "Date":
627
627
  return new Date(
628
628
  this.year(),
629
- this.month() - (s.options("monthFromZero") ? 0 : 1),
629
+ this.month() - (i.options("monthFromZero") ? 0 : 1),
630
630
  this.day(),
631
631
  this.hours(),
632
632
  this.minutes(),
@@ -636,7 +636,7 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
636
636
  case "DateUTC":
637
637
  return new Date(Date.UTC(
638
638
  this.year(),
639
- this.month() - (s.options("monthFromZero") ? 0 : 1),
639
+ this.month() - (i.options("monthFromZero") ? 0 : 1),
640
640
  this.day(),
641
641
  this.hours(),
642
642
  this.minutes(),
@@ -670,15 +670,15 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
670
670
  timestamp: this.timestamp()
671
671
  };
672
672
  }
673
- }, O.fn.format = function(t) {
673
+ }, b.fn.format = function(t) {
674
674
  for (var a = 0, d = "", g; a < t.length; )
675
- t.charAt(a) === "%" ? (g = t.charAt(a) + t.charAt(a + 1), S[g] !== e ? (d += S[g].format(this), a += 1) : d += "%") : d += t.charAt(a), a += 1;
675
+ t.charAt(a) === "%" ? (g = t.charAt(a) + t.charAt(a + 1), M[g] !== e ? (d += M[g].format(this), a += 1) : d += "%") : d += t.charAt(a), a += 1;
676
676
  return d;
677
- }, O.fn.valid = function() {
677
+ }, b.fn.valid = function() {
678
678
  return this._i.year === !1 && this._i.month === !1 && this._i.day === !1 && this._i.hours === !1 && this._i.minutes === !1 && this._i.seconds === !1 && this._i.milliseconds === !1;
679
- }, O.fn.errors = function() {
679
+ }, b.fn.errors = function() {
680
680
  return this._i;
681
- }, O.fn.between = function(t, a) {
681
+ }, b.fn.between = function(t, a) {
682
682
  var d = this.timestamp(), g = t.timestamp();
683
683
  switch (a) {
684
684
  case "year":
@@ -696,124 +696,267 @@ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`) : a(JSON.pars
696
696
  default:
697
697
  return e;
698
698
  }
699
- }, O.fn.calc = function(t) {
699
+ }, b.fn.calc = function(t) {
700
700
  return t.year !== e && this._d.setFullYear(this._d.getFullYear() + t.year), t.month !== e && this._d.setMonth(this._d.getMonth() + t.month), t.day !== e && this._d.setDate(this._d.getDate() + t.day), t.hours !== e && this._d.setHours(this._d.getHours() + t.hours), t.minutes !== e && this._d.setMinutes(this._d.getMinutes() + t.minutes), t.seconds !== e && this._d.setSeconds(this._d.getSeconds() + t.seconds), t.milliseconds !== e && this._d.setMilliseconds(this._d.getMilliseconds() + t.milliseconds), this;
701
- }, s = function(t, a, d) {
702
- return new O(t, a, d);
703
- }, s.MIN_YEAR = 1e3, s.MAX_YEAR = 3e3, s.MIN_MONTH = 1, s.MAX_MONTH = 12, s.MIN_DAY = 1, s.MAX_DAY_IN_MONTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], s.MIN_DAY_OF_WEEK = 0, s.MAX_DAY_OF_WEEK = 6, s.MIN_HOURS = 0, s.MAX_HOURS = 23, s.MIN_MINUTES = 0, s.MAX_MINUTES = 59, s.MIN_SECONDS = 0, s.MAX_SECONDS = 59, s.MIN_MILLISECONDS = 0, s.MAX_MILLISECONDS = 999, s.VERSION = "0.2.18", s.options = function(t, a) {
701
+ }, i = function(t, a, d) {
702
+ return new b(t, a, d);
703
+ }, i.MIN_YEAR = 1e3, i.MAX_YEAR = 3e3, i.MIN_MONTH = 1, i.MAX_MONTH = 12, i.MIN_DAY = 1, i.MAX_DAY_IN_MONTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], i.MIN_DAY_OF_WEEK = 0, i.MAX_DAY_OF_WEEK = 6, i.MIN_HOURS = 0, i.MAX_HOURS = 23, i.MIN_MINUTES = 0, i.MAX_MINUTES = 59, i.MIN_SECONDS = 0, i.MAX_SECONDS = 59, i.MIN_MILLISECONDS = 0, i.MAX_MILLISECONDS = 999, i.VERSION = "0.2.18", i.options = function(t, a) {
704
704
  if (t === e)
705
- return W;
706
- if (W.hasOwnProperty(t)) {
705
+ return H;
706
+ if (H.hasOwnProperty(t)) {
707
707
  if (a === e)
708
- return W[t];
709
- W[t] = a, t === "monthFromZero" && (s.MIN_MONTH = a ? 0 : 1, s.MAX_MONTH = a ? 11 : 12);
708
+ return H[t];
709
+ H[t] = a, t === "monthFromZero" && (i.MIN_MONTH = a ? 0 : 1, i.MAX_MONTH = a ? 11 : 12);
710
710
  }
711
711
  return e;
712
- }, s.noConflict = function() {
713
- return i.tempus = h, s;
714
- }, s.generate = function(t) {
715
- var a, d, g, k, E, L, v, Y;
716
- if (typeof t.dateFrom != "number" && (t.dateFrom instanceof O ? a = t.dateFrom.utc() : a = s(t.dateFrom, t.formatFrom).utc()), typeof t.dateTo != "number" && (t.dateTo instanceof O ? d = t.dateTo.utc() : d = s(t.dateTo, t.formatTo !== e ? t.formatTo : t.formatFrom).utc()), typeof t.period == "number" ? E = {
712
+ }, i.noConflict = function() {
713
+ return s.tempus = l, i;
714
+ }, i.generate = function(t) {
715
+ var a, d, g, D, L, B, Q, W;
716
+ if (typeof t.dateFrom != "number" && (t.dateFrom instanceof b ? a = t.dateFrom.utc() : a = i(t.dateFrom, t.formatFrom).utc()), typeof t.dateTo != "number" && (t.dateTo instanceof b ? d = t.dateTo.utc() : d = i(t.dateTo, t.formatTo !== e ? t.formatTo : t.formatFrom).utc()), typeof t.period == "number" ? L = {
717
717
  year: 0,
718
718
  month: 0,
719
719
  day: 0,
720
720
  hours: 0,
721
721
  minutes: 0,
722
722
  seconds: t.period
723
- } : typeof t.period == "string" ? E = {
723
+ } : typeof t.period == "string" ? L = {
724
724
  year: t.period === "year" ? 1 : 0,
725
725
  month: t.period === "month" ? 1 : 0,
726
726
  day: t.period === "day" ? 1 : 0,
727
727
  hours: t.period === "hours" ? 1 : 0,
728
728
  minutes: t.period === "minutes" ? 1 : 0,
729
729
  seconds: t.period === "seconds" ? 1 : 0
730
- } : typeof t.period == "object" && (E = {
730
+ } : typeof t.period == "object" && (L = {
731
731
  year: t.period.year !== e ? t.period.year : 0,
732
732
  month: t.period.month !== e ? t.period.month : 0,
733
733
  day: t.period.day !== e ? t.period.day : 0,
734
734
  hours: t.period.hours !== e ? t.period.hours : 0,
735
735
  minutes: t.period.minutes !== e ? t.period.minutes : 0,
736
736
  seconds: t.period.seconds !== e ? t.period.seconds : 0
737
- }), t.groupBy === e ? L = t.asObject === !0 ? {} : [] : (L = [], L.push([]), v = s(a).get()[t.groupBy]), Y = function(x, w, H) {
738
- return t.asObject === !0 ? t.format !== e ? x[s(w).format(t.format)] = {} : x[s(w).format("%F %H:%M:%S")] = {} : t.format !== e ? x.push(H ? null : s(w).format(t.format)) : x.push(H ? null : s(w)), x;
737
+ }), t.groupBy === e ? B = t.asObject === !0 ? {} : [] : (B = [], B.push([]), Q = i(a).get()[t.groupBy]), W = function(X, Y, G) {
738
+ return t.asObject === !0 ? t.format !== e ? X[i(Y).format(t.format)] = {} : X[i(Y).format("%F %H:%M:%S")] = {} : t.format !== e ? X.push(G ? null : i(Y).format(t.format)) : X.push(G ? null : i(Y)), X;
739
739
  }, t.groupBy !== e && t.fillNulls) {
740
- var G = {
741
- year: E.year ? -E.year : e,
742
- month: E.month ? -E.month : e,
743
- day: E.day ? -E.day : e,
744
- hours: E.hours ? -E.hours : e,
745
- minutes: E.minutes ? -E.minutes : e,
746
- seconds: E.seconds ? -E.seconds : e,
747
- milliseconds: E.milliseconds ? -E.milliseconds : e
740
+ var x = {
741
+ year: L.year ? -L.year : e,
742
+ month: L.month ? -L.month : e,
743
+ day: L.day ? -L.day : e,
744
+ hours: L.hours ? -L.hours : e,
745
+ minutes: L.minutes ? -L.minutes : e,
746
+ seconds: L.seconds ? -L.seconds : e,
747
+ milliseconds: L.milliseconds ? -L.milliseconds : e
748
748
  };
749
- for (g = s(a).calc(G).utc(); s(g).get()[t.groupBy] === v; )
750
- Y(L[L.length - 1], g, !0), g = s(g).calc(G).utc();
749
+ for (g = i(a).calc(x).utc(); i(g).get()[t.groupBy] === Q; )
750
+ W(B[B.length - 1], g, !0), g = i(g).calc(x).utc();
751
751
  if (t.groupBy === "week") {
752
- var C = s(a).dayOfWeek();
753
- for (g = s(a).dayOfWeek(0).utc(); L[0].length < C && g < a; )
754
- Y(L[L.length - 1], g, !0), g = s(g).calc(E).utc();
752
+ var P = i(a).dayOfWeek();
753
+ for (g = i(a).dayOfWeek(0).utc(); B[0].length < P && g < a; )
754
+ W(B[B.length - 1], g, !0), g = i(g).calc(L).utc();
755
755
  }
756
756
  }
757
757
  for (; a <= d; )
758
- t.groupBy === e ? Y(L, a) : s(a).get()[t.groupBy] === v ? Y(L[L.length - 1], a) : (L.push([]), Y(L[L.length - 1], a), v = s(a).get()[t.groupBy]), a = s(a).calc(E).utc();
758
+ t.groupBy === e ? W(B, a) : i(a).get()[t.groupBy] === Q ? W(B[B.length - 1], a) : (B.push([]), W(B[B.length - 1], a), Q = i(a).get()[t.groupBy]), a = i(a).calc(L).utc();
759
759
  if (t.groupBy !== e && t.fillNulls)
760
- for (k = s(d).calc(E).utc(); s(k).get()[t.groupBy] === v; )
761
- Y(L[L.length - 1], k, !0), k = s(k).calc(E).utc();
762
- return L;
763
- }, s.monthNames = function(t) {
760
+ for (D = i(d).calc(L).utc(); i(D).get()[t.groupBy] === Q; )
761
+ W(B[B.length - 1], D, !0), D = i(D).calc(L).utc();
762
+ return B;
763
+ }, i.monthNames = function(t) {
764
764
  switch (t) {
765
765
  case "long":
766
- return b;
766
+ return p;
767
767
  default:
768
- return M;
768
+ return T;
769
769
  }
770
- }, s.dayNames = function(t) {
770
+ }, i.dayNames = function(t) {
771
771
  switch (t) {
772
772
  case "long":
773
- return D;
773
+ return k;
774
774
  default:
775
- return B;
775
+ return C;
776
776
  }
777
- }, s.lang = function(t) {
777
+ }, i.lang = function(t) {
778
778
  if (t !== e)
779
- A = t, u[A] === e && (A = "en"), b = N(), M = y(), D = p(), B = R();
779
+ c = t, f[c] === e && (c = "en"), p = O(), T = _(), k = m(), C = N();
780
780
  else
781
- return A;
781
+ return c;
782
782
  return e;
783
- }, s.availableLangs = function() {
784
- return Object.keys(u);
785
- }, s.registerFormat = function(t, a, d, g, k, E) {
786
- S[t] = {
783
+ }, i.availableLangs = function() {
784
+ return Object.keys(f);
785
+ }, i.registerFormat = function(t, a, d, g, D, L) {
786
+ M[t] = {
787
787
  format: a,
788
788
  parse: d,
789
789
  minLength: g,
790
- maxLength: k,
791
- type: E
790
+ maxLength: D,
791
+ type: L
792
792
  };
793
- }, s.unregisterFormat = function(t) {
794
- delete S[t];
795
- }, s.detectFormat = function(t) {
793
+ }, i.unregisterFormat = function(t) {
794
+ delete M[t];
795
+ }, i.detectFormat = function(t) {
796
796
  var a, d, g;
797
- return a = c(t, 0), a !== "" && (g = 10), d = t.charAt(g), (d === "T" || d === " ") && (a += d, g += 1), a += l(t, g), a;
798
- }, f = {
799
- TempusDate: O
800
- }, s.classes = function(t, a) {
797
+ return a = A(t, 0), a !== "" && (g = 10), d = t.charAt(g), (d === "T" || d === " ") && (a += d, g += 1), a += h(t, g), a;
798
+ }, u = {
799
+ TempusDate: b
800
+ }, i.classes = function(t, a) {
801
801
  if (a === e)
802
- return f[t];
803
- f[t] = a;
804
- }, s.loadTranslations = function(t) {
805
- typeof t == "object" ? u = t : typeof t == "string" && F(t, function(a) {
806
- u = a;
802
+ return u[t];
803
+ u[t] = a;
804
+ }, i.loadTranslations = function(t) {
805
+ typeof t == "object" ? f = t : typeof t == "string" && U(t, function(a) {
806
+ f = a;
807
807
  }, function(a) {
808
808
  });
809
- }, A = (m.language || m.systemLanguage || m.userLanguage || "en").substr(0, 2).toLowerCase(), u[A] === e && (A = "en"), b = N(), M = y(), D = p(), B = R(), _.exports && (r = _.exports = s), r.tempus = s;
810
- }).call(Tt);
811
- })(lt, lt.exports);
812
- var Lt = lt.exports;
813
- const rt = /* @__PURE__ */ Rt(Lt);
814
- class K {
809
+ }, c = (y.language || y.systemLanguage || y.userLanguage || "en").substr(0, 2).toLowerCase(), f[c] === e && (c = "en"), p = O(), T = _(), k = m(), C = N(), S.exports && (r = S.exports = i), r.tempus = i;
810
+ }).call(Vt);
811
+ })(Ct, Ct.exports);
812
+ var te = Ct.exports;
813
+ const mt = /* @__PURE__ */ $t(te);
814
+ var gt, Yt, yt, pt, Nt, Ot, it, dt, _t, Gt, Tt, Wt, q, st, Z, ot, V, At, Et, xt, ht, kt;
815
+ const j = class j {
815
816
  constructor(r) {
816
- this.callBatch = r, this.result = {}, this.errors = {}, this.limit = 50, this.canContinue = !0, this.progressCall = "", this.limitCall = "", this.progressData = "", this.progressTimer = "", this.progressDelay = 100, this.oldPercent = "no", this.chunkRate = 1, this.totalProgress = 0, this.skipList = /* @__PURE__ */ new Set(), this.filterChunkSize = 50;
817
+ /**
818
+ * Режим «прогресс по доле завершённых подкоманд» — только когда пачка похожа на
819
+ * много параллельных list (crm.deal.list × N и т.п.). Иначе сохраняется старая
820
+ * формула sum(count)/sum(total)×chunkRate (один длинный list, batchTotalCount, смешанные batch).
821
+ * @returns {boolean}
822
+ */
823
+ I(this, gt);
824
+ /**
825
+ * Одно обновление колбэка прогресса, если снимок изменился.
826
+ * @returns {void}
827
+ */
828
+ I(this, it);
829
+ /**
830
+ * Проверяет, изменились ли метрики прогресса относительно предыдущей отправки.
831
+ *
832
+ * @param {{percent: number, allCount: number, allTotal: number}} snapshot - Текущий снимок прогресса.
833
+ * @returns {boolean} `true`, если нужно отправить callback прогресса.
834
+ */
835
+ I(this, _t);
836
+ /**
837
+ * Уведомляет подписчиков о текущем состоянии лимита.
838
+ *
839
+ * @returns {void}
840
+ */
841
+ I(this, Tt);
842
+ /**
843
+ * Включает состояние лимита, выдерживает паузу и затем выключает лимит.
844
+ * Используется как единый "cooldown" перед повторной отправкой chunk.
845
+ *
846
+ * @param {number} [pauseMs=this.defaultPauseMs] - Длительность паузы; для batch по умолчанию 120 с, для `call()` — `callLimitPauseMs` (30 с).
847
+ * @returns {Promise<void>}
848
+ */
849
+ I(this, q);
850
+ /**
851
+ * Проверяет operating-time в результате batch и ставит паузу,
852
+ * если сервер приблизился к лимиту выполнения.
853
+ *
854
+ * @param {Object} result - Результат текущего batch-запроса.
855
+ * @returns {Promise<number>} Максимальный operating-time среди команд.
856
+ */
857
+ I(this, Z);
858
+ /**
859
+ * Выполняет один chunk с автоматическим повтором после лимит-паузы.
860
+ * Повтор запускается при ошибках QUERY_LIMIT_EXCEEDED, OPERATION_TIME_LIMIT или TIMEOUT.
861
+ *
862
+ * @param {Object} chunk - Объект команд текущего chunk.
863
+ * @param {(result: Object) => Promise<void>} processResult - Обработчик успешного результата chunk.
864
+ * @returns {Promise<void>}
865
+ */
866
+ I(this, V);
867
+ /**
868
+ * Выполняет BX24.callMethod с таймаутом ожидания ответа.
869
+ *
870
+ * @param {string} method - Имя REST-метода.
871
+ * @param {Object} params - Параметры REST-метода.
872
+ * @returns {Promise<Object|null>} Raw-result BX24 или null при таймауте/ошибке вызова.
873
+ */
874
+ I(this, Et);
875
+ /**
876
+ * Resets mutable runtime state before each public batch run.
877
+ * @param {Function} progressCall - Progress callback for current run.
878
+ * @returns {void}
879
+ */
880
+ I(this, ht);
881
+ typeof r == "function" ? (this.callBatch = r, this.callMethod = null) : (this.callBatch = (r == null ? void 0 : r.callBatch) || null, this.callMethod = (r == null ? void 0 : r.callMethod) || null), this.result = {}, this.errors = {}, this.timeLimit = {
882
+ limit: !1,
883
+ date: void 0,
884
+ pauseMs: void 0
885
+ }, this.timeLimitListeners = /* @__PURE__ */ new Set(), this.canContinue = !0, this.progressCall = "", this.progressData = "", this.progressTimer = "", this.lastProgressSnapshot = null, this.chunkRate = 1, this.totalProgress = 0, this.batchCommandKeyOrder = [], this.totalBatchCommands = 0, this.batchCommandMethods = [], this.filterChunkSize = 50, this.limit = 50, this.progressDelay = 100, this.operatingThreshold = 475, this.defaultPauseMs = 12e4, this.callLimitPauseMs = 3e4, this.requestTimeoutMs = 6e4;
886
+ }
887
+ /**
888
+ * Вычисление текущего прогресса выполнения batch запросов
889
+ * @returns {{percent: number, allCount: number, allTotal: number}}
890
+ */
891
+ get progressPercent() {
892
+ if (!this.progressData)
893
+ return { percent: 0, allCount: 0, allTotal: 0 };
894
+ const r = this.totalBatchCommands || 0;
895
+ if (r > 0 && Array.isArray(this.batchCommandKeyOrder) && this.batchCommandKeyOrder.length && E(this, gt, Yt).call(this)) {
896
+ let A = 0;
897
+ for (const c of this.batchCommandKeyOrder) {
898
+ const f = this.progressData[c];
899
+ if (!f)
900
+ continue;
901
+ const O = Number(f.total) || 0, _ = Number(f.count) || 0;
902
+ O === 0 && _ === 0 ? A += 1 : O > 0 && (A += Math.min(1, _ / O));
903
+ }
904
+ const l = A / r * 100;
905
+ let i = Math.max(0, Math.min(100, Math.floor(l)));
906
+ const u = r, y = Math.min(r, Math.floor(A));
907
+ return { percent: i, allCount: y, allTotal: u };
908
+ }
909
+ let e = 0, s = 0;
910
+ for (const A of Object.values(this.progressData)) {
911
+ const { total: l, count: i } = A;
912
+ e += l ?? 0, s += i ?? 0;
913
+ }
914
+ const n = Number(this.chunkRate) || 0;
915
+ let o = 0;
916
+ e ? o = s / e * 100 * n + this.totalProgress : s === 0 && e === 0 ? o = 100 * n + this.totalProgress : o = 100, o = Math.max(0, Math.min(o, 100));
917
+ let h = Math.floor(o);
918
+ return e > 0 && s >= e && (h = 100), { percent: h, allCount: s, allTotal: e };
919
+ }
920
+ /**
921
+ * Обновление данных прогресса выполнения
922
+ * @param {Object} params
923
+ * @param {string} params.key - Ключ запроса
924
+ * @param {Object} params.value - Значение ответа от API
925
+ * @param {string} params.type - Тип обработки ('count' или undefined)
926
+ */
927
+ setProgressData({ key: r, value: e, type: s }) {
928
+ var f, O;
929
+ if (!this.progressCall)
930
+ return;
931
+ const n = this.getData(e.data()), o = Array.isArray(n) ? n.length : 0;
932
+ let h = o;
933
+ if (typeof e.total == "function") {
934
+ const _ = e.total();
935
+ if (_ != null && _ !== "") {
936
+ const m = Number(_);
937
+ Number.isFinite(m) && (h = m);
938
+ }
939
+ }
940
+ s === "count" && (h = o);
941
+ let A = 1;
942
+ n && (A = o), this.progressData || (this.progressData = {});
943
+ const l = ((f = this.progressData[r]) == null ? void 0 : f.total) ?? 0, i = ((O = this.progressData[r]) == null ? void 0 : O.count) ?? 0, u = A + i, y = Math.max(l, h ?? 0, u);
944
+ if (this.progressData[r] = {
945
+ total: y,
946
+ count: Math.min(u, y)
947
+ }, typeof document < "u" && (document == null ? void 0 : document.hidden) === !0) {
948
+ E(this, it, dt).call(this);
949
+ return;
950
+ }
951
+ E(this, it, dt).call(this), this.progressTimer || (this.progressTimer = setInterval(() => {
952
+ if (!this.progressCall) {
953
+ this.clearProgressData();
954
+ return;
955
+ }
956
+ E(this, it, dt).call(this);
957
+ const { percent: _ } = this.progressPercent;
958
+ _ >= 100 && (clearInterval(this.progressTimer), this.progressTimer = "");
959
+ }, this.progressDelay));
817
960
  }
818
961
  /**
819
962
  * Извлечение данных из ответа API с учетом различных форматов
@@ -821,7 +964,38 @@ class K {
821
964
  * @returns {any} Данные из ответа
822
965
  */
823
966
  getData(r) {
824
- return (r == null ? void 0 : r.items) ?? (r == null ? void 0 : r.tasks) ?? (r == null ? void 0 : r.types) ?? (r == null ? void 0 : r.type) ?? (r == null ? void 0 : r.fields) ?? (r == null ? void 0 : r.workgroups) ?? r;
967
+ if (r == null)
968
+ return r;
969
+ let e = (r == null ? void 0 : r.items) ?? (r == null ? void 0 : r.tasks) ?? (r == null ? void 0 : r.types) ?? (r == null ? void 0 : r.type) ?? (r == null ? void 0 : r.fields) ?? (r == null ? void 0 : r.workgroups) ?? r;
970
+ return e && typeof e == "object" && !Array.isArray(e) && Array.isArray(e.result) && (e = e.result), e;
971
+ }
972
+ /**
973
+ * Устанавливает состояние лимита и уведомляет подписчиков об изменении.
974
+ *
975
+ * @param {boolean} limit - Активен ли лимит.
976
+ * @param {string|undefined} date - ISO-дата начала лимита.
977
+ * @param {number|undefined} pauseMs - Длительность текущей лимит-паузы (мс); при снятии лимита не передаётся.
978
+ * @returns {void}
979
+ */
980
+ setTimeLimitState(r, e, s) {
981
+ this.timeLimit.limit = !!r, this.timeLimit.date = r ? e : void 0, r && typeof s == "number" && s > 0 ? this.timeLimit.pauseMs = s : this.timeLimit.pauseMs = void 0, E(this, Tt, Wt).call(this);
982
+ }
983
+ /**
984
+ * Подписывает внешний код на изменения состояния лимита.
985
+ * Callback вызывается сразу с текущим состоянием.
986
+ *
987
+ * @param {(state: {limit: boolean, date?: string, pauseMs?: number}) => void} callback - Обработчик состояния лимита.
988
+ * @returns {() => void} Функция отписки.
989
+ */
990
+ subscribeTimeLimit(r) {
991
+ return typeof r != "function" ? () => {
992
+ } : (this.timeLimitListeners.add(r), r({
993
+ limit: this.timeLimit.limit,
994
+ date: this.timeLimit.date,
995
+ pauseMs: this.timeLimit.pauseMs
996
+ }), () => {
997
+ this.timeLimitListeners.delete(r);
998
+ });
825
999
  }
826
1000
  /**
827
1001
  * Проверяет, содержит ли запрос большие массивы в фильтрах, которые могут вызвать 500 ошибку
@@ -831,26 +1005,26 @@ class K {
831
1005
  * @returns {Array} Массив запросов (может быть один или несколько)
832
1006
  */
833
1007
  splitLargeFilters(r, e) {
834
- const { method: i, params: n } = e;
1008
+ const { method: s, params: n } = e;
835
1009
  if (!n)
836
1010
  return [{ key: r, request: e }];
837
1011
  const o = n.filter || n.FILTER;
838
1012
  if (!o || typeof o != "object" || Array.isArray(o))
839
1013
  return [{ key: r, request: e }];
840
- for (const [l, c] of Object.entries(o))
841
- if (Array.isArray(c) && c.length > this.filterChunkSize) {
842
- const h = [];
843
- for (let s = 0; s < c.length; s += this.filterChunkSize) {
844
- const f = c.slice(s, s + this.filterChunkSize), m = s === 0 ? r : `${r}__chunk_${Math.floor(s / this.filterChunkSize)}`, A = { ...n };
845
- n.filter ? (A.filter = { ...o }, A.filter[l] = f) : n.FILTER && (A.FILTER = { ...o }, A.FILTER[l] = f), h.push({
846
- key: m,
847
- request: { method: i, params: A },
1014
+ for (const [h, A] of Object.entries(o))
1015
+ if (!String(h).trim().startsWith("!") && Array.isArray(A) && A.length > this.filterChunkSize) {
1016
+ const l = [];
1017
+ for (let i = 0; i < A.length; i += this.filterChunkSize) {
1018
+ const u = A.slice(i, i + this.filterChunkSize), y = i === 0 ? r : `${r}__chunk_${Math.floor(i / this.filterChunkSize)}`, c = { ...n };
1019
+ n.filter ? (c.filter = { ...o }, c.filter[h] = u) : n.FILTER && (c.FILTER = { ...o }, c.FILTER[h] = u), l.push({
1020
+ key: y,
1021
+ request: { method: s, params: c },
848
1022
  originalKey: r,
849
- filterKey: l,
850
- chunkIndex: Math.floor(s / this.filterChunkSize)
1023
+ filterKey: h,
1024
+ chunkIndex: Math.floor(i / this.filterChunkSize)
851
1025
  });
852
1026
  }
853
- return h;
1027
+ return l;
854
1028
  }
855
1029
  return [{ key: r, request: e }];
856
1030
  }
@@ -861,58 +1035,22 @@ class K {
861
1035
  * @returns {Array} Объединенный массив результатов
862
1036
  */
863
1037
  mergeSplitResults(r, e) {
864
- const i = [], n = Object.keys(r).filter((o) => o.startsWith(e)).sort((o, l) => {
865
- const c = o.match(/__chunk_(\d+)$/), h = l.match(/__chunk_(\d+)$/);
866
- return c ? h ? parseInt(c[1]) - parseInt(h[1]) : 1 : -1;
1038
+ const s = [], n = String(e).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), o = new RegExp(`^${n}(?:__chunk_\\d+)?$`), h = Object.keys(r).filter((A) => o.test(A)).sort((A, l) => {
1039
+ const i = A.match(/__chunk_(\d+)$/), u = l.match(/__chunk_(\d+)$/);
1040
+ return i ? u ? parseInt(i[1]) - parseInt(u[1]) : 1 : -1;
867
1041
  });
868
- for (const o of n) {
869
- const l = r[o];
870
- Array.isArray(l) ? i.push(...l) : l && i.push(l);
1042
+ for (const A of h) {
1043
+ const l = r[A];
1044
+ Array.isArray(l) ? s.push(...l) : l && s.push(l);
871
1045
  }
872
- return i;
873
- }
874
- /**
875
- * Вычисление текущего прогресса выполнения batch запросов
876
- * @returns {{percent: number, allCount: number, allTotal: number}}
877
- */
878
- get progressPercent() {
879
- let r = 0;
880
- if (!this.progressData)
881
- return { percent: Math.round(r), allCount: 0, allTotal: 0 };
882
- let e = 0, i = 0;
883
- return Object.values(this.progressData).forEach((n) => {
884
- const { total: o, count: l } = n;
885
- e += o ?? 0, i += l ?? 0;
886
- }), e ? r = i / e * 100 * this.chunkRate + this.totalProgress : i === 0 && e === 0 ? r = 100 * this.chunkRate + this.totalProgress : r = 100, { percent: Math.round(r), allCount: i, allTotal: e };
887
- }
888
- /**
889
- * Обновление данных прогресса выполнения
890
- * @param {Object} params
891
- * @param {string} params.key - Ключ запроса
892
- * @param {Object} params.value - Значение ответа от API
893
- * @param {string} params.type - Тип обработки ('count' или undefined)
894
- */
895
- setProgressData({ key: r, value: e, type: i }) {
896
- const n = this.getData(e.data()), o = Array.isArray(n) ? n.length : 0;
897
- let l = e.total() || o;
898
- i === "count" && (l = o);
899
- let c = 1;
900
- n && (c = o), this.progressCall && (this.progressData || (this.progressData = {}), this.progressData[r] && this.progressData[r].count && (c += this.progressData[r].count), this.progressData[r] ? this.progressData[r].count = c : this.progressData[r] = { total: l, count: c }, this.progressTimer || (this.progressTimer = setInterval(() => {
901
- const { percent: h, allCount: s, allTotal: f } = this.progressPercent;
902
- (this.oldPercent === "no" || this.oldPercent < this.progressPercent.percent) && (this.progressCall({
903
- data: this.progressData,
904
- percent: h,
905
- allCount: s,
906
- allTotal: f
907
- }), this.oldPercent = this.progressPercent.percent), h >= 100 && this.clearProgressData();
908
- }, this.progressDelay)));
1046
+ return s;
909
1047
  }
910
1048
  /**
911
1049
  * Задержка между запросами
912
1050
  * @returns {Promise<void>}
913
1051
  */
914
1052
  delay() {
915
- return new Promise((r) => setTimeout(r, 500));
1053
+ return typeof document < "u" && (document == null ? void 0 : document.hidden) === !0 ? Promise.resolve() : new Promise((e) => setTimeout(e, 500));
916
1054
  }
917
1055
  /**
918
1056
  * Обертка над callBatch с таймаутом для предотвращения зависаний
@@ -923,31 +1061,29 @@ class K {
923
1061
  * @returns {Promise<void>}
924
1062
  */
925
1063
  callBatchWithTimeout(r, e) {
926
- return new Promise((i, n) => {
927
- let o = !1;
928
- const l = 6e4;
929
- let c = !1, h = !1, s = !1, f = null, m = null;
930
- const A = async (y, p) => {
1064
+ return new Promise((s, n) => {
1065
+ let o = !1, h = null;
1066
+ const A = async (i) => {
931
1067
  if (!o) {
932
- o = !0, f && clearTimeout(f), m && clearTimeout(m);
1068
+ o = !0, h && clearTimeout(h);
933
1069
  try {
934
- await Promise.resolve(e(y)), i();
935
- } catch (R) {
936
- console.error(`Error in callBatch callback (attempt ${p}):`, R), n(R);
1070
+ await Promise.resolve(e(i)), s();
1071
+ } catch (u) {
1072
+ console.error("Error in callBatch callback:", u), n(u);
937
1073
  }
938
1074
  }
939
- }, u = async () => {
1075
+ }, l = async () => {
940
1076
  if (!o) {
941
- o = !0, f && clearTimeout(f), m && clearTimeout(m), console.warn(
942
- `Batch request timeout after ${l}ms on both attempts. This may indicate a CORS or network error.`
1077
+ o = !0, h && clearTimeout(h), console.warn(
1078
+ `Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`
943
1079
  );
944
- const y = {};
945
- Object.keys(r).forEach((p) => {
946
- y[p] = {
1080
+ const i = {};
1081
+ Object.keys(r).forEach((u) => {
1082
+ i[u] = {
947
1083
  error: () => ({
948
1084
  ex: {
949
1085
  error: "TIMEOUT",
950
- error_description: "Request timeout after 30 seconds. Possible CORS or network error."
1086
+ error_description: "Request timeout after 60 seconds. Possible CORS or network error."
951
1087
  }
952
1088
  }),
953
1089
  data: () => [],
@@ -955,27 +1091,24 @@ class K {
955
1091
  };
956
1092
  });
957
1093
  try {
958
- await Promise.resolve(e(y)), i();
959
- } catch (p) {
960
- console.error("Error in timeout callback:", p), i();
1094
+ await Promise.resolve(e(i)), s();
1095
+ } catch (u) {
1096
+ console.error("Error in timeout callback:", u), s();
961
1097
  }
962
1098
  }
963
- }, N = (y) => {
964
- try {
965
- this.callBatch(r, async (p) => {
966
- y === 1 && !c && !o ? (c = !0, await A(p, 1)) : y === 2 && !s && !o && (s = !0, await A(p, 2));
967
- });
968
- } catch (p) {
969
- o || console.error(`Error calling callBatch (attempt ${y}):`, p);
970
- }
971
1099
  };
972
- N(1), f = setTimeout(async () => {
973
- !c && !o && !h && (console.warn(
974
- `First batch request attempt timeout after ${l}ms. Starting second attempt...`
975
- ), h = !0, N(2), m = setTimeout(async () => {
976
- !c && !s && !o && await u();
977
- }, l));
978
- }, l);
1100
+ try {
1101
+ this.callBatch(r, async (i) => {
1102
+ await A(i);
1103
+ });
1104
+ } catch (i) {
1105
+ o || console.error("Error calling callBatch:", i);
1106
+ }
1107
+ h = setTimeout(async () => {
1108
+ o || (console.warn(
1109
+ `Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`
1110
+ ), await l());
1111
+ }, this.requestTimeoutMs);
979
1112
  });
980
1113
  }
981
1114
  /**
@@ -988,47 +1121,65 @@ class K {
988
1121
  * Очистка данных прогресса
989
1122
  */
990
1123
  clearProgressData() {
991
- clearInterval(this.progressTimer), this.progressTimer = "", this.progressData = "", this.progressCall = "", this.limitCall = "", this.oldPercent = "no";
1124
+ clearInterval(this.progressTimer), this.progressTimer = "", this.progressData = "", this.progressCall = "", this.lastProgressSnapshot = null;
992
1125
  }
993
1126
  /** Основная функция при вызове batch
994
- * @param {Array/Object} request - Массив/объект методов
995
- * @param {Function} progressCall - Функция получающая данные выполнения батча
996
- * @returns {Promise}
1127
+ * @param {Array|Object} requestList - Массив/объект методов.
1128
+ * @param {Function} progressCall - Функция получающая данные выполнения батча.
1129
+ * @param {{oneBatch?: boolean}} [options] - Опции выполнения.
1130
+ * @returns {Promise<Object>}
997
1131
  */
998
- async batch(r, e, i) {
999
- this.progressTimer && this.clearProgressData(), e && (this.progressCall = e), i && (this.limitCall = i), this.canContinue = !0, this.result = {}, this.errors = {};
1000
- const n = {}, o = {}, l = {};
1001
- for (const [f, m] of Object.entries(r)) {
1002
- const A = this.arrayChunk(m);
1003
- if (!A)
1132
+ async batch(r, e, s = {}) {
1133
+ E(this, ht, kt).call(this, e);
1134
+ const n = {}, o = {}, h = {};
1135
+ for (const [u, y] of Object.entries(r)) {
1136
+ const c = this.arrayChunk(y);
1137
+ if (!c)
1004
1138
  continue;
1005
- const u = this.splitLargeFilters(f, A);
1006
- if (u.length === 1)
1007
- o[f] = A;
1139
+ const f = this.splitLargeFilters(u, c);
1140
+ if (f.length === 1)
1141
+ o[u] = c;
1008
1142
  else {
1009
- l[f] = [];
1010
- for (const N of u)
1011
- o[N.key] = N.request, l[f].push(N.key);
1143
+ h[u] = [];
1144
+ for (const O of f)
1145
+ o[O.key] = O.request, h[u].push(O.key);
1012
1146
  }
1013
1147
  }
1014
- this.chunkRate = (1 / Math.ceil(Object.keys(o).length / this.limit)).toFixed(5);
1015
- let c = {}, h = 0;
1016
- const s = Object.keys(o).length;
1017
- for (const [f, m] of Object.entries(o)) {
1148
+ this.batchCommandKeyOrder = Object.keys(o), this.totalBatchCommands = this.batchCommandKeyOrder.length, this.batchCommandMethods = this.batchCommandKeyOrder.map(
1149
+ (u) => {
1150
+ var y;
1151
+ return String(((y = o[u]) == null ? void 0 : y.method) || "");
1152
+ }
1153
+ ), this.chunkRate = (1 / Math.ceil(Object.keys(o).length / this.limit)).toFixed(5);
1154
+ let A = {}, l = 0;
1155
+ const i = Object.keys(o).length;
1156
+ for (const [u, y] of Object.entries(o)) {
1018
1157
  if (!this.canContinue)
1019
1158
  break;
1020
- c[f] = m, (Object.keys(c).length >= 50 || h + 1 === s) && (await this.batchChunk(c), Object.entries(this.result).forEach(([A, u]) => {
1021
- n[A] = u;
1022
- }), this.totalProgress = Math.round(
1023
- h / s * 100
1024
- ), c = {}), h++;
1159
+ if (A[u] = y, Object.keys(A).length >= this.limit || l + 1 === i) {
1160
+ const c = l + 1 === i;
1161
+ await this.batchChunk(
1162
+ A,
1163
+ void 0,
1164
+ !c,
1165
+ {
1166
+ disablePagination: !1,
1167
+ oneBatch: !!(s != null && s.oneBatch)
1168
+ }
1169
+ ), Object.entries(this.result).forEach(([f, O]) => {
1170
+ n[f] = O;
1171
+ }), this.totalProgress = Math.round(
1172
+ l / i * 100
1173
+ ), A = {};
1174
+ }
1175
+ l++;
1025
1176
  }
1026
- for (const [f, m] of Object.entries(l))
1027
- if (m && m.length > 0) {
1028
- const A = this.mergeSplitResults(n, f);
1029
- for (const u of m)
1030
- delete n[u];
1031
- n[f] = A;
1177
+ for (const [u, y] of Object.entries(h))
1178
+ if (y && y.length > 0) {
1179
+ const c = this.mergeSplitResults(n, u);
1180
+ for (const f of y)
1181
+ delete n[f];
1182
+ n[u] = c;
1032
1183
  }
1033
1184
  return Object.entries(this.errors).length && (n.errorsList = this.errors), e && e({ percent: 100 }), Promise.resolve(n);
1034
1185
  }
@@ -1039,76 +1190,106 @@ class K {
1039
1190
  *
1040
1191
  * @param {Object} requestList - Объект с методами для выполнения
1041
1192
  * @param {Function} progressCall - Callback для отслеживания прогресса
1042
- * @param {Function} limitCall - Callback при превышении лимитов
1043
1193
  * @returns {Promise<Object>} Объект с количеством элементов для каждого ключа
1044
1194
  */
1045
- async batchTotalCount(r, e, i) {
1046
- this.progressTimer && this.clearProgressData(), e && (this.progressCall = e), i && (this.limitCall = i), this.canContinue = !0, this.result = {}, this.errors = {};
1047
- const n = {}, o = {}, l = {};
1048
- for (const [s, f] of Object.entries(r)) {
1049
- const m = this.arrayChunk(f);
1050
- if (!m)
1195
+ async batchTotalCount(r, e) {
1196
+ E(this, ht, kt).call(this, e);
1197
+ const s = {}, n = {}, o = {};
1198
+ for (const [l, i] of Object.entries(r)) {
1199
+ const u = this.arrayChunk(i);
1200
+ if (!u)
1051
1201
  continue;
1052
- const A = this.splitLargeFilters(s, m);
1053
- if (A.length === 1)
1054
- o[s] = m;
1202
+ const y = this.splitLargeFilters(l, u);
1203
+ if (y.length === 1)
1204
+ n[l] = u;
1055
1205
  else {
1056
- l[s] = [];
1057
- for (const u of A)
1058
- o[u.key] = u.request, l[s].push(u.key);
1206
+ o[l] = [];
1207
+ for (const c of y)
1208
+ n[c.key] = c.request, o[l].push(c.key);
1059
1209
  }
1060
1210
  }
1061
- const c = [], h = Object.entries(o);
1062
- for (let s = 0; s < h.length; s += this.limit) {
1063
- const f = h.slice(s, s + this.limit), m = {};
1064
- for (const [A, u] of f) {
1211
+ const h = [], A = Object.entries(n);
1212
+ for (let l = 0; l < A.length; l += this.limit) {
1213
+ const i = A.slice(l, l + this.limit), u = {};
1214
+ for (const [y, c] of i) {
1065
1215
  if (!this.canContinue)
1066
1216
  break;
1067
- m[A] = u;
1217
+ u[y] = c;
1068
1218
  }
1069
- Object.keys(m).length > 0 && c.push(m);
1219
+ Object.keys(u).length > 0 && h.push(u);
1070
1220
  }
1071
- this.chunkRate = (1 / c.length).toFixed(5);
1072
- for (const [s, f] of Object.entries(c)) {
1221
+ this.chunkRate = (1 / h.length).toFixed(5);
1222
+ for (const [l, i] of Object.entries(h)) {
1073
1223
  if (!this.canContinue)
1074
1224
  break;
1075
- this.totalProgress = Math.round(Number(s) / c.length * 100), await this.callBatchWithTimeout(f, async (m) => {
1076
- var A, u, N, y, p, R, b;
1077
- for (const [M, D] of Object.entries(m)) {
1225
+ this.totalProgress = Math.round(Number(l) / h.length * 100);
1226
+ const u = Number(l) === h.length - 1;
1227
+ await E(this, V, At).call(this, i, async (y) => {
1228
+ var c, f, O, _, m;
1229
+ for (const [N, p] of Object.entries(y)) {
1078
1230
  if (!this.canContinue)
1079
1231
  return;
1080
- if (D.error()) {
1081
- const O = (u = (A = D.error()) == null ? void 0 : A.ex) == null ? void 0 : u.error, t = (y = (N = D.error()) == null ? void 0 : N.ex) == null ? void 0 : y.error_description;
1082
- this.errors[M] = O && O.trim() || t && t.trim() || ((p = D.error()) == null ? void 0 : p.toString()) || "Неизвестная ошибка", n[M] = 0;
1083
- const a = ((b = (R = D.error()) == null ? void 0 : R.ex) == null ? void 0 : b.error) ?? "";
1084
- let d = "";
1085
- const g = f[M];
1086
- switch (Array.isArray(g) ? [d] = g : g != null && g.method && (d = g.method), a) {
1087
- case "OPERATION_TIME_LIMIT":
1088
- d && this.skipList.add(d), this.limitCall && this.limitCall(M);
1089
- break;
1090
- case "ACCESS_DENIED":
1091
- d && this.skipList.add(d);
1092
- break;
1093
- case "TIMEOUT":
1094
- d && this.skipList.add(d), this.limitCall && this.limitCall(M);
1095
- break;
1096
- }
1232
+ if (p.error()) {
1233
+ const M = (f = (c = p.error()) == null ? void 0 : c.ex) == null ? void 0 : f.error, H = (_ = (O = p.error()) == null ? void 0 : O.ex) == null ? void 0 : _.error_description;
1234
+ this.errors[N] = M && M.trim() || H && H.trim() || ((m = p.error()) == null ? void 0 : m.toString()) || "Неизвестная ошибка", s[N] = 0;
1097
1235
  continue;
1098
1236
  }
1099
- const B = this.getData(D.data()), F = Array.isArray(B) ? B.length : 0, W = typeof D.total == "function" && D.total() !== void 0 ? D.total() : F;
1100
- n[M] = W, this.setProgressData({ key: M, value: D, type: "count" });
1237
+ const T = this.getData(p.data()), k = Array.isArray(T) ? T.length : 0, U = typeof p.total == "function" && p.total() !== void 0 ? p.total() : k;
1238
+ s[N] = U, this.setProgressData({ key: N, value: p, type: "count" });
1101
1239
  }
1240
+ await E(this, Z, ot).call(this, y, !u);
1102
1241
  });
1103
1242
  }
1104
- for (const [s, f] of Object.entries(l))
1105
- if (f && f.length > 0) {
1106
- let m = 0;
1107
- for (const A of f)
1108
- n[A] !== void 0 && (m += n[A] || 0), delete n[A];
1109
- n[s] = m;
1243
+ for (const [l, i] of Object.entries(o))
1244
+ if (i && i.length > 0) {
1245
+ let u = 0;
1246
+ for (const y of i)
1247
+ s[y] !== void 0 && (u += s[y] || 0), delete s[y];
1248
+ s[l] = u;
1249
+ }
1250
+ return Object.entries(this.errors).length && (s.errorsList = this.errors, this.errorLogger()), e && e({ percent: 100 }), Promise.resolve(s);
1251
+ }
1252
+ /**
1253
+ * Выполняет одиночный REST-вызов с таймаутом и авто-повтором после лимит-паузы.
1254
+ * Повторяет вызов при QUERY_LIMIT_EXCEEDED / OPERATION_TIME_LIMIT / TIMEOUT.
1255
+ *
1256
+ * @param {{method: string, params?: Object}} request - Описание REST-вызова.
1257
+ * @returns {Promise<{success: boolean, data: any, answer: Object, error: string|null}>}
1258
+ */
1259
+ async call({ method: r, params: e = {} }) {
1260
+ var s, n, o, h, A, l, i;
1261
+ for (; ; ) {
1262
+ const u = await E(this, Et, xt).call(this, r, e);
1263
+ if (!u) {
1264
+ await E(this, q, st).call(this, this.callLimitPauseMs);
1265
+ continue;
1266
+ }
1267
+ const y = {};
1268
+ if (u != null && u.answer)
1269
+ for (const [f, O] of Object.entries(u.answer))
1270
+ f !== "result" && O && (y[f] = O);
1271
+ if (u.error()) {
1272
+ const f = ((n = (s = u.error()) == null ? void 0 : s.ex) == null ? void 0 : n.error) ?? "";
1273
+ if (["QUERY_LIMIT_EXCEEDED", "OPERATION_TIME_LIMIT", "TIMEOUT"].includes(f)) {
1274
+ await E(this, q, st).call(this, this.callLimitPauseMs);
1275
+ continue;
1276
+ }
1277
+ const O = ((o = u.error()) == null ? void 0 : o.toString()) || ((A = (h = u.error()) == null ? void 0 : h.ex) == null ? void 0 : A.error_description) || ((i = (l = u.error()) == null ? void 0 : l.ex) == null ? void 0 : i.error) || "Неизвестная ошибка";
1278
+ return {
1279
+ success: !1,
1280
+ data: !1,
1281
+ answer: y,
1282
+ error: O
1283
+ };
1110
1284
  }
1111
- return Object.entries(this.errors).length && (n.errorsList = this.errors, this.errorLogger()), e && e({ percent: 100 }), Promise.resolve(n);
1285
+ let c = u.data();
1286
+ return c != null && c.items && (c = c.items), {
1287
+ success: !0,
1288
+ data: c,
1289
+ answer: y,
1290
+ error: null
1291
+ };
1292
+ }
1112
1293
  }
1113
1294
  /** Валидация запросов
1114
1295
  * Чтобы не перегружать Битрикс сервера запросами с start - добавляем нужные поля в параметры
@@ -1116,32 +1297,30 @@ class K {
1116
1297
  * @param {Array/Object} request - Массив/объект методов
1117
1298
  */
1118
1299
  arrayChunk(r) {
1119
- let e = "", i = {};
1120
- if (Array.isArray(r) ? [e] = r : (e = r.method, i = r.params), this.skipList.has(e))
1121
- return !1;
1122
- if ((e.includes("list") || e === "user.get") && e !== "task.item.list") {
1123
- if (!i)
1124
- i = {
1300
+ let e = "", s = {};
1301
+ if (Array.isArray(r) ? [e] = r : (e = r.method, s = r.params), (e.includes("list") || e === "user.get" || e === "entity.item.get") && e !== "task.item.list") {
1302
+ if (!s)
1303
+ s = e === "entity.item.get" ? { SORT: { ID: "ASC" } } : {
1125
1304
  order: { ID: "ASC", id: "ASC" }
1126
1305
  };
1127
1306
  else {
1128
- e === "tasks.task.list" ? (i.order || (i.order = {}), i.order.ID = "asc") : e === "user.get" ? (i.sort || (i.sort = "ID"), i.order || (i.order = "ASC")) : i.order = { ID: "ASC", id: "ASC" }, Array.isArray(i.select) && !i.select.includes("ID") && i.select.push("ID");
1129
- const n = e === "user.get" ? i.FILTER : i.filter;
1130
- typeof n == "object" && n !== null && !Array.isArray(n) && Object.entries(n).forEach(([o, l]) => {
1131
- (i.start === void 0 || i.start !== -1) && ["id", "ID"].includes(o) && (typeof l == "string" || Array.isArray(l) && l.length <= 50) && (i.start = -1);
1307
+ e === "entity.item.get" ? (s.SORT || (s.SORT = { ID: "ASC" }), Array.isArray(s.select) ? s.select.includes("ID") || s.select.push("ID") : s.select = ["ID"]) : e === "tasks.task.list" ? (s.order || (s.order = {}), s.order.ID = "asc") : e === "user.get" ? (s.sort || (s.sort = "ID"), s.order || (s.order = "ASC")) : s.order = { ID: "ASC", id: "ASC" }, Array.isArray(s.select) && !s.select.includes("ID") && s.select.push("ID");
1308
+ const n = e === "user.get" || e === "entity.item.get" ? s.FILTER : s.filter;
1309
+ typeof n == "object" && n !== null && !Array.isArray(n) && Object.entries(n).forEach(([o, h]) => {
1310
+ (s.start === void 0 || s.start !== -1) && ["id", "ID"].includes(o) && (typeof h == "string" || Array.isArray(h) && h.length <= 50) && (s.start = -1);
1132
1311
  });
1133
1312
  }
1134
- e === "crm.type.list" && i.order && delete i.order.ID;
1313
+ e === "crm.type.list" && s.order && delete s.order.ID;
1135
1314
  }
1136
1315
  if (e === "task.item.list")
1137
- if (!i)
1138
- i = [{ ID: "ASC" }, [""], [""], ["ID"]];
1316
+ if (!s)
1317
+ s = [{ ID: "ASC" }, [""], [""], ["ID"]];
1139
1318
  else {
1140
- Array.isArray(i[0]) && (i[0] = {});
1141
- const [n, o, l, c] = i;
1142
- n.ID = "ASC", c[0] !== "" && c.includes("ID") || c.push("ID");
1319
+ Array.isArray(s[0]) && (s[0] = {});
1320
+ const [n, o, h, A] = s;
1321
+ n.ID = "ASC", A[0] !== "" && A.includes("ID") || A.push("ID");
1143
1322
  }
1144
- return { method: e, params: i };
1323
+ return { method: e, params: s };
1145
1324
  }
1146
1325
  /** Выполняет первичный запрос с массивом методов
1147
1326
  * При наличии более 50 элементов в нем, подготоваливаем данные и передаем в this.batchPayload
@@ -1149,133 +1328,149 @@ class K {
1149
1328
  * @param {Array} query - Тот же массив с методами
1150
1329
  * @returns {Object} Объект с результатами запросов
1151
1330
  */
1152
- async batchChunk(r, e) {
1153
- return new Promise((i) => {
1154
- const n = [];
1155
- let o;
1156
- this.callBatchWithTimeout(r, async (l) => {
1157
- var c, h, s, f, m, A, u;
1158
- for (const [N, y] of Object.entries(l)) {
1159
- if (!this.canContinue)
1160
- return;
1161
- if (y.error()) {
1162
- const B = (h = (c = y.error()) == null ? void 0 : c.ex) == null ? void 0 : h.error, F = (f = (s = y.error()) == null ? void 0 : s.ex) == null ? void 0 : f.error_description;
1163
- switch (this.errors[N] = B && B.trim() || F && F.trim() || ((m = y.error()) == null ? void 0 : m.toString()) || "Неизвестная ошибка", o = !0, ((u = (A = y.error()) == null ? void 0 : A.ex) == null ? void 0 : u.error) ?? "") {
1164
- case "OPERATION_TIME_LIMIT":
1165
- this.skipList.add(r[N].method), this.limitCall && this.limitCall(N);
1166
- break;
1167
- case "ACCESS_DENIED":
1168
- this.skipList.add(r[N].method);
1169
- break;
1170
- case "TIMEOUT":
1171
- let W = r[N], O = "";
1172
- Array.isArray(W) ? [O] = W : W != null && W.method && (O = W.method), O && this.skipList.add(O), this.limitCall && this.limitCall(N);
1173
- break;
1331
+ async batchChunk(r, e, s = !0, n = {}) {
1332
+ return new Promise((o) => {
1333
+ const h = [];
1334
+ let A;
1335
+ const l = !!(n != null && n.disablePagination);
1336
+ (async () => {
1337
+ await E(this, V, At).call(this, r, async (u) => {
1338
+ var c, f, O, _, m;
1339
+ for (const [N, p] of Object.entries(u)) {
1340
+ if (!this.canContinue)
1341
+ return;
1342
+ if (p.error()) {
1343
+ const g = (f = (c = p.error()) == null ? void 0 : c.ex) == null ? void 0 : f.error, D = (_ = (O = p.error()) == null ? void 0 : O.ex) == null ? void 0 : _.error_description;
1344
+ this.errors[N] = g && g.trim() || D && D.trim() || ((m = p.error()) == null ? void 0 : m.toString()) || "Неизвестная ошибка", A = !0;
1174
1345
  }
1175
- }
1176
- const p = this.getData(y.data()), R = Array.isArray(p) ? p.length : 0, b = typeof y.total == "function" && y.total() !== void 0, M = b ? y.total() : R;
1177
- e === "count" ? this.result[N] ? this.result[N] += R : this.result[N] = M : this.result[N] = p, this.setProgressData({ key: N, value: y, type: e });
1178
- const D = e === "count" ? !b && R === this.limit : M > this.limit && M > R;
1179
- if (!this.canContinue || D) {
1180
- let B = r[N];
1181
- if (Array.isArray(B)) {
1182
- const [F, S = {}] = B;
1183
- B = [F, S];
1184
- } else {
1185
- const { method: F, params: S = {} } = B;
1186
- B = [F, S];
1346
+ const T = this.getData(p.data()), k = Array.isArray(T) ? T.length : 0, C = typeof p.total == "function" && p.total() !== void 0, U = C ? p.total() : k;
1347
+ e === "count" ? this.result[N] ? this.result[N] += k : this.result[N] = U : this.result[N] = T, this.setProgressData({ key: N, value: p, type: e });
1348
+ const M = r[N], H = Array.isArray(M) ? M[0] : M == null ? void 0 : M.method, b = typeof H == "string" && (H.includes(".list") || H === "user.get" || H === "entity.item.get"), t = e === "count" ? !C && k === this.limit : b ? k === this.limit : U > this.limit && U > k, a = e !== "count" && H === "entity.item.get" && k === this.limit && !t, d = t || a;
1349
+ if (!l && (!this.canContinue || d)) {
1350
+ let g = r[N];
1351
+ if (Array.isArray(g)) {
1352
+ const [D, L = {}] = g;
1353
+ g = [D, L];
1354
+ } else {
1355
+ const { method: D, params: L = {} } = g;
1356
+ g = [D, L];
1357
+ }
1358
+ h.push([
1359
+ N,
1360
+ g,
1361
+ U,
1362
+ { entityItemGetScan: a }
1363
+ ]);
1187
1364
  }
1188
- n.push([N, B, M]);
1189
1365
  }
1190
- }
1191
- o > 0 && this.errorLogger(), n.length ? await this.batchPayload(n, e).then(
1192
- () => i(this.result)
1193
- ) : i(this.result);
1194
- });
1366
+ A > 0 && this.errorLogger();
1367
+ const y = h.length > 0 || s;
1368
+ await E(this, Z, ot).call(this, u, y), h.length ? await this.batchPayload(h, e, n).then(
1369
+ () => o(this.result)
1370
+ ) : o(this.result);
1371
+ });
1372
+ })();
1195
1373
  });
1196
1374
  }
1197
1375
  /** Функция для запроса списочных методов
1198
1376
  * @param {Array} payloadList - Массив с подмассивами списочных методов
1199
1377
  * @param {String} type - Тип обработки результатов ('count' или undefined)
1378
+ * @param {{oneBatch?: boolean}} [options] - Опции выполнения payload.
1200
1379
  */
1201
- async batchPayload(r, e) {
1202
- const i = /* @__PURE__ */ new Map(), n = (h, s, f, m) => {
1203
- let A = "ID";
1204
- this.result[h][this.result[h].length - 1].ID || (A = "id");
1205
- let u = `${A}`;
1206
- if (JSON.stringify(m[1]).toLocaleLowerCase().includes('"id":"desc"') ? u = "<" + u : u = ">" + u, s === 1 || f.length === 0)
1380
+ async batchPayload(r, e, s = {}) {
1381
+ const n = !!(s != null && s.oneBatch), o = (O, _, m, N) => {
1382
+ let p = "ID";
1383
+ this.result[O][this.result[O].length - 1].ID || (p = "id");
1384
+ let T = `${p}`;
1385
+ if (JSON.stringify(N[1]).toLocaleLowerCase().includes('"id":"desc"') ? T = "<" + T : T = ">" + T, _ === 1 || m.length === 0)
1207
1386
  return {
1208
- field: u,
1209
- id: this.result[h][this.result[h].length - 1][A]
1387
+ field: T,
1388
+ id: this.result[O][this.result[O].length - 1][p]
1210
1389
  };
1211
- let y = "";
1212
- const [p, R] = m;
1213
- return (p === "tasks.task.list" || p === "task.item.list") && (y = "[tasks]"), ["crm.item.list", "crm.stagehistory.list"].includes(p) && (y = "[items]"), p === "crm.type.list" && (y = "[types]"), p === "socialnetwork.api.workgroup.list" && (y = "[workgroups]"), {
1214
- field: u,
1215
- id: `$result[${[h, s - 1].join("__")}]${y}[49][${A}]`
1390
+ let C = "";
1391
+ const [U, M] = N;
1392
+ return (U === "tasks.task.list" || U === "task.item.list") && (C = "[tasks]"), ["crm.item.list", "crm.stagehistory.list"].includes(U) && (C = "[items]"), U === "crm.type.list" && (C = "[types]"), U === "socialnetwork.api.workgroup.list" && (C = "[workgroups]"), {
1393
+ field: T,
1394
+ id: `$result[${[O, _ - 1].join("__")}]${C}[49][${p}]`
1216
1395
  };
1217
- }, o = (h, s) => {
1218
- const [f, m] = h;
1219
- let A = JSON.parse(JSON.stringify(m)), u;
1220
- if (f === "task.item.list") {
1221
- A = [...A];
1222
- const [N, y, p, R] = A;
1223
- return y[s.field] = s.id, [f, A];
1396
+ }, h = (O, _) => {
1397
+ const [m, N] = O;
1398
+ let p = JSON.parse(JSON.stringify(N)), T;
1399
+ if (m === "task.item.list") {
1400
+ p = [...p];
1401
+ const [k, C, U, M] = p;
1402
+ return C[_.field] = _.id, [m, p];
1224
1403
  }
1225
- return ["user.get"].includes(f) || A.FILTER ? (A.FILTER || (A.FILTER = {}), u = A.FILTER) : (A.filter || (A.filter = {}), u = A.filter), [
1404
+ return ["user.get"].includes(m) || p.FILTER ? (p.FILTER || (p.FILTER = {}), T = p.FILTER) : (p.filter || (p.filter = {}), T = p.filter), [
1226
1405
  "socialnetwork.api.workgroup.list",
1227
1406
  "tasks.task.list"
1228
- ].includes(f) ? u[">ID"] = s.id : u[s.field] = s.id, [f, { ...A, start: -1 }];
1229
- }, l = (h) => {
1230
- Object.entries(h).forEach(([s, f]) => {
1231
- var u, N, y, p, R, b, M;
1232
- const [m] = s.split("__"), A = this.getData(f.data());
1233
- if (Array.isArray(A) && (e === "count" ? this.result[m] += A.length : this.result[m].push(...A)), f.error()) {
1234
- const D = (N = (u = f.error()) == null ? void 0 : u.ex) == null ? void 0 : N.error, B = (p = (y = f.error()) == null ? void 0 : y.ex) == null ? void 0 : p.error_description;
1235
- this.errors[m] = D && D.trim() || B && B.trim() || ((R = f.error()) == null ? void 0 : R.toString()) || "Неизвестная ошибка";
1236
- const F = ((M = (b = f.error()) == null ? void 0 : b.ex) == null ? void 0 : M.error) ?? "", S = i.get(m);
1237
- switch (F) {
1238
- case "OPERATION_TIME_LIMIT":
1239
- S && (this.skipList.add(S), this.limitCall && this.limitCall(m));
1240
- break;
1241
- case "QUERY_LIMIT_EXCEEDED":
1242
- this.canContinue = !1;
1243
- break;
1244
- case "ACCESS_DENIED":
1245
- S && this.skipList.add(S);
1246
- break;
1247
- case "TIMEOUT":
1248
- S && (this.skipList.add(S), this.limitCall && this.limitCall(m));
1249
- break;
1250
- }
1407
+ ].includes(m) ? T[">ID"] = _.id : T[_.field] = _.id, [m, { ...p, start: -1 }];
1408
+ }, A = (O) => {
1409
+ Object.entries(O).forEach(([_, m]) => {
1410
+ var T, k, C, U, M;
1411
+ const [N] = _.split("__"), p = this.getData(m.data());
1412
+ if (Array.isArray(p) && (e === "count" ? this.result[N] += p.length : this.result[N].push(...p)), m.error()) {
1413
+ const H = (k = (T = m.error()) == null ? void 0 : T.ex) == null ? void 0 : k.error, b = (U = (C = m.error()) == null ? void 0 : C.ex) == null ? void 0 : U.error_description;
1414
+ this.errors[N] = H && H.trim() || b && b.trim() || ((M = m.error()) == null ? void 0 : M.toString()) || "Неизвестная ошибка";
1251
1415
  }
1252
- this.setProgressData({ key: m, value: f, type: e });
1416
+ this.setProgressData({ key: N, value: m, type: e });
1253
1417
  });
1418
+ }, l = (O, _) => {
1419
+ if (!Array.isArray(O) || O.length === 0)
1420
+ return null;
1421
+ const m = O[O.length - 1];
1422
+ let N = "ID";
1423
+ m.ID || (N = "id");
1424
+ let p = N;
1425
+ return JSON.stringify(_[1]).toLocaleLowerCase().includes('"id":"desc"') ? p = "<" + p : p = ">" + p, { field: p, id: m[N] };
1426
+ }, i = 1e4, u = async (O, _) => {
1427
+ var N, p;
1428
+ let m = this.limit;
1429
+ for (let T = 1; this.canContinue && m === this.limit && T <= i; T++) {
1430
+ const k = this.result[O], C = l(k, _);
1431
+ if (!C)
1432
+ break;
1433
+ const U = `${O}__eiscan_${T}`, M = h(_, C);
1434
+ let H = null;
1435
+ await E(this, V, At).call(this, { [U]: M }, async (d) => {
1436
+ H = d, A(d);
1437
+ });
1438
+ const b = T < i;
1439
+ await E(this, Z, ot).call(this, H, b), await this.delay();
1440
+ const t = H == null ? void 0 : H[U];
1441
+ if ((N = t == null ? void 0 : t.error) != null && N.call(t)) {
1442
+ m = 0;
1443
+ break;
1444
+ }
1445
+ const a = this.getData((p = t == null ? void 0 : t.data) == null ? void 0 : p.call(t));
1446
+ m = Array.isArray(a) ? a.length : 0;
1447
+ }
1254
1448
  };
1255
- let c = [];
1256
- for await (const [h, s, f] of r) {
1449
+ let y = [], c = 0;
1450
+ const f = async (O = !0) => y.length ? (await E(this, V, At).call(this, Object.fromEntries(y), async (_) => {
1451
+ A(_), await E(this, Z, ot).call(this, _, O);
1452
+ }), c++, y = [], n && c >= 1 ? !0 : (await this.delay(), !1)) : !1;
1453
+ for await (const O of r) {
1257
1454
  if (!this.canContinue)
1258
1455
  return;
1259
- const [m] = s;
1260
- if (i.set(h, m), this.skipList.has(m))
1456
+ const [_, m, N, p = {}] = O;
1457
+ if (p.entityItemGetScan) {
1458
+ if (await f(!0))
1459
+ return;
1460
+ if (n)
1461
+ continue;
1462
+ await u(_, m);
1261
1463
  continue;
1262
- let A = 1;
1263
- for (; f > A * 50 && !this.skipList.has(m); ) {
1264
- const u = [h, A].join("__"), N = n(h, A, c, s);
1265
- c.push([u, o(s, N)]), c.length % 50 === 0 && (await this.callBatchWithTimeout(
1266
- Object.fromEntries(c),
1267
- (y) => {
1268
- l(y);
1269
- }
1270
- ), c = [], await this.delay()), A++;
1271
1464
  }
1272
- }
1273
- c.length && (await this.callBatchWithTimeout(
1274
- Object.fromEntries(c),
1275
- (h) => {
1276
- l(h);
1465
+ let T = 1;
1466
+ for (; N > T * this.limit; ) {
1467
+ const k = [_, T].join("__"), C = o(_, T, y, m);
1468
+ if (y.push([k, h(m, C)]), n && y.length === 49 && await f(!0) || y.length % 50 === 0 && await f(!0))
1469
+ return;
1470
+ T++;
1277
1471
  }
1278
- ), await this.delay());
1472
+ }
1473
+ await f(!1);
1279
1474
  }
1280
1475
  /**
1281
1476
  * Вывод ошибок в консоль в группированном виде
@@ -1285,11 +1480,123 @@ class K {
1285
1480
  e && console.log(`[${r}]`, e.toString());
1286
1481
  }), console.groupEnd();
1287
1482
  }
1288
- }
1289
- var z;
1290
- class mt {
1483
+ };
1484
+ gt = new WeakSet(), Yt = function() {
1485
+ const r = this.totalBatchCommands || 0, e = this.batchCommandMethods;
1486
+ if (r < R(j, yt) || !Array.isArray(e) || e.length !== r)
1487
+ return !1;
1488
+ if (e.filter((o) => o === "crm.deal.list").length >= R(j, pt))
1489
+ return !0;
1490
+ const n = e.filter(
1491
+ (o) => typeof o == "string" && o.includes(".list")
1492
+ ).length;
1493
+ return n >= R(j, Nt) && n / r >= R(j, Ot);
1494
+ }, yt = new WeakMap(), pt = new WeakMap(), Nt = new WeakMap(), Ot = new WeakMap(), it = new WeakSet(), dt = function() {
1495
+ if (!this.progressCall || !this.progressData)
1496
+ return;
1497
+ const { percent: r, allCount: e, allTotal: s } = this.progressPercent, n = { percent: r, allCount: e, allTotal: s };
1498
+ E(this, _t, Gt).call(this, n) && (this.progressCall({
1499
+ data: this.progressData,
1500
+ percent: r,
1501
+ allCount: e,
1502
+ allTotal: s
1503
+ }), this.lastProgressSnapshot = n);
1504
+ }, _t = new WeakSet(), Gt = function(r) {
1505
+ return this.lastProgressSnapshot ? this.lastProgressSnapshot.percent !== r.percent || this.lastProgressSnapshot.allCount !== r.allCount || this.lastProgressSnapshot.allTotal !== r.allTotal : !0;
1506
+ }, Tt = new WeakSet(), Wt = function() {
1507
+ const r = {
1508
+ limit: this.timeLimit.limit,
1509
+ date: this.timeLimit.date,
1510
+ pauseMs: this.timeLimit.pauseMs
1511
+ };
1512
+ for (const e of this.timeLimitListeners)
1513
+ try {
1514
+ e(r);
1515
+ } catch (s) {
1516
+ console.warn("Batch timeLimit listener error:", s);
1517
+ }
1518
+ }, q = new WeakSet(), st = async function(r = this.defaultPauseMs) {
1519
+ this.setTimeLimitState(!0, (/* @__PURE__ */ new Date()).toISOString(), r), await new Promise((e) => setTimeout(e, r)), this.setTimeLimitState(!1, void 0);
1520
+ }, Z = new WeakSet(), ot = async function(r, e = !0) {
1521
+ if (!e)
1522
+ return 0;
1523
+ let s = 0;
1524
+ if (!r || typeof r != "object")
1525
+ return 0;
1526
+ for (const n of Object.values(r))
1527
+ if (!(!n || typeof n != "object"))
1528
+ try {
1529
+ if (typeof n.time == "function") {
1530
+ const o = n.time();
1531
+ o && typeof o.operating == "number" && (s = Math.max(s, o.operating));
1532
+ }
1533
+ } catch {
1534
+ }
1535
+ s >= this.operatingThreshold && await E(this, q, st).call(this);
1536
+ }, V = new WeakSet(), At = async function(r, e) {
1537
+ let s = !1, n = r;
1538
+ do
1539
+ s = !1, await this.callBatchWithTimeout(n, async (o) => {
1540
+ var l, i;
1541
+ let h = !1;
1542
+ const A = /* @__PURE__ */ new Set();
1543
+ for (const [u, y] of Object.entries(o || {})) {
1544
+ if (!(y != null && y.error) || !y.error())
1545
+ continue;
1546
+ const c = ((i = (l = y.error()) == null ? void 0 : l.ex) == null ? void 0 : i.error) ?? "";
1547
+ if (c === "TIMEOUT") {
1548
+ h = !0;
1549
+ break;
1550
+ }
1551
+ ["QUERY_LIMIT_EXCEEDED", "OPERATION_TIME_LIMIT"].includes(c) && A.add(u);
1552
+ }
1553
+ if (h) {
1554
+ s = !0, await E(this, q, st).call(this);
1555
+ return;
1556
+ }
1557
+ if (A.size > 0) {
1558
+ const u = {};
1559
+ for (const [c, f] of Object.entries(o || {}))
1560
+ A.has(c) || (u[c] = f);
1561
+ Object.keys(u).length && await e(u);
1562
+ const y = {};
1563
+ for (const c of A)
1564
+ n[c] && (y[c] = n[c]);
1565
+ n = y, Object.keys(n).length && (s = !0, await E(this, q, st).call(this));
1566
+ return;
1567
+ }
1568
+ await e(o);
1569
+ });
1570
+ while (s);
1571
+ }, Et = new WeakSet(), xt = function(r, e) {
1572
+ return new Promise((s) => {
1573
+ if (typeof this.callMethod != "function") {
1574
+ s(null);
1575
+ return;
1576
+ }
1577
+ let n = !1;
1578
+ const o = setTimeout(() => {
1579
+ n || (n = !0, s(null));
1580
+ }, this.requestTimeoutMs);
1581
+ try {
1582
+ this.callMethod(r, e, (h) => {
1583
+ n || (n = !0, clearTimeout(o), s(h));
1584
+ });
1585
+ } catch {
1586
+ n || (n = !0, clearTimeout(o), s(null));
1587
+ }
1588
+ });
1589
+ }, ht = new WeakSet(), kt = function(r) {
1590
+ this.clearProgressData(), this.progressCall = typeof r == "function" ? r : "", this.canContinue = !0, this.result = {}, this.errors = {}, this.chunkRate = 1, this.totalProgress = 0, this.batchCommandKeyOrder = [], this.totalBatchCommands = 0, this.batchCommandMethods = [], this.setTimeLimitState(!1, void 0);
1591
+ }, /** Не включать вес по командам для совсем маленьких batch. */
1592
+ I(j, yt, 5), /** Явный сигнал: много отдельных выборок сделок по фильтрам. */
1593
+ I(j, pt, 5), /** Достаточно «list»-методов в пачке и доля list от всех команд. */
1594
+ I(j, Nt, 8), I(j, Ot, 0.65);
1595
+ let v = j;
1596
+ var $;
1597
+ class Ft {
1291
1598
  constructor() {
1292
- U(this, z, {});
1599
+ I(this, $, {});
1293
1600
  }
1294
1601
  /**
1295
1602
  * Получить случайный хеш-код длиной 8 символов
@@ -1304,11 +1611,11 @@ class mt {
1304
1611
  * @returns {string}
1305
1612
  */
1306
1613
  createHash(r) {
1307
- let e = "abcdefghijklmnopqrstuvwxyz0123456789", i = "";
1614
+ let e = "abcdefghijklmnopqrstuvwxyz0123456789", s = "";
1308
1615
  r = r || 6;
1309
1616
  for (let n = 0; n < r; n++)
1310
- i += e.charAt(Math.floor(Math.random() * e.length));
1311
- return i;
1617
+ s += e.charAt(Math.floor(Math.random() * e.length));
1618
+ return s;
1312
1619
  }
1313
1620
  /**
1314
1621
  * Фильтр часто запускаемых действий (debounce)
@@ -1317,9 +1624,9 @@ class mt {
1317
1624
  * @param {number} params.duration - Задержка в миллисекундах (по умолчанию 10)
1318
1625
  * @param {Function} params.action - Функция для выполнения
1319
1626
  */
1320
- actionFilter({ keyTimer: r, duration: e = 10, action: i }) {
1321
- T(this, z)[r] && (clearTimeout(T(this, z)[r]), T(this, z)[r] = null), i && (T(this, z)[r] = setTimeout(() => {
1322
- i();
1627
+ actionFilter({ keyTimer: r, duration: e = 10, action: s }) {
1628
+ R(this, $)[r] && (clearTimeout(R(this, $)[r]), R(this, $)[r] = null), s && (R(this, $)[r] = setTimeout(() => {
1629
+ s();
1323
1630
  }, e));
1324
1631
  }
1325
1632
  /**
@@ -1350,63 +1657,63 @@ class mt {
1350
1657
  * @param {string} filename - Имя файла без расширения
1351
1658
  */
1352
1659
  downloadFileJson(r, e) {
1353
- let i = new Blob([JSON.stringify(r)], { type: "application/json" }), n = URL.createObjectURL(i), o = document.createElement("a");
1660
+ let s = new Blob([JSON.stringify(r)], { type: "application/json" }), n = URL.createObjectURL(s), o = document.createElement("a");
1354
1661
  o.style.display = "none", o.href = n, o.download = `${e}.json`, document.body.appendChild(o), o.click(), setTimeout(() => {
1355
1662
  document.body.removeChild(o), URL.revokeObjectURL(n);
1356
1663
  }, 200);
1357
1664
  }
1358
1665
  }
1359
- z = new WeakMap();
1360
- const ht = new mt();
1361
- var j, Q, Z, q, P, V, $, st, dt, tt, ut, it, gt, nt, pt, at, yt;
1362
- class bt {
1666
+ $ = new WeakMap();
1667
+ const wt = new Ft();
1668
+ var K, z, tt, nt, F, et, at, Lt, Xt, lt, Ht, Rt, Jt, bt, jt, St, Kt;
1669
+ class ee {
1363
1670
  constructor() {
1364
- U(this, st);
1671
+ I(this, Lt);
1365
1672
  /** Вывод ошибок логера
1366
1673
  * @param {'entity'} type - тип ошибки
1367
1674
  */
1368
- U(this, tt);
1369
- U(this, it);
1370
- U(this, nt);
1371
- U(this, at);
1372
- U(this, j, "logger");
1373
- U(this, Q, !1);
1374
- U(this, Z, /* @__PURE__ */ new Map());
1375
- U(this, q, {});
1376
- U(this, P, null);
1377
- U(this, V, !1);
1378
- U(this, $, !1);
1675
+ I(this, lt);
1676
+ I(this, Rt);
1677
+ I(this, bt);
1678
+ I(this, St);
1679
+ I(this, K, "logger");
1680
+ I(this, z, !1);
1681
+ I(this, tt, /* @__PURE__ */ new Map());
1682
+ I(this, nt, {});
1683
+ I(this, F, null);
1684
+ I(this, et, !1);
1685
+ I(this, at, !1);
1379
1686
  /** Очистка хранилища элементов старше 'N' месяцев */
1380
- I(this, "periodClear", 3);
1381
- J(this, st, dt).call(this);
1687
+ w(this, "periodClear", 3);
1688
+ E(this, Lt, Xt).call(this);
1382
1689
  }
1383
1690
  /** Инициализация логера */
1384
1691
  async init() {
1385
1692
  try {
1386
- let r = new K(BX24.callBatch), { entityList: e } = await r.batch({
1693
+ let r = new v(BX24.callBatch), { entityList: e } = await r.batch({
1387
1694
  entityList: { method: "entity.get" }
1388
1695
  });
1389
1696
  if (e && Array.isArray(e))
1390
1697
  if (e.find(
1391
- (n) => n.ENTITY == T(this, j)
1698
+ (n) => n.ENTITY == R(this, K)
1392
1699
  ))
1393
- X(this, Q, !0);
1700
+ J(this, z, !0);
1394
1701
  else {
1395
1702
  let { entityAdd: n } = await r.batch({
1396
1703
  entityAdd: {
1397
1704
  method: "entity.add",
1398
1705
  params: {
1399
- ENTITY: T(this, j),
1400
- NAME: T(this, j),
1706
+ ENTITY: R(this, K),
1707
+ NAME: R(this, K),
1401
1708
  ACCESS: { AU: "X" }
1402
1709
  }
1403
1710
  }
1404
1711
  });
1405
- n && X(this, Q, !0);
1712
+ n && J(this, z, !0);
1406
1713
  }
1407
- return J(this, nt, pt).call(this).catch((i) => {
1408
- console.error("Ошибка при проверке периода очистки:", i);
1409
- }), T(this, Q);
1714
+ return E(this, bt, jt).call(this).catch((s) => {
1715
+ console.error("Ошибка при проверке периода очистки:", s);
1716
+ }), R(this, z);
1410
1717
  } catch (r) {
1411
1718
  return console.error("Ошибка при инициализации логера:", r), !1;
1412
1719
  }
@@ -1421,20 +1728,20 @@ class bt {
1421
1728
  * @returns {string|null}
1422
1729
  */
1423
1730
  start({ type: r, data: e }) {
1424
- if (!T(this, Q))
1425
- return J(this, tt, ut).call(this, "entity"), null;
1731
+ if (!R(this, z))
1732
+ return E(this, lt, Ht).call(this, "entity"), null;
1426
1733
  if (!r || !e)
1427
1734
  return console.error("Невалидные данные для логирования:", { type: r, data: e }), null;
1428
- const i = ht.hash, n = {
1735
+ const s = wt.hash, n = {
1429
1736
  type: r,
1430
1737
  data: e,
1431
- userInfo: T(this, q),
1738
+ userInfo: R(this, nt),
1432
1739
  errorList: {},
1433
1740
  status: "",
1434
1741
  answer: null,
1435
1742
  date: (/* @__PURE__ */ new Date()).getTime()
1436
1743
  };
1437
- return T(this, Z).set(i, n), X(this, $, !0), i;
1744
+ return R(this, tt).set(s, n), J(this, at, !0), s;
1438
1745
  }
1439
1746
  /**
1440
1747
  * @param {{
@@ -1443,20 +1750,20 @@ class bt {
1443
1750
  * status: 'success'|'fail'|'fail-runtime',
1444
1751
  * answer: { [key]: unknown } }}
1445
1752
  */
1446
- async stop({ key: r, errorList: e, status: i, answer: n }) {
1447
- var l;
1448
- if (!T(this, $))
1753
+ async stop({ key: r, errorList: e, status: s, answer: n }) {
1754
+ var h;
1755
+ if (!R(this, at))
1449
1756
  return;
1450
- if (!T(this, Q)) {
1451
- J(this, tt, ut).call(this, "entity");
1757
+ if (!R(this, z)) {
1758
+ E(this, lt, Ht).call(this, "entity");
1452
1759
  return;
1453
1760
  }
1454
- let o = T(this, Z).get(r);
1761
+ let o = R(this, tt).get(r);
1455
1762
  if (!o) {
1456
1763
  console.error(`Не найдены данные логирования для ключа: ${r}`);
1457
1764
  return;
1458
1765
  }
1459
- e && (o.errorList = e), i && (o.status = i), n && (o.answer = n), await J(this, it, gt).call(this), (l = o == null ? void 0 : o.data) != null && l.updateList && X(this, V, !0), X(this, $, !1);
1766
+ e && (o.errorList = e), s && (o.status = s), n && (o.answer = n), await E(this, Rt, Jt).call(this), (h = o == null ? void 0 : o.data) != null && h.updateList && J(this, et, !0), J(this, at, !1);
1460
1767
  }
1461
1768
  /**
1462
1769
  * @param { ({percent}:{percent:number})=>{} } progressCall - коллбэк
@@ -1464,14 +1771,14 @@ class bt {
1464
1771
  async getEntityList(r) {
1465
1772
  var e;
1466
1773
  try {
1467
- if ((e = T(this, P)) != null && e.length && !T(this, V))
1468
- return T(this, P);
1469
- let i = new K(BX24.callBatch), { entityList: n } = await i.batch(
1774
+ if ((e = R(this, F)) != null && e.length && !R(this, et))
1775
+ return R(this, F);
1776
+ let s = new v(BX24.callBatch), { entityList: n } = await s.batch(
1470
1777
  {
1471
1778
  entityList: {
1472
1779
  method: "entity.item.get",
1473
1780
  params: {
1474
- ENTITY: T(this, j),
1781
+ ENTITY: R(this, K),
1475
1782
  SORT: { ID: "DESC" }
1476
1783
  }
1477
1784
  }
@@ -1480,31 +1787,31 @@ class bt {
1480
1787
  );
1481
1788
  return !n || !Array.isArray(n) ? (console.warn("Получен невалидный список записей"), []) : (n = n.map((o) => {
1482
1789
  try {
1483
- const { ID: l, DATE_CREATE: c, DETAIL_TEXT: h } = o;
1790
+ const { ID: h, DATE_CREATE: A, DETAIL_TEXT: l } = o;
1484
1791
  return {
1485
- ...JSON.parse(h),
1486
- id: l,
1487
- dateCreate: c
1792
+ ...JSON.parse(l),
1793
+ id: h,
1794
+ dateCreate: A
1488
1795
  };
1489
- } catch (l) {
1796
+ } catch (h) {
1490
1797
  return console.error(
1491
1798
  `Ошибка парсинга записи ${o.ID}:`,
1492
- l
1799
+ h
1493
1800
  ), null;
1494
1801
  }
1495
- }).filter((o) => o !== null), X(this, V, !1), X(this, P, n), n);
1496
- } catch (i) {
1497
- return console.error("Ошибка при получении списка записей:", i), [];
1802
+ }).filter((o) => o !== null), J(this, et, !1), J(this, F, n), n);
1803
+ } catch (s) {
1804
+ return console.error("Ошибка при получении списка записей:", s), [];
1498
1805
  }
1499
1806
  }
1500
1807
  /** Выгрузка всех данных из хранилища в JSON-файл */
1501
1808
  async downAllEntityJson() {
1502
1809
  try {
1503
- if (T(this, P) || await this.getEntityList(), !T(this, P) || T(this, P).length === 0)
1810
+ if (R(this, F) || await this.getEntityList(), !R(this, F) || R(this, F).length === 0)
1504
1811
  return console.warn("Нет данных для выгрузки"), !1;
1505
- let r = rt().format("%Y-%m-%d");
1506
- return ht.downloadFileJson(
1507
- T(this, P),
1812
+ let r = mt().format("%Y-%m-%d");
1813
+ return wt.downloadFileJson(
1814
+ R(this, F),
1508
1815
  `sdklogger-entity-data__${r}`
1509
1816
  ), !0;
1510
1817
  } catch (r) {
@@ -1512,113 +1819,120 @@ class bt {
1512
1819
  }
1513
1820
  }
1514
1821
  }
1515
- j = new WeakMap(), Q = new WeakMap(), Z = new WeakMap(), q = new WeakMap(), P = new WeakMap(), V = new WeakMap(), $ = new WeakMap(), st = new WeakSet(), dt = async function() {
1822
+ K = new WeakMap(), z = new WeakMap(), tt = new WeakMap(), nt = new WeakMap(), F = new WeakMap(), et = new WeakMap(), at = new WeakMap(), Lt = new WeakSet(), Xt = async function() {
1516
1823
  try {
1517
- const r = new K(BX24.callBatch), e = BX24.isAdmin(), { curUser: i } = await r.batch({
1824
+ const r = new v(BX24.callBatch), e = BX24.isAdmin(), { curUser: s } = await r.batch({
1518
1825
  curUser: { method: "user.current" }
1519
1826
  });
1520
- X(this, q, { isAdmin: e, curUser: i });
1827
+ J(this, nt, { isAdmin: e, curUser: s });
1521
1828
  } catch (r) {
1522
1829
  console.error(
1523
1830
  "Ошибка при получении информации о пользователе:",
1524
1831
  r
1525
- ), X(this, q, { isAdmin: !1, curUser: null });
1832
+ ), J(this, nt, { isAdmin: !1, curUser: null });
1526
1833
  }
1527
- }, tt = new WeakSet(), ut = function(r) {
1528
- r == "entity" && ht.actionFilter({
1834
+ }, lt = new WeakSet(), Ht = function(r) {
1835
+ r == "entity" && wt.actionFilter({
1529
1836
  keyTimer: "error.logger.entity",
1530
1837
  duration: 500,
1531
1838
  action: () => {
1532
1839
  console.error("Хранилище для логгера не инициализировано");
1533
1840
  }
1534
1841
  });
1535
- }, it = new WeakSet(), gt = async function() {
1842
+ }, Rt = new WeakSet(), Jt = async function() {
1536
1843
  try {
1537
- let r = {}, e = new K(BX24.callBatch);
1538
- for (let [i, n] of T(this, Z).entries())
1844
+ let r = {}, e = new v(BX24.callBatch);
1845
+ for (let [s, n] of R(this, tt).entries())
1539
1846
  if (n.status) {
1540
1847
  const o = JSON.stringify(n);
1541
- r[i] = {
1848
+ r[s] = {
1542
1849
  method: "entity.item.add",
1543
1850
  params: {
1544
- ENTITY: T(this, j),
1545
- NAME: T(this, j),
1851
+ ENTITY: R(this, K),
1852
+ NAME: R(this, K),
1546
1853
  DETAIL_TEXT: o
1547
1854
  }
1548
1855
  };
1549
1856
  }
1550
1857
  if (Object.keys(r).length) {
1551
- let i = await e.batch(r), { errors: n } = e;
1552
- for (let [o, l] of Object.entries({ ...i, ...n }))
1553
- T(this, Z).delete(o);
1858
+ let s = await e.batch(r), { errors: n } = e;
1859
+ for (let [o, h] of Object.entries({ ...s, ...n }))
1860
+ R(this, tt).delete(o);
1554
1861
  return !0;
1555
1862
  }
1556
1863
  return !1;
1557
1864
  } catch (r) {
1558
1865
  return console.error("Ошибка при добавлении записей в хранилище:", r), !1;
1559
1866
  }
1560
- }, nt = new WeakSet(), pt = async function() {
1867
+ }, bt = new WeakSet(), jt = async function() {
1561
1868
  try {
1562
- let r = new K(BX24.callBatch), { serverTime: e } = await r.batch({
1869
+ let r = new v(BX24.callBatch), { serverTime: e } = await r.batch({
1563
1870
  serverTime: { method: "server.time" }
1564
1871
  });
1565
1872
  if (!e) {
1566
1873
  console.error("Не удалось получить время сервера");
1567
1874
  return;
1568
1875
  }
1569
- if (T(this, P) || await this.getEntityList(), !T(this, P) || T(this, P).length === 0)
1876
+ if (R(this, F) || await this.getEntityList(), !R(this, F) || R(this, F).length === 0)
1570
1877
  return;
1571
- let i = T(this, P).filter((n) => {
1878
+ let s = R(this, F).filter((n) => {
1572
1879
  try {
1573
1880
  let { dateCreate: o } = n;
1574
- return o ? rt(new Date(o)).between(
1575
- rt(new Date(e)),
1881
+ return o ? mt(new Date(o)).between(
1882
+ mt(new Date(e)),
1576
1883
  "month"
1577
1884
  ) >= this.periodClear : !1;
1578
1885
  } catch (o) {
1579
1886
  return console.error("Ошибка при проверке даты записи:", o), !1;
1580
1887
  }
1581
1888
  });
1582
- i.length > 0 && (console.log(
1583
- `Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`
1584
- ), await J(this, at, yt).call(this, i));
1889
+ s.length > 0 && (console.log(
1890
+ `Найдено ${s.length} записей для очистки (старше ${this.periodClear} месяцев)`
1891
+ ), await E(this, St, Kt).call(this, s));
1585
1892
  } catch (r) {
1586
1893
  console.error("Ошибка при проверке периода очистки:", r);
1587
1894
  }
1588
- }, at = new WeakSet(), yt = async function(r) {
1895
+ }, St = new WeakSet(), Kt = async function(r) {
1589
1896
  try {
1590
1897
  if (!r || r.length === 0)
1591
1898
  return !1;
1592
- let e = new K(BX24.callBatch), i = r.filter((o) => o && o.id).map((o) => {
1593
- let { id: l } = o;
1899
+ let e = new v(BX24.callBatch), s = r.filter((o) => o && o.id).map((o) => {
1900
+ let { id: h } = o;
1594
1901
  return {
1595
1902
  method: "entity.item.delete",
1596
1903
  params: {
1597
- ENTITY: T(this, j),
1598
- ID: l
1904
+ ENTITY: R(this, K),
1905
+ ID: h
1599
1906
  }
1600
1907
  };
1601
1908
  });
1602
- if (i.length === 0)
1909
+ if (s.length === 0)
1603
1910
  return !1;
1604
- const n = await e.batch(i);
1605
- return console.log(`Успешно удалено ${i.length} записей`), X(this, V, !0), n;
1911
+ const n = await e.batch(s);
1912
+ return console.log(`Успешно удалено ${s.length} записей`), J(this, et, !0), n;
1606
1913
  } catch (e) {
1607
1914
  return console.error("Ошибка при очистке устаревших записей:", e), !1;
1608
1915
  }
1609
1916
  };
1610
- var ot, Nt, At, Ot, et, ft;
1611
- class It {
1917
+ var rt, ct, It, vt, Mt, Qt, ut, Ut, ft, Pt, Dt, qt;
1918
+ class se {
1612
1919
  /**
1613
1920
  * @param {Object} appConst - Константы приложения
1614
1921
  * @param {string} appConst.appName - Название приложения
1615
1922
  * @param {string} appConst.pathApp - Путь к приложению
1616
1923
  */
1617
1924
  constructor(r) {
1925
+ /**
1926
+ * Returns shared Batch instance for all batch operations.
1927
+ * Keeps a single stateful Batch (including timeLimit) within current BxBoot lifecycle.
1928
+ *
1929
+ * @returns {Batch} Shared Batch instance.
1930
+ */
1931
+ I(this, rt);
1618
1932
  /** Запрос данных о приложении */
1619
- U(this, ot);
1933
+ I(this, It);
1620
1934
  /** Запрос данных о текущем пользователе */
1621
- U(this, At);
1935
+ I(this, Mt);
1622
1936
  /**
1623
1937
  * Расширяет errorList для случаев TIMEOUT и LIMIT
1624
1938
  * Если есть ошибки TIMEOUT или LIMIT, добавляет все необработанные сущности из commandList
@@ -1628,17 +1942,42 @@ class It {
1628
1942
  * @param {Array} updateList - Список обновлений для логирования (опционально)
1629
1943
  * @returns {Object} Расширенный список ошибок
1630
1944
  */
1631
- U(this, et);
1632
- I(this, "domain", "");
1633
- I(this, "isAdmin", !1);
1634
- I(this, "appInfo", null);
1635
- I(this, "appConst", null);
1636
- I(this, "userInfo", null);
1637
- I(this, "placeData", null);
1638
- I(this, "placeInfo", null);
1639
- I(this, "logger", !1);
1945
+ I(this, ut);
1946
+ /**
1947
+ * Нормализует входные данные в массив объектов {placement, handler?}
1948
+ * @private
1949
+ */
1950
+ I(this, ft);
1951
+ /**
1952
+ * Находит встройки с устаревшим handler (не содержащим текущий pathApp)
1953
+ * @private
1954
+ */
1955
+ I(this, Dt);
1956
+ w(this, "domain", "");
1957
+ w(this, "isAdmin", !1);
1958
+ w(this, "appInfo", null);
1959
+ w(this, "appConst", null);
1960
+ w(this, "userInfo", null);
1961
+ w(this, "placeData", null);
1962
+ w(this, "placeInfo", null);
1963
+ w(this, "logger", !1);
1964
+ w(this, "timeLimit", {
1965
+ limit: !1,
1966
+ date: void 0,
1967
+ pauseMs: void 0
1968
+ });
1969
+ w(this, "batchClient", null);
1640
1970
  this.appConst = r;
1641
1971
  }
1972
+ /**
1973
+ * Подписывает внешний код на изменения состояния timeLimit в Batch.
1974
+ *
1975
+ * @param {(state: {limit: boolean, date?: string, pauseMs?: number}) => void} callback - Обработчик состояния лимита.
1976
+ * @returns {() => void} Функция отписки.
1977
+ */
1978
+ subscribeTimeLimit(r) {
1979
+ return E(this, rt, ct).call(this).subscribeTimeLimit(r);
1980
+ }
1642
1981
  /**
1643
1982
  * Инициализация Bitrix24 SDK
1644
1983
  * @returns {Promise<boolean>}
@@ -1648,7 +1987,7 @@ class It {
1648
1987
  return new Promise((r, e) => {
1649
1988
  let n = setInterval(() => {
1650
1989
  window.BX24 && BX24.init(async () => {
1651
- console.info("init BX24"), clearInterval(n), clearTimeout(o), this.domain = BX24.getDomain(), this.isAdmin = BX24.isAdmin(), this.placeInfo = BX24.placement.info(), this.logger ? (this.logger = new bt(), await this.logger.init()) : this.logger = {
1990
+ console.info("init BX24"), clearInterval(n), clearTimeout(o), this.domain = BX24.getDomain(), this.isAdmin = BX24.isAdmin(), this.placeInfo = BX24.placement.info(), this.logger ? (this.logger = new ee(), await this.logger.init()) : this.logger = {
1652
1991
  start: () => {
1653
1992
  },
1654
1993
  stop: () => {
@@ -1656,18 +1995,18 @@ class It {
1656
1995
  getEntityList: () => {
1657
1996
  }
1658
1997
  };
1659
- const [l, c] = await Promise.all([
1660
- J(this, ot, Nt).call(this),
1661
- J(this, At, Ot).call(this)
1998
+ const [h, A] = await Promise.all([
1999
+ E(this, It, vt).call(this),
2000
+ E(this, Mt, Qt).call(this)
1662
2001
  ]);
1663
- this.appInfo = l, this.userInfo = c;
1664
- let h = new mt();
2002
+ this.appInfo = h, this.userInfo = A;
2003
+ let l = new Ft();
1665
2004
  try {
1666
- h.noSleep();
1667
- } catch (s) {
2005
+ l.noSleep();
2006
+ } catch (i) {
1668
2007
  console.warn(
1669
2008
  "Failed to initialize noSleep:",
1670
- s
2009
+ i
1671
2010
  );
1672
2011
  }
1673
2012
  r(!0);
@@ -1675,10 +2014,10 @@ class It {
1675
2014
  }, 100);
1676
2015
  const o = setTimeout(() => {
1677
2016
  clearInterval(n);
1678
- const l = new Error(
2017
+ const h = new Error(
1679
2018
  "BX24 initialization timeout: BX24 object not found within 30 seconds"
1680
2019
  );
1681
- console.error(l), e(l);
2020
+ console.error(h), e(h);
1682
2021
  }, 3e4);
1683
2022
  });
1684
2023
  }
@@ -1724,51 +2063,41 @@ class It {
1724
2063
  * }[]
1725
2064
  * }[]
1726
2065
  */
1727
- async call({ method: r, params: e, updateList: i }) {
2066
+ async call({ method: r, params: e, updateList: s }) {
1728
2067
  let n;
1729
- if (i && (n = this.logger.start({
2068
+ if (s && (n = this.logger.start({
1730
2069
  type: "call",
1731
- data: { method: r, params: e, updateList: i }
2070
+ data: { method: r, params: e, updateList: s }
1732
2071
  })), e || (e = {}), typeof BX24 > "u" || !BX24.callMethod) {
1733
- const o = new Error("BX24 is not initialized");
1734
- throw console.error(o), o;
2072
+ const A = new Error("BX24 is not initialized");
2073
+ throw console.error(A), A;
1735
2074
  }
1736
- return new Promise((o, l) => {
1737
- BX24.callMethod(r, e, async (c) => {
1738
- let h = {};
1739
- if (c != null && c.answer)
1740
- for (let [s, f] of Object.entries(c.answer))
1741
- s !== "result" && f && (h[s] = f);
1742
- if (c.error()) {
1743
- let s = c.error();
1744
- if (console.error(s), n)
1745
- try {
1746
- await this.logger.stop({
1747
- answer: h,
1748
- key: n,
1749
- status: "fail",
1750
- errorList: { 0: s.toString() }
1751
- });
1752
- } catch (f) {
1753
- console.error("Logger error:", f);
1754
- }
1755
- o(!1);
1756
- } else {
1757
- let s = c.data();
1758
- if (s != null && s.items && (s = s.items), n)
1759
- try {
1760
- await this.logger.stop({
1761
- answer: h,
1762
- key: n,
1763
- status: "success"
1764
- });
1765
- } catch (f) {
1766
- console.error("Logger error:", f);
1767
- }
1768
- o(s);
2075
+ const h = await E(this, rt, ct).call(this).call({ method: r, params: e });
2076
+ if (!h.success) {
2077
+ if (console.error(h.error), n)
2078
+ try {
2079
+ await this.logger.stop({
2080
+ answer: h.answer,
2081
+ key: n,
2082
+ status: "fail",
2083
+ errorList: { 0: h.error || "Unknown call error" }
2084
+ });
2085
+ } catch (A) {
2086
+ console.error("Logger error:", A);
1769
2087
  }
1770
- });
1771
- });
2088
+ return !1;
2089
+ }
2090
+ if (n)
2091
+ try {
2092
+ await this.logger.stop({
2093
+ answer: h.answer,
2094
+ key: n,
2095
+ status: "success"
2096
+ });
2097
+ } catch (A) {
2098
+ console.error("Logger error:", A);
2099
+ }
2100
+ return h.data;
1772
2101
  }
1773
2102
  /**
1774
2103
  * @param commandList - объект/массив команд
@@ -1789,58 +2118,57 @@ class It {
1789
2118
  * }[]
1790
2119
  * }}
1791
2120
  */
1792
- async batch(r, e, { errorCall: i, limitCommandSerial: n, updateList: o, limitCall: l } = {}) {
2121
+ async batch(r, e, { errorCall: s, updateList: n, batchOptions: o } = {}) {
1793
2122
  if (typeof BX24 > "u" || !BX24.callBatch) {
1794
- const s = new Error("BX24 is not initialized");
1795
- return console.error(s), !1;
2123
+ const l = new Error("BX24 is not initialized");
2124
+ return console.error(l), !1;
1796
2125
  }
1797
- let c = new K(BX24.callBatch), h;
1798
- o && (h = this.logger.start({
2126
+ const h = E(this, rt, ct).call(this);
2127
+ let A;
2128
+ n && (A = this.logger.start({
1799
2129
  type: "batch",
1800
- data: { commandList: r, updateList: o }
1801
- })), n && console.warn(
1802
- "limitCommandSerial is deprecated and not used in current Batch implementation"
1803
- );
2130
+ data: { commandList: r, updateList: n }
2131
+ }));
1804
2132
  try {
1805
- let s = await c.batch(
2133
+ let l = await h.batch(
1806
2134
  r,
1807
2135
  e,
1808
- l
2136
+ o
1809
2137
  );
1810
- const f = J(this, et, ft).call(this, c, s, r, o);
1811
- if (Object.keys(f).length) {
1812
- if (i && i(f), h)
2138
+ const i = E(this, ut, Ut).call(this, h, l, r, n);
2139
+ if (Object.keys(i).length) {
2140
+ if (s && s(i), A)
1813
2141
  try {
1814
2142
  await this.logger.stop({
1815
- key: h,
2143
+ key: A,
1816
2144
  status: "fail",
1817
- errorList: f
2145
+ errorList: i
1818
2146
  });
1819
- } catch (m) {
1820
- console.error("Logger error:", m);
2147
+ } catch (u) {
2148
+ console.error("Logger error:", u);
1821
2149
  }
1822
- } else if (h)
2150
+ } else if (A)
1823
2151
  try {
1824
2152
  await this.logger.stop({
1825
- key: h,
2153
+ key: A,
1826
2154
  status: "success"
1827
2155
  });
1828
- } catch (m) {
1829
- console.error("Logger error:", m);
2156
+ } catch (u) {
2157
+ console.error("Logger error:", u);
1830
2158
  }
1831
- return s;
1832
- } catch (s) {
1833
- if (h)
2159
+ return l;
2160
+ } catch (l) {
2161
+ if (A)
1834
2162
  try {
1835
2163
  await this.logger.stop({
1836
- key: h,
2164
+ key: A,
1837
2165
  status: "fail-runtime",
1838
- errorList: { 0: s == null ? void 0 : s.toString() }
2166
+ errorList: { 0: l == null ? void 0 : l.toString() }
1839
2167
  });
1840
- } catch (f) {
1841
- console.error("Logger error:", f);
2168
+ } catch (i) {
2169
+ console.error("Logger error:", i);
1842
2170
  }
1843
- return console.error(s), !1;
2171
+ return console.error(l), !1;
1844
2172
  }
1845
2173
  }
1846
2174
  /**
@@ -1861,151 +2189,144 @@ class It {
1861
2189
  * }
1862
2190
  * }[]
1863
2191
  * }[],
1864
- * errorCall: Function,
1865
- * limitCall: Function
2192
+ * errorCall: Function
1866
2193
  * }}
1867
2194
  * @returns {Promise<Object|false>}
1868
2195
  */
1869
- async batchTotalCount(r, e, { errorCall: i, updateList: n, limitCall: o } = {}) {
2196
+ async batchTotalCount(r, e, { errorCall: s, updateList: n } = {}) {
1870
2197
  if (typeof BX24 > "u" || !BX24.callBatch) {
1871
- const h = new Error("BX24 is not initialized");
1872
- return console.error(h), !1;
2198
+ const A = new Error("BX24 is not initialized");
2199
+ return console.error(A), !1;
1873
2200
  }
1874
- let l = new K(BX24.callBatch), c;
1875
- n && (c = this.logger.start({
2201
+ const o = E(this, rt, ct).call(this);
2202
+ let h;
2203
+ n && (h = this.logger.start({
1876
2204
  type: "batch-total-count",
1877
2205
  data: { commandList: r }
1878
2206
  }));
1879
2207
  try {
1880
- let h = await l.batchTotalCount(
2208
+ let A = await o.batchTotalCount(
1881
2209
  r,
1882
- e,
1883
- o
2210
+ e
1884
2211
  );
1885
- const s = J(this, et, ft).call(this, l, h, r, n);
1886
- if (Object.keys(s).length) {
1887
- if (i && i(s), c)
2212
+ const l = E(this, ut, Ut).call(this, o, A, r, n);
2213
+ if (Object.keys(l).length) {
2214
+ if (s && s(l), h)
1888
2215
  try {
1889
2216
  await this.logger.stop({
1890
- key: c,
2217
+ key: h,
1891
2218
  status: "fail",
1892
- errorList: s
2219
+ errorList: l
1893
2220
  });
1894
- } catch (f) {
1895
- console.error("Logger error:", f);
2221
+ } catch (i) {
2222
+ console.error("Logger error:", i);
1896
2223
  }
1897
- } else if (c)
2224
+ } else if (h)
1898
2225
  try {
1899
2226
  await this.logger.stop({
1900
- key: c,
2227
+ key: h,
1901
2228
  status: "success"
1902
2229
  });
1903
- } catch (f) {
1904
- console.error("Logger error:", f);
2230
+ } catch (i) {
2231
+ console.error("Logger error:", i);
1905
2232
  }
1906
- return h;
1907
- } catch (h) {
1908
- if (c)
2233
+ return A;
2234
+ } catch (A) {
2235
+ if (h)
1909
2236
  try {
1910
2237
  await this.logger.stop({
1911
- key: c,
2238
+ key: h,
1912
2239
  status: "fail-runtime",
1913
- errorList: { 0: h == null ? void 0 : h.toString() }
2240
+ errorList: { 0: A == null ? void 0 : A.toString() }
1914
2241
  });
1915
- } catch (s) {
1916
- console.error("Logger error:", s);
2242
+ } catch (l) {
2243
+ console.error("Logger error:", l);
1917
2244
  }
1918
- return console.error(h), !1;
2245
+ return console.error(A), !1;
1919
2246
  }
1920
2247
  }
1921
2248
  /** Запрос данных о местах встройки приложения */
1922
2249
  async getPlacement() {
1923
2250
  return await this.call({ method: "placement.get" }).then((r) => (this.placeData || (this.placeData = r), r));
1924
2251
  }
1925
- /** Встройка приложения в place */
1926
- async placementBind(r, e = !0) {
1927
- var f;
1928
- if (!this.isAdmin)
2252
+ /**
2253
+ * Встройка приложения в указанные места
2254
+ * @param {string|string[]|Object|Object[]} place - Место или массив мест для встройки
2255
+ */
2256
+ async placementBind(r) {
2257
+ var y;
2258
+ if (!this.isAdmin || (this.placeData = await this.getPlacement(), !this.placeData))
1929
2259
  return;
1930
- e && await this.placementCheck();
1931
- let i = [];
1932
- if (Array.isArray(r) ? i = r.map((m) => typeof m == "string" ? { placement: m } : m) : typeof r == "string" ? i = [{ placement: r }] : i = [r], i = i.filter(
1933
- (m) => m.placement !== "PAGE_BACKGROUND_WORKER" && m.placement !== "PAGE_BACKGROUND_WORKER_ALL"
1934
- ), this.placeData = await this.getPlacement(), !this.placeData)
2260
+ const { appName: e, pathApp: s } = this.appConst;
2261
+ let n = E(this, ft, Pt).call(this, r);
2262
+ n = n.filter(
2263
+ (c) => c.placement !== "PAGE_BACKGROUND_WORKER" && c.placement !== "PAGE_BACKGROUND_WORKER_ALL"
2264
+ );
2265
+ const o = E(this, Dt, qt).call(this, s), h = new Set(n.map((c) => c.placement));
2266
+ for (const c of o)
2267
+ h.has(c.placement) || n.push({ placement: c.placement });
2268
+ if (n.length === 0)
1935
2269
  return;
1936
- const { appName: n, pathApp: o } = this.appConst;
1937
- let l = n;
1938
- this.domain === "szdl.bitrix24.ru" && ((f = this.appInfo) != null && f.ID) && (l = `${n}: #${this.appInfo.ID}`);
1939
- const c = l.replace(" CRM", ""), h = {}, s = [];
1940
- for (let m = 0; m < i.length; m++) {
1941
- const u = i[m].placement, N = o;
2270
+ let A = e;
2271
+ this.domain === "szdl.bitrix24.ru" && ((y = this.appInfo) != null && y.ID) && (A = `${e}: #${this.appInfo.ID}`);
2272
+ const l = A.replace(" CRM", ""), i = {}, u = [];
2273
+ for (let c = 0; c < n.length; c++) {
2274
+ const f = n[c].placement;
1942
2275
  if (this.placeData.find(
1943
- (b) => b.placement === u && b.handler === N
2276
+ (m) => m.placement === f && m.handler === s
1944
2277
  ))
1945
2278
  continue;
1946
- const p = this.placeData.find(
1947
- (b) => b.placement === u && b.handler !== N
2279
+ const _ = this.placeData.filter(
2280
+ (m) => m.placement === f && m.handler !== s
1948
2281
  );
1949
- p && s.push({
1950
- placement: u,
1951
- handler: p.handler
1952
- });
1953
- const R = {
1954
- PLACEMENT: u,
1955
- HANDLER: N,
1956
- LANG_ALL: {
1957
- ru: {
1958
- TITLE: u === "USER_PROFILE_TOOLBAR" ? c : l
2282
+ for (const m of _)
2283
+ u.push({
2284
+ placement: f,
2285
+ handler: m.handler
2286
+ });
2287
+ i[`bind_${c}`] = {
2288
+ method: "placement.bind",
2289
+ params: {
2290
+ PLACEMENT: f,
2291
+ HANDLER: s,
2292
+ LANG_ALL: {
2293
+ ru: {
2294
+ TITLE: f === "USER_PROFILE_TOOLBAR" ? l : A
2295
+ }
2296
+ },
2297
+ OPTIONS: {
2298
+ errorHandlerUrl: s
1959
2299
  }
1960
- },
1961
- OPTIONS: {
1962
- errorHandlerUrl: N
1963
2300
  }
1964
2301
  };
1965
- h[`bind_${m}`] = {
1966
- method: "placement.bind",
1967
- params: R
1968
- };
1969
2302
  }
1970
- s.length > 0 && await this.placementUnBind(s), Object.keys(h).length > 0 && await this.batch(h), Object.keys(h).length > 0 && (this.placeData = await this.getPlacement(), Object.values(h).forEach((m) => {
1971
- console.log(
1972
- "Приложение успешно встроено в",
1973
- m.params.PLACEMENT
1974
- );
2303
+ u.length > 0 && await this.placementUnBind(u), Object.keys(i).length > 0 && (await this.batch(i), this.placeData = await this.getPlacement(), Object.values(i).forEach((c) => {
2304
+ console.log("Приложение успешно встроено в", c.params.PLACEMENT);
1975
2305
  }));
1976
2306
  }
1977
- /* Отвязка встройки из place */
2307
+ /**
2308
+ * Отвязка встройки из указанных мест
2309
+ * @param {string|string[]|Object|Object[]} place - Место или массив мест для отвязки
2310
+ */
1978
2311
  async placementUnBind(r) {
1979
- let e = [];
1980
- Array.isArray(r) ? e = r.map((n) => typeof n == "string" ? { placement: n } : n) : typeof r == "string" ? e = [{ placement: r }] : e = [r], e = e.filter(
2312
+ let e = E(this, ft, Pt).call(this, r);
2313
+ if (e = e.filter(
1981
2314
  (n) => n.placement !== "PAGE_BACKGROUND_WORKER" && n.placement !== "PAGE_BACKGROUND_WORKER_ALL"
1982
- );
1983
- const i = {};
2315
+ ), e.length === 0)
2316
+ return;
2317
+ const s = {};
1984
2318
  for (let n = 0; n < e.length; n++) {
1985
- const o = e[n], l = o.placement, c = o.handler, h = {
1986
- PLACEMENT: l
2319
+ const o = {
2320
+ PLACEMENT: e[n].placement
1987
2321
  };
1988
- c && (h.HANDLER = c), i[`unbind_${n}`] = {
2322
+ e[n].handler && (o.HANDLER = e[n].handler), s[`unbind_${n}`] = {
1989
2323
  method: "placement.unbind",
1990
- params: h
2324
+ params: o
1991
2325
  };
1992
2326
  }
1993
- Object.keys(i).length > 0 && (await this.batch(i), e.forEach((n) => {
2327
+ await this.batch(s), e.forEach((n) => {
1994
2328
  console.log("Встройка отвязана", n.placement);
1995
- }));
1996
- }
1997
- /** Удаляем фоновые обработчики прошлых версий и создаем новые */
1998
- async placementCheck() {
1999
- if (this.placeData = await this.getPlacement(), !this.placeData)
2000
- return;
2001
- const { pathApp: r } = this.appConst, e = [], i = [];
2002
- for (const n of this.placeData) {
2003
- if (n.placement === "PAGE_BACKGROUND_WORKER" || !n.handler || n.handler.includes(r))
2004
- continue;
2005
- const { placement: o, handler: l, userId: c } = n;
2006
- e.push({ placement: o, handler: l }), i.push({ placement: o, userId: c });
2007
- }
2008
- e.length > 0 && await this.placementUnBind(e), i.length > 0 && await this.placementBind(i, !1);
2329
+ });
2009
2330
  }
2010
2331
  /** Чат-бот */
2011
2332
  /* получение списка ботов */
@@ -2019,8 +2340,8 @@ class It {
2019
2340
  });
2020
2341
  }
2021
2342
  /* регистрация бота */
2022
- regBot({ code: r, type: e, name: i }) {
2023
- const { appName: n, pathApp: o, chatBotLogo: l } = this.appConst, c = this.appInfo.ID;
2343
+ regBot({ code: r, type: e, name: s }) {
2344
+ const { appName: n, pathApp: o, chatBotLogo: h } = this.appConst, A = this.appInfo.ID;
2024
2345
  return this.call({
2025
2346
  method: "imbot.register",
2026
2347
  params: {
@@ -2036,7 +2357,7 @@ class It {
2036
2357
  // строковый идентификатор чат-бота, используется только в режиме Вебхуков
2037
2358
  PROPERTIES: {
2038
2359
  // Личные данные чат-бота (обяз.)
2039
- NAME: `${i ?? n} - бот #${c}`,
2360
+ NAME: `${s ?? n} - бот #${A}`,
2040
2361
  // Имя чат-бота (обязательное одно из полей NAME или LAST_NAME)
2041
2362
  LAST_NAME: "",
2042
2363
  // Фамилия чат-бота (обязательное одно из полей NAME или LAST_NAME)
@@ -2044,7 +2365,7 @@ class It {
2044
2365
  // Цвет чат-бота для мобильного приложения RED, GREEN, MINT, LIGHT_BLUE, DARK_BLUE, PURPLE, AQUA, PINK, LIME, BROWN, AZURE, KHAKI, SAND, MARENGO, GRAY, GRAPHITE
2045
2366
  EMAIL: "",
2046
2367
  // E-mail для связи. НЕЛЬЗЯ использовать e-mail, дублирующий e-mail реальных пользователей
2047
- PERSONAL_BIRTHDAY: rt().format("%Y-%m-%d"),
2368
+ PERSONAL_BIRTHDAY: mt().format("%Y-%m-%d"),
2048
2369
  // День рождения в формате YYYY-mm-dd
2049
2370
  WORK_POSITION: "Почтальон",
2050
2371
  // Занимаемая должность, используется как описание чат-бота
@@ -2052,11 +2373,11 @@ class It {
2052
2373
  // Ссылка на сайт
2053
2374
  PERSONAL_GENDER: "M",
2054
2375
  // Пол чат-бота, допустимые значения M - мужской, F - женский, пусто, если не требуется указывать
2055
- PERSONAL_PHOTO: l ?? ""
2376
+ PERSONAL_PHOTO: h ?? ""
2056
2377
  // Аватар чат-бота - base64
2057
2378
  }
2058
2379
  }
2059
- }).then((h) => (console.log("Чат-бот добавлен", h), h));
2380
+ }).then((l) => (console.log("Чат-бот добавлен", l), l));
2060
2381
  }
2061
2382
  /* Убрать регистрацию бота */
2062
2383
  unRegBot(r) {
@@ -2072,66 +2393,80 @@ class It {
2072
2393
  return this.logger.getEntityList(r);
2073
2394
  }
2074
2395
  }
2075
- ot = new WeakSet(), Nt = function() {
2396
+ rt = new WeakSet(), ct = function() {
2397
+ return this.batchClient || (this.batchClient = new v({
2398
+ callBatch: BX24.callBatch,
2399
+ callMethod: BX24.callMethod
2400
+ }), this.timeLimit = this.batchClient.timeLimit), this.batchClient;
2401
+ }, It = new WeakSet(), vt = function() {
2076
2402
  return this.call({ method: "app.info" });
2077
- }, At = new WeakSet(), Ot = function() {
2403
+ }, Mt = new WeakSet(), Qt = function() {
2078
2404
  return this.call({ method: "user.current" });
2079
- }, et = new WeakSet(), ft = function(r, e, i, n) {
2405
+ }, ut = new WeakSet(), Ut = function(r, e, s, n) {
2080
2406
  let o = { ...r.errors };
2081
2407
  if (Object.values(r.errors).some(
2082
- (c) => {
2083
- if (typeof c != "string")
2408
+ (A) => {
2409
+ if (typeof A != "string")
2084
2410
  return !1;
2085
- const h = c.toUpperCase();
2086
- return h === "TIMEOUT" || h === "OPERATION_TIME_LIMIT" || h.includes("TIMEOUT") || h.includes("OPERATION_TIME_LIMIT");
2411
+ const l = A.toUpperCase();
2412
+ return l === "TIMEOUT" || l === "OPERATION_TIME_LIMIT" || l.includes("TIMEOUT") || l.includes("OPERATION_TIME_LIMIT");
2087
2413
  }
2088
2414
  ) && n) {
2089
- const c = e ? Object.keys(e).filter((m) => m !== "errorsList") : [], h = new Set(Object.keys(r.errors || {})), s = /* @__PURE__ */ new Set();
2415
+ const A = e ? Object.keys(e).filter((y) => y !== "errorsList") : [], l = new Set(Object.keys(r.errors || {})), i = /* @__PURE__ */ new Set();
2090
2416
  if (e) {
2091
- for (const m of c)
2092
- if (!h.has(m)) {
2093
- const A = e[m];
2094
- A != null && s.add(m);
2417
+ for (const y of A)
2418
+ if (!l.has(y)) {
2419
+ const c = e[y];
2420
+ c != null && i.add(y);
2095
2421
  }
2096
2422
  }
2097
- const f = Object.values(r.errors).find(
2098
- (m) => {
2099
- if (typeof m != "string")
2423
+ const u = Object.values(r.errors).find(
2424
+ (y) => {
2425
+ if (typeof y != "string")
2100
2426
  return !1;
2101
- const A = m.toUpperCase();
2102
- return A === "TIMEOUT" || A === "OPERATION_TIME_LIMIT" || A.includes("TIMEOUT") || A.includes("OPERATION_TIME_LIMIT");
2427
+ const c = y.toUpperCase();
2428
+ return c === "TIMEOUT" || c === "OPERATION_TIME_LIMIT" || c.includes("TIMEOUT") || c.includes("OPERATION_TIME_LIMIT");
2103
2429
  }
2104
2430
  );
2105
- for (const m of Object.keys(i))
2106
- !s.has(m) && !r.errors[m] && (o[m] = f || "TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан");
2431
+ for (const y of Object.keys(s))
2432
+ !i.has(y) && !r.errors[y] && (o[y] = u || "TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан");
2107
2433
  }
2108
2434
  return o;
2435
+ }, ft = new WeakSet(), Pt = function(r) {
2436
+ if (!r)
2437
+ return [];
2438
+ let e = [];
2439
+ return Array.isArray(r) ? e = r.map(
2440
+ (s) => typeof s == "string" ? { placement: s } : s
2441
+ ) : typeof r == "string" ? e = [{ placement: r }] : e = [r], e;
2442
+ }, Dt = new WeakSet(), qt = function(r) {
2443
+ return this.placeData ? this.placeData.filter((e) => !(e.placement === "PAGE_BACKGROUND_WORKER" || !e.handler || e.handler.includes(r))) : [];
2109
2444
  };
2110
- class Mt {
2445
+ class ie {
2111
2446
  constructor(r) {
2112
- I(this, "entityName", "tabs");
2113
- I(this, "maxTabs", 20);
2114
- I(this, "tabList", []);
2115
- I(this, "id", 0);
2116
- I(this, "hasStarted", !1);
2117
- I(this, "heartbeat");
2118
- I(this, "runHeartbeat");
2119
- I(this, "random", this.getRandomNum());
2120
- I(this, "activeMaxPause", 5 * 60 * 1e3 + this.random);
2121
- I(this, "quickCleanupThreshold", 2 * 60 * 1e3);
2447
+ w(this, "entityName", "tabs");
2448
+ w(this, "maxTabs", 20);
2449
+ w(this, "tabList", []);
2450
+ w(this, "id", 0);
2451
+ w(this, "hasStarted", !1);
2452
+ w(this, "heartbeat");
2453
+ w(this, "runHeartbeat");
2454
+ w(this, "random", this.getRandomNum());
2455
+ w(this, "activeMaxPause", 5 * 60 * 1e3 + this.random);
2456
+ w(this, "quickCleanupThreshold", 2 * 60 * 1e3);
2122
2457
  // агрессивная очистка при переполнении
2123
- I(this, "pollInterval", (60 + this.random) * 1e3);
2458
+ w(this, "pollInterval", (60 + this.random) * 1e3);
2124
2459
  // 30-90 cек для выбора лидера
2125
- I(this, "sessionId", `${Date.now()}-${Math.random().toString(16).slice(2)}`);
2126
- I(this, "continueCondition");
2127
- I(this, "defaultContinueBackground", () => !0);
2128
- var l, c, h;
2460
+ w(this, "sessionId", `${Date.now()}-${Math.random().toString(16).slice(2)}`);
2461
+ w(this, "continueCondition");
2462
+ w(this, "defaultContinueBackground", () => !0);
2463
+ var h, A, l;
2129
2464
  if (!r) {
2130
2465
  console.error("BackgroundWorker: Нет опций конструктора");
2131
2466
  return;
2132
2467
  }
2133
- const { appFunc: e, bx: i, users: n, continueBackground: o } = r;
2134
- this.bx = i, this.appInit = e, this.users = n, this.appPath = ((l = i == null ? void 0 : i.appConst) == null ? void 0 : l.pathApp) ?? "", this.appName = ((c = i == null ? void 0 : i.appConst) == null ? void 0 : c.appName) ?? "", this.appCodeName = ((h = i == null ? void 0 : i.appConst) == null ? void 0 : h.appCodeName) ?? "", this.start = /* @__PURE__ */ new Date(), this.continueCondition = typeof o == "function" ? o : this.defaultContinueBackground;
2468
+ const { appFunc: e, bx: s, users: n, continueBackground: o } = r;
2469
+ this.bx = s, this.appInit = e, this.users = n, this.appPath = ((h = s == null ? void 0 : s.appConst) == null ? void 0 : h.pathApp) ?? "", this.appName = ((A = s == null ? void 0 : s.appConst) == null ? void 0 : A.appName) ?? "", this.appCodeName = ((l = s == null ? void 0 : s.appConst) == null ? void 0 : l.appCodeName) ?? "", this.start = /* @__PURE__ */ new Date(), this.continueCondition = typeof o == "function" ? o : this.defaultContinueBackground;
2135
2470
  }
2136
2471
  async init() {
2137
2472
  if (!this.appInit) {
@@ -2162,8 +2497,8 @@ class Mt {
2162
2497
  return;
2163
2498
  }
2164
2499
  await this.refreshTabs(!0), await this.ensureTabRegistered();
2165
- const e = this.selectLeaderId(), i = e && +this.id == +e;
2166
- await this.updateTabState(i), i && !this.hasStarted && (this.hasStarted = !0, await this.runAsLeader());
2500
+ const e = this.selectLeaderId(), s = e && +this.id == +e;
2501
+ await this.updateTabState(s), s && !this.hasStarted && (this.hasStarted = !0, await this.runAsLeader());
2167
2502
  }
2168
2503
  stopTimers() {
2169
2504
  this.heartbeat && (clearInterval(this.heartbeat), this.heartbeat = void 0), this.runHeartbeat && (clearInterval(this.runHeartbeat), this.runHeartbeat = void 0);
@@ -2173,18 +2508,18 @@ class Mt {
2173
2508
  if (typeof BX24 > "u" || !((r = BX24.placement) != null && r.info))
2174
2509
  return !1;
2175
2510
  try {
2176
- const e = BX24.placement.info(), i = e == null ? void 0 : e.placement, n = (e == null ? void 0 : e.options) || {}, o = (n == null ? void 0 : n.URI) || "", l = i === "PAGE_BACKGROUND_WORKER" || (n == null ? void 0 : n.ID) === "PAGE_BACKGROUND_WORKER", c = typeof o == "string" && (o.includes("marketplace/app") || o.includes("marketplace/apps") || o.includes("placement") || o.includes("sozdavatel" + this.appCodeName));
2177
- return !l || c;
2511
+ const e = BX24.placement.info(), s = e == null ? void 0 : e.placement, n = (e == null ? void 0 : e.options) || {}, o = (n == null ? void 0 : n.URI) || "", h = s === "PAGE_BACKGROUND_WORKER" || (n == null ? void 0 : n.ID) === "PAGE_BACKGROUND_WORKER", A = typeof o == "string" && (o.includes("marketplace/app") || o.includes("marketplace/apps") || o.includes("placement") || o.includes("sozdavatel" + this.appCodeName));
2512
+ return !h || A;
2178
2513
  } catch {
2179
2514
  return !1;
2180
2515
  }
2181
2516
  }
2182
2517
  async checkEntity() {
2183
- var i;
2518
+ var s;
2184
2519
  const r = await this.safeCall(
2185
2520
  () => this.bx.call({ method: "entity.get" })
2186
2521
  );
2187
- ((i = r == null ? void 0 : r.find) == null ? void 0 : i.call(
2522
+ ((s = r == null ? void 0 : r.find) == null ? void 0 : s.call(
2188
2523
  r,
2189
2524
  (n) => n.ENTITY === this.entityName
2190
2525
  )) || await this.safeCall(
@@ -2216,10 +2551,10 @@ class Mt {
2216
2551
  if (!e)
2217
2552
  return { id: void 0, data: void 0 };
2218
2553
  try {
2219
- const i = JSON.parse(e.DETAIL_TEXT);
2220
- return { id: +e.ID || 0, data: i };
2221
- } catch (i) {
2222
- return console.log("BackgroundWorker: parse tab error", i), { id: +e.ID || 0, data: void 0 };
2554
+ const s = JSON.parse(e.DETAIL_TEXT);
2555
+ return { id: +e.ID || 0, data: s };
2556
+ } catch (s) {
2557
+ return console.log("BackgroundWorker: parse tab error", s), { id: +e.ID || 0, data: void 0 };
2223
2558
  }
2224
2559
  });
2225
2560
  }
@@ -2237,12 +2572,12 @@ class Mt {
2237
2572
  sessionId: this.sessionId
2238
2573
  }, e = await this.safeCall(
2239
2574
  () => {
2240
- var i;
2575
+ var s;
2241
2576
  return this.bx.call({
2242
2577
  method: "entity.item.add",
2243
2578
  params: {
2244
2579
  ENTITY: this.entityName,
2245
- NAME: (i = this.bx.userInfo) == null ? void 0 : i.ID,
2580
+ NAME: (s = this.bx.userInfo) == null ? void 0 : s.ID,
2246
2581
  DETAIL_TEXT: JSON.stringify(r)
2247
2582
  }
2248
2583
  });
@@ -2261,13 +2596,13 @@ class Mt {
2261
2596
  };
2262
2597
  await this.safeCall(
2263
2598
  () => {
2264
- var i;
2599
+ var s;
2265
2600
  return this.bx.call({
2266
2601
  method: "entity.item.update",
2267
2602
  params: {
2268
2603
  ENTITY: this.entityName,
2269
2604
  ID: this.id,
2270
- NAME: (i = this.bx.userInfo) == null ? void 0 : i.ID,
2605
+ NAME: (s = this.bx.userInfo) == null ? void 0 : s.ID,
2271
2606
  DETAIL_TEXT: JSON.stringify(e)
2272
2607
  }
2273
2608
  });
@@ -2277,9 +2612,9 @@ class Mt {
2277
2612
  async deleteTabs(r = []) {
2278
2613
  if (!r.length)
2279
2614
  return;
2280
- const e = r.map((i) => ({
2615
+ const e = r.map((s) => ({
2281
2616
  method: "entity.item.delete",
2282
- params: { ENTITY: this.entityName, ID: i.id }
2617
+ params: { ENTITY: this.entityName, ID: s.id }
2283
2618
  }));
2284
2619
  await this.safeCall(() => this.bx.batch(e));
2285
2620
  }
@@ -2297,24 +2632,24 @@ class Mt {
2297
2632
  return console.log(
2298
2633
  "BackgroundWorker: Не получили список размещений, продолжаем"
2299
2634
  ), !0;
2300
- const i = +(((r = this.bx.userInfo) == null ? void 0 : r.ID) ?? 0), n = this.isIndividualPlacement(
2635
+ const s = +(((r = this.bx.userInfo) == null ? void 0 : r.ID) ?? 0), n = this.isIndividualPlacement(
2301
2636
  typeof window < "u" ? window.location.href : ""
2302
2637
  ), o = !n;
2303
- if (!i)
2638
+ if (!s)
2304
2639
  return !0;
2305
- let l = !1;
2306
- for (const c of e) {
2307
- if (c.placement !== "PAGE_BACKGROUND_WORKER" || !(c.userId || c.handler && c.handler.includes("USER_ID=")))
2640
+ let h = !1;
2641
+ for (const A of e) {
2642
+ if (A.placement !== "PAGE_BACKGROUND_WORKER" || !(A.userId || A.handler && A.handler.includes("USER_ID=")))
2308
2643
  continue;
2309
- const s = c.userId || (c.handler ? this.extractUserIdFromHandler(c.handler) : null);
2310
- if (s && +s === i) {
2311
- l = !0;
2644
+ const i = A.userId || (A.handler ? this.extractUserIdFromHandler(A.handler) : null);
2645
+ if (i && +i === s) {
2646
+ h = !0;
2312
2647
  break;
2313
2648
  }
2314
2649
  }
2315
2650
  return n ? (console.log(
2316
2651
  "BackgroundWorker: Индивидуальная встройка - разрешено"
2317
- ), !0) : o && l ? (console.log(
2652
+ ), !0) : o && h ? (console.log(
2318
2653
  "BackgroundWorker: Есть личная встройка, общую не запускаем"
2319
2654
  ), !1) : (console.log(
2320
2655
  "BackgroundWorker: Проверка типа встройки пройдена, продолжаем"
@@ -2349,30 +2684,30 @@ class Mt {
2349
2684
  }
2350
2685
  }
2351
2686
  async refreshTabs(r = !1, e = this.activeMaxPause) {
2352
- const i = [], n = [], o = Date.now(), l = await this.getTabs();
2353
- for (const c of l) {
2354
- if (!(c != null && c.data)) {
2355
- i.push(c);
2687
+ const s = [], n = [], o = Date.now(), h = await this.getTabs();
2688
+ for (const A of h) {
2689
+ if (!(A != null && A.data)) {
2690
+ s.push(A);
2356
2691
  continue;
2357
2692
  }
2358
- if (o - new Date(c.data.lastActive || 0).getTime() > e) {
2359
- i.push(c);
2693
+ if (o - new Date(A.data.lastActive || 0).getTime() > e) {
2694
+ s.push(A);
2360
2695
  continue;
2361
2696
  }
2362
- n.push(c);
2697
+ n.push(A);
2363
2698
  }
2364
- return r && i.length && await this.deleteTabs(i), this.tabList = n, n;
2699
+ return r && s.length && await this.deleteTabs(s), this.tabList = n, n;
2365
2700
  }
2366
2701
  selectLeaderId() {
2367
2702
  var e;
2368
- return this.tabList.length && +((e = [...this.tabList].sort((i, n) => {
2369
- var c, h, s, f;
2703
+ return this.tabList.length && +((e = [...this.tabList].sort((s, n) => {
2704
+ var A, l, i, u;
2370
2705
  const o = new Date(
2371
- ((c = i.data) == null ? void 0 : c.createdAt) || ((h = i.data) == null ? void 0 : h.lastActive) || 0
2372
- ).getTime(), l = new Date(
2373
- ((s = n.data) == null ? void 0 : s.createdAt) || ((f = n.data) == null ? void 0 : f.lastActive) || 0
2706
+ ((A = s.data) == null ? void 0 : A.createdAt) || ((l = s.data) == null ? void 0 : l.lastActive) || 0
2707
+ ).getTime(), h = new Date(
2708
+ ((i = n.data) == null ? void 0 : i.createdAt) || ((u = n.data) == null ? void 0 : u.lastActive) || 0
2374
2709
  ).getTime();
2375
- return o === l ? (+i.id || 0) - (+n.id || 0) : o - l;
2710
+ return o === h ? (+s.id || 0) - (+n.id || 0) : o - h;
2376
2711
  })[0]) == null ? void 0 : e.id) || 0;
2377
2712
  }
2378
2713
  async runAsLeader() {
@@ -2395,70 +2730,81 @@ class Mt {
2395
2730
  this.stopTimers(), this.id && (await this.deleteTabs([{ id: this.id }]), this.id = 0);
2396
2731
  }
2397
2732
  async setBackgroundWorkerAll() {
2398
- var N, y;
2399
- if (!((N = this.bx) != null && N.isAdmin)) {
2733
+ var O, _;
2734
+ if (!((O = this.bx) != null && O.isAdmin)) {
2400
2735
  console.log(
2401
2736
  "BackgroundWorker: setBackgroundWorkerAll доступен только админам"
2402
2737
  );
2403
2738
  return;
2404
2739
  }
2405
- (y = this.users) != null && y.length || await this.getEntityData();
2740
+ (_ = this.users) != null && _.length || await this.getEntityData();
2406
2741
  const r = await this.safeCall(
2407
2742
  () => this.bx.getPlacement()
2408
2743
  ), e = /* @__PURE__ */ new Map();
2409
- let i = null;
2410
- (r || []).forEach((p) => {
2411
- if (p.placement !== "PAGE_BACKGROUND_WORKER")
2744
+ let s = null;
2745
+ (r || []).forEach((m) => {
2746
+ if (m.placement !== "PAGE_BACKGROUND_WORKER")
2412
2747
  return;
2413
- if (p.userId || p.handler && p.handler.includes("USER_ID=")) {
2414
- const b = p.userId || (p.handler ? this.extractUserIdFromHandler(p.handler) : null);
2415
- b && e.set(+b, p);
2748
+ if (m.userId || m.handler && m.handler.includes("USER_ID=")) {
2749
+ const p = m.userId || (m.handler ? this.extractUserIdFromHandler(m.handler) : null);
2750
+ p && e.set(+p, m);
2416
2751
  } else
2417
- i = p;
2752
+ s = m;
2418
2753
  });
2419
2754
  const n = await this.resolveAdmins(), o = await this.getEligibleUsersForBackgroundWorker(n);
2420
- o.sort((p, R) => {
2421
- const b = p.LAST_LOGIN ? new Date(p.LAST_LOGIN) : /* @__PURE__ */ new Date(0);
2422
- return (R.LAST_LOGIN ? new Date(R.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) - b;
2755
+ o.sort((m, N) => {
2756
+ const p = m.LAST_LOGIN ? new Date(m.LAST_LOGIN) : /* @__PURE__ */ new Date(0);
2757
+ return (N.LAST_LOGIN ? new Date(N.LAST_LOGIN) : /* @__PURE__ */ new Date(0)) - p;
2423
2758
  });
2424
- const l = 10, h = o.slice(0, l).filter(
2425
- (p) => !e.has(+p.ID)
2426
- ), s = [];
2427
- for (const [p] of e) {
2428
- const R = +p || 0;
2429
- o.find((M) => +M.ID === R) || s.push(R);
2759
+ const h = 10, A = o.slice(0, h), l = A.filter((m) => {
2760
+ const N = e.get(+m.ID);
2761
+ if (!N)
2762
+ return !0;
2763
+ const p = `${this.appPath}?USER_ID=${m.ID}/`;
2764
+ return N.handler !== p;
2765
+ }), i = [];
2766
+ for (const [m] of e) {
2767
+ const N = +m || 0;
2768
+ o.find((T) => +T.ID === N) || i.push(N);
2430
2769
  }
2431
- const f = [];
2432
- for (const p of s)
2433
- this.appPath && f.push({
2770
+ for (const m of A) {
2771
+ const N = e.get(+m.ID);
2772
+ if (!N)
2773
+ continue;
2774
+ const p = `${this.appPath}?USER_ID=${m.ID}/`;
2775
+ N.handler !== p && i.push(+m.ID);
2776
+ }
2777
+ const u = [];
2778
+ for (const m of i)
2779
+ this.appPath && u.push({
2434
2780
  method: "placement.unbind",
2435
2781
  params: {
2436
2782
  PLACEMENT: "PAGE_BACKGROUND_WORKER",
2437
- HANDLER: `${this.appPath}?USER_ID=${p}/`
2783
+ HANDLER: `${this.appPath}?USER_ID=${m}/`
2438
2784
  }
2439
2785
  });
2440
- const m = i && h.length > 0;
2441
- m && this.appPath && f.push({
2786
+ const y = s && (l.length > 0 || s.handler !== `${this.appPath}`);
2787
+ y && this.appPath && u.push({
2442
2788
  method: "placement.unbind",
2443
2789
  params: {
2444
2790
  PLACEMENT: "PAGE_BACKGROUND_WORKER",
2445
- HANDLER: i.handler || `${this.appPath}`
2791
+ HANDLER: s.handler || `${this.appPath}`
2446
2792
  }
2447
2793
  });
2448
- for (const p of h)
2449
- this.appPath && f.push({
2794
+ for (const m of l)
2795
+ this.appPath && u.push({
2450
2796
  method: "placement.bind",
2451
2797
  params: {
2452
2798
  PLACEMENT: "PAGE_BACKGROUND_WORKER",
2453
- HANDLER: `${this.appPath}?USER_ID=${p.ID}/`,
2799
+ HANDLER: `${this.appPath}?USER_ID=${m.ID}/`,
2454
2800
  LANG_ALL: { ru: { TITLE: this.appName } },
2455
2801
  OPTIONS: {
2456
- errorHandlerUrl: `${this.appPath}?USER_ID=${p.ID}/`
2802
+ errorHandlerUrl: `${this.appPath}?USER_ID=${m.ID}/`
2457
2803
  },
2458
- USER_ID: p.ID
2804
+ USER_ID: m.ID
2459
2805
  }
2460
2806
  });
2461
- (!i || m) && this.appPath && f.push({
2807
+ (!s || y) && this.appPath && u.push({
2462
2808
  method: "placement.bind",
2463
2809
  params: {
2464
2810
  PLACEMENT: "PAGE_BACKGROUND_WORKER",
@@ -2467,51 +2813,51 @@ class Mt {
2467
2813
  OPTIONS: { errorHandlerUrl: `${this.appPath}` }
2468
2814
  }
2469
2815
  });
2470
- const A = f.filter(
2471
- (p) => p.method === "placement.unbind"
2472
- ), u = f.filter(
2473
- (p) => p.method === "placement.bind"
2816
+ const c = u.filter(
2817
+ (m) => m.method === "placement.unbind"
2818
+ ), f = u.filter(
2819
+ (m) => m.method === "placement.bind"
2474
2820
  );
2475
- A.length && await this.safeCall(
2821
+ c.length && await this.safeCall(
2476
2822
  () => this.bx.batch(
2477
2823
  Object.fromEntries(
2478
- A.map((p, R) => [`unbind_${R}`, p])
2824
+ c.map((m, N) => [`unbind_${N}`, m])
2479
2825
  )
2480
2826
  )
2481
- ), u.length && await this.safeCall(
2827
+ ), f.length && await this.safeCall(
2482
2828
  () => this.bx.batch(
2483
2829
  Object.fromEntries(
2484
- u.map((p, R) => [`bind_${R}`, p])
2830
+ f.map((m, N) => [`bind_${N}`, m])
2485
2831
  )
2486
2832
  )
2487
- ), f.length || console.log("setBackgroundWorkerAll: Нет операций");
2833
+ ), u.length || console.log("setBackgroundWorkerAll: Нет операций");
2488
2834
  }
2489
2835
  async resolveAdmins() {
2490
2836
  var r, e;
2491
2837
  try {
2492
- const i = +(((r = this.bx.userInfo) == null ? void 0 : r.ID) ?? 0), n = !!((e = this.bx) != null && e.isAdmin), o = await this.getAdminsList() || [];
2838
+ const s = +(((r = this.bx.userInfo) == null ? void 0 : r.ID) ?? 0), n = !!((e = this.bx) != null && e.isAdmin), o = await this.getAdminsList() || [];
2493
2839
  if (!n) {
2494
- if (i && o.includes(+i)) {
2495
- const h = o.filter(
2496
- (s) => +s != +i
2840
+ if (s && o.includes(+s)) {
2841
+ const l = o.filter(
2842
+ (i) => +i != +s
2497
2843
  );
2498
- return await this.saveAdminsList(h), h;
2844
+ return await this.saveAdminsList(l), l;
2499
2845
  }
2500
2846
  return o;
2501
2847
  }
2502
- const l = /* @__PURE__ */ new Set([...o || []]);
2503
- i && l.add(+i);
2504
- const c = [...l].filter(Boolean);
2505
- return await this.saveAdminsList(c), c;
2506
- } catch (i) {
2507
- return console.error("BackgroundWorker: resolveAdmins error", i), [];
2848
+ const h = /* @__PURE__ */ new Set([...o || []]);
2849
+ s && h.add(+s);
2850
+ const A = [...h].filter(Boolean);
2851
+ return await this.saveAdminsList(A), A;
2852
+ } catch (s) {
2853
+ return console.error("BackgroundWorker: resolveAdmins error", s), [];
2508
2854
  }
2509
2855
  }
2510
2856
  async getEligibleUsersForBackgroundWorker(r = []) {
2511
2857
  const e = (this.users ?? []).filter(
2512
2858
  (n) => n.ACTIVE === "Y" || n.ACTIVE === !0
2513
- ), i = r.map((n) => +n || 0).filter(Boolean);
2514
- return e.filter((n) => i.includes(+n.ID || 0));
2859
+ ), s = r.map((n) => +n || 0).filter(Boolean);
2860
+ return e.filter((n) => s.includes(+n.ID || 0));
2515
2861
  }
2516
2862
  async saveAdminsList(r = []) {
2517
2863
  try {
@@ -2523,7 +2869,7 @@ class Mt {
2523
2869
  async getAdminsList() {
2524
2870
  try {
2525
2871
  const r = BX24.appOption.get("adminsList"), e = r ? JSON.parse(r) : [];
2526
- return Array.isArray(e) ? e.map((i) => +i || 0).filter(Boolean) : [];
2872
+ return Array.isArray(e) ? e.map((s) => +s || 0).filter(Boolean) : [];
2527
2873
  } catch (r) {
2528
2874
  return console.error("BackgroundWorker: getAdminsList error", r), [];
2529
2875
  }
@@ -2532,7 +2878,7 @@ class Mt {
2532
2878
  const r = {
2533
2879
  users: { method: "user.get", params: { filter: { ACTIVE: "Y" } } }
2534
2880
  }, { users: e } = await this.safeCall(
2535
- () => this.bx.batch(r).then((i) => i ? (Array.isArray(i.users) || (i.users = []), i) : { users: [] })
2881
+ () => this.bx.batch(r).then((s) => s ? (Array.isArray(s.users) || (s.users = []), s) : { users: [] })
2536
2882
  );
2537
2883
  this.users = e;
2538
2884
  }
@@ -2545,9 +2891,9 @@ class Mt {
2545
2891
  (r = this.bx) != null && r.isAdmin && ((e = this.users) != null && e.length || await this.getEntityData(), await this.setBackgroundWorkerAll());
2546
2892
  }
2547
2893
  pause(r = 500, e) {
2548
- return new Promise((i) => {
2894
+ return new Promise((s) => {
2549
2895
  setTimeout(() => {
2550
- e && e(), i(!0);
2896
+ e && e(), s(!0);
2551
2897
  }, r);
2552
2898
  });
2553
2899
  }
@@ -2561,10 +2907,10 @@ class Mt {
2561
2907
  }
2562
2908
  }
2563
2909
  export {
2564
- Mt as BackgroundWorker,
2565
- K as Batch,
2566
- It as BxBoot,
2567
- mt as BxHelper,
2568
- bt as BxLogger,
2569
- rt as tempus
2910
+ ie as BackgroundWorker,
2911
+ v as Batch,
2912
+ se as BxBoot,
2913
+ Ft as BxHelper,
2914
+ ee as BxLogger,
2915
+ mt as tempus
2570
2916
  };