szdl-utils-kit 0.3.31 → 0.3.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,1489 @@
1
- var Je=Object.defineProperty;var je=(I,C,G)=>C in I?Je(I,C,{enumerable:!0,configurable:!0,writable:!0,value:G}):I[C]=G;var D=(I,C,G)=>(je(I,typeof C!="symbol"?C+"":C,G),G),ne=(I,C,G)=>{if(!C.has(I))throw TypeError("Cannot "+G)};var L=(I,C,G)=>(ne(I,C,"read from private field"),G?G.call(I):C.get(I)),E=(I,C,G)=>{if(C.has(I))throw TypeError("Cannot add the same private member more than once");C instanceof WeakSet?C.add(I):C.set(I,G)},X=(I,C,G,ct)=>(ne(I,C,"write to private field"),ct?ct.call(I,G):C.set(I,G),G);var y=(I,C,G)=>(ne(I,C,"access private method"),G);(function(I,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):(I=typeof globalThis<"u"?globalThis:I||self,C(I["szdl-utils-kit"]={}))})(this,function(I){var Dt,Ne,kt,Bt,Ct,wt,ht,Zt,Ht,Oe,Ut,_e,rt,It,V,lt,yt,ae,it,Mt,Pt,Te,Gt,Ee,ut,Vt,Nt,oe,Ot,Ae,nt,Z,$,at,ft,_t,tt,J,ot,dt,Yt,Re,Tt,le,Wt,Le,xt,be,Ft,Ie,mt,$t,vt,Me,Et,ce,Xt,Se,Jt,De,jt,ke,et,gt,Rt,he,Kt,Be,Lt,ue,qt,Ce,zt,we,bt,fe,At,St,Qt,He;"use strict";var C=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function G(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}var ct={exports:{}};(function(_,e){(function(t){Array.prototype.indexOf||(Array.prototype.indexOf=function(s,o){var m,p;for(m=o||0,p=this.length;m<p;m+=1)if(this[m]===s)return m;return-1});var r=this,i=function(s,o){for(var m=s.toString();m.length<o;)m="0"+m;return m},a=function(s,o){return o!==t?(s.year(o.year()||o.year),s.month(o.month()||o.month),s.day(o.day()||o.day),s.hours(o.hours()||o.hours),s.minutes(o.minutes()||o.minutes),s.seconds(o.seconds()||o.seconds),s.milliseconds(o.milliseconds()||o.milliseconds),s):t},l=function(s,o){var m,p="";return m=s.slice(o,o+1),m!==""&&!isNaN(Number(m))&&(p+="%H"),m=s.charAt(o+2),m!==""&&m===":"&&(p+=m),m=s.slice(o+3,o+4),m!==""&&!isNaN(Number(m))&&(p+="%M"),m=s.charAt(o+5),m!==""&&m===":"&&(p+=m),m=s.slice(o+6,o+7),m!==""&&!isNaN(Number(m))&&(p+="%S"),p},h=function(s,o){var m,p=[s.slice(o,o+1),s.charAt(o+2),s.slice(o+3,o+4),s.charAt(o+5),s.slice(o+6,o+9)],Y;return!isNaN(Number(p[0]))&&!isNaN(Number(p[2]))&&!isNaN(Number(p[4]))?(p[1]==="."&&p[3]==="."?m="%d.%m.%Y":p[1]==="-"&&p[3]==="-"?m="%m-%d-%Y":p[1]==="/"&&p[3]==="/"&&(m="%m/%d/%Y"),m):(Y=[s.slice(o,o+3),s.charAt(o+4),s.slice(o+5,o+6),s.charAt(o+7),s.slice(o+8,o+9)],!isNaN(Number(Y[0]))&&!isNaN(Number(Y[2]))&&!isNaN(Number(Y[4]))?(Y[1]==="-"&&Y[3]==="-"&&(m="%Y-%m-%d"),m):"")},u=r.tempus,n,d,f=r.navigator||{},A="en",c={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},N=function(){return[c[A].JANUARY_LONG,c[A].FEBRUARY_LONG,c[A].MARCH_LONG,c[A].APRIL_LONG,c[A].MAY_LONG,c[A].JUNE_LONG,c[A].JULY_LONG,c[A].AUGUST_LONG,c[A].SEPTEMBER_LONG,c[A].OCTOBER_LONG,c[A].NOVEMBER_LONG,c[A].DECEMBER_LONG]},O=function(){return[c[A].JANUARY_SHORT,c[A].FEBRUARY_SHORT,c[A].MARCH_SHORT,c[A].APRIL_SHORT,c[A].MAY_SHORT,c[A].JUNE_SHORT,c[A].JULY_SHORT,c[A].AUGUST_SHORT,c[A].SEPTEMBER_SHORT,c[A].OCTOBER_SHORT,c[A].NOVEMBER_SHORT,c[A].DECEMBER_SHORT]},R=function(){return[c[A].SUNDAY_LONG,c[A].MONDAY_LONG,c[A].TUESDAY_LONG,c[A].WEDNESDAY_LONG,c[A].THURSDAY_LONG,c[A].FRIDAY_LONG,c[A].SATURDAY_LONG]},k=function(){return[c[A].SUNDAY_SHORT,c[A].MONDAY_SHORT,c[A].TUESDAY_SHORT,c[A].WEDNESDAY_SHORT,c[A].THURSDAY_SHORT,c[A].FRIDAY_SHORT,c[A].SATURDAY_SHORT]},T,g,B,b,P=function(s,o,m){var p;r.XMLHttpRequest?p=new XMLHttpRequest:p=new ActiveXObject("Microsoft.XMLHTTP"),p.onreadystatechange=function(){p.readyState===4&&(p.status===200?o&&(r.JSON===t?alert(`Please, include json2 into your project if you want use old browsers!
2
- https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(p.responseText))):m&&m(p))},p.open("GET",s,!1),p.send()},H={"%d":{format:function(s){return i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s);return{day:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(s){return i(s.month()||n.MIN_MONTH,2)},parse:function(s){var o=Number(s);return{month:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(s){return i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s);return{year:isNaN(o)?t:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(s){return s.dayOfWeek()||n.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(s){var o=s.dayOfWeek();return b[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(s){var o=s.dayOfWeek();return B[o!==t?o:n.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return g[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames().indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(s){var o=n.options("monthFromZero")?s.month():s.month()-1;return T[o!==t?o:n.MIN_MONTH]},parse:function(s){var o=n.monthNames(!0).indexOf(s)+(n.options("monthFromZero")?0:1);return{month:o!==-1?o:t}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(s){return i(s.hours()||n.MIN_HOURS,2)},parse:function(s){var o=Number(s);return{hours:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(s){return i(s.minutes()||n.MIN_MINUTES,2)},parse:function(s){var o=Number(s);return{minutes:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(s){return i(s.seconds()||n.MIN_SECONDS,2)},parse:function(s){var o=Number(s);return{seconds:isNaN(o)?t:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(s){return s.timestamp()},parse:function(s){return isNaN(Number(s))?{}:n(Number(s)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(s){return i(s.year()||n.MIN_YEAR,4)+"-"+i(s.month()||n.MIN_MONTH,2)+"-"+i(s.day()||n.MIN_DAY,2)},parse:function(s){var o=Number(s.slice(0,4)),m=Number(s.slice(5,7)),p=Number(s.slice(8,10));return{year:o,month:m,day:p}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(s){return i(s.month()||n.MIN_MONTH,2)+"/"+i(s.day()||n.MIN_DAY,2)+"/"+i(s.year()||n.MIN_YEAR,4)},parse:function(s){var o=Number(s.slice(0,2)),m=Number(s.slice(3,5)),p=Number(s.slice(6,10));return{year:p,month:o,day:m}},minLength:10,maxLength:10,type:"string"}},U={useMilliseconds:!1,monthFromZero:!1},M;M=function(s,o,m){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s!==t&&this.set(s,o,m),this},M.fn=M.prototype,M.fn.dayCount=function(){var s=this.month(),o=n.MAX_DAY_IN_MONTHS[s-(n.options("monthFromZero")?0:1)];return this.leapYear()&&s===(n.options("monthFromZero")?1:2)&&(o+=1),o},M.fn.year=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_YEAR&&Number(s)<=n.MAX_YEAR?(this._d.setFullYear(Number(s)),this._i.year=!1):this._i.year=Number(s):(this._d.setFullYear(n.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},M.fn.month=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MONTH&&Number(s)<=n.MAX_MONTH?(this._d.setMonth(n.options("monthFromZero")?Number(s):Number(s)-1),this._i.month=!1):this._i.month=Number(s):(this._d.setMonth(n.options("monthFromZero")?n.MIN_MONTH:n.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?n.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},M.fn.day=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_DAY&&Number(s)<=this.dayCount()?(this._d.setDate(Number(s)),this._i.day=!1):this._i.day=Number(s):(this._d.setDate(n.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},M.fn.hours=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_HOURS&&Number(s)<=n.MAX_HOURS?(this._d.setHours(Number(s)),this._i.hours=!1):this._i.hours=Number(s):(this._d.setHours(n.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},M.fn.minutes=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MINUTES&&Number(s)<=n.MAX_MINUTES?(this._d.setMinutes(Number(s)),this._i.minutes=!1):this._i.minutes=Number(s):(this._d.setMinutes(n.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},M.fn.seconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_SECONDS&&Number(s)<=n.MAX_SECONDS?(this._d.setSeconds(Number(s)),this._i.seconds=!1):this._i.seconds=Number(s):(this._d.setSeconds(n.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},M.fn.milliseconds=function(s){if(arguments.length!==0)(typeof s=="number"||typeof s=="string")&&!isNaN(Number(s))?Number(s)>=n.MIN_MILLISECONDS&&Number(s)<=n.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(s)),this._i.milliseconds=!1):this._i.milliseconds=Number(s):(this._d.setMilliseconds(n.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},M.fn.week=function(){var s=new Date(this.year(),0,1),o=n(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-s.getTime())/864e5+s.getDay()+1)/7)},M.fn.set=function(s,o,m){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},s===t)return this._d=new Date,this;if(s instanceof Date)return this._d=s,this;if(typeof s=="number")return this._d=new Date(s*(n.options("useMilliseconds")?1:1e3)),this;if(typeof s=="object"&&(s instanceof Array?(this.day(n.MIN_DAY),this.year(s[0]),this.month(s[1]),this.day(s[2]),this.hours(s[3]),this.minutes(s[4]),this.seconds(s[5]),this.milliseconds(s[6])):(this.day(n.MIN_DAY),this.year(s.year),this.month(s.month),this.day(s.day),this.hours(s.hours),this.minutes(s.minutes),this.seconds(s.seconds),this.milliseconds(s.milliseconds))),typeof s=="string"){var p,Y=[],S,w,st=[],v=0,j=0,W,K,x={},F;if(s===t)return S=a(this,m),S===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),S;for(o===t&&(o=n.detectFormat(s));v<o.length;){if(o.charAt(v)==="%"){if(w=o.charAt(v)+o.charAt(v+1),H[w]!==t){switch(W=0,K="",H[w].type){case"number":for(;W<H[w].maxLength&&j+W<s.length&&!isNaN(Number(s.charAt(j+W)));)K+=s.charAt(j+W),W+=1;break;case"word":for(;W<H[w].maxLength&&j+W<s.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(s.charAt(j+W));)K+=s.charAt(j+W),W+=1;break;case"string":for(;W<H[w].maxLength&&j+W<s.length;)K+=s.charAt(j+W),W+=1;break}if(W<H[w].minLength)return S=a(this,m),S===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),S;Y.push(w),st.push(K),W-=1,j+=W,v+=1}}else if(s.charAt(j)!==o.charAt(v))return S=a(this,m),S===t&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),S;v+=1,j+=1}for(p in Y)Y.hasOwnProperty(p)&&H.hasOwnProperty(Y[p])&&(F=H[Y[p]].parse(st[p]),x={year:F.year!==t?F.year:x.year,month:F.month!==t?F.month:x.month,day:F.day!==t?F.day:x.day,hours:F.hours!==t?F.hours:x.hours,minutes:F.minutes!==t?F.minutes:x.minutes,seconds:F.seconds!==t?F.seconds:x.seconds});this.day(n.MIN_DAY),this.year(x.year),this.month(x.month),this.day(x.day),this.hours(x.hours),this.minutes(x.minutes),this.seconds(x.seconds),this.milliseconds(x.milliseconds)}return this},M.fn.leapYear=function(){var s=this.year();return s%4===0?s%100===0?s%400===0:!0:!1},M.fn.timestamp=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):n.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},M.fn.utc=function(s){return arguments.length!==0?(this._d=new Date(Number(s)*(n.options("useMilliseconds")?1:1e3)),this):n.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},M.fn.dayOfWeek=function(s){if(s==="long")return B[this._d.getDay()];if(s==="short")return b[this._d.getDay()];if(s===t)return this._d.getDay();if(s===0||s==="Sunday")return this.calc({day:-this.dayOfWeek()});if(s===1||s==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(s===2||s==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(s===3||s==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(s===4||s==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(s===5||s==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(s===6||s==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},M.fn.timezone=function(s){switch(s){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},M.fn.get=function(s){switch(s){case"Date":return new Date(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(n.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},M.fn.format=function(s){for(var o=0,m="",p;o<s.length;)s.charAt(o)==="%"?(p=s.charAt(o)+s.charAt(o+1),H[p]!==t?(m+=H[p].format(this),o+=1):m+="%"):m+=s.charAt(o),o+=1;return m},M.fn.valid=function(){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},M.fn.errors=function(){return this._i},M.fn.between=function(s,o){var m=this.timestamp(),p=s.timestamp();switch(o){case"year":return Math.floor((p-m)/31556952);case"month":return Math.floor((p-m)/2629746);case"day":return Math.floor((p-m)/86400);case"hours":return Math.floor((p-m)/3600);case"minutes":return Math.floor((p-m)/60);case"seconds":return p-m;default:return t}},M.fn.calc=function(s){return s.year!==t&&this._d.setFullYear(this._d.getFullYear()+s.year),s.month!==t&&this._d.setMonth(this._d.getMonth()+s.month),s.day!==t&&this._d.setDate(this._d.getDate()+s.day),s.hours!==t&&this._d.setHours(this._d.getHours()+s.hours),s.minutes!==t&&this._d.setMinutes(this._d.getMinutes()+s.minutes),s.seconds!==t&&this._d.setSeconds(this._d.getSeconds()+s.seconds),s.milliseconds!==t&&this._d.setMilliseconds(this._d.getMilliseconds()+s.milliseconds),this},n=function(s,o,m){return new M(s,o,m)},n.MIN_YEAR=1e3,n.MAX_YEAR=3e3,n.MIN_MONTH=1,n.MAX_MONTH=12,n.MIN_DAY=1,n.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],n.MIN_DAY_OF_WEEK=0,n.MAX_DAY_OF_WEEK=6,n.MIN_HOURS=0,n.MAX_HOURS=23,n.MIN_MINUTES=0,n.MAX_MINUTES=59,n.MIN_SECONDS=0,n.MAX_SECONDS=59,n.MIN_MILLISECONDS=0,n.MAX_MILLISECONDS=999,n.VERSION="0.2.18",n.options=function(s,o){if(s===t)return U;if(U.hasOwnProperty(s)){if(o===t)return U[s];U[s]=o,s==="monthFromZero"&&(n.MIN_MONTH=o?0:1,n.MAX_MONTH=o?11:12)}return t},n.noConflict=function(){return r.tempus=u,n},n.generate=function(s){var o,m,p,Y,S,w,st,v;if(typeof s.dateFrom!="number"&&(s.dateFrom instanceof M?o=s.dateFrom.utc():o=n(s.dateFrom,s.formatFrom).utc()),typeof s.dateTo!="number"&&(s.dateTo instanceof M?m=s.dateTo.utc():m=n(s.dateTo,s.formatTo!==t?s.formatTo:s.formatFrom).utc()),typeof s.period=="number"?S={year:0,month:0,day:0,hours:0,minutes:0,seconds:s.period}:typeof s.period=="string"?S={year:s.period==="year"?1:0,month:s.period==="month"?1:0,day:s.period==="day"?1:0,hours:s.period==="hours"?1:0,minutes:s.period==="minutes"?1:0,seconds:s.period==="seconds"?1:0}:typeof s.period=="object"&&(S={year:s.period.year!==t?s.period.year:0,month:s.period.month!==t?s.period.month:0,day:s.period.day!==t?s.period.day:0,hours:s.period.hours!==t?s.period.hours:0,minutes:s.period.minutes!==t?s.period.minutes:0,seconds:s.period.seconds!==t?s.period.seconds:0}),s.groupBy===t?w=s.asObject===!0?{}:[]:(w=[],w.push([]),st=n(o).get()[s.groupBy]),v=function(K,x,F){return s.asObject===!0?s.format!==t?K[n(x).format(s.format)]={}:K[n(x).format("%F %H:%M:%S")]={}:s.format!==t?K.push(F?null:n(x).format(s.format)):K.push(F?null:n(x)),K},s.groupBy!==t&&s.fillNulls){var j={year:S.year?-S.year:t,month:S.month?-S.month:t,day:S.day?-S.day:t,hours:S.hours?-S.hours:t,minutes:S.minutes?-S.minutes:t,seconds:S.seconds?-S.seconds:t,milliseconds:S.milliseconds?-S.milliseconds:t};for(p=n(o).calc(j).utc();n(p).get()[s.groupBy]===st;)v(w[w.length-1],p,!0),p=n(p).calc(j).utc();if(s.groupBy==="week"){var W=n(o).dayOfWeek();for(p=n(o).dayOfWeek(0).utc();w[0].length<W&&p<o;)v(w[w.length-1],p,!0),p=n(p).calc(S).utc()}}for(;o<=m;)s.groupBy===t?v(w,o):n(o).get()[s.groupBy]===st?v(w[w.length-1],o):(w.push([]),v(w[w.length-1],o),st=n(o).get()[s.groupBy]),o=n(o).calc(S).utc();if(s.groupBy!==t&&s.fillNulls)for(Y=n(m).calc(S).utc();n(Y).get()[s.groupBy]===st;)v(w[w.length-1],Y,!0),Y=n(Y).calc(S).utc();return w},n.monthNames=function(s){switch(s){case"long":return T;default:return g}},n.dayNames=function(s){switch(s){case"long":return B;default:return b}},n.lang=function(s){if(s!==t)A=s,c[A]===t&&(A="en"),T=N(),g=O(),B=R(),b=k();else return A;return t},n.availableLangs=function(){return Object.keys(c)},n.registerFormat=function(s,o,m,p,Y,S){H[s]={format:o,parse:m,minLength:p,maxLength:Y,type:S}},n.unregisterFormat=function(s){delete H[s]},n.detectFormat=function(s){var o,m,p;return o=h(s,0),o!==""&&(p=10),m=s.charAt(p),(m==="T"||m===" ")&&(o+=m,p+=1),o+=l(s,p),o},d={TempusDate:M},n.classes=function(s,o){if(o===t)return d[s];d[s]=o},n.loadTranslations=function(s){typeof s=="object"?c=s:typeof s=="string"&&P(s,function(o){c=o},function(o){})},A=(f.language||f.systemLanguage||f.userLanguage||"en").substr(0,2).toLowerCase(),c[A]===t&&(A="en"),T=N(),g=O(),B=R(),b=k(),_.exports&&(e=_.exports=n),e.tempus=n}).call(C)})(ct,ct.exports);var Ue=ct.exports;const pt=G(Ue),Q=class Q{constructor(e){E(this,Dt);E(this,ht);E(this,Ht);E(this,Ut);E(this,rt);E(this,V);E(this,yt);E(this,it);E(this,Pt);E(this,Gt);E(this,ut);E(this,Nt);E(this,Ot);typeof e=="function"?(this.callBatch=e,this.callMethod=null):(this.callBatch=(e==null?void 0:e.callBatch)||null,this.callMethod=(e==null?void 0:e.callMethod)||null),this.result={},this.errors={},this.errorMessages={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=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}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const e=this.totalBatchCommands||0;if(e>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&y(this,Dt,Ne).call(this)){let u=0;for(const c of this.batchCommandKeyOrder){const N=this.progressData[c];if(!N)continue;const O=Number(N.total)||0,R=Number(N.count)||0;O===0&&R===0?u+=1:O>0&&(u+=Math.min(1,R/O))}const n=u/e*100;let d=Math.max(0,Math.min(100,Math.floor(n)));const f=e,A=Math.min(e,Math.floor(u));return{percent:d,allCount:A,allTotal:f}}let t=0,r=0;for(const u of Object.values(this.progressData)){const{total:n,count:d}=u;t+=n??0,r+=d??0}const i=Number(this.chunkRate)||0;let a=0;t?a=r/t*100*i+this.totalProgress:r===0&&t===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let l=Math.floor(a);const h=Number(this.chunkRate)||0;return t>0&&r>=t&&h>=1&&(l=100),{percent:l,allCount:r,allTotal:t}}setProgressData({key:e,value:t,type:r}){var c,N;if(!this.progressCall)return;const i=this.getData(t.data()),a=Array.isArray(i)?i.length:0;let l=a;if(typeof t.total=="function"){const O=t.total();if(O!=null&&O!==""){const R=Number(O);Number.isFinite(R)&&(l=R)}}let h=1;r==="count"?(l||(l=a),h=l>0?l:a>0?a:1):i&&(h=a),this.progressData||(this.progressData={});const u=((c=this.progressData[e])==null?void 0:c.total)??0,n=((N=this.progressData[e])==null?void 0:N.count)??0,d=h+n,f=Math.max(u,l??0,d);if(this.progressData[e]={total:f,count:Math.min(d,f)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){y(this,ht,Zt).call(this);return}y(this,ht,Zt).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}y(this,ht,Zt).call(this);const{percent:O}=this.progressPercent;O>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(e){if(e==null)return e;let t=(e==null?void 0:e.items)??(e==null?void 0:e.tasks)??(e==null?void 0:e.types)??(e==null?void 0:e.type)??(e==null?void 0:e.fields)??(e==null?void 0:e.workgroups)??e;return t&&typeof t=="object"&&!Array.isArray(t)&&Array.isArray(t.result)&&(t=t.result),t}setTimeLimitState(e,t,r){this.timeLimit.limit=!!e,this.timeLimit.date=e?t:void 0,e&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,y(this,Ut,_e).call(this)}subscribeTimeLimit(e){return typeof e!="function"?()=>{}:(this.timeLimitListeners.add(e),e({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(e)})}splitLargeFilters(e,t){const{method:r,params:i}=t;if(!i)return[{key:e,request:t}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:e,request:t}];for(const[l,h]of Object.entries(a))if(!String(l).trim().startsWith("!")&&Array.isArray(h)&&h.length>this.filterChunkSize){const u=[];for(let n=0;n<h.length;n+=this.filterChunkSize){const d=h.slice(n,n+this.filterChunkSize),f=n===0?e:`${e}__chunk_${Math.floor(n/this.filterChunkSize)}`,A={...i};i.filter?(A.filter={...a},A.filter[l]=d):i.FILTER&&(A.FILTER={...a},A.FILTER[l]=d),u.push({key:f,request:{method:r,params:A},originalKey:e,filterKey:l,chunkIndex:Math.floor(n/this.filterChunkSize)})}return u}return[{key:e,request:t}]}mergeSplitResults(e,t){const r=[],i=String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),l=Object.keys(e).filter(h=>a.test(h)).sort((h,u)=>{const n=h.match(/__chunk_(\d+)$/),d=u.match(/__chunk_(\d+)$/);return n?d?parseInt(n[1])-parseInt(d[1]):1:-1});for(const h of l){const u=e[h];Array.isArray(u)?r.push(...u):u&&r.push(u)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(t=>setTimeout(t,500))}callBatchWithTimeout(e,t,r={}){const{onLateResponse:i}=r;return new Promise((a,l)=>{let h=!1,u=null;const n=async f=>{if(h)typeof i=="function"&&i(f);else{h=!0,u&&clearTimeout(u);try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in callBatch callback:",A),l(A)}}},d=async()=>{if(!h){h=!0,u&&clearTimeout(u),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const f={};Object.keys(e).forEach(A=>{f[A]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(t(f)),a()}catch(A){console.error("Error in timeout callback:",A),a()}}};try{this.callBatch(e,async f=>{await n(f)})}catch(f){h||console.error("Error calling callBatch:",f)}u=setTimeout(async()=>{h||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await d())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(e,t,r={}){y(this,Ot,Ae).call(this,t);const i={},a={},l={};for(const[d,f]of Object.entries(e)){const A=this.arrayChunk(f);if(!A)continue;const c=this.splitLargeFilters(d,A);if(c.length===1)a[d]=A;else{l[d]=[];for(const N of c)a[N.key]=N.request,l[d].push(N.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(d=>{var f;return String(((f=a[d])==null?void 0:f.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let h={},u=0;const n=Object.keys(a).length;for(const[d,f]of Object.entries(a)){if(!this.canContinue)break;if(h[d]=f,Object.keys(h).length>=this.limit||u+1===n){const A=u+1===n;await this.batchChunk(h,void 0,!A,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([c,N])=>{i[c]=N}),this.totalProgress=Math.round(u/n*100),h={}}u++}for(const[d,f]of Object.entries(l))if(f&&f.length>0){const A=this.mergeSplitResults(i,d);for(const c of f)delete i[c];i[d]=A}return y(this,Nt,oe).call(this,i),t&&t({percent:100}),Promise.resolve(i)}async batchTotalCount(e,t){y(this,Ot,Ae).call(this,t);const r={},i={},a={};for(const[u,n]of Object.entries(e)){const d=this.arrayChunk(n);if(!d)continue;const f=this.splitLargeFilters(u,d);if(f.length===1)i[u]=d;else{a[u]=[];for(const A of f)i[A.key]=A.request,a[u].push(A.key)}}const l=[],h=Object.entries(i);for(let u=0;u<h.length;u+=this.limit){const n=h.slice(u,u+this.limit),d={};for(const[f,A]of n){if(!this.canContinue)break;d[f]=A}Object.keys(d).length>0&&l.push(d)}this.chunkRate=(1/l.length).toFixed(5);for(const[u,n]of Object.entries(l)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(u)/l.length*100),this.progressData={},this.lastProgressSnapshot=null;const d=Number(u)===l.length-1;await y(this,it,Mt).call(this,n,async f=>{for(const[A,c]of Object.entries(f)){if(!this.canContinue)return;if(c.error()){y(this,ut,Vt).call(this,A,c),r[A]=0;continue}const N=this.getData(c.data()),O=Array.isArray(N)?N.length:0,k=typeof c.total=="function"&&c.total()!==void 0?c.total():O;r[A]=k,this.setProgressData({key:A,value:c,type:"count"})}await y(this,V,lt).call(this,f,!d)})}for(const[u,n]of Object.entries(a))if(n&&n.length>0){let d=0;for(const f of n)r[f]!==void 0&&(d+=r[f]||0),delete r[f];r[u]=d}return Object.entries(this.errors).length&&(y(this,Nt,oe).call(this,r),this.errorLogger()),t&&t({percent:100}),Promise.resolve(r)}async call({method:e,params:t={}}){var i,a,l,h,u,n,d;const r=y(this,yt,ae).call(this,this.callLimitPauseMs);for(;;){let f=await y(this,Pt,Te).call(this,e,t,{onLateResponse:N=>r.notifyLateResponse(N)});if(!f)if(r.inRetryCycle=!0,await r.waitForLateOrLimit(),r.lateResult)f=r.lateResult,r.resetLateResult(),r.inRetryCycle=!1;else continue;const A={};if(f!=null&&f.answer)for(const[N,O]of Object.entries(f.answer))N!=="result"&&O&&(A[N]=O);if(f.error()){const N=((a=(i=f.error())==null?void 0:i.ex)==null?void 0:a.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(N)){await y(this,rt,It).call(this,this.callLimitPauseMs);continue}const O=((l=f.error())==null?void 0:l.toString())||((u=(h=f.error())==null?void 0:h.ex)==null?void 0:u.error_description)||((d=(n=f.error())==null?void 0:n.ex)==null?void 0:d.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:A,error:O}}let c=f.data();return c!=null&&c.items&&(c=c.items),r.inRetryCycle=!1,{success:!0,data:c,answer:A,error:null}}}arrayChunk(e){let t="",r={};if(Array.isArray(e)?[t]=e:(t=e.method,r=e.params),(t.includes("list")||t==="user.get"||t==="entity.item.get"||t==="sonet_group.get")&&t!=="task.item.list"){if(!r)r=t==="entity.item.get"?{SORT:{ID:"ASC"}}:t==="sonet_group.get"?{ORDER:{ID:"ASC"}}:t.startsWith("crm.")?{order:{ID:"ASC",id:"ASC"}}:{order:{ID:"ASC"}};else{t==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):t==="sonet_group.get"?r.ORDER?!r.ORDER.ID&&!r.ORDER.id&&(r.ORDER.ID="ASC"):r.ORDER={ID:"ASC"}:t==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):t==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):t.startsWith("crm.")?r.order={ID:"ASC",id:"ASC"}:r.order?!r.order.ID&&!r.order.id&&(r.order.ID="ASC"):r.order={ID:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=t==="user.get"||t==="entity.item.get"||t==="sonet_group.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,l])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof l=="string"||Array.isArray(l)&&l.length<=50)&&(r.start=-1)})}t==="crm.type.list"&&r.order&&delete r.order.ID}if(t==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,l,h]=r;i.ID="ASC",h[0]!==""&&h.includes("ID")||h.push("ID")}return{method:t,params:r}}async batchChunk(e,t,r=!0,i={}){return new Promise(a=>{const l=[];let h;const u=!!(i!=null&&i.disablePagination);(async()=>{await y(this,it,Mt).call(this,e,async d=>{for(const[A,c]of Object.entries(d)){if(!this.canContinue)return;c.error()&&(y(this,ut,Vt).call(this,A,c),h=!0);const N=this.getData(c.data()),O=Array.isArray(N)?N.length:0,R=typeof c.total=="function"&&c.total()!==void 0,k=R?c.total():O;t==="count"?this.result[A]?this.result[A]+=O:this.result[A]=k:this.result[A]=N,this.setProgressData({key:A,value:c,type:t});const T=e[A],g=Array.isArray(T)?T[0]:T==null?void 0:T.method,B=typeof g=="string"&&(g.includes(".list")||g.endsWith("getlist")||g==="user.get"||g==="entity.item.get"||g==="sonet_group.get"),b=t==="count"?!R&&O===this.limit:B?O===this.limit:k>this.limit&&k>O,P=t!=="count"&&g==="entity.item.get"&&O===this.limit&&!b,H=b||P;if(!u&&(!this.canContinue||H)){let U=e[A];if(Array.isArray(U)){const[M,s={}]=U;U=[M,s]}else{const{method:M,params:s={}}=U;U=[M,s]}l.push([A,U,k,{entityItemGetScan:P}])}}h>0&&this.errorLogger();const f=l.length>0||r;await y(this,V,lt).call(this,d,f),l.length?await this.batchPayload(l,t,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(e,t,r={}){const i=!!(r!=null&&r.oneBatch),a=(N,O,R,k)=>{let T="ID";this.result[N][this.result[N].length-1].ID||(T="id");let g=`${T}`;if(JSON.stringify(k[1]).toLocaleLowerCase().includes('"id":"desc"')?g="<"+g:g=">"+g,O===1||R.length===0)return{field:g,id:this.result[N][this.result[N].length-1][T]};let b="";const[P,H]=k;return(P==="tasks.task.list"||P==="task.item.list")&&(b="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(P)&&(b="[items]"),P==="crm.type.list"&&(b="[types]"),P==="socialnetwork.api.workgroup.list"&&(b="[workgroups]"),{field:g,id:`$result[${[N,O-1].join("__")}]${b}[49][${T}]`}},l=(N,O)=>{const[R,k]=N;let T=JSON.parse(JSON.stringify(k)),g;if(R==="task.item.list"){T=[...T];const[B,b,P,H]=T;return b[O.field]=O.id,[R,T]}return["user.get","sonet_group.get"].includes(R)||T.FILTER?(T.FILTER||(T.FILTER={}),g=T.FILTER):(T.filter||(T.filter={}),g=T.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(R)?g[">ID"]=O.id:g[O.field]=O.id,[R,{...T,start:-1}]},h=N=>{Object.entries(N).forEach(([O,R])=>{const[k]=O.split("__"),T=this.getData(R.data());Array.isArray(T)&&(t==="count"?this.result[k]+=T.length:this.result[k].push(...T)),R.error()&&y(this,ut,Vt).call(this,k,R),this.setProgressData({key:k,value:R,type:t})})},u=(N,O)=>{if(!Array.isArray(N)||N.length===0)return null;const R=N[N.length-1];let k="ID";R.ID||(k="id");let T=k;return JSON.stringify(O[1]).toLocaleLowerCase().includes('"id":"desc"')?T="<"+T:T=">"+T,{field:T,id:R[k]}},n=1e4,d=async(N,O)=>{var R,k;for(let T=1;this.canContinue&&T<=n;T++){const g=this.result[N],B=u(g,O);if(!B)break;const b=`${N}__page_${T}`,P=l(O,B);let H=null;await y(this,it,Mt).call(this,{[b]:P},async o=>{H=o,h(o)});const U=H==null?void 0:H[b];if((R=U==null?void 0:U.error)!=null&&R.call(U)){await y(this,V,lt).call(this,H,!1);break}const M=this.getData((k=U==null?void 0:U.data)==null?void 0:k.call(U));if((Array.isArray(M)?M.length:0)===0){await y(this,V,lt).call(this,H,!1);break}await y(this,V,lt).call(this,H,T<n)}};let f=[],A=0;const c=async(N=!0)=>f.length?(await y(this,it,Mt).call(this,Object.fromEntries(f),async O=>{h(O),await y(this,V,lt).call(this,O,N)}),A++,f=[],i&&A>=1?!0:(await this.delay(),!1)):!1;for await(const N of e){if(!this.canContinue)return;const[O,R,k,T={}]=N;if(T.entityItemGetScan||!i){if(await c(!0))return;if(i)continue;await d(O,R);continue}let g=1;for(;k>g*this.limit;){const B=[O,g].join("__"),b=a(O,g,f,R);if(f.push([B,l(R,b)]),i&&f.length===49&&await c(!0)||f.length%50===0&&await c(!0))return;g++}}await c(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,t])=>{t&&console.log(`[${e}]`,t.toString())}),console.groupEnd()}};Dt=new WeakSet,Ne=function(){const e=this.totalBatchCommands||0,t=this.batchCommandMethods;if(e<L(Q,kt)||!Array.isArray(t)||t.length!==e)return!1;if(t.filter(a=>a==="crm.deal.list").length>=L(Q,Bt))return!0;const i=t.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=L(Q,Ct)&&i/e>=L(Q,wt)},kt=new WeakMap,Bt=new WeakMap,Ct=new WeakMap,wt=new WeakMap,ht=new WeakSet,Zt=function(){if(!this.progressCall||!this.progressData)return;const{percent:e,allCount:t,allTotal:r}=this.progressPercent,i={percent:e,allCount:t,allTotal:r};y(this,Ht,Oe).call(this,i)&&(this.progressCall({data:this.progressData,percent:e,allCount:t,allTotal:r}),this.lastProgressSnapshot=i)},Ht=new WeakSet,Oe=function(e){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==e.percent||this.lastProgressSnapshot.allCount!==e.allCount||this.lastProgressSnapshot.allTotal!==e.allTotal:!0},Ut=new WeakSet,_e=function(){const e={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const t of this.timeLimitListeners)try{t(e)}catch(r){console.warn("Batch timeLimit listener error:",r)}},rt=new WeakSet,It=async function(e=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),e),await new Promise(t=>setTimeout(t,e)),this.setTimeLimitState(!1,void 0)},V=new WeakSet,lt=async function(e,t=!0){if(!t)return 0;let r=0;if(!e||typeof e!="object")return 0;for(const i of Object.values(e))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await y(this,rt,It).call(this)},yt=new WeakSet,ae=function(e=this.defaultPauseMs){const t=this;return{inRetryCycle:!1,inTimeoutWait:!1,lateResult:null,lateWaiters:[],notifyLateResponse(i){if(!(!this.inRetryCycle&&!this.inTimeoutWait)){this.lateResult=i;for(const a of this.lateWaiters)a(i);this.lateWaiters=[]}},waitForLateOrLimit(){var a;this.inTimeoutWait=!0;const i=new Promise(l=>{if(this.lateResult){l(this.lateResult);return}this.lateWaiters.push(l)});return Promise.race([y(a=t,rt,It).call(a,e),i]).finally(()=>{this.inTimeoutWait=!1})},resetLateResult(){this.lateResult=null}}},it=new WeakSet,Mt=async function(e,t){let r=!1,i=e;const a=y(this,yt,ae).call(this);do r=!1,await this.callBatchWithTimeout(i,async l=>{var n,d;let h=!1;const u=new Set;for(const[f,A]of Object.entries(l||{})){if(!(A!=null&&A.error)||!A.error())continue;const c=((d=(n=A.error())==null?void 0:n.ex)==null?void 0:d.error)??"";if(c==="TIMEOUT"){h=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(c)&&u.add(f)}if(h){if(a.inRetryCycle=!0,r=!0,await a.waitForLateOrLimit(),a.lateResult){r=!1,a.inRetryCycle=!1;const f=a.lateResult;a.resetLateResult(),await t(f)}return}if(u.size>0){const f={};for(const[c,N]of Object.entries(l||{}))u.has(c)||(f[c]=N);Object.keys(f).length&&await t(f);const A={};for(const c of u)i[c]&&(A[c]=i[c]);i=A,Object.keys(i).length&&(r=!0,await y(this,rt,It).call(this));return}a.inRetryCycle=!1,await t(l)},{onLateResponse:l=>a.notifyLateResponse(l)});while(r)},Pt=new WeakSet,Te=function(e,t,r={}){const{onLateResponse:i}=r;return new Promise(a=>{if(typeof this.callMethod!="function"){a(null);return}let l=!1;const h=setTimeout(()=>{l||(l=!0,a(null))},this.requestTimeoutMs);try{this.callMethod(e,t,u=>{l?typeof i=="function"&&i(u):(l=!0,clearTimeout(h),a(u))})}catch{l||(l=!0,clearTimeout(h),a(null))}})},Gt=new WeakSet,Ee=function(e){const t=typeof(e==null?void 0:e.error)=="function"?e.error():null,r=(t==null?void 0:t.ex)||{},i=String(r.error||"").trim(),a=String(r.error_description||"").trim(),l=typeof(t==null?void 0:t.toString)=="function"?String(t.toString()).trim():"";let h=a;return!h&&l&&l!==i&&(h=l),h||(h=i||"Неизвестная ошибка"),{code:i||h,message:h}},ut=new WeakSet,Vt=function(e,t){const{code:r,message:i}=y(this,Gt,Ee).call(this,t);this.errors[e]=r,this.errorMessages[e]=i},Nt=new WeakSet,oe=function(e){Object.entries(this.errors).length&&(e.errorsList={...this.errors},Object.entries(this.errorMessages).length&&(e.errorsListMessages={...this.errorMessages}))},Ot=new WeakSet,Ae=function(e){this.clearProgressData(),this.progressCall=typeof e=="function"?e:"",this.canContinue=!0,this.result={},this.errors={},this.errorMessages={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},E(Q,kt,5),E(Q,Bt,5),E(Q,Ct,8),E(Q,wt,.65);let q=Q;class te{constructor(){E(this,nt,{})}get hash(){return this.createHash(8)}createHash(e){let t="abcdefghijklmnopqrstuvwxyz0123456789",r="";e=e||6;for(let i=0;i<e;i++)r+=t.charAt(Math.floor(Math.random()*t.length));return r}actionFilter({keyTimer:e,duration:t=10,action:r}){L(this,nt)[e]&&(clearTimeout(L(this,nt)[e]),L(this,nt)[e]=null),r&&(L(this,nt)[e]=setTimeout(()=>{r()},t))}async noSleep(){let e=document.createElement("video");e.classList.add("no-sleep"),e.muted=!0,e.autoplay=!0,e.setAttribute("playsinline",""),e.addEventListener("loadeddata",()=>{e.style.position="fixed",e.style.left="-9999px",document.querySelector("body").append(e),e.play().catch(t=>{console.warn("noSleep: autoplay prevented",t)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(t=>{console.warn("noSleep: replay prevented",t)})}})}),e.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(e,t){let r=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${t}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}nt=new WeakMap;const ee=new te;class de{constructor(){E(this,Yt);E(this,Tt);E(this,Wt);E(this,xt);E(this,Ft);E(this,Z,"logger");E(this,$,!1);E(this,at,new Map);E(this,ft,{});E(this,_t,!1);E(this,tt,null);E(this,J,null);E(this,ot,!1);E(this,dt,!1);D(this,"periodClear",3)}async init(){try{let e=new q(BX24.callBatch),{entityList:t}=await e.batch({entityList:{method:"entity.get"}});if(t&&Array.isArray(t))if(t.find(i=>i.ENTITY==L(this,Z)))X(this,$,!0);else{let{entityAdd:i}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:L(this,Z),NAME:L(this,Z),ACCESS:{AU:"X"}}}});i&&X(this,$,!0)}return L(this,$)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}enableBackworkerMode(){return X(this,$,!0),!0}start({type:e,data:t}){if(!L(this,$))return y(this,Tt,le).call(this,"entity"),null;if(!e||!t)return console.error("Невалидные данные для логирования:",{type:e,data:t}),null;const r=ee.hash,i={type:e,data:t,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return L(this,at).set(r,i),X(this,dt,!0),r}async stop({key:e,errorList:t,status:r,answer:i}){var l;if(!L(this,dt))return;if(!L(this,$)){y(this,Tt,le).call(this,"entity");return}let a=L(this,at).get(e);if(!a){console.error(`Не найдены данные логирования для ключа: ${e}`);return}t&&(a.errorList=t),r&&(a.status=r),i&&(a.answer=i),await y(this,Yt,Re).call(this),a.userInfo=L(this,ft),await y(this,Wt,Le).call(this),(l=a==null?void 0:a.data)!=null&&l.updateList&&X(this,ot,!0),X(this,dt,!1)}async getEntityList(e){var t;try{if((t=L(this,J))!=null&&t.length&&!L(this,ot))return L(this,J);let r=new q(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:L(this,Z),SORT:{ID:"DESC"}}}},e);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:l,DATE_CREATE:h,DETAIL_TEXT:u}=a;return{...JSON.parse(u),id:l,dateCreate:h}}catch(l){return console.error(`Ошибка парсинга записи ${a.ID}:`,l),null}}).filter(a=>a!==null),X(this,ot,!1),X(this,J,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return y(this,xt,be).call(this)}async downAllEntityJson(){try{if(L(this,J)||await this.getEntityList(),!L(this,J)||L(this,J).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=pt().format("%Y-%m-%d");return ee.downloadFileJson(L(this,J),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}Z=new WeakMap,$=new WeakMap,at=new WeakMap,ft=new WeakMap,_t=new WeakMap,tt=new WeakMap,J=new WeakMap,ot=new WeakMap,dt=new WeakMap,Yt=new WeakSet,Re=async function(){if(!L(this,_t))return L(this,tt)?L(this,tt):(X(this,tt,(async()=>{try{const e=new q(BX24.callBatch),t=BX24.isAdmin(),{curUser:r}=await e.batch({curUser:{method:"user.current"}});X(this,ft,{isAdmin:t,curUser:r})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),X(this,ft,{isAdmin:!1,curUser:null})}finally{X(this,_t,!0),X(this,tt,null)}})()),L(this,tt))},Tt=new WeakSet,le=function(e){e=="entity"&&ee.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Wt=new WeakSet,Le=async function(){try{let e={},t=new q(BX24.callBatch);for(let[r,i]of L(this,at).entries())if(i.status){const a=JSON.stringify(i);e[r]={method:"entity.item.add",params:{ENTITY:L(this,Z),NAME:L(this,Z),DETAIL_TEXT:a}}}if(Object.keys(e).length){let r=await t.batch(e),{errors:i}=t;for(let[a,l]of Object.entries({...r,...i}))L(this,at).delete(a);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},xt=new WeakSet,be=async function(){try{let e=new q(BX24.callBatch),{serverTime:t}=await e.batch({serverTime:{method:"server.time"}});if(!t){console.error("Не удалось получить время сервера");return}if(L(this,J)||await this.getEntityList(),!L(this,J)||L(this,J).length===0)return;let r=L(this,J).filter(i=>{try{let{dateCreate:a}=i;return a?pt(new Date(a)).between(pt(new Date(t)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await y(this,Ft,Ie).call(this,r))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},Ft=new WeakSet,Ie=async function(e){try{if(!e||e.length===0)return!1;let t=new q(BX24.callBatch),r=e.filter(a=>a&&a.id).map(a=>{let{id:l}=a;return{method:"entity.item.delete",params:{ENTITY:L(this,Z),ID:l}}});if(r.length===0)return!1;const i=await t.batch(r);return console.log(`Успешно удалено ${r.length} записей`),X(this,ot,!0),i}catch(t){return console.error("Ошибка при очистке устаревших записей:",t),!1}};function se(_){if(!_||typeof _!="string")return"";try{const e=new URL(_);e.search="",e.hash="";let t=e.toString();return t.endsWith("/")&&e.pathname!=="/"&&(t=t.slice(0,-1)),t}catch{return _.split("?")[0].split("#")[0].replace(/\/$/,"")}}function me(_){return!_||typeof _!="string"?!1:_.toLowerCase().includes("/marketplace/app")}function Pe(){var e;if(typeof window>"u"||!((e=window.location)!=null&&e.href))return"";const _=se(window.location.href);return me(_)?"":_}function re(_){if(!(_!=null&&_.appConst)||typeof _.appConst!="object")return"";const e=Pe();return e?(_.appConst.pathApp=e,e):se(_.appConst.pathApp??"")}class Ge{constructor(e){E(this,mt);E(this,vt);E(this,Et);E(this,Xt);E(this,Jt);E(this,jt);E(this,et);E(this,Rt);E(this,Kt);E(this,Lt);E(this,qt);D(this,"domain","");D(this,"isAdmin",!1);D(this,"appInfo",null);D(this,"appConst",null);D(this,"userInfo",null);D(this,"placeData",null);D(this,"placeInfo",null);D(this,"logger",!1);D(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});D(this,"batchClient",null);this.appConst=e}subscribeTimeLimit(e){return y(this,mt,$t).call(this).subscribeTimeLimit(e)}init(){return new Promise((e,t)=>{const i=setTimeout(()=>{clearInterval(a);const l=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(l),t(l)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const l=y(this,Xt,Se).call(this);if(console.info(l?"init BX24 (background worker)":"init BX24"),this.appInfo=await y(this,Jt,De).call(this),this.userInfo=await y(this,jt,ke).call(this),re(this),l)await y(this,Et,ce).call(this,!1,{skipInit:!0});else{await y(this,Et,ce).call(this,!0);const h=new te;try{h.noSleep()}catch(u){console.warn("Failed to initialize noSleep:",u)}}e({isBackworker:l})})},100)})}userOption(e,t){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.userOption.set(e,t):BX24.userOption.get(e)}appOption(e,t){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return t!==void 0?BX24.appOption.set(e,t):BX24.appOption.get(e)}async call({method:e,params:t,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:e,params:t,updateList:r}})),t||(t={}),typeof BX24>"u"||!BX24.callMethod){const h=new Error("BX24 is not initialized");throw console.error(h),h}const l=await y(this,mt,$t).call(this).call({method:e,params:t});return l.success?(await y(this,et,gt).call(this,i,{answer:l.answer,status:"success"}),l.data):(console.error(l.error),await y(this,et,gt).call(this,i,{answer:l.answer,status:"fail",errorList:{0:l.error||"Unknown call error"}}),!1)}async batch(e,t,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const l=new Error("BX24 is not initialized");return console.error(l),!1}return y(this,Rt,he).call(this,{mode:"batch",commandList:e,progressCall:t,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(e,t,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return y(this,Rt,he).call(this,{mode:"batch-total-count",commandList:e,progressCall:t,errorCall:r,updateList:i})}async getPlacement(){const e=await this.call({method:"placement.get"});return this.placeData||(this.placeData=e),e}async placementBind(e){var A;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:t,pathApp:r}=this.appConst;let i=y(this,Lt,ue).call(this,e);i=i.filter(c=>c.placement!=="PAGE_BACKGROUND_WORKER"&&c.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=y(this,qt,Ce).call(this,r),l=new Set(i.map(c=>c.placement));for(const c of a)l.has(c.placement)||i.push({placement:c.placement});if(i.length===0)return;let h=t;this.domain==="szdl.bitrix24.ru"&&((A=this.appInfo)!=null&&A.ID)&&(h=`${t}: #${this.appInfo.ID}`);const u=h.replace(" CRM",""),n={},d=[],f=new Map;for(const c of this.placeData)f.has(c.placement)||f.set(c.placement,[]),f.get(c.placement).push(c);for(let c=0;c<i.length;c++){const{placement:N,options:O}=i[c],R=f.get(N)||[];if(R.some(g=>g.handler===r))continue;const T=R.filter(g=>g.handler!==r);for(const g of T)d.push({placement:N,handler:g.handler});n[`bind_${c}`]={method:"placement.bind",params:{PLACEMENT:N,HANDLER:r,LANG_ALL:{ru:{TITLE:N==="USER_PROFILE_TOOLBAR"?u:h}},OPTIONS:{errorHandlerUrl:r,...O&&typeof O=="object"?O:{}}}}}d.length>0&&await this.placementUnBind(d),Object.keys(n).length>0&&(await this.batch(n),this.placeData=await this.getPlacement(),Object.values(n).forEach(c=>{console.log("Приложение успешно встроено в",c.params.PLACEMENT)}))}async placementUnBind(e){let t=y(this,Lt,ue).call(this,e);if(t=t.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),t.length===0)return;const r={};for(let i=0;i<t.length;i++){const a={PLACEMENT:t[i].placement};t[i].handler&&(a.HANDLER=t[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),t.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const e=await this.call({method:"imbot.bot.list",params:{}}),t=Object.values(e);return console.log("chat-bot list:",t),t}async regBot({code:e,type:t,name:r}){const{appName:i,pathApp:a,chatBotLogo:l}=this.appConst,h=this.appInfo.ID,u=await this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:t??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${h}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:pt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:l??""}}});return console.log("Чат-бот добавлен",u),u}async unRegBot(e){const t=await this.call({method:"imbot.unregister",params:{BOT_ID:e}});return console.log("чат-бот удален",t),t}getLoggerList(e){return this.logger.getEntityList(e)}}mt=new WeakSet,$t=function(){return this.batchClient||(this.batchClient=new q({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},vt=new WeakSet,Me=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Et=new WeakSet,ce=async function(e,{skipInit:t=!1}={}){this.logger?(this.logger=new de,t?this.logger.enableBackworkerMode():await this.logger.init(),e&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=y(this,vt,Me).call(this)},Xt=new WeakSet,Se=function(){var r,i,a;const e=(r=this.placeInfo)==null?void 0:r.placement,t=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return e==="PAGE_BACKGROUND_WORKER"||t==="PAGE_BACKGROUND_WORKER"},Jt=new WeakSet,De=function(){return this.call({method:"app.info"})},jt=new WeakSet,ke=function(){return this.call({method:"user.current"})},et=new WeakSet,gt=async function(e,t){if(e)try{await this.logger.stop({key:e,...t})}catch(r){console.error("Logger error:",r)}},Rt=new WeakSet,he=async function({mode:e,commandList:t,progressCall:r,errorCall:i,updateList:a,batchOptions:l}){const h=y(this,mt,$t).call(this),u=a?this.logger.start({type:e,data:e==="batch"?{commandList:t,updateList:a}:{commandList:t}}):void 0;try{const n=e==="batch"?await h.batch(t,r,l):await h.batchTotalCount(t,r),d=y(this,Kt,Be).call(this,h,n,t,a);return Object.keys(d).length?(i&&i(d),await y(this,et,gt).call(this,u,{status:"fail",errorList:d})):await y(this,et,gt).call(this,u,{status:"success"}),n}catch(n){return await y(this,et,gt).call(this,u,{status:"fail-runtime",errorList:{0:n==null?void 0:n.toString()}}),console.error(n),!1}},Kt=new WeakSet,Be=function(e,t,r,i){let a={...e.errors};if(Object.values(e.errors).some(h=>{if(typeof h!="string")return!1;const u=h.toUpperCase();return u==="TIMEOUT"||u==="OPERATION_TIME_LIMIT"||u.includes("TIMEOUT")||u.includes("OPERATION_TIME_LIMIT")})&&i){const h=t?Object.keys(t).filter(f=>f!=="errorsList"&&f!=="errorsListMessages"):[],u=new Set(Object.keys(e.errors||{})),n=new Set;if(t){for(const f of h)if(!u.has(f)){const A=t[f];A!=null&&n.add(f)}}const d=Object.values(e.errors).find(f=>{if(typeof f!="string")return!1;const A=f.toUpperCase();return A==="TIMEOUT"||A==="OPERATION_TIME_LIMIT"||A.includes("TIMEOUT")||A.includes("OPERATION_TIME_LIMIT")});for(const f of Object.keys(r))!n.has(f)&&!e.errors[f]&&(a[f]=d||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Lt=new WeakSet,ue=function(e){if(!e)return[];let t=[];return Array.isArray(e)?t=e.map(r=>typeof r=="string"?{placement:r}:r):typeof e=="string"?t=[{placement:e}]:t=[e],t},qt=new WeakSet,Ce=function(e){return this.placeData?this.placeData.filter(t=>!(t.placement==="PAGE_BACKGROUND_WORKER"||!t.handler||t.handler.includes(e))):[]};const ge="szdl-utils-kit|";function Ye(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let _=sessionStorage.getItem("szdl-cross-tab-instance-id");return _||(_=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",_)),_}function We(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const ie=new Map;function xe(_="default"){if(typeof BroadcastChannel>"u")return null;const e=`${ge}bc:${_}`;return ie.has(e)||ie.set(e,new BroadcastChannel(e)),ie.get(e)}function pe(_,e){const t=xe(_);if(t)try{const r=e&&typeof e=="object"&&!Array.isArray(e)?e:{data:e};t.postMessage({...r,tabId:Ye(),ts:Date.now()})}catch{}}async function Fe(_,e,t={}){const{ifAvailable:r=!1}=t,i=typeof _=="string"&&_.length>0?_:"default",a=`${ge}${i}`;return We()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async l=>{if(r&&l==null)return{skipped:!0,coordination:"locks"};pe(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await e(),coordination:"locks"}}finally{pe(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await e(),coordination:"none"}}const z={startDelayMs:0,pollIntervalMs:60*1e3,pollIntervalJitterMs:30*1e3,leaderConfirmDelayMs:60*1e3,activeMaxPauseMs:3*60*1e3,quickCleanupThresholdMs:5*60*1e3,leaderHeartbeatMs:null};function ve(_){return _==null?"user":_==="user"||_==="portal"?_:(console.warn(`BackgroundWorker: coordinationScope должен быть 'user' или 'portal', получено ${JSON.stringify(_)} — используется 'user'`),"user")}function ye(_={}){const e={...z,..._};for(const t of Object.keys(z)){if(t==="leaderHeartbeatMs"){const i=_==null?void 0:_.leaderHeartbeatMs;if(i==null){e.leaderHeartbeatMs=null;continue}const a=Number(i);e.leaderHeartbeatMs=Number.isFinite(a)&&a>=0?a:null;continue}const r=Number(e[t]);e[t]=Number.isFinite(r)&&r>=0?r:z[t]}return e}class Xe{constructor(e){E(this,zt);E(this,bt);E(this,At);E(this,Qt);D(this,"entityName","tabs");D(this,"maxTabs",20);D(this,"tabList",[]);D(this,"id",0);D(this,"hasStarted",!1);D(this,"heartbeat");D(this,"runHeartbeat");D(this,"startDelay",0);D(this,"activeMaxPause",z.activeMaxPauseMs);D(this,"quickCleanupThreshold",z.quickCleanupThresholdMs);D(this,"pollInterval",z.pollIntervalMs);D(this,"pollIntervalBase",z.pollIntervalMs);D(this,"pollIntervalJitter",z.pollIntervalJitterMs);D(this,"leaderConfirmDelay",z.leaderConfirmDelayMs);D(this,"leaderHeartbeatMs",null);D(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);D(this,"continueCondition");D(this,"defaultContinueBackground",()=>!0);D(this,"coordinationScope","user");D(this,"bindGeneralPlacement",!0);D(this,"ensureAdminPlacementsBeforeAppInit");var d,f,A;if(!e){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:t,bx:r,users:i,continueBackground:a,timing:l,coordinationScope:h,bindGeneralPlacement:u,ensureAdminPlacementsBeforeAppInit:n}=e;this.bx=r,this.appInit=t,this.users=i,this.coordinationScope=ve(h),this.bindGeneralPlacement=u!==!1,this.ensureAdminPlacementsBeforeAppInit=n,y(this,zt,we).call(this,l),re(r),this.appPath=y(this,bt,fe).call(this,((d=r==null?void 0:r.appConst)==null?void 0:d.pathApp)??""),this.appName=((f=r==null?void 0:r.appConst)==null?void 0:f.appName)??"",this.appCodeName=((A=r==null?void 0:r.appConst)==null?void 0:A.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.startDelay>0&&(console.log(`BackgroundWorker: старт отложен на ${this.startDelay} мс`),await this.pause(this.startDelay)),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(t=>{console.error("BackgroundWorker: backgroundTick failed",t)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const t=this.selectLeaderId(),r=t&&+this.id==+t;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var e;if(typeof BX24>"u"||!((e=BX24.placement)!=null&&e.info))return!1;try{const t=BX24.placement.info(),r=t==null?void 0:t.placement,i=(t==null?void 0:t.options)||{},a=(i==null?void 0:i.URI)||"",l=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",h=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!l||h}catch{return!1}}async checkEntity(){var r;const e=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=e==null?void 0:e.find)==null?void 0:r.call(e,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const e=y(this,At,St).call(this),t=await this.safeCall(()=>this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:e},SORT:{DATE_CREATE:"DESC"}}}));return!Array.isArray(t)||!t.length?[]:t.map(r=>{if(!r)return{id:void 0,data:void 0};try{const i=JSON.parse(r.DETAIL_TEXT);return{id:+r.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+r.ID||0,data:void 0}}})}async ensureTabRegistered(){var r,i;if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const e={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID},t=await this.safeCall(()=>this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:y(this,At,St).call(this),DETAIL_TEXT:JSON.stringify(e)}}))||0;return this.id=+t||0,this.id}async updateTabState(e){var r,i;if(!this.id)return;const t={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:e,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID};await this.safeCall(()=>this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:y(this,At,St).call(this),DETAIL_TEXT:JSON.stringify(t)}}))}async deleteTabs(e=[]){if(!e.length)return;const t=e.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(t))}async checkPlacementType(){var e,t;try{if(!((e=this.bx)!=null&&e.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((t=this.bx.userInfo)==null?void 0:t.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),l=!a;if(!i)return!0;let h=!1;for(const u of r){if(u.placement!=="PAGE_BACKGROUND_WORKER"||!(u.userId||u.handler&&u.handler.includes("USER_ID=")))continue;const d=u.userId||(u.handler?this.extractUserIdFromHandler(u.handler):null);if(d&&+d===i){h=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):l&&h?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(e){return!e||typeof e!="string"?!1:e.includes("USER_ID=")}extractUserIdFromHandler(e){if(!e||typeof e!="string")return null;const t=e.match(/USER_ID=(\d+)/);return t?+t[1]:null}async continueBackground(){try{const t=!!await Promise.resolve(this.continueCondition(this));return console.log(t?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),t}catch(e){return console.error("BackgroundWorker: Ошибка в continueCondition",e),!1}}async refreshTabs(e=!1,t=this.activeMaxPause){const r=[],i=[],a=Date.now(),l=await this.getTabs();for(const h of l){if(!(h!=null&&h.data)){r.push(h);continue}if(a-new Date(h.data.lastActive||0).getTime()>t){r.push(h);continue}i.push(h)}return e&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var t;return this.tabList.length&&+((t=[...this.tabList].sort((r,i)=>{var h,u,n,d;const a=new Date(((h=r.data)==null?void 0:h.createdAt)||((u=r.data)==null?void 0:u.lastActive)||0).getTime(),l=new Date(((n=i.data)==null?void 0:n.createdAt)||((d=i.data)==null?void 0:d.lastActive)||0).getTime();return a===l?(+r.id||0)-(+i.id||0):a-l})[0])==null?void 0:t.id)||0}async confirmLeaderAfterLock(){await this.refreshTabs(!0);const e=this.selectLeaderId();return!!(e&&+this.id==+e)}async runAsLeader(){const e=y(this,Qt,He).call(this);(await Fe(e,async()=>{if(await this.updateTabState(!0),console.log(`BackgroundWorker: захват лидерства, пауза ${this.leaderConfirmDelay} мс перед запуском`),await this.pause(this.leaderConfirmDelay),!await this.confirmLeaderAfterLock()){console.log("BackgroundWorker: запуск отменён — после паузы лидером оказалась другая вкладка"),await this.updateTabState(!1);return}this.hasStarted=!0;const i=this.leaderHeartbeatMs??Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(a=>console.error("BackgroundWorker: heartbeat update failed",a))},i);try{await this._ensurePlacementsBeforeAppInitIfNeeded(),await this.appInit()}catch(a){console.error("BackgroundWorker: appInit failed",a)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (подтверждение лидерства)")}async _ensurePlacementsBeforeAppInitIfNeeded(){var r;const e=this.ensureAdminPlacementsBeforeAppInit;if(!(!e||!((r=this.bx)!=null&&r.isAdmin)||!(typeof e=="function"?await Promise.resolve(e(this)):e)))try{await this.ensureAdminPlacements()}catch(i){console.error("BackgroundWorker: ensureAdminPlacements before appInit failed",i)}}async setBackgroundWorkerAll(){var O,R,k,T;if(!((O=this.bx)!=null&&O.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(R=this.users)!=null&&R.length||await this.getEntityData(),re(this.bx);const e=y(this,bt,fe).call(this,((T=(k=this.bx)==null?void 0:k.appConst)==null?void 0:T.pathApp)??"");if(!e){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const t=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(t||[]).forEach(g=>{if(g.placement!=="PAGE_BACKGROUND_WORKER")return;if(g.userId||g.handler&&g.handler.includes("USER_ID=")){const b=g.userId||(g.handler?this.extractUserIdFromHandler(g.handler):null);if(b){const P=+b;r.set(P,g),i.has(P)||i.set(P,[]),i.get(P).push(g)}}else a=g});const l=await this.resolveAdmins(),h=await this.getEligibleUsersForBackgroundWorker(l);h.sort((g,B)=>{const b=g.LAST_LOGIN?new Date(g.LAST_LOGIN):new Date(0);return(B.LAST_LOGIN?new Date(B.LAST_LOGIN):new Date(0))-b});const u=10,n=h.slice(0,u),d=n.filter(g=>{const B=r.get(+g.ID);if(!B)return!0;const b=`${e}?USER_ID=${g.ID}/`;return B.handler!==b}),f=[];for(const[g]of r){const B=+g||0;h.find(P=>+P.ID===B)||f.push(B)}for(const g of n){const B=r.get(+g.ID);if(!B)continue;const b=`${e}?USER_ID=${g.ID}/`;B.handler!==b&&f.push(+g.ID)}const A=[],c=[...new Set(f)];for(const g of c){const B=i.get(+g)||[];for(const b of B)b!=null&&b.handler&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:b.handler}})}const N=a&&(!this.bindGeneralPlacement||d.length>0||a.handler!==`${e}`);N&&A.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${e}`}});for(const g of d)A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}?USER_ID=${g.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}?USER_ID=${g.ID}/`},USER_ID:g.ID}});this.bindGeneralPlacement&&(!a||N)&&A.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${e}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${e}`}}}),A.length?await this.safeCall(()=>this.bx.batch(Object.fromEntries(A.map((g,B)=>[`placement_${B}`,g])))):console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var e,t;try{const r=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),i=!!((t=this.bx)!=null&&t.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const u=a.filter(n=>+n!=+r);return await this.saveAdminsList(u),u}return a}const l=new Set([...a||[]]);r&&l.add(+r);const h=[...l].filter(Boolean);return await this.saveAdminsList(h),h}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(e=[]){const t=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=e.map(i=>+i||0).filter(Boolean);return t.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(e=[]){try{BX24.appOption.set("adminsList",JSON.stringify(e))}catch(t){console.error("BackgroundWorker: saveAdminsList error",t)}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList"),t=e?JSON.parse(e):[];return Array.isArray(t)?t.map(r=>+r||0).filter(Boolean):[]}catch(e){return console.error("BackgroundWorker: getAdminsList error",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:t}=await this.safeCall(()=>this.bx.batch(e).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=t}async ensureAdminPlacements(){var e,t;(e=this.bx)!=null&&e.isAdmin&&((t=this.users)!=null&&t.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(e=500,t){return new Promise(r=>{setTimeout(()=>{t&&t(),r(!0)},e)})}async safeCall(e){try{return await e()}catch(t){console.error("BackgroundWorker: safeCall error",t);return}}}zt=new WeakSet,we=function(e){const t=ye(e);this.startDelay=t.startDelayMs,this.leaderConfirmDelay=t.leaderConfirmDelayMs,this.activeMaxPause=t.activeMaxPauseMs,this.quickCleanupThreshold=t.quickCleanupThresholdMs,this.pollIntervalBase=t.pollIntervalMs,this.pollIntervalJitter=t.pollIntervalJitterMs,this.pollInterval=t.pollIntervalMs+(t.pollIntervalJitterMs>0?Math.floor(Math.random()*t.pollIntervalJitterMs):0),this.leaderHeartbeatMs=t.leaderHeartbeatMs;const r=t.pollIntervalMs+t.pollIntervalJitterMs+t.leaderConfirmDelayMs;t.activeMaxPauseMs<r&&console.warn(`BackgroundWorker: activeMaxPauseMs (${t.activeMaxPauseMs}) меньше poll+jitter+leaderConfirm (${r}) — «живые» вкладки могут удаляться раньше следующего тика`)},bt=new WeakSet,fe=function(e){if(!e||typeof e!="string")return"";const t=se(e).replace(/\/+$/,"");return t?me(t)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):t:""},At=new WeakSet,St=function(){var e,t;return this.coordinationScope==="portal"?`${this.appCodeName||"app"}:portal`:String(((t=(e=this.bx)==null?void 0:e.userInfo)==null?void 0:t.ID)??"")},Qt=new WeakSet,He=function(){return`background-worker:${this.entityName}:${y(this,At,St).call(this)}`},I.BackgroundWorker=Xe,I.Batch=q,I.BxBoot=Ge,I.BxHelper=te,I.BxLogger=de,I.DEFAULT_BACKGROUND_WORKER_TIMING=z,I.resolveBackgroundWorkerTiming=ye,I.tempus=pt,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
1
+ var nn=Object.defineProperty;var rn=(T,P,H)=>P in T?nn(T,P,{enumerable:!0,configurable:!0,writable:!0,value:H}):T[P]=H;var D=(T,P,H)=>(rn(T,typeof P!="symbol"?P+"":P,H),H),ce=(T,P,H)=>{if(!P.has(T))throw TypeError("Cannot "+H)};var E=(T,P,H)=>(ce(T,P,"read from private field"),H?H.call(T):P.get(T)),R=(T,P,H)=>{if(P.has(T))throw TypeError("Cannot add the same private member more than once");P instanceof WeakSet?P.add(T):P.set(T,H)},W=(T,P,H,ut)=>(ce(T,P,"write to private field"),ut?ut.call(T,H):P.set(T,H),H);var _=(T,P,H)=>(ce(T,P,"access private method"),H);(function(T,P){typeof exports=="object"&&typeof module<"u"?P(exports):typeof define=="function"&&define.amd?define(["exports"],P):(T=typeof globalThis<"u"?globalThis:T||self,P(T["szdl-utils-kit"]={}))})(this,function(T){var wt,Te,Pt,kt,Ct,xt,At,$t,Ht,Me,Ut,Ie,rt,Mt,V,ct,gt,ue,it,It,vt,Le,jt,De,ht,te,bt,Ae,_t,he,st,Z,$,at,ft,Ot,tt,F,ot,dt,Gt,Be,St,fe,Xt,we,Yt,Pe,Wt,ke,mt,ee,Ft,Ce,Nt,de,Jt,xe,qt,He,Kt,Ue,et,pt,Rt,me,zt,ve,Et,pe,Qt,je,Zt,Ge,Tt,ye,lt,Lt,Vt,Xe;"use strict";var P=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function H(m){return m&&m.__esModule&&Object.prototype.hasOwnProperty.call(m,"default")?m.default:m}var ut={exports:{}};(function(m,t){(function(e){Array.prototype.indexOf||(Array.prototype.indexOf=function(n,o){var y,b;for(y=o||0,b=this.length;y<b;y+=1)if(this[y]===n)return y;return-1});var r=this,i=function(n,o){for(var y=n.toString();y.length<o;)y="0"+y;return y},a=function(n,o){return o!==e?(n.year(o.year()||o.year),n.month(o.month()||o.month),n.day(o.day()||o.day),n.hours(o.hours()||o.hours),n.minutes(o.minutes()||o.minutes),n.seconds(o.seconds()||o.seconds),n.milliseconds(o.milliseconds()||o.milliseconds),n):e},c=function(n,o){var y,b="";return y=n.slice(o,o+1),y!==""&&!isNaN(Number(y))&&(b+="%H"),y=n.charAt(o+2),y!==""&&y===":"&&(b+=y),y=n.slice(o+3,o+4),y!==""&&!isNaN(Number(y))&&(b+="%M"),y=n.charAt(o+5),y!==""&&y===":"&&(b+=y),y=n.slice(o+6,o+7),y!==""&&!isNaN(Number(y))&&(b+="%S"),b},A=function(n,o){var y,b=[n.slice(o,o+1),n.charAt(o+2),n.slice(o+3,o+4),n.charAt(o+5),n.slice(o+6,o+9)],U;return!isNaN(Number(b[0]))&&!isNaN(Number(b[2]))&&!isNaN(Number(b[4]))?(b[1]==="."&&b[3]==="."?y="%d.%m.%Y":b[1]==="-"&&b[3]==="-"?y="%m-%d-%Y":b[1]==="/"&&b[3]==="/"&&(y="%m/%d/%Y"),y):(U=[n.slice(o,o+3),n.charAt(o+4),n.slice(o+5,o+6),n.charAt(o+7),n.slice(o+8,o+9)],!isNaN(Number(U[0]))&&!isNaN(Number(U[2]))&&!isNaN(Number(U[4]))?(U[1]==="-"&&U[3]==="-"&&(y="%Y-%m-%d"),y):"")},f=r.tempus,s,d,h=r.navigator||{},l="en",u={en:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"Mar",APRIL_SHORT:"Apr",MAY_SHORT:"May",JUNE_SHORT:"Jun",JULY_SHORT:"Jul",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sep",OCTOBER_SHORT:"Oct",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dec",JANUARY_LONG:"January",FEBRUARY_LONG:"February",MARCH_LONG:"March",APRIL_LONG:"April",MAY_LONG:"May",JUNE_LONG:"June",JULY_LONG:"July",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"October",NOVEMBER_LONG:"November",DECEMBER_LONG:"December",SUNDAY_SHORT:"Sun",MONDAY_SHORT:"Mon",TUESDAY_SHORT:"Tue",WEDNESDAY_SHORT:"Wed",THURSDAY_SHORT:"Thu",FRIDAY_SHORT:"Fri",SATURDAY_SHORT:"Sat",SUNDAY_LONG:"Sunday",MONDAY_LONG:"Monday",TUESDAY_LONG:"Tuesday",WEDNESDAY_LONG:"Wednesday",THURSDAY_LONG:"Thursday",FRIDAY_LONG:"Friday",SATURDAY_LONG:"Saturday"},ru:{JANUARY_SHORT:"Янв",FEBRUARY_SHORT:"Фев",MARCH_SHORT:"Мар",APRIL_SHORT:"Апр",MAY_SHORT:"Май",JUNE_SHORT:"Июн",JULY_SHORT:"Июл",AUGUST_SHORT:"Авг",SEPTEMBER_SHORT:"Сен",OCTOBER_SHORT:"Окт",NOVEMBER_SHORT:"Ноя",DECEMBER_SHORT:"Дек",JANUARY_LONG:"Январь",FEBRUARY_LONG:"Февраль",MARCH_LONG:"Март",APRIL_LONG:"Апрель",MAY_LONG:"Май",JUNE_LONG:"Июнь",JULY_LONG:"Июль",AUGUST_LONG:"Август",SEPTEMBER_LONG:"Сентябрь",OCTOBER_LONG:"Октябрь",NOVEMBER_LONG:"Ноябрь",DECEMBER_LONG:"Декабрь",SUNDAY_SHORT:"Вс",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Воскресенье",MONDAY_LONG:"Понедельник",TUESDAY_LONG:"Вторник",WEDNESDAY_LONG:"Среда",THURSDAY_LONG:"Четверг",FRIDAY_LONG:"Пятница",SATURDAY_LONG:"Суббота"},ua:{JANUARY_SHORT:"Січ",FEBRUARY_SHORT:"Лют",MARCH_SHORT:"Берез",APRIL_SHORT:"Квіт",MAY_SHORT:"Трав",JUNE_SHORT:"Черв",JULY_SHORT:"Лип",AUGUST_SHORT:"Серп",SEPTEMBER_SHORT:"Верес",OCTOBER_SHORT:"Жовт",NOVEMBER_SHORT:"Листоп",DECEMBER_SHORT:"Груд",JANUARY_LONG:"Січень",FEBRUARY_LONG:"Лютий",MARCH_LONG:"Березень",APRIL_LONG:"Квітень",MAY_LONG:"Травень",JUNE_LONG:"Червень",JULY_LONG:"Липень",AUGUST_LONG:"Серпень",SEPTEMBER_LONG:"Вересень",OCTOBER_LONG:"Жовтень",NOVEMBER_LONG:"Листопад",DECEMBER_LONG:"Грудень",SUNDAY_SHORT:"Нд",MONDAY_SHORT:"Пн",TUESDAY_SHORT:"Вт",WEDNESDAY_SHORT:"Ср",THURSDAY_SHORT:"Чт",FRIDAY_SHORT:"Пт",SATURDAY_SHORT:"Сб",SUNDAY_LONG:"Неділя",MONDAY_LONG:"Понеділок",TUESDAY_LONG:"Вівторок",WEDNESDAY_LONG:"Середа",THURSDAY_LONG:"Четвер",FRIDAY_LONG:"П’ятниця",SATURDAY_LONG:"Субота"},de:{JANUARY_SHORT:"Jan",FEBRUARY_SHORT:"Feb",MARCH_SHORT:"März",APRIL_SHORT:"Apr",MAY_SHORT:"Mai",JUNE_SHORT:"Juni",JULY_SHORT:"Juli",AUGUST_SHORT:"Aug",SEPTEMBER_SHORT:"Sept",OCTOBER_SHORT:"Okt",NOVEMBER_SHORT:"Nov",DECEMBER_SHORT:"Dez",JANUARY_LONG:"Januar",FEBRUARY_LONG:"Februar",MARCH_LONG:"März",APRIL_LONG:"April",MAY_LONG:"Mai",JUNE_LONG:"Juni",JULY_LONG:"Juli",AUGUST_LONG:"August",SEPTEMBER_LONG:"September",OCTOBER_LONG:"Oktober",NOVEMBER_LONG:"November",DECEMBER_LONG:"Dezember",SUNDAY_SHORT:"So",MONDAY_SHORT:"Mo",TUESDAY_SHORT:"Di",WEDNESDAY_SHORT:"Mi",THURSDAY_SHORT:"Do",FRIDAY_SHORT:"Fr",SATURDAY_SHORT:"Sa",SUNDAY_LONG:"Sonntag",MONDAY_LONG:"Montag",TUESDAY_LONG:"Dienstag",WEDNESDAY_LONG:"Mittwoch",THURSDAY_LONG:"Donnerstag",FRIDAY_LONG:"Freitag",SATURDAY_LONG:"Samstag"}},p=function(){return[u[l].JANUARY_LONG,u[l].FEBRUARY_LONG,u[l].MARCH_LONG,u[l].APRIL_LONG,u[l].MAY_LONG,u[l].JUNE_LONG,u[l].JULY_LONG,u[l].AUGUST_LONG,u[l].SEPTEMBER_LONG,u[l].OCTOBER_LONG,u[l].NOVEMBER_LONG,u[l].DECEMBER_LONG]},O=function(){return[u[l].JANUARY_SHORT,u[l].FEBRUARY_SHORT,u[l].MARCH_SHORT,u[l].APRIL_SHORT,u[l].MAY_SHORT,u[l].JUNE_SHORT,u[l].JULY_SHORT,u[l].AUGUST_SHORT,u[l].SEPTEMBER_SHORT,u[l].OCTOBER_SHORT,u[l].NOVEMBER_SHORT,u[l].DECEMBER_SHORT]},N=function(){return[u[l].SUNDAY_LONG,u[l].MONDAY_LONG,u[l].TUESDAY_LONG,u[l].WEDNESDAY_LONG,u[l].THURSDAY_LONG,u[l].FRIDAY_LONG,u[l].SATURDAY_LONG]},B=function(){return[u[l].SUNDAY_SHORT,u[l].MONDAY_SHORT,u[l].TUESDAY_SHORT,u[l].WEDNESDAY_SHORT,u[l].THURSDAY_SHORT,u[l].FRIDAY_SHORT,u[l].SATURDAY_SHORT]},S,g,w,M,x=function(n,o,y){var b;r.XMLHttpRequest?b=new XMLHttpRequest:b=new ActiveXObject("Microsoft.XMLHTTP"),b.onreadystatechange=function(){b.readyState===4&&(b.status===200?o&&(r.JSON===e?alert(`Please, include json2 into your project if you want use old browsers!
2
+ https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):o(JSON.parse(b.responseText))):y&&y(b))},b.open("GET",n,!1),b.send()},k={"%d":{format:function(n){return i(n.day()||s.MIN_DAY,2)},parse:function(n){var o=Number(n);return{day:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(n){return i(n.month()||s.MIN_MONTH,2)},parse:function(n){var o=Number(n);return{month:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(n){return i(n.year()||s.MIN_YEAR,4)},parse:function(n){var o=Number(n);return{year:isNaN(o)?e:o}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(n){return n.dayOfWeek()||s.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(n){var o=n.dayOfWeek();return M[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(n){var o=n.dayOfWeek();return w[o!==e?o:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(n){var o=s.options("monthFromZero")?n.month():n.month()-1;return g[o!==e?o:s.MIN_MONTH]},parse:function(n){var o=s.monthNames().indexOf(n)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(n){var o=s.options("monthFromZero")?n.month():n.month()-1;return S[o!==e?o:s.MIN_MONTH]},parse:function(n){var o=s.monthNames(!0).indexOf(n)+(s.options("monthFromZero")?0:1);return{month:o!==-1?o:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(n){return i(n.hours()||s.MIN_HOURS,2)},parse:function(n){var o=Number(n);return{hours:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(n){return i(n.minutes()||s.MIN_MINUTES,2)},parse:function(n){var o=Number(n);return{minutes:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(n){return i(n.seconds()||s.MIN_SECONDS,2)},parse:function(n){var o=Number(n);return{seconds:isNaN(o)?e:o}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(n){return n.timestamp()},parse:function(n){return isNaN(Number(n))?{}:s(Number(n)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(n){return i(n.year()||s.MIN_YEAR,4)+"-"+i(n.month()||s.MIN_MONTH,2)+"-"+i(n.day()||s.MIN_DAY,2)},parse:function(n){var o=Number(n.slice(0,4)),y=Number(n.slice(5,7)),b=Number(n.slice(8,10));return{year:o,month:y,day:b}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(n){return i(n.month()||s.MIN_MONTH,2)+"/"+i(n.day()||s.MIN_DAY,2)+"/"+i(n.year()||s.MIN_YEAR,4)},parse:function(n){var o=Number(n.slice(0,2)),y=Number(n.slice(3,5)),b=Number(n.slice(6,10));return{year:b,month:o,day:y}},minLength:10,maxLength:10,type:"string"}},G={useMilliseconds:!1,monthFromZero:!1},I;I=function(n,o,y){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},n!==e&&this.set(n,o,y),this},I.fn=I.prototype,I.fn.dayCount=function(){var n=this.month(),o=s.MAX_DAY_IN_MONTHS[n-(s.options("monthFromZero")?0:1)];return this.leapYear()&&n===(s.options("monthFromZero")?1:2)&&(o+=1),o},I.fn.year=function(n){if(arguments.length!==0)(typeof n=="number"||typeof n=="string")&&!isNaN(Number(n))?Number(n)>=s.MIN_YEAR&&Number(n)<=s.MAX_YEAR?(this._d.setFullYear(Number(n)),this._i.year=!1):this._i.year=Number(n):(this._d.setFullYear(s.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},I.fn.month=function(n){if(arguments.length!==0)(typeof n=="number"||typeof n=="string")&&!isNaN(Number(n))?Number(n)>=s.MIN_MONTH&&Number(n)<=s.MAX_MONTH?(this._d.setMonth(s.options("monthFromZero")?Number(n):Number(n)-1),this._i.month=!1):this._i.month=Number(n):(this._d.setMonth(s.options("monthFromZero")?s.MIN_MONTH:s.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?s.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},I.fn.day=function(n){if(arguments.length!==0)(typeof n=="number"||typeof n=="string")&&!isNaN(Number(n))?Number(n)>=s.MIN_DAY&&Number(n)<=this.dayCount()?(this._d.setDate(Number(n)),this._i.day=!1):this._i.day=Number(n):(this._d.setDate(s.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},I.fn.hours=function(n){if(arguments.length!==0)(typeof n=="number"||typeof n=="string")&&!isNaN(Number(n))?Number(n)>=s.MIN_HOURS&&Number(n)<=s.MAX_HOURS?(this._d.setHours(Number(n)),this._i.hours=!1):this._i.hours=Number(n):(this._d.setHours(s.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},I.fn.minutes=function(n){if(arguments.length!==0)(typeof n=="number"||typeof n=="string")&&!isNaN(Number(n))?Number(n)>=s.MIN_MINUTES&&Number(n)<=s.MAX_MINUTES?(this._d.setMinutes(Number(n)),this._i.minutes=!1):this._i.minutes=Number(n):(this._d.setMinutes(s.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},I.fn.seconds=function(n){if(arguments.length!==0)(typeof n=="number"||typeof n=="string")&&!isNaN(Number(n))?Number(n)>=s.MIN_SECONDS&&Number(n)<=s.MAX_SECONDS?(this._d.setSeconds(Number(n)),this._i.seconds=!1):this._i.seconds=Number(n):(this._d.setSeconds(s.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},I.fn.milliseconds=function(n){if(arguments.length!==0)(typeof n=="number"||typeof n=="string")&&!isNaN(Number(n))?Number(n)>=s.MIN_MILLISECONDS&&Number(n)<=s.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(n)),this._i.milliseconds=!1):this._i.milliseconds=Number(n):(this._d.setMilliseconds(s.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},I.fn.week=function(){var n=new Date(this.year(),0,1),o=s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((o-n.getTime())/864e5+n.getDay()+1)/7)},I.fn.set=function(n,o,y){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},n===e)return this._d=new Date,this;if(n instanceof Date)return this._d=n,this;if(typeof n=="number")return this._d=new Date(n*(s.options("useMilliseconds")?1:1e3)),this;if(typeof n=="object"&&(n instanceof Array?(this.day(s.MIN_DAY),this.year(n[0]),this.month(n[1]),this.day(n[2]),this.hours(n[3]),this.minutes(n[4]),this.seconds(n[5]),this.milliseconds(n[6])):(this.day(s.MIN_DAY),this.year(n.year),this.month(n.month),this.day(n.day),this.hours(n.hours),this.minutes(n.minutes),this.seconds(n.seconds),this.milliseconds(n.milliseconds))),typeof n=="string"){var b,U=[],L,C,nt=[],Y=0,J=0,v,q,j={},X;if(n===e)return L=a(this,y),L===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),L;for(o===e&&(o=s.detectFormat(n));Y<o.length;){if(o.charAt(Y)==="%"){if(C=o.charAt(Y)+o.charAt(Y+1),k[C]!==e){switch(v=0,q="",k[C].type){case"number":for(;v<k[C].maxLength&&J+v<n.length&&!isNaN(Number(n.charAt(J+v)));)q+=n.charAt(J+v),v+=1;break;case"word":for(;v<k[C].maxLength&&J+v<n.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(n.charAt(J+v));)q+=n.charAt(J+v),v+=1;break;case"string":for(;v<k[C].maxLength&&J+v<n.length;)q+=n.charAt(J+v),v+=1;break}if(v<k[C].minLength)return L=a(this,y),L===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),L;U.push(C),nt.push(q),v-=1,J+=v,Y+=1}}else if(n.charAt(J)!==o.charAt(Y))return L=a(this,y),L===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),L;Y+=1,J+=1}for(b in U)U.hasOwnProperty(b)&&k.hasOwnProperty(U[b])&&(X=k[U[b]].parse(nt[b]),j={year:X.year!==e?X.year:j.year,month:X.month!==e?X.month:j.month,day:X.day!==e?X.day:j.day,hours:X.hours!==e?X.hours:j.hours,minutes:X.minutes!==e?X.minutes:j.minutes,seconds:X.seconds!==e?X.seconds:j.seconds});this.day(s.MIN_DAY),this.year(j.year),this.month(j.month),this.day(j.day),this.hours(j.hours),this.minutes(j.minutes),this.seconds(j.seconds),this.milliseconds(j.milliseconds)}return this},I.fn.leapYear=function(){var n=this.year();return n%4===0?n%100===0?n%400===0:!0:!1},I.fn.timestamp=function(n){return arguments.length!==0?(this._d=new Date(Number(n)*(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},I.fn.utc=function(n){return arguments.length!==0?(this._d=new Date(Number(n)*(s.options("useMilliseconds")?1:1e3)),this):s.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},I.fn.dayOfWeek=function(n){if(n==="long")return w[this._d.getDay()];if(n==="short")return M[this._d.getDay()];if(n===e)return this._d.getDay();if(n===0||n==="Sunday")return this.calc({day:-this.dayOfWeek()});if(n===1||n==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(n===2||n==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(n===3||n==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(n===4||n==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(n===5||n==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(n===6||n==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},I.fn.timezone=function(n){switch(n){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},I.fn.get=function(n){switch(n){case"Date":return new Date(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds());case"DateUTC":return new Date(Date.UTC(this.year(),this.month()-(s.options("monthFromZero")?0:1),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()));case"Array":return[this.year(),this.month(),this.day(),this.hours(),this.minutes(),this.seconds(),this.milliseconds()];default:return{year:this.year(),month:this.month(),week:this.week(),day:this.day(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds(),utc:this.utc(),dayOfWeek:this.dayOfWeek(),dayOfWeekShort:this.dayOfWeek("short"),dayOfWeekLong:this.dayOfWeek("long"),timestamp:this.timestamp()}}},I.fn.format=function(n){for(var o=0,y="",b;o<n.length;)n.charAt(o)==="%"?(b=n.charAt(o)+n.charAt(o+1),k[b]!==e?(y+=k[b].format(this),o+=1):y+="%"):y+=n.charAt(o),o+=1;return y},I.fn.valid=function(){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},I.fn.errors=function(){return this._i},I.fn.between=function(n,o){var y=this.timestamp(),b=n.timestamp();switch(o){case"year":return Math.floor((b-y)/31556952);case"month":return Math.floor((b-y)/2629746);case"day":return Math.floor((b-y)/86400);case"hours":return Math.floor((b-y)/3600);case"minutes":return Math.floor((b-y)/60);case"seconds":return b-y;default:return e}},I.fn.calc=function(n){return n.year!==e&&this._d.setFullYear(this._d.getFullYear()+n.year),n.month!==e&&this._d.setMonth(this._d.getMonth()+n.month),n.day!==e&&this._d.setDate(this._d.getDate()+n.day),n.hours!==e&&this._d.setHours(this._d.getHours()+n.hours),n.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+n.minutes),n.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+n.seconds),n.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+n.milliseconds),this},s=function(n,o,y){return new I(n,o,y)},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(n,o){if(n===e)return G;if(G.hasOwnProperty(n)){if(o===e)return G[n];G[n]=o,n==="monthFromZero"&&(s.MIN_MONTH=o?0:1,s.MAX_MONTH=o?11:12)}return e},s.noConflict=function(){return r.tempus=f,s},s.generate=function(n){var o,y,b,U,L,C,nt,Y;if(typeof n.dateFrom!="number"&&(n.dateFrom instanceof I?o=n.dateFrom.utc():o=s(n.dateFrom,n.formatFrom).utc()),typeof n.dateTo!="number"&&(n.dateTo instanceof I?y=n.dateTo.utc():y=s(n.dateTo,n.formatTo!==e?n.formatTo:n.formatFrom).utc()),typeof n.period=="number"?L={year:0,month:0,day:0,hours:0,minutes:0,seconds:n.period}:typeof n.period=="string"?L={year:n.period==="year"?1:0,month:n.period==="month"?1:0,day:n.period==="day"?1:0,hours:n.period==="hours"?1:0,minutes:n.period==="minutes"?1:0,seconds:n.period==="seconds"?1:0}:typeof n.period=="object"&&(L={year:n.period.year!==e?n.period.year:0,month:n.period.month!==e?n.period.month:0,day:n.period.day!==e?n.period.day:0,hours:n.period.hours!==e?n.period.hours:0,minutes:n.period.minutes!==e?n.period.minutes:0,seconds:n.period.seconds!==e?n.period.seconds:0}),n.groupBy===e?C=n.asObject===!0?{}:[]:(C=[],C.push([]),nt=s(o).get()[n.groupBy]),Y=function(q,j,X){return n.asObject===!0?n.format!==e?q[s(j).format(n.format)]={}:q[s(j).format("%F %H:%M:%S")]={}:n.format!==e?q.push(X?null:s(j).format(n.format)):q.push(X?null:s(j)),q},n.groupBy!==e&&n.fillNulls){var J={year:L.year?-L.year:e,month:L.month?-L.month:e,day:L.day?-L.day:e,hours:L.hours?-L.hours:e,minutes:L.minutes?-L.minutes:e,seconds:L.seconds?-L.seconds:e,milliseconds:L.milliseconds?-L.milliseconds:e};for(b=s(o).calc(J).utc();s(b).get()[n.groupBy]===nt;)Y(C[C.length-1],b,!0),b=s(b).calc(J).utc();if(n.groupBy==="week"){var v=s(o).dayOfWeek();for(b=s(o).dayOfWeek(0).utc();C[0].length<v&&b<o;)Y(C[C.length-1],b,!0),b=s(b).calc(L).utc()}}for(;o<=y;)n.groupBy===e?Y(C,o):s(o).get()[n.groupBy]===nt?Y(C[C.length-1],o):(C.push([]),Y(C[C.length-1],o),nt=s(o).get()[n.groupBy]),o=s(o).calc(L).utc();if(n.groupBy!==e&&n.fillNulls)for(U=s(y).calc(L).utc();s(U).get()[n.groupBy]===nt;)Y(C[C.length-1],U,!0),U=s(U).calc(L).utc();return C},s.monthNames=function(n){switch(n){case"long":return S;default:return g}},s.dayNames=function(n){switch(n){case"long":return w;default:return M}},s.lang=function(n){if(n!==e)l=n,u[l]===e&&(l="en"),S=p(),g=O(),w=N(),M=B();else return l;return e},s.availableLangs=function(){return Object.keys(u)},s.registerFormat=function(n,o,y,b,U,L){k[n]={format:o,parse:y,minLength:b,maxLength:U,type:L}},s.unregisterFormat=function(n){delete k[n]},s.detectFormat=function(n){var o,y,b;return o=A(n,0),o!==""&&(b=10),y=n.charAt(b),(y==="T"||y===" ")&&(o+=y,b+=1),o+=c(n,b),o},d={TempusDate:I},s.classes=function(n,o){if(o===e)return d[n];d[n]=o},s.loadTranslations=function(n){typeof n=="object"?u=n:typeof n=="string"&&x(n,function(o){u=o},function(o){})},l=(h.language||h.systemLanguage||h.userLanguage||"en").substr(0,2).toLowerCase(),u[l]===e&&(l="en"),S=p(),g=O(),w=N(),M=B(),m.exports&&(t=m.exports=s),t.tempus=s}).call(P)})(ut,ut.exports);var Ye=ut.exports;const yt=H(Ye),Q=class Q{constructor(t){R(this,wt);R(this,At);R(this,Ht);R(this,Ut);R(this,rt);R(this,V);R(this,gt);R(this,it);R(this,vt);R(this,jt);R(this,ht);R(this,bt);R(this,_t);typeof t=="function"?(this.callBatch=t,this.callMethod=null):(this.callBatch=(t==null?void 0:t.callBatch)||null,this.callMethod=(t==null?void 0:t.callMethod)||null),this.result={},this.errors={},this.errorMessages={},this.timeLimit={limit:!1,date:void 0,pauseMs:void 0},this.timeLimitListeners=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.pageSize=50,this.progressDelay=100,this.operatingThreshold=475,this.defaultPauseMs=12e4,this.callLimitPauseMs=3e4,this.requestTimeoutMs=6e4}get progressPercent(){if(!this.progressData)return{percent:0,allCount:0,allTotal:0};const t=this.totalBatchCommands||0;if(t>0&&Array.isArray(this.batchCommandKeyOrder)&&this.batchCommandKeyOrder.length&&_(this,wt,Te).call(this)){let f=0;for(const u of this.batchCommandKeyOrder){const p=this.progressData[u];if(!p)continue;const O=Number(p.total)||0,N=Number(p.count)||0;O===0&&N===0?f+=1:O>0&&(f+=Math.min(1,N/O))}const s=f/t*100;let d=Math.max(0,Math.min(100,Math.floor(s)));const h=t,l=Math.min(t,Math.floor(f));return{percent:d,allCount:l,allTotal:h}}let e=0,r=0;for(const f of Object.values(this.progressData)){const{total:s,count:d}=f;e+=s??0,r+=d??0}const i=Number(this.chunkRate)||0;let a=0;e?a=r/e*100*i+this.totalProgress:r===0&&e===0?a=i<1?this.totalProgress:100*i+this.totalProgress:a=100,a=Math.max(0,Math.min(a,100));let c=Math.floor(a);const A=Number(this.chunkRate)||0;return e>0&&r>=e&&A>=1&&(c=100),{percent:c,allCount:r,allTotal:e}}setProgressData({key:t,value:e,type:r}){var u,p;if(!this.progressCall)return;const i=this.getData(e.data()),a=Array.isArray(i)?i.length:0;let c=a;if(typeof e.total=="function"){const O=e.total();if(O!=null&&O!==""){const N=Number(O);Number.isFinite(N)&&(c=N)}}let A=1;r==="count"?(c||(c=a),A=c>0?c:a>0?a:1):i&&(A=a),this.progressData||(this.progressData={});const f=((u=this.progressData[t])==null?void 0:u.total)??0,s=((p=this.progressData[t])==null?void 0:p.count)??0,d=A+s,h=Math.max(f,c??0,d);if(this.progressData[t]={total:h,count:Math.min(d,h)},typeof document<"u"&&(document==null?void 0:document.hidden)===!0){_(this,At,$t).call(this);return}_(this,At,$t).call(this),this.progressTimer||(this.progressTimer=setInterval(()=>{if(!this.progressCall){this.clearProgressData();return}_(this,At,$t).call(this);const{percent:O}=this.progressPercent;O>=100&&(clearInterval(this.progressTimer),this.progressTimer="")},this.progressDelay))}getData(t){if(t==null)return t;let e=(t==null?void 0:t.items)??(t==null?void 0:t.tasks)??(t==null?void 0:t.types)??(t==null?void 0:t.type)??(t==null?void 0:t.fields)??(t==null?void 0:t.workgroups)??t;return e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.result)&&(e=e.result),e}setTimeLimitState(t,e,r){this.timeLimit.limit=!!t,this.timeLimit.date=t?e:void 0,t&&typeof r=="number"&&r>0?this.timeLimit.pauseMs=r:this.timeLimit.pauseMs=void 0,_(this,Ut,Ie).call(this)}subscribeTimeLimit(t){return typeof t!="function"?()=>{}:(this.timeLimitListeners.add(t),t({limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs}),()=>{this.timeLimitListeners.delete(t)})}splitLargeFilters(t,e){const{method:r,params:i}=e;if(!i)return[{key:t,request:e}];const a=i.filter||i.FILTER;if(!a||typeof a!="object"||Array.isArray(a))return[{key:t,request:e}];for(const[c,A]of Object.entries(a))if(!String(c).trim().startsWith("!")&&Array.isArray(A)&&A.length>this.filterChunkSize){const f=[];for(let s=0;s<A.length;s+=this.filterChunkSize){const d=A.slice(s,s+this.filterChunkSize),h=s===0?t:`${t}__chunk_${Math.floor(s/this.filterChunkSize)}`,l={...i};i.filter?(l.filter={...a},l.filter[c]=d):i.FILTER&&(l.FILTER={...a},l.FILTER[c]=d),f.push({key:h,request:{method:r,params:l},originalKey:t,filterKey:c,chunkIndex:Math.floor(s/this.filterChunkSize)})}return f}return[{key:t,request:e}]}mergeSplitResults(t,e){const r=[],i=String(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${i}(?:__chunk_\\d+)?$`),c=Object.keys(t).filter(A=>a.test(A)).sort((A,f)=>{const s=A.match(/__chunk_(\d+)$/),d=f.match(/__chunk_(\d+)$/);return s?d?parseInt(s[1])-parseInt(d[1]):1:-1});for(const A of c){const f=t[A];Array.isArray(f)?r.push(...f):f&&r.push(f)}return r}delay(){return typeof document<"u"&&(document==null?void 0:document.hidden)===!0?Promise.resolve():new Promise(e=>setTimeout(e,500))}callBatchWithTimeout(t,e,r={}){const{onLateResponse:i}=r;return new Promise((a,c)=>{let A=!1,f=null;const s=async h=>{if(A)typeof i=="function"&&i(h);else{A=!0,f&&clearTimeout(f);try{await Promise.resolve(e(h)),a()}catch(l){console.error("Error in callBatch callback:",l),c(l)}}},d=async()=>{if(!A){A=!0,f&&clearTimeout(f),console.warn(`Batch request timeout after ${this.requestTimeoutMs}ms. This may indicate a CORS or network error.`);const h={};Object.keys(t).forEach(l=>{h[l]={error:()=>({ex:{error:"TIMEOUT",error_description:"Request timeout after 60 seconds. Possible CORS or network error."}}),data:()=>[],total:()=>0}});try{await Promise.resolve(e(h)),a()}catch(l){console.error("Error in timeout callback:",l),a()}}};try{this.callBatch(t,async h=>{await s(h)})}catch(h){A||console.error("Error calling callBatch:",h)}f=setTimeout(async()=>{A||(console.warn(`Batch request attempt timeout after ${this.requestTimeoutMs}ms. Switching to timeout fallback result.`),await d())},this.requestTimeoutMs)})}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.lastProgressSnapshot=null}async batch(t,e,r={}){_(this,_t,he).call(this,e);const i={},a={},c={};for(const[d,h]of Object.entries(t)){const l=this.arrayChunk(h);if(!l)continue;const u=this.splitLargeFilters(d,l);if(u.length===1)a[d]=l;else{c[d]=[];for(const p of u)a[p.key]=p.request,c[d].push(p.key)}}this.batchCommandKeyOrder=Object.keys(a),this.totalBatchCommands=this.batchCommandKeyOrder.length,this.batchCommandMethods=this.batchCommandKeyOrder.map(d=>{var h;return String(((h=a[d])==null?void 0:h.method)||"")}),this.chunkRate=(1/Math.ceil(Object.keys(a).length/this.limit)).toFixed(5);let A={},f=0;const s=Object.keys(a).length;for(const[d,h]of Object.entries(a)){if(!this.canContinue)break;if(A[d]=h,Object.keys(A).length>=this.limit||f+1===s){const l=f+1===s;await this.batchChunk(A,void 0,!l,{disablePagination:!1,oneBatch:!!(r!=null&&r.oneBatch)}),Object.entries(this.result).forEach(([u,p])=>{i[u]=p}),this.totalProgress=Math.round(f/s*100),A={}}f++}for(const[d,h]of Object.entries(c))if(h&&h.length>0){const l=this.mergeSplitResults(i,d);for(const u of h)delete i[u];i[d]=l}return _(this,bt,Ae).call(this,i),e&&e({percent:100}),Promise.resolve(i)}async batchTotalCount(t,e){_(this,_t,he).call(this,e);const r={},i={},a={};for(const[f,s]of Object.entries(t)){const d=this.arrayChunk(s);if(!d)continue;const h=this.splitLargeFilters(f,d);if(h.length===1)i[f]=d;else{a[f]=[];for(const l of h)i[l.key]=l.request,a[f].push(l.key)}}const c=[],A=Object.entries(i);for(let f=0;f<A.length;f+=this.limit){const s=A.slice(f,f+this.limit),d={};for(const[h,l]of s){if(!this.canContinue)break;d[h]=l}Object.keys(d).length>0&&c.push(d)}this.chunkRate=(1/c.length).toFixed(5);for(const[f,s]of Object.entries(c)){if(!this.canContinue)break;this.totalProgress=Math.round(Number(f)/c.length*100),this.progressData={},this.lastProgressSnapshot=null;const d=Number(f)===c.length-1;await _(this,it,It).call(this,s,async h=>{for(const[l,u]of Object.entries(h)){if(!this.canContinue)return;if(u.error()){_(this,ht,te).call(this,l,u),r[l]=0;continue}const p=this.getData(u.data()),O=Array.isArray(p)?p.length:0,B=typeof u.total=="function"&&u.total()!==void 0?u.total():O;r[l]=B,this.setProgressData({key:l,value:u,type:"count"})}await _(this,V,ct).call(this,h,!d)})}for(const[f,s]of Object.entries(a))if(s&&s.length>0){let d=0;for(const h of s)r[h]!==void 0&&(d+=r[h]||0),delete r[h];r[f]=d}return Object.entries(this.errors).length&&(_(this,bt,Ae).call(this,r),this.errorLogger()),e&&e({percent:100}),Promise.resolve(r)}async call({method:t,params:e={}}){var i,a,c,A,f,s,d;const r=_(this,gt,ue).call(this,this.callLimitPauseMs);for(;;){let h=await _(this,vt,Le).call(this,t,e,{onLateResponse:p=>r.notifyLateResponse(p)});if(!h)if(r.inRetryCycle=!0,await r.waitForLateOrLimit(),r.lateResult)h=r.lateResult,r.resetLateResult(),r.inRetryCycle=!1;else continue;const l={};if(h!=null&&h.answer)for(const[p,O]of Object.entries(h.answer))p!=="result"&&O&&(l[p]=O);if(h.error()){const p=((a=(i=h.error())==null?void 0:i.ex)==null?void 0:a.error)??"";if(["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT","TIMEOUT"].includes(p)){await _(this,rt,Mt).call(this,this.callLimitPauseMs);continue}const O=((c=h.error())==null?void 0:c.toString())||((f=(A=h.error())==null?void 0:A.ex)==null?void 0:f.error_description)||((d=(s=h.error())==null?void 0:s.ex)==null?void 0:d.error)||"Неизвестная ошибка";return{success:!1,data:!1,answer:l,error:O}}let u=h.data();return u!=null&&u.items&&(u=u.items),r.inRetryCycle=!1,{success:!0,data:u,answer:l,error:null}}}arrayChunk(t){let e="",r={};if(Array.isArray(t)?[e]=t:(e=t.method,r=t.params),(e.includes("list")||e==="user.get"||e==="entity.item.get"||e==="sonet_group.get")&&e!=="task.item.list"){if(!r)r=e==="entity.item.get"?{SORT:{ID:"ASC"}}:e==="sonet_group.get"?{ORDER:{ID:"ASC"}}:e.startsWith("crm.")?{order:{ID:"ASC",id:"ASC"}}:{order:{ID:"ASC"}};else{e==="entity.item.get"?(r.SORT||(r.SORT={ID:"ASC"}),Array.isArray(r.select)?r.select.includes("ID")||r.select.push("ID"):r.select=["ID"]):e==="sonet_group.get"?r.ORDER?!r.ORDER.ID&&!r.ORDER.id&&(r.ORDER.ID="ASC"):r.ORDER={ID:"ASC"}:e==="tasks.task.list"?(r.order||(r.order={}),r.order.ID="asc"):e==="user.get"?(r.sort||(r.sort="ID"),r.order||(r.order="ASC")):e.startsWith("crm.")?r.order={ID:"ASC",id:"ASC"}:r.order?!r.order.ID&&!r.order.id&&(r.order.ID="ASC"):r.order={ID:"ASC"},Array.isArray(r.select)&&!r.select.includes("ID")&&r.select.push("ID");const i=e==="user.get"||e==="entity.item.get"||e==="sonet_group.get"?r.FILTER:r.filter;typeof i=="object"&&i!==null&&!Array.isArray(i)&&Object.entries(i).forEach(([a,c])=>{(r.start===void 0||r.start!==-1)&&["id","ID"].includes(a)&&(typeof c=="string"||Array.isArray(c)&&c.length<=50)&&(r.start=-1)})}e==="crm.type.list"&&r.order&&delete r.order.ID}if(e==="task.item.list")if(!r)r=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(r[0])&&(r[0]={});const[i,a,c,A]=r;i.ID="ASC",A[0]!==""&&A.includes("ID")||A.push("ID")}return{method:e,params:r}}async batchChunk(t,e,r=!0,i={}){return new Promise(a=>{const c=[];let A;const f=!!(i!=null&&i.disablePagination);(async()=>{await _(this,it,It).call(this,t,async d=>{for(const[l,u]of Object.entries(d)){if(!this.canContinue)return;u.error()&&(_(this,ht,te).call(this,l,u),A=!0);const p=this.getData(u.data()),O=Array.isArray(p)?p.length:0,N=typeof u.total=="function"&&u.total()!==void 0,B=N?u.total():O;e==="count"?this.result[l]?this.result[l]+=O:this.result[l]=B:this.result[l]=p,this.setProgressData({key:l,value:u,type:e});const S=t[l],g=Array.isArray(S)?S[0]:S==null?void 0:S.method,w=typeof g=="string"&&(g.includes(".list")||g.endsWith("getlist")||g==="user.get"||g==="entity.item.get"||g==="sonet_group.get"),M=this.pageSize||50,x=e==="count"?!N&&O===M:w?O===M:B>M&&B>O,k=e!=="count"&&g==="entity.item.get"&&O===M&&!x,G=x||k;if(!f&&(!this.canContinue||G)){let I=t[l];if(Array.isArray(I)){const[n,o={}]=I;I=[n,o]}else{const{method:n,params:o={}}=I;I=[n,o]}c.push([l,I,B,{entityItemGetScan:k}])}}A>0&&this.errorLogger();const h=c.length>0||r;await _(this,V,ct).call(this,d,h),c.length?await this.batchPayload(c,e,i).then(()=>a(this.result)):a(this.result)})})()})}async batchPayload(t,e,r={}){const i=!!(r!=null&&r.oneBatch),a=(p,O,N,B)=>{let S="ID";this.result[p][this.result[p].length-1].ID||(S="id");let g=`${S}`;if(JSON.stringify(B[1]).toLocaleLowerCase().includes('"id":"desc"')?g="<"+g:g=">"+g,O===1||N.length===0)return{field:g,id:this.result[p][this.result[p].length-1][S]};let M="";const[x,k]=B;return(x==="tasks.task.list"||x==="task.item.list")&&(M="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(x)&&(M="[items]"),x==="crm.type.list"&&(M="[types]"),x==="socialnetwork.api.workgroup.list"&&(M="[workgroups]"),{field:g,id:`$result[${[p,O-1].join("__")}]${M}[49][${S}]`}},c=(p,O)=>{const[N,B]=p;let S=JSON.parse(JSON.stringify(B)),g;if(N==="task.item.list"){S=[...S];const[w,M,x,k]=S;return M[O.field]=O.id,[N,S]}return["user.get","sonet_group.get"].includes(N)||S.FILTER?(S.FILTER||(S.FILTER={}),g=S.FILTER):(S.filter||(S.filter={}),g=S.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(N)?g[">ID"]=O.id:g[O.field]=O.id,[N,{...S,start:-1}]},A=p=>{Object.entries(p).forEach(([O,N])=>{const[B]=O.split("__"),S=this.getData(N.data());Array.isArray(S)&&(e==="count"?this.result[B]+=S.length:this.result[B].push(...S)),N.error()&&_(this,ht,te).call(this,B,N),this.setProgressData({key:B,value:N,type:e})})},f=(p,O)=>{if(!Array.isArray(p)||p.length===0)return null;const N=p[p.length-1];let B="ID";N.ID||(B="id");let S=B;return JSON.stringify(O[1]).toLocaleLowerCase().includes('"id":"desc"')?S="<"+S:S=">"+S,{field:S,id:N[B]}},s=1e4,d=async(p,O)=>{var N,B;for(let S=1;this.canContinue&&S<=s;S++){const g=this.result[p],w=f(g,O);if(!w)break;const M=`${p}__page_${S}`,x=c(O,w);let k=null;await _(this,it,It).call(this,{[M]:x},async o=>{k=o,A(o)});const G=k==null?void 0:k[M];if((N=G==null?void 0:G.error)!=null&&N.call(G)){await _(this,V,ct).call(this,k,!1);break}const I=this.getData((B=G==null?void 0:G.data)==null?void 0:B.call(G));if((Array.isArray(I)?I.length:0)===0){await _(this,V,ct).call(this,k,!1);break}await _(this,V,ct).call(this,k,S<s)}};let h=[],l=0;const u=async(p=!0)=>h.length?(await _(this,it,It).call(this,Object.fromEntries(h),async O=>{A(O),await _(this,V,ct).call(this,O,p)}),l++,h=[],i&&l>=1?!0:(await this.delay(),!1)):!1;for await(const p of t){if(!this.canContinue)return;const[O,N,B,S={}]=p;if(S.entityItemGetScan||!i){if(await u(!0))return;if(i)continue;await d(O,N);continue}let g=1;const w=this.pageSize||50,M=Math.max(1,Math.min(50,Number(this.limit)||50));for(;B>g*w;){const x=[O,g].join("__"),k=a(O,g,h,N);if(h.push([x,c(N,k)]),i&&h.length===M-1&&await u(!0)||h.length%M===0&&await u(!0))return;g++}}await u(!1)}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([t,e])=>{e&&console.log(`[${t}]`,e.toString())}),console.groupEnd()}};wt=new WeakSet,Te=function(){const t=this.totalBatchCommands||0,e=this.batchCommandMethods;if(t<E(Q,Pt)||!Array.isArray(e)||e.length!==t)return!1;if(e.filter(a=>a==="crm.deal.list").length>=E(Q,kt))return!0;const i=e.filter(a=>typeof a=="string"&&a.includes(".list")).length;return i>=E(Q,Ct)&&i/t>=E(Q,xt)},Pt=new WeakMap,kt=new WeakMap,Ct=new WeakMap,xt=new WeakMap,At=new WeakSet,$t=function(){if(!this.progressCall||!this.progressData)return;const{percent:t,allCount:e,allTotal:r}=this.progressPercent,i={percent:t,allCount:e,allTotal:r};_(this,Ht,Me).call(this,i)&&(this.progressCall({data:this.progressData,percent:t,allCount:e,allTotal:r}),this.lastProgressSnapshot=i)},Ht=new WeakSet,Me=function(t){return this.lastProgressSnapshot?this.lastProgressSnapshot.percent!==t.percent||this.lastProgressSnapshot.allCount!==t.allCount||this.lastProgressSnapshot.allTotal!==t.allTotal:!0},Ut=new WeakSet,Ie=function(){const t={limit:this.timeLimit.limit,date:this.timeLimit.date,pauseMs:this.timeLimit.pauseMs};for(const e of this.timeLimitListeners)try{e(t)}catch(r){console.warn("Batch timeLimit listener error:",r)}},rt=new WeakSet,Mt=async function(t=this.defaultPauseMs){this.setTimeLimitState(!0,new Date().toISOString(),t),await new Promise(e=>setTimeout(e,t)),this.setTimeLimitState(!1,void 0)},V=new WeakSet,ct=async function(t,e=!0){if(!e)return 0;let r=0;if(!t||typeof t!="object")return 0;for(const i of Object.values(t))if(!(!i||typeof i!="object"))try{if(typeof i.time=="function"){const a=i.time();a&&typeof a.operating=="number"&&(r=Math.max(r,a.operating))}}catch{}r>=this.operatingThreshold&&await _(this,rt,Mt).call(this)},gt=new WeakSet,ue=function(t=this.defaultPauseMs){const e=this;return{inRetryCycle:!1,inTimeoutWait:!1,lateResult:null,lateWaiters:[],notifyLateResponse(i){if(!(!this.inRetryCycle&&!this.inTimeoutWait)){this.lateResult=i;for(const a of this.lateWaiters)a(i);this.lateWaiters=[]}},waitForLateOrLimit(){var a;this.inTimeoutWait=!0;const i=new Promise(c=>{if(this.lateResult){c(this.lateResult);return}this.lateWaiters.push(c)});return Promise.race([_(a=e,rt,Mt).call(a,t),i]).finally(()=>{this.inTimeoutWait=!1})},resetLateResult(){this.lateResult=null}}},it=new WeakSet,It=async function(t,e){let r=!1,i=t;const a=_(this,gt,ue).call(this);do r=!1,await this.callBatchWithTimeout(i,async c=>{var s,d;let A=!1;const f=new Set;for(const[h,l]of Object.entries(c||{})){if(!(l!=null&&l.error)||!l.error())continue;const u=((d=(s=l.error())==null?void 0:s.ex)==null?void 0:d.error)??"";if(u==="TIMEOUT"){A=!0;break}["QUERY_LIMIT_EXCEEDED","OPERATION_TIME_LIMIT"].includes(u)&&f.add(h)}if(A){if(a.inRetryCycle=!0,r=!0,await a.waitForLateOrLimit(),a.lateResult){r=!1,a.inRetryCycle=!1;const h=a.lateResult;a.resetLateResult(),await e(h)}return}if(f.size>0){const h={};for(const[u,p]of Object.entries(c||{}))f.has(u)||(h[u]=p);Object.keys(h).length&&await e(h);const l={};for(const u of f)i[u]&&(l[u]=i[u]);i=l,Object.keys(i).length&&(r=!0,await _(this,rt,Mt).call(this));return}a.inRetryCycle=!1,await e(c)},{onLateResponse:c=>a.notifyLateResponse(c)});while(r)},vt=new WeakSet,Le=function(t,e,r={}){const{onLateResponse:i}=r;return new Promise(a=>{if(typeof this.callMethod!="function"){a(null);return}let c=!1;const A=setTimeout(()=>{c||(c=!0,a(null))},this.requestTimeoutMs);try{this.callMethod(t,e,f=>{c?typeof i=="function"&&i(f):(c=!0,clearTimeout(A),a(f))})}catch{c||(c=!0,clearTimeout(A),a(null))}})},jt=new WeakSet,De=function(t){const e=typeof(t==null?void 0:t.error)=="function"?t.error():null,r=(e==null?void 0:e.ex)||{},i=String(r.error||"").trim(),a=String(r.error_description||"").trim(),c=typeof(e==null?void 0:e.toString)=="function"?String(e.toString()).trim():"";let A=a;return!A&&c&&c!==i&&(A=c),A||(A=i||"Неизвестная ошибка"),{code:i||A,message:A}},ht=new WeakSet,te=function(t,e){const{code:r,message:i}=_(this,jt,De).call(this,e);this.errors[t]=r,this.errorMessages[t]=i},bt=new WeakSet,Ae=function(t){Object.entries(this.errors).length&&(t.errorsList={...this.errors},Object.entries(this.errorMessages).length&&(t.errorsListMessages={...this.errorMessages}))},_t=new WeakSet,he=function(t){this.clearProgressData(),this.progressCall=typeof t=="function"?t:"",this.canContinue=!0,this.result={},this.errors={},this.errorMessages={},this.chunkRate=1,this.totalProgress=0,this.batchCommandKeyOrder=[],this.totalBatchCommands=0,this.batchCommandMethods=[],this.setTimeLimitState(!1,void 0)},R(Q,Pt,5),R(Q,kt,5),R(Q,Ct,8),R(Q,xt,.65);let K=Q;class ne{constructor(){R(this,st,{})}get hash(){return this.createHash(8)}createHash(t){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";t=t||6;for(let i=0;i<t;i++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}actionFilter({keyTimer:t,duration:e=10,action:r}){E(this,st)[t]&&(clearTimeout(E(this,st)[t]),E(this,st)[t]=null),r&&(E(this,st)[t]=setTimeout(()=>{r()},e))}async noSleep(){let t=document.createElement("video");t.classList.add("no-sleep"),t.muted=!0,t.autoplay=!0,t.setAttribute("playsinline",""),t.addEventListener("loadeddata",()=>{t.style.position="fixed",t.style.left="-9999px",document.querySelector("body").append(t),t.play().catch(e=>{console.warn("noSleep: autoplay prevented",e)})}),t.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{t.play().catch(e=>{console.warn("noSleep: replay prevented",e)})}})}),t.src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAAP5tZGF0AAAAAQYAAADlZYiEE28FmH9jNWDBjI+Z/1tIBZsjfhbmcNNUpBFej0U3p+zhaJ3eemJRL2LUMa5tkidy6bp+eatLE3jBIY864TvaAmqEFCgLMTCwVbem1n3myAw9yDXQdR5HfU/8iYf+eneVnRf7Qx9M70XDUuPx1MJX671XJwAE0VAMpnhbcUDx0pTldvUX9KQPhkZNH3eyZHmObkAeyEJ2tl+BEBJIGc90BiqKL60+5EA6fXB6iG5UU/M5KsW8BNAAUw5CbRJIqohNk10fwKbUXwya03rqGkE8+wuYGtEbrVYXb+iOl1mHHVPLYQbIAAcGyAAHAAAFNG1vb3YAAABsbXZoZAAAAAAAAAAAAAAAAAAAA+gAAAAvAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAIldHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAFAAAAA8AAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAAAAAAAAAAAQAAAAABnW1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAAQAAAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAUhtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEIc3RibAAAAKRzdHNkAAAAAAAAAAEAAACUYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAFAAPAASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAC5hdmNDAU1AC//hABZnTUAL2wUH7ARAAAADAEAAAAQDxQq4AQAFaOrAZXIAAAAQcGFzcAAAAAEAAAABAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAAAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAO4AAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAAIadHJhawAAAFx0a2hkAAAAAwAAAAAAAAAAAAAAAgAAAAAAAAAvAAAAAAAAAAAAAAABAQAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAAAALwAAAAAAAQAAAAABkm1kaWEAAAAgbWRoZAAAAAAAAAAAAAAAAAAArEQAAAgAVcQAAAAAAC1oZGxyAAAAAAAAAABzb3VuAAAAAAAAAAAAAAAAU291bmRIYW5kbGVyAAAAAT1taW5mAAAAEHNtaGQAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAAAQAAAQFzdGJsAAAAZ3N0c2QAAAAAAAAAAQAAAFdtcDRhAAAAAAAAAAEAAAAAAAAAAAACABAAAAAArEQAAAAAADNlc2RzAAAAAAOAgIAiAAIABICAgBRAFQAAAAAC7gAAAAViBYCAgAISCAaAgIABAgAAABhzdHRzAAAAAAAAAAEAAAACAAAEAAAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAUc3RzegAAAAAAAAAEAAAAAgAAABRzdGNvAAAAAAAAAAEAAAEeAAAAGnNncGQBAAAAcm9sbAAAAAIAAAAB//8AAAAcc2JncAAAAAByb2xsAAAAAQAAAAIAAAABAAAAgXVkdGEAAAB5bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWR0YQAAAAAAAAAAAAAAAAAAAAAfa2V5cwAAAAAAAAABAAAAD21kdGFlbmNvZGVyAAAALWlsc3QAAAAlAAAAAQAAAB1kYXRhAAAAAQAAAABMYXZmNTguMTIuMTAw"}downloadFileJson(t,e){let r=new Blob([JSON.stringify(t)],{type:"application/json"}),i=URL.createObjectURL(r),a=document.createElement("a");a.style.display="none",a.href=i,a.download=`${e}.json`,document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(i)},200)}}st=new WeakMap;const re=new ne;class ge{constructor(){R(this,Gt);R(this,St);R(this,Xt);R(this,Yt);R(this,Wt);R(this,Z,"logger");R(this,$,!1);R(this,at,new Map);R(this,ft,{});R(this,Ot,!1);R(this,tt,null);R(this,F,null);R(this,ot,!1);R(this,dt,!1);D(this,"periodClear",3)}async init(){try{let t=new K(BX24.callBatch),{entityList:e}=await t.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(i=>i.ENTITY==E(this,Z)))W(this,$,!0);else{let{entityAdd:i}=await t.batch({entityAdd:{method:"entity.add",params:{ENTITY:E(this,Z),NAME:E(this,Z),ACCESS:{AU:"X"}}}});i&&W(this,$,!0)}return E(this,$)}catch(t){return console.error("Ошибка при инициализации логера:",t),!1}}enableBackworkerMode(){return W(this,$,!0),!0}start({type:t,data:e}){if(!E(this,$))return _(this,St,fe).call(this,"entity"),null;if(!t||!e)return console.error("Невалидные данные для логирования:",{type:t,data:e}),null;const r=re.hash,i={type:t,data:e,userInfo:null,errorList:{},status:"",answer:null,date:new Date().getTime()};return E(this,at).set(r,i),W(this,dt,!0),r}async stop({key:t,errorList:e,status:r,answer:i}){var c;if(!E(this,dt))return;if(!E(this,$)){_(this,St,fe).call(this,"entity");return}let a=E(this,at).get(t);if(!a){console.error(`Не найдены данные логирования для ключа: ${t}`);return}e&&(a.errorList=e),r&&(a.status=r),i&&(a.answer=i),await _(this,Gt,Be).call(this),a.userInfo=E(this,ft),await _(this,Xt,we).call(this),(c=a==null?void 0:a.data)!=null&&c.updateList&&W(this,ot,!0),W(this,dt,!1)}async getEntityList(t){var e;try{if((e=E(this,F))!=null&&e.length&&!E(this,ot))return E(this,F);let r=new K(BX24.callBatch),{entityList:i}=await r.batch({entityList:{method:"entity.item.get",params:{ENTITY:E(this,Z),SORT:{ID:"DESC"}}}},t);return!i||!Array.isArray(i)?(console.warn("Получен невалидный список записей"),[]):(i=i.map(a=>{try{const{ID:c,DATE_CREATE:A,DETAIL_TEXT:f}=a;return{...JSON.parse(f),id:c,dateCreate:A}}catch(c){return console.error(`Ошибка парсинга записи ${a.ID}:`,c),null}}).filter(a=>a!==null),W(this,ot,!1),W(this,F,i),i)}catch(r){return console.error("Ошибка при получении списка записей:",r),[]}}runStorageMaintenance(){return _(this,Yt,Pe).call(this)}async downAllEntityJson(){try{if(E(this,F)||await this.getEntityList(),!E(this,F)||E(this,F).length===0)return console.warn("Нет данных для выгрузки"),!1;let t=yt().format("%Y-%m-%d");return re.downloadFileJson(E(this,F),`sdklogger-entity-data__${t}`),!0}catch(t){return console.error("Ошибка при выгрузке данных в JSON:",t),!1}}}Z=new WeakMap,$=new WeakMap,at=new WeakMap,ft=new WeakMap,Ot=new WeakMap,tt=new WeakMap,F=new WeakMap,ot=new WeakMap,dt=new WeakMap,Gt=new WeakSet,Be=async function(){if(!E(this,Ot))return E(this,tt)?E(this,tt):(W(this,tt,(async()=>{try{const t=new K(BX24.callBatch),e=BX24.isAdmin(),{curUser:r}=await t.batch({curUser:{method:"user.current"}});W(this,ft,{isAdmin:e,curUser:r})}catch(t){console.error("Ошибка при получении информации о пользователе:",t),W(this,ft,{isAdmin:!1,curUser:null})}finally{W(this,Ot,!0),W(this,tt,null)}})()),E(this,tt))},St=new WeakSet,fe=function(t){t=="entity"&&re.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Xt=new WeakSet,we=async function(){try{let t={},e=new K(BX24.callBatch);for(let[r,i]of E(this,at).entries())if(i.status){const a=JSON.stringify(i);t[r]={method:"entity.item.add",params:{ENTITY:E(this,Z),NAME:E(this,Z),DETAIL_TEXT:a}}}if(Object.keys(t).length){let r=await e.batch(t),{errors:i}=e;for(let[a,c]of Object.entries({...r,...i}))E(this,at).delete(a);return!0}return!1}catch(t){return console.error("Ошибка при добавлении записей в хранилище:",t),!1}},Yt=new WeakSet,Pe=async function(){try{let t=new K(BX24.callBatch),{serverTime:e}=await t.batch({serverTime:{method:"server.time"}});if(!e){console.error("Не удалось получить время сервера");return}if(E(this,F)||await this.getEntityList(),!E(this,F)||E(this,F).length===0)return;let r=E(this,F).filter(i=>{try{let{dateCreate:a}=i;return a?yt(new Date(a)).between(yt(new Date(e)),"month")>=this.periodClear:!1}catch(a){return console.error("Ошибка при проверке даты записи:",a),!1}});r.length>0&&(console.log(`Найдено ${r.length} записей для очистки (старше ${this.periodClear} месяцев)`),await _(this,Wt,ke).call(this,r))}catch(t){console.error("Ошибка при проверке периода очистки:",t)}},Wt=new WeakSet,ke=async function(t){try{if(!t||t.length===0)return!1;let e=new K(BX24.callBatch),r=t.filter(a=>a&&a.id).map(a=>{let{id:c}=a;return{method:"entity.item.delete",params:{ENTITY:E(this,Z),ID:c}}});if(r.length===0)return!1;const i=await e.batch(r);return console.log(`Успешно удалено ${r.length} записей`),W(this,ot,!0),i}catch(e){return console.error("Ошибка при очистке устаревших записей:",e),!1}};function ie(m){if(!m||typeof m!="string")return"";try{const t=new URL(m);t.search="",t.hash="";let e=t.toString();return e.endsWith("/")&&t.pathname!=="/"&&(e=e.slice(0,-1)),e}catch{return m.split("?")[0].split("#")[0].replace(/\/$/,"")}}function be(m){return!m||typeof m!="string"?!1:m.toLowerCase().includes("/marketplace/app")}function We(){var t;if(typeof window>"u"||!((t=window.location)!=null&&t.href))return"";const m=ie(window.location.href);return be(m)?"":m}function se(m){if(!(m!=null&&m.appConst)||typeof m.appConst!="object")return"";const t=We();return t?(m.appConst.pathApp=t,t):ie(m.appConst.pathApp??"")}const _e=Object.freeze([Object.freeze({name:"com",url:"//api.bitrix24.com/api/v1/"}),Object.freeze({name:"tech",url:"//api.bitrix24.tech/api/v1/"})]),ae=3e3,Oe="__szdlBx24Stub",Dt="__szdlBx24LoadPromise";class oe extends Error{constructor(t){super(`BX24 library loaded from "${t}" but failed to initialize (app is not opened inside Bitrix24 frame?)`),this.name="Bx24EnvironmentError",this.source=t}}function Bt(m){const t=m.BX24;return!!t&&typeof t.init=="function"&&!t[Oe]}function Fe(m,t){if(t){for(const e of t.installQueue.splice(0))m.BX24.install(e);for(const e of t.initQueue.splice(0))m.BX24.init(e)}}function Je({win:m,doc:t,loadLocalCode:e,sources:r=_e,timeoutMs:i=ae,logger:a=console}){const c=d=>(t.head||t.documentElement).appendChild(d),A=d=>{d.parentNode&&d.parentNode.removeChild(d)},f=d=>new Promise(h=>{const l=t.createElement("script");let u=!1;const p=N=>{u||(u=!0,clearTimeout(O),l.onload=null,l.onerror=null,N!=="ok"&&A(l),h(N))},O=setTimeout(()=>p("timeout"),i);l.onload=()=>{Bt(m)?p("ok"):p(m.BX24===null?"env-error":"error")},l.onerror=()=>p("error"),l.src=d,c(l)}),s=async()=>{const d=await e(),h=t.createElement("script");h.text=d;try{c(h)}catch{}if(!Bt(m))throw m.BX24===null?new oe("local"):new Error("BX24 local copy failed to initialize")};return async function(){var u;if(Bt(m))return{source:"preloaded"};const h=((u=m.BX24)==null?void 0:u[Oe])??null,l=p=>(Fe(m,h),a.info(`BX24 loaded from "${p}"`),{source:p});for(const{name:p,url:O}of r){const N=await f(O);if(N==="ok")return l(p);if(N==="env-error")throw new oe(p);if(Bt(m))return l(p);a.warn(`BX24 source "${p}" (${O}) failed: ${N}`)}return await s(),l("local")}}function qe(m){const{win:t}=m;return t[Dt]||(t[Dt]=Je(m)().catch(e=>{throw delete t[Dt],e})),t[Dt]}function Se({timeoutMs:m=ae}={}){return qe({win:window,doc:document,timeoutMs:m,loadLocalCode:()=>Promise.resolve().then(()=>en).then(t=>t.default)})}class Ke{constructor(t){R(this,mt);R(this,Ft);R(this,Nt);R(this,Jt);R(this,qt);R(this,Kt);R(this,et);R(this,Rt);R(this,zt);R(this,Et);R(this,Qt);D(this,"domain","");D(this,"isAdmin",!1);D(this,"appInfo",null);D(this,"appConst",null);D(this,"userInfo",null);D(this,"placeData",null);D(this,"placeInfo",null);D(this,"logger",!1);D(this,"timeLimit",{limit:!1,date:void 0,pauseMs:void 0});D(this,"batchClient",null);this.appConst=t}subscribeTimeLimit(t){return _(this,mt,ee).call(this).subscribeTimeLimit(t)}init(){return new Promise((t,e)=>{const i=setTimeout(()=>{clearInterval(a);const c=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(c),e(c)},3e4);let a=setInterval(()=>{window.BX24&&BX24.init(async()=>{clearInterval(a),clearTimeout(i),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info();const c=_(this,Jt,xe).call(this);if(console.info(c?"init BX24 (background worker)":"init BX24"),this.appInfo=await _(this,qt,He).call(this),this.userInfo=await _(this,Kt,Ue).call(this),se(this),c)await _(this,Nt,de).call(this,!1,{skipInit:!0});else{await _(this,Nt,de).call(this,!0);const A=new ne;try{A.noSleep()}catch(f){console.warn("Failed to initialize noSleep:",f)}}t({isBackworker:c})})},100);Se().catch(c=>{clearInterval(a),clearTimeout(i),console.error(c),e(c)})})}userOption(t,e){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.userOption.set(t,e):BX24.userOption.get(t)}appOption(t,e){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return e!==void 0?BX24.appOption.set(t,e):BX24.appOption.get(t)}async call({method:t,params:e,updateList:r}){let i;if(r&&(i=this.logger.start({type:"call",data:{method:t,params:e,updateList:r}})),e||(e={}),typeof BX24>"u"||!BX24.callMethod){const A=new Error("BX24 is not initialized");throw console.error(A),A}const c=await _(this,mt,ee).call(this).call({method:t,params:e});return c.success?(await _(this,et,pt).call(this,i,{answer:c.answer,status:"success"}),c.data):(console.error(c.error),await _(this,et,pt).call(this,i,{answer:c.answer,status:"fail",errorList:{0:c.error||"Unknown call error"}}),!1)}async batch(t,e,{errorCall:r,updateList:i,batchOptions:a}={}){if(typeof BX24>"u"||!BX24.callBatch){const c=new Error("BX24 is not initialized");return console.error(c),!1}return _(this,Rt,me).call(this,{mode:"batch",commandList:t,progressCall:e,errorCall:r,updateList:i,batchOptions:a})}async batchTotalCount(t,e,{errorCall:r,updateList:i}={}){if(typeof BX24>"u"||!BX24.callBatch){const a=new Error("BX24 is not initialized");return console.error(a),!1}return _(this,Rt,me).call(this,{mode:"batch-total-count",commandList:t,progressCall:e,errorCall:r,updateList:i})}async getPlacement(){const t=await this.call({method:"placement.get"});return this.placeData||(this.placeData=t),t}async placementBind(t){var l;if(!this.isAdmin||(this.placeData=await this.getPlacement(),!this.placeData))return;const{appName:e,pathApp:r}=this.appConst;let i=_(this,Et,pe).call(this,t);i=i.filter(u=>u.placement!=="PAGE_BACKGROUND_WORKER"&&u.placement!=="PAGE_BACKGROUND_WORKER_ALL");const a=_(this,Qt,je).call(this,r),c=new Set(i.map(u=>u.placement));for(const u of a)c.has(u.placement)||i.push({placement:u.placement});if(i.length===0)return;let A=e;this.domain==="szdl.bitrix24.ru"&&((l=this.appInfo)!=null&&l.ID)&&(A=`${e}: #${this.appInfo.ID}`);const f=A.replace(" CRM",""),s={},d=[],h=new Map;for(const u of this.placeData)h.has(u.placement)||h.set(u.placement,[]),h.get(u.placement).push(u);for(let u=0;u<i.length;u++){const{placement:p,options:O}=i[u],N=h.get(p)||[];if(N.some(g=>g.handler===r))continue;const S=N.filter(g=>g.handler!==r);for(const g of S)d.push({placement:p,handler:g.handler});s[`bind_${u}`]={method:"placement.bind",params:{PLACEMENT:p,HANDLER:r,LANG_ALL:{ru:{TITLE:p==="USER_PROFILE_TOOLBAR"?f:A}},OPTIONS:{errorHandlerUrl:r,...O&&typeof O=="object"?O:{}}}}}d.length>0&&await this.placementUnBind(d),Object.keys(s).length>0&&(await this.batch(s),this.placeData=await this.getPlacement(),Object.values(s).forEach(u=>{console.log("Приложение успешно встроено в",u.params.PLACEMENT)}))}async placementUnBind(t){let e=_(this,Et,pe).call(this,t);if(e=e.filter(i=>i.placement!=="PAGE_BACKGROUND_WORKER"&&i.placement!=="PAGE_BACKGROUND_WORKER_ALL"),e.length===0)return;const r={};for(let i=0;i<e.length;i++){const a={PLACEMENT:e[i].placement};e[i].handler&&(a.HANDLER=e[i].handler),r[`unbind_${i}`]={method:"placement.unbind",params:a}}await this.batch(r),e.forEach(i=>{console.log("Встройка отвязана",i.placement)})}async getBotList(){const t=await this.call({method:"imbot.bot.list",params:{}}),e=Object.values(t);return console.log("chat-bot list:",e),e}async regBot({code:t,type:e,name:r}){const{appName:i,pathApp:a,chatBotLogo:c}=this.appConst,A=this.appInfo.ID,f=await this.call({method:"imbot.register",params:{CODE:t??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:a,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${r??i} - бот #${A}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:yt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:c??""}}});return console.log("Чат-бот добавлен",f),f}async unRegBot(t){const e=await this.call({method:"imbot.unregister",params:{BOT_ID:t}});return console.log("чат-бот удален",e),e}getLoggerList(t){return this.logger.getEntityList(t)}}mt=new WeakSet,ee=function(){return this.batchClient||(this.batchClient=new K({callBatch:BX24.callBatch,callMethod:BX24.callMethod}),this.timeLimit=this.batchClient.timeLimit),this.batchClient},Ft=new WeakSet,Ce=function(){return{start:()=>{},stop:()=>{},getEntityList:()=>{}}},Nt=new WeakSet,de=async function(t,{skipInit:e=!1}={}){this.logger?(this.logger=new ge,e?this.logger.enableBackworkerMode():await this.logger.init(),t&&typeof this.logger.runStorageMaintenance=="function"&&this.logger.runStorageMaintenance()):this.logger=_(this,Ft,Ce).call(this)},Jt=new WeakSet,xe=function(){var r,i,a;const t=(r=this.placeInfo)==null?void 0:r.placement,e=(a=(i=this.placeInfo)==null?void 0:i.options)==null?void 0:a.ID;return t==="PAGE_BACKGROUND_WORKER"||e==="PAGE_BACKGROUND_WORKER"},qt=new WeakSet,He=function(){return this.call({method:"app.info"})},Kt=new WeakSet,Ue=function(){return this.call({method:"user.current"})},et=new WeakSet,pt=async function(t,e){if(t)try{await this.logger.stop({key:t,...e})}catch(r){console.error("Logger error:",r)}},Rt=new WeakSet,me=async function({mode:t,commandList:e,progressCall:r,errorCall:i,updateList:a,batchOptions:c}){const A=_(this,mt,ee).call(this),f=a?this.logger.start({type:t,data:t==="batch"?{commandList:e,updateList:a}:{commandList:e}}):void 0;try{const s=t==="batch"?await A.batch(e,r,c):await A.batchTotalCount(e,r),d=_(this,zt,ve).call(this,A,s,e,a);return Object.keys(d).length?(i&&i(d),await _(this,et,pt).call(this,f,{status:"fail",errorList:d})):await _(this,et,pt).call(this,f,{status:"success"}),s}catch(s){return await _(this,et,pt).call(this,f,{status:"fail-runtime",errorList:{0:s==null?void 0:s.toString()}}),console.error(s),!1}},zt=new WeakSet,ve=function(t,e,r,i){let a={...t.errors};if(Object.values(t.errors).some(A=>{if(typeof A!="string")return!1;const f=A.toUpperCase();return f==="TIMEOUT"||f==="OPERATION_TIME_LIMIT"||f.includes("TIMEOUT")||f.includes("OPERATION_TIME_LIMIT")})&&i){const A=e?Object.keys(e).filter(h=>h!=="errorsList"&&h!=="errorsListMessages"):[],f=new Set(Object.keys(t.errors||{})),s=new Set;if(e){for(const h of A)if(!f.has(h)){const l=e[h];l!=null&&s.add(h)}}const d=Object.values(t.errors).find(h=>{if(typeof h!="string")return!1;const l=h.toUpperCase();return l==="TIMEOUT"||l==="OPERATION_TIME_LIMIT"||l.includes("TIMEOUT")||l.includes("OPERATION_TIME_LIMIT")});for(const h of Object.keys(r))!s.has(h)&&!t.errors[h]&&(a[h]=d||"TIMEOUT или OPERATION_TIME_LIMIT: запрос не был обработан")}return a},Et=new WeakSet,pe=function(t){if(!t)return[];let e=[];return Array.isArray(t)?e=t.map(r=>typeof r=="string"?{placement:r}:r):typeof t=="string"?e=[{placement:t}]:e=[t],e},Qt=new WeakSet,je=function(t){return this.placeData?this.placeData.filter(e=>!(e.placement==="PAGE_BACKGROUND_WORKER"||!e.handler||e.handler.includes(t))):[]};const Ne="szdl-utils-kit|";function ze(){if(typeof sessionStorage>"u")return`ephemeral-${Date.now()}-${Math.random().toString(16).slice(2)}`;let m=sessionStorage.getItem("szdl-cross-tab-instance-id");return m||(m=`${Date.now()}-${Math.random().toString(16).slice(2)}`,sessionStorage.setItem("szdl-cross-tab-instance-id",m)),m}function Qe(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}const le=new Map;function Ze(m="default"){if(typeof BroadcastChannel>"u")return null;const t=`${Ne}bc:${m}`;return le.has(t)||le.set(t,new BroadcastChannel(t)),le.get(t)}function Re(m,t){const e=Ze(m);if(e)try{const r=t&&typeof t=="object"&&!Array.isArray(t)?t:{data:t};e.postMessage({...r,tabId:ze(),ts:Date.now()})}catch{}}async function Ve(m,t,e={}){const{ifAvailable:r=!1}=e,i=typeof m=="string"&&m.length>0?m:"default",a=`${Ne}${i}`;return Qe()?navigator.locks.request(a,{mode:"exclusive",ifAvailable:!!r},async c=>{if(r&&c==null)return{skipped:!0,coordination:"locks"};Re(i,{type:"lock-acquired",resource:i});try{return{skipped:!1,result:await t(),coordination:"locks"}}finally{Re(i,{type:"lock-released",resource:i})}}):{skipped:!1,result:await t(),coordination:"none"}}const z={startDelayMs:0,pollIntervalMs:60*1e3,pollIntervalJitterMs:30*1e3,leaderConfirmDelayMs:60*1e3,activeMaxPauseMs:3*60*1e3,quickCleanupThresholdMs:5*60*1e3,leaderHeartbeatMs:null};function $e(m){return m==null?"user":m==="user"||m==="portal"?m:(console.warn(`BackgroundWorker: coordinationScope должен быть 'user' или 'portal', получено ${JSON.stringify(m)} — используется 'user'`),"user")}function Ee(m={}){const t={...z,...m};for(const e of Object.keys(z)){if(e==="leaderHeartbeatMs"){const i=m==null?void 0:m.leaderHeartbeatMs;if(i==null){t.leaderHeartbeatMs=null;continue}const a=Number(i);t.leaderHeartbeatMs=Number.isFinite(a)&&a>=0?a:null;continue}const r=Number(t[e]);t[e]=Number.isFinite(r)&&r>=0?r:z[e]}return t}class tn{constructor(t){R(this,Zt);R(this,Tt);R(this,lt);R(this,Vt);D(this,"entityName","tabs");D(this,"maxTabs",20);D(this,"tabList",[]);D(this,"id",0);D(this,"hasStarted",!1);D(this,"heartbeat");D(this,"runHeartbeat");D(this,"startDelay",0);D(this,"activeMaxPause",z.activeMaxPauseMs);D(this,"quickCleanupThreshold",z.quickCleanupThresholdMs);D(this,"pollInterval",z.pollIntervalMs);D(this,"pollIntervalBase",z.pollIntervalMs);D(this,"pollIntervalJitter",z.pollIntervalJitterMs);D(this,"leaderConfirmDelay",z.leaderConfirmDelayMs);D(this,"leaderHeartbeatMs",null);D(this,"sessionId",`${Date.now()}-${Math.random().toString(16).slice(2)}`);D(this,"continueCondition");D(this,"defaultContinueBackground",()=>!0);D(this,"coordinationScope","user");D(this,"bindGeneralPlacement",!0);D(this,"ensureAdminPlacementsBeforeAppInit");var d,h,l;if(!t){console.error("BackgroundWorker: Нет опций конструктора");return}const{appFunc:e,bx:r,users:i,continueBackground:a,timing:c,coordinationScope:A,bindGeneralPlacement:f,ensureAdminPlacementsBeforeAppInit:s}=t;this.bx=r,this.appInit=e,this.users=i,this.coordinationScope=$e(A),this.bindGeneralPlacement=f!==!1,this.ensureAdminPlacementsBeforeAppInit=s,_(this,Zt,Ge).call(this,c),se(r),this.appPath=_(this,Tt,ye).call(this,((d=r==null?void 0:r.appConst)==null?void 0:d.pathApp)??""),this.appName=((h=r==null?void 0:r.appConst)==null?void 0:h.appName)??"",this.appCodeName=((l=r==null?void 0:r.appConst)==null?void 0:l.appCodeName)??"",this.start=new Date,this.continueCondition=typeof a=="function"?a:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("BackgroundWorker: appInit не передан");return}if(!this.bx){console.error("BackgroundWorker: bx не передан");return}if(this.isAppPage()){console.log("BackgroundWorker: Страница приложения, фоновый воркер не запускается");return}await this.checkPlacementType()&&await this.continueBackground()&&(await this.checkEntity(),await this.refreshTabs(!0),await this.ensureTabRegistered(),this.startDelay>0&&(console.log(`BackgroundWorker: старт отложен на ${this.startDelay} мс`),await this.pause(this.startDelay)),this.heartbeat=setInterval(()=>{this.backgroundTick().catch(e=>{console.error("BackgroundWorker: backgroundTick failed",e)})},this.pollInterval),await this.backgroundTick())}async backgroundTick(){if(!await this.continueBackground()){this.stopTimers(),console.log("BackgroundWorker: Остановка backgroundTick - условие не выполнено");return}await this.refreshTabs(!0),await this.ensureTabRegistered();const e=this.selectLeaderId(),r=e&&+this.id==+e;await this.updateTabState(r),r&&!this.hasStarted&&await this.runAsLeader()}stopTimers(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=void 0),this.runHeartbeat&&(clearInterval(this.runHeartbeat),this.runHeartbeat=void 0)}isAppPage(){var t;if(typeof BX24>"u"||!((t=BX24.placement)!=null&&t.info))return!1;try{const e=BX24.placement.info(),r=e==null?void 0:e.placement,i=(e==null?void 0:e.options)||{},a=(i==null?void 0:i.URI)||"",c=r==="PAGE_BACKGROUND_WORKER"||(i==null?void 0:i.ID)==="PAGE_BACKGROUND_WORKER",A=typeof a=="string"&&(a.includes("marketplace/app")||a.includes("marketplace/apps")||a.includes("placement")||a.includes("sozdavatel"+this.appCodeName));return!c||A}catch{return!1}}async checkEntity(){var r;const t=await this.safeCall(()=>this.bx.call({method:"entity.get"}));((r=t==null?void 0:t.find)==null?void 0:r.call(t,i=>i.ENTITY===this.entityName))||await this.safeCall(()=>this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}}))}async getTabs(){const t=_(this,lt,Lt).call(this),e=await this.safeCall(()=>this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:t},SORT:{DATE_CREATE:"DESC"}}}));return!Array.isArray(e)||!e.length?[]:e.map(r=>{if(!r)return{id:void 0,data:void 0};try{const i=JSON.parse(r.DETAIL_TEXT);return{id:+r.ID||0,data:i}}catch(i){return console.log("BackgroundWorker: parse tab error",i),{id:+r.ID||0,data:void 0}}})}async ensureTabRegistered(){var r,i;if(this.id)return+this.id||0;if(this.tabList.length>=this.maxTabs&&await this.refreshTabs(!0,this.quickCleanupThreshold),this.tabList.length>=this.maxTabs)return console.log("BackgroundWorker: Достигнут лимит вкладок даже после быстрой очистки, не регистрируемся"),0;const t={lastActive:new Date().toISOString(),createdAt:new Date().toISOString(),start:!1,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID},e=await this.safeCall(()=>this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:_(this,lt,Lt).call(this),DETAIL_TEXT:JSON.stringify(t)}}))||0;return this.id=+e||0,this.id}async updateTabState(t){var r,i;if(!this.id)return;const e={lastActive:new Date().toISOString(),createdAt:this.start.toISOString(),start:t,sessionId:this.sessionId,userId:(i=(r=this.bx)==null?void 0:r.userInfo)==null?void 0:i.ID};await this.safeCall(()=>this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:_(this,lt,Lt).call(this),DETAIL_TEXT:JSON.stringify(e)}}))}async deleteTabs(t=[]){if(!t.length)return;const e=t.map(r=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:r.id}}));await this.safeCall(()=>this.bx.batch(e))}async checkPlacementType(){var t,e;try{if(!((t=this.bx)!=null&&t.isAdmin))return!0;const r=await this.safeCall(()=>this.bx.getPlacement());if(!r||!Array.isArray(r))return console.log("BackgroundWorker: Не получили список размещений, продолжаем"),!0;const i=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0),a=this.isIndividualPlacement(typeof window<"u"?window.location.href:""),c=!a;if(!i)return!0;let A=!1;for(const f of r){if(f.placement!=="PAGE_BACKGROUND_WORKER"||!(f.userId||f.handler&&f.handler.includes("USER_ID=")))continue;const d=f.userId||(f.handler?this.extractUserIdFromHandler(f.handler):null);if(d&&+d===i){A=!0;break}}return a?(console.log("BackgroundWorker: Индивидуальная встройка - разрешено"),!0):c&&A?(console.log("BackgroundWorker: Есть личная встройка, общую не запускаем"),!1):(console.log("BackgroundWorker: Проверка типа встройки пройдена, продолжаем"),!0)}catch(r){return console.error("BackgroundWorker: Ошибка при проверке типа встройки",r),!0}}isIndividualPlacement(t){return!t||typeof t!="string"?!1:t.includes("USER_ID=")}extractUserIdFromHandler(t){if(!t||typeof t!="string")return null;const e=t.match(/USER_ID=(\d+)/);return e?+e[1]:null}async continueBackground(){try{const e=!!await Promise.resolve(this.continueCondition(this));return console.log(e?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: continueBackground вернул false"),e}catch(t){return console.error("BackgroundWorker: Ошибка в continueCondition",t),!1}}async refreshTabs(t=!1,e=this.activeMaxPause){const r=[],i=[],a=Date.now(),c=await this.getTabs();for(const A of c){if(!(A!=null&&A.data)){r.push(A);continue}if(a-new Date(A.data.lastActive||0).getTime()>e){r.push(A);continue}i.push(A)}return t&&r.length&&await this.deleteTabs(r),this.tabList=i,i}selectLeaderId(){var e;return this.tabList.length&&+((e=[...this.tabList].sort((r,i)=>{var A,f,s,d;const a=new Date(((A=r.data)==null?void 0:A.createdAt)||((f=r.data)==null?void 0:f.lastActive)||0).getTime(),c=new Date(((s=i.data)==null?void 0:s.createdAt)||((d=i.data)==null?void 0:d.lastActive)||0).getTime();return a===c?(+r.id||0)-(+i.id||0):a-c})[0])==null?void 0:e.id)||0}async confirmLeaderAfterLock(){await this.refreshTabs(!0);const t=this.selectLeaderId();return!!(t&&+this.id==+t)}async runAsLeader(){const t=_(this,Vt,Xe).call(this);(await Ve(t,async()=>{if(await this.updateTabState(!0),console.log(`BackgroundWorker: захват лидерства, пауза ${this.leaderConfirmDelay} мс перед запуском`),await this.pause(this.leaderConfirmDelay),!await this.confirmLeaderAfterLock()){console.log("BackgroundWorker: запуск отменён — после паузы лидером оказалась другая вкладка"),await this.updateTabState(!1);return}this.hasStarted=!0;const i=this.leaderHeartbeatMs??Math.min(this.activeMaxPause-1500,Math.max(2500,Math.floor(this.pollInterval/2)));this.runHeartbeat=setInterval(()=>{this.updateTabState(!0).catch(a=>console.error("BackgroundWorker: heartbeat update failed",a))},i);try{await this._ensurePlacementsBeforeAppInitIfNeeded(),await this.appInit()}catch(a){console.error("BackgroundWorker: appInit failed",a)}this.stopTimers(),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)},{ifAvailable:!0})).skipped&&console.log("BackgroundWorker: runAsLeader пропущен — Web Lock у другой вкладки (подтверждение лидерства)")}async _ensurePlacementsBeforeAppInitIfNeeded(){var r;const t=this.ensureAdminPlacementsBeforeAppInit;if(!(!t||!((r=this.bx)!=null&&r.isAdmin)||!(typeof t=="function"?await Promise.resolve(t(this)):t)))try{await this.ensureAdminPlacements()}catch(i){console.error("BackgroundWorker: ensureAdminPlacements before appInit failed",i)}}async setBackgroundWorkerAll(){var O,N,B,S;if(!((O=this.bx)!=null&&O.isAdmin)){console.log("BackgroundWorker: setBackgroundWorkerAll доступен только админам");return}(N=this.users)!=null&&N.length||await this.getEntityData(),se(this.bx);const t=_(this,Tt,ye).call(this,((S=(B=this.bx)==null?void 0:B.appConst)==null?void 0:S.pathApp)??"");if(!t){console.error("BackgroundWorker: setBackgroundWorkerAll — нет валидного pathApp, привязка PAGE_BACKGROUND_WORKER пропущена");return}const e=await this.safeCall(()=>this.bx.getPlacement()),r=new Map,i=new Map;let a=null;(e||[]).forEach(g=>{if(g.placement!=="PAGE_BACKGROUND_WORKER")return;if(g.userId||g.handler&&g.handler.includes("USER_ID=")){const M=g.userId||(g.handler?this.extractUserIdFromHandler(g.handler):null);if(M){const x=+M;r.set(x,g),i.has(x)||i.set(x,[]),i.get(x).push(g)}}else a=g});const c=await this.resolveAdmins(),A=await this.getEligibleUsersForBackgroundWorker(c);A.sort((g,w)=>{const M=g.LAST_LOGIN?new Date(g.LAST_LOGIN):new Date(0);return(w.LAST_LOGIN?new Date(w.LAST_LOGIN):new Date(0))-M});const f=10,s=A.slice(0,f),d=s.filter(g=>{const w=r.get(+g.ID);if(!w)return!0;const M=`${t}?USER_ID=${g.ID}/`;return w.handler!==M}),h=[];for(const[g]of r){const w=+g||0;A.find(x=>+x.ID===w)||h.push(w)}for(const g of s){const w=r.get(+g.ID);if(!w)continue;const M=`${t}?USER_ID=${g.ID}/`;w.handler!==M&&h.push(+g.ID)}const l=[],u=[...new Set(h)];for(const g of u){const w=i.get(+g)||[];for(const M of w)M!=null&&M.handler&&l.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:M.handler}})}const p=a&&(!this.bindGeneralPlacement||d.length>0||a.handler!==`${t}`);p&&l.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:a.handler||`${t}`}});for(const g of d)l.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${t}?USER_ID=${g.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${t}?USER_ID=${g.ID}/`},USER_ID:g.ID}});this.bindGeneralPlacement&&(!a||p)&&l.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${t}`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${t}`}}}),l.length?await this.safeCall(()=>this.bx.batch(Object.fromEntries(l.map((g,w)=>[`placement_${w}`,g])))):console.log("setBackgroundWorkerAll: Нет операций")}async resolveAdmins(){var t,e;try{const r=+(((t=this.bx.userInfo)==null?void 0:t.ID)??0),i=!!((e=this.bx)!=null&&e.isAdmin),a=await this.getAdminsList()||[];if(!i){if(r&&a.includes(+r)){const f=a.filter(s=>+s!=+r);return await this.saveAdminsList(f),f}return a}const c=new Set([...a||[]]);r&&c.add(+r);const A=[...c].filter(Boolean);return await this.saveAdminsList(A),A}catch(r){return console.error("BackgroundWorker: resolveAdmins error",r),[]}}async getEligibleUsersForBackgroundWorker(t=[]){const e=(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0),r=t.map(i=>+i||0).filter(Boolean);return e.filter(i=>r.includes(+i.ID||0))}async saveAdminsList(t=[]){try{BX24.appOption.set("adminsList",JSON.stringify(t))}catch(e){console.error("BackgroundWorker: saveAdminsList error",e)}}async getAdminsList(){try{const t=BX24.appOption.get("adminsList"),e=t?JSON.parse(t):[];return Array.isArray(e)?e.map(r=>+r||0).filter(Boolean):[]}catch(t){return console.error("BackgroundWorker: getAdminsList error",t),[]}}async getEntityData(){const t={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:e}=await this.safeCall(()=>this.bx.batch(t).then(r=>r?(Array.isArray(r.users)||(r.users=[]),r):{users:[]}));this.users=e}async ensureAdminPlacements(){var t,e;(t=this.bx)!=null&&t.isAdmin&&((e=this.users)!=null&&e.length||await this.getEntityData(),await this.setBackgroundWorkerAll())}pause(t=500,e){return new Promise(r=>{setTimeout(()=>{e&&e(),r(!0)},t)})}async safeCall(t){try{return await t()}catch(e){console.error("BackgroundWorker: safeCall error",e);return}}}Zt=new WeakSet,Ge=function(t){const e=Ee(t);this.startDelay=e.startDelayMs,this.leaderConfirmDelay=e.leaderConfirmDelayMs,this.activeMaxPause=e.activeMaxPauseMs,this.quickCleanupThreshold=e.quickCleanupThresholdMs,this.pollIntervalBase=e.pollIntervalMs,this.pollIntervalJitter=e.pollIntervalJitterMs,this.pollInterval=e.pollIntervalMs+(e.pollIntervalJitterMs>0?Math.floor(Math.random()*e.pollIntervalJitterMs):0),this.leaderHeartbeatMs=e.leaderHeartbeatMs;const r=e.pollIntervalMs+e.pollIntervalJitterMs+e.leaderConfirmDelayMs;e.activeMaxPauseMs<r&&console.warn(`BackgroundWorker: activeMaxPauseMs (${e.activeMaxPauseMs}) меньше poll+jitter+leaderConfirm (${r}) — «живые» вкладки могут удаляться раньше следующего тика`)},Tt=new WeakSet,ye=function(t){if(!t||typeof t!="string")return"";const e=ie(t).replace(/\/+$/,"");return e?be(e)?(console.error("BackgroundWorker: pathApp не должен указывать на /marketplace/app/… Откройте приложение во встроенном iframe (entry CDN), не в оболочке маркетплейса."),""):e:""},lt=new WeakSet,Lt=function(){var t,e;return this.coordinationScope==="portal"?`${this.appCodeName||"app"}:portal`:String(((e=(t=this.bx)==null?void 0:t.userInfo)==null?void 0:e.ID)??"")},Vt=new WeakSet,Xe=function(){return`background-worker:${this.entityName}:${_(this,lt,Lt).call(this)}`};const en=Object.freeze(Object.defineProperty({__proto__:null,default:`;(function(){
3
+
4
+ 'use strict';
5
+
6
+ window.BX24 = {};
7
+
8
+ /***************** private properties ******************/
9
+ var
10
+ isInit = false,
11
+ initList = [],
12
+ installList = [],
13
+
14
+ /* ready props */
15
+ isReady = false,
16
+ readyList = [],
17
+
18
+ /* list of registered proxy functions */
19
+ proxySalt = Math.random(),
20
+ proxyId = 1,
21
+ proxyList = [],
22
+ proxyContext = null,
23
+
24
+ /* list of registered event handlers */
25
+ eventsList = [],
26
+
27
+ /* chars list for string id generator */
28
+ charsList = '0123456789abcdefghijklmnopqrstuvwxyz';
29
+
30
+ /*************** public section ***********************/
31
+
32
+ BX24.init = function(callback)
33
+ {
34
+ if(!!callback)
35
+ {
36
+ initList.push(callback);
37
+ }
38
+ };
39
+
40
+ BX24.install = function(callback)
41
+ {
42
+ if(!!callback)
43
+ {
44
+ installList.push(callback);
45
+ }
46
+ };
47
+
48
+ BX24.installFinish = function()
49
+ {
50
+ sendMessage('setInstallFinish',{});
51
+ };
52
+
53
+ BX24.callMethod = function(method, params, callback)
54
+ {
55
+ return ajax({
56
+ method: method,
57
+ data: params,
58
+ callback: callback
59
+ });
60
+ };
61
+
62
+ /*
63
+ calls = [[method,params],[method,params]];
64
+ calls = [{method:method,params:params},[method,params]];
65
+ calls = {call_id:[method,params],...};
66
+ */
67
+ BX24.callBatch = function(calls, callback, bHaltOnError)
68
+ {
69
+ var cmd = util.type.isArray(calls) ? [] : {}, cnt = 0, cb = function(cmd){
70
+ ajax.batch(cmd, callback, bHaltOnError);
71
+ };
72
+
73
+ for(var i in calls)
74
+ {
75
+ var method = null, params = null;
76
+
77
+ if(!!calls[i] && calls.hasOwnProperty(i))
78
+ {
79
+ if(util.type.isArray(calls[i]))
80
+ {
81
+ method = calls[i][0]; params = calls[i][1];
82
+ }
83
+ else if (!!calls[i].method)
84
+ {
85
+ method = calls[i].method; params = calls[i].params;
86
+ }
87
+
88
+ if(!!method)
89
+ {
90
+ cnt++;
91
+ cmd[i] = [method,params];
92
+ }
93
+ }
94
+ }
95
+
96
+ if(cnt > 0)
97
+ {
98
+ var e = function(i)
99
+ {
100
+ return function(str)
101
+ {
102
+ cmd[i] = cmd[i][0]+'?'+str;
103
+ if(--cnt <= 0)
104
+ cb(cmd);
105
+ }
106
+ }
107
+
108
+ for(var i in cmd)
109
+ {
110
+ ajax.prepareData(cmd[i][1], '', e(i));
111
+ }
112
+ }
113
+
114
+ return;
115
+ };
116
+
117
+ BX24.callBind = function(event, handler, auth_type, callback)
118
+ {
119
+ if(!isInit)
120
+ {
121
+ var _a = arguments;
122
+ BX24.init(function(){
123
+ BX24.callBind.apply(document,_a);
124
+ });
125
+ }
126
+ else if(BX24.isAdmin())
127
+ {
128
+ var p = {
129
+ event: event||'',
130
+ handler: handler||'',
131
+ auth_type: (typeof auth_type == 'undefined') ? 0 : auth_type
132
+ };
133
+
134
+ return BX24.callMethod('event.bind', p, callback);
135
+ }
136
+
137
+ return false;
138
+ };
139
+
140
+ BX24.callUnBind =
141
+ BX24.callUnbind = function(event, handler, auth_type, callback)
142
+ {
143
+ if(!isInit)
144
+ {
145
+ var _a = arguments;
146
+ BX24.init(function(){
147
+ BX24.callUnBind.apply(document,_a);
148
+ });
149
+ }
150
+ else if(BX24.isAdmin())
151
+ {
152
+ var p = {
153
+ event: event||'',
154
+ handler: handler||''
155
+ };
156
+
157
+ if(typeof auth_type != 'undefined' && auth_type !== null)
158
+ {
159
+ p.auth_type = auth_type;
160
+ }
161
+
162
+ return BX24.callMethod('event.unbind', p, callback);
163
+ }
164
+
165
+ return false;
166
+ };
167
+
168
+ BX24.canUse = function(method)
169
+ {
170
+ switch(method)
171
+ {
172
+ case 'upload':
173
+ return fileReader.canUse();
174
+ default:
175
+ return true;
176
+ }
177
+ };
178
+
179
+ BX24.isAdmin = function()
180
+ {
181
+ return !!PARAMS.IS_ADMIN;
182
+ };
183
+
184
+ BX24.getAuth = function()
185
+ {
186
+ return (isInit && PARAMS.AUTH_EXPIRES > (new Date()).valueOf())
187
+ ? {access_token: PARAMS.AUTH_ID, refresh_token: PARAMS.REFRESH_ID, expires_in: PARAMS.AUTH_EXPIRES, domain: PARAMS.DOMAIN, member_id: PARAMS.MEMBER_ID}
188
+ : false;
189
+ };
190
+
191
+ BX24.getLang = function()
192
+ {
193
+ return PARAMS.LANG;
194
+ };
195
+
196
+ BX24.getDomain = function()
197
+ {
198
+ return PARAMS.DOMAIN;
199
+ };
200
+
201
+ BX24.refreshAuth = function(cb)
202
+ {
203
+ if(isInit)
204
+ {
205
+ sendMessage('refreshAuth', {}, function(p){
206
+ PARAMS.AUTH_ID = p.AUTH_ID;
207
+ PARAMS.REFRESH_ID = p.REFRESH_ID;
208
+ PARAMS.AUTH_EXPIRES = (new Date()).valueOf()+p.AUTH_EXPIRES*1000;
209
+ if(!!cb)
210
+ {
211
+ cb(BX24.getAuth());
212
+ }
213
+ });
214
+ }
215
+ };
216
+
217
+ BX24.resizeWindow = function(width, height, cb)
218
+ {
219
+ width = parseInt(width); height = parseInt(height);
220
+ if(width > 0 && height > 0)
221
+ {
222
+ sendMessage('resizeWindow', {width:width,height:height}, cb);
223
+ }
224
+ };
225
+
226
+ BX24.fitWindow = function(cb)
227
+ {
228
+ sendMessage('resizeWindow', {
229
+ width:'100%', height:BX24.getScrollSize().scrollHeight
230
+ }, cb);
231
+ };
232
+
233
+ BX24.reloadWindow = function(cb)
234
+ {
235
+ sendMessage('reloadWindow', {}, cb);
236
+ };
237
+
238
+ BX24.setTitle = function(title, cb)
239
+ {
240
+ sendMessage('setTitle', {title:title.toString()}, cb);
241
+ };
242
+
243
+ BX24.scrollParentWindow = function(scroll, cb)
244
+ {
245
+ scroll = parseInt(scroll);
246
+ if(!isNaN(scroll))
247
+ {
248
+ sendMessage('setScroll', {scroll:scroll}, cb);
249
+ }
250
+ };
251
+
252
+ BX24.isReady = function()
253
+ {
254
+ return !!isReady;
255
+ };
256
+
257
+ BX24.ready = function(handler)
258
+ {
259
+ if (util.type.isFunction(handler))
260
+ {
261
+ readyList.push(handler);
262
+ }
263
+ };
264
+
265
+ BX24.proxy = function(func, thisObject)
266
+ {
267
+ if (!func || !thisObject)
268
+ return func;
269
+
270
+ util.initObjectProxy(thisObject)
271
+
272
+ if (typeof func['__proxy_id_' + proxySalt] == 'undefined')
273
+ func['__proxy_id_' + proxySalt] = proxyId++;
274
+
275
+ if (!proxyList[thisObject['__proxy_id_' + proxySalt]][func['__proxy_id_' + proxySalt]])
276
+ proxyList[thisObject['__proxy_id_' + proxySalt]][func['__proxy_id_' + proxySalt]] = util.delegate(func, thisObject);
277
+
278
+ return proxyList[thisObject['__proxy_id_' + proxySalt]][func['__proxy_id_' + proxySalt]];
279
+ };
280
+
281
+ BX24.proxyContext = function()
282
+ {
283
+ return proxyContext;
284
+ };
285
+
286
+ BX24.bind = function(el, evname, func)
287
+ {
288
+ if (!el)
289
+ return;
290
+
291
+ if (evname === 'mousewheel')
292
+ {
293
+ BX24.bind(el, 'DOMMouseScroll', func);
294
+ }
295
+ else if (evname === 'transitionend')
296
+ {
297
+ BX24.bind(el, 'webkitTransitionEnd', func);
298
+ BX24.bind(el, 'msTransitionEnd', func);
299
+ BX24.bind(el, 'oTransitionEnd', func);
300
+ // IE8-9 doesn't support this feature!
301
+ }
302
+
303
+ if (el.addEventListener)
304
+ el.addEventListener(evname, func, false);
305
+ else if(el.attachEvent) // IE
306
+ el.attachEvent("on" + evname, BX24.proxy(func, el));
307
+ else
308
+ el["on" + evname] = func;
309
+
310
+ eventsList[eventsList.length] = {'element': el, 'event': evname, 'fn': func};
311
+
312
+ };
313
+
314
+ BX24.unbind = function(el, evname, func)
315
+ {
316
+ if (!el)
317
+ return;
318
+
319
+ if (evname === 'mousewheel')
320
+ BX24.unbind(el, 'DOMMouseScroll', func);
321
+
322
+ if(el.removeEventListener) // Gecko / W3C
323
+ el.removeEventListener(evname, func, false);
324
+ else if(el.detachEvent) // IE
325
+ el.detachEvent("on" + evname, BX24.proxy(func, el));
326
+ else
327
+ el["on" + evname] = null;
328
+ };
329
+
330
+ BX24.getScrollSize = function()
331
+ {
332
+ return {
333
+ scrollWidth: Math.max(document.documentElement.scrollWidth, document.documentElement.offsetWidth),
334
+ scrollHeight: Math.max(document.documentElement.scrollHeight, document.documentElement.offsetHeight)
335
+ };
336
+ };
337
+
338
+ BX24.selectAccess = function(title, value, cb)
339
+ {
340
+ if(!util.type.isString(title))
341
+ {
342
+ cb = value; value = title;
343
+ }
344
+
345
+ if(util.type.isFunction(value))
346
+ {
347
+ cb = value; value = [];
348
+ }
349
+
350
+ sendMessage('selectAccess', {value:value}, cb);
351
+ };
352
+
353
+ BX24.selectUser = function(title, cb)
354
+ {
355
+ if(util.type.isFunction(title))
356
+ {
357
+ cb = title; title = '';
358
+ }
359
+
360
+ sendMessage('selectUser', {title: title, mult:false}, cb);
361
+ };
362
+
363
+ BX24.selectUsers = function(title, cb)
364
+ {
365
+ if(util.type.isFunction(title))
366
+ {
367
+ cb = title; title = '';
368
+ }
369
+
370
+ sendMessage('selectUser', {title: title, mult:true}, cb);
371
+ };
372
+
373
+ BX24.selectCRM = function(params, cb)
374
+ {
375
+ if(util.type.isFunction(params))
376
+ {
377
+ cb = params;
378
+ params = {};
379
+ }
380
+
381
+ sendMessage('selectCRM', {
382
+ entityType: params.entityType,
383
+ multiple: params.multiple,
384
+ value: params.value,
385
+ }, cb);
386
+ };
387
+
388
+ BX24.openApplication = function(params, cb, settings)
389
+ {
390
+ if(util.type.isFunction(params))
391
+ {
392
+ cb = params;
393
+ params = {};
394
+ }
395
+
396
+ if(util.type.isObject(settings))
397
+ {
398
+ for (var item in settings)
399
+ {
400
+ params["bx24_" + item] = settings[item];
401
+ }
402
+ }
403
+
404
+ sendMessage('openApplication', params, cb);
405
+ };
406
+
407
+ BX24.openPath = function(path, cb)
408
+ {
409
+ sendMessage(
410
+ 'openPath',
411
+ {
412
+ path: path
413
+ },
414
+ cb
415
+ );
416
+ };
417
+
418
+ BX24.closeApplication = function(cb)
419
+ {
420
+ sendMessage('closeApplication', cb);
421
+ };
422
+
423
+ BX24.im = {
424
+ callTo: function(userId, video)
425
+ {
426
+ sendMessage('imCallTo', {userId: userId, video: video});
427
+ },
428
+ phoneTo: function(phone)
429
+ {
430
+ sendMessage('imPhoneTo', {phone: phone});
431
+ },
432
+ openMessenger: function(dialogId)
433
+ {
434
+ sendMessage('imOpenMessenger', {dialogId: dialogId});
435
+ },
436
+ openHistory: function(dialogId)
437
+ {
438
+ sendMessage('imOpenHistory', {dialogId: dialogId});
439
+ }
440
+ };
441
+
442
+ BX24.placement = {
443
+
444
+ info: function()
445
+ {
446
+ return {
447
+ placement: PARAMS.PLACEMENT,
448
+ options: PARAMS.PLACEMENT_OPTIONS
449
+ }
450
+ },
451
+
452
+ getInterface: function(cb)
453
+ {
454
+ sendMessage('getInterface', cb);
455
+ },
456
+
457
+ call: function(cmd, params, cb)
458
+ {
459
+ if(!!BX24[cmd])
460
+ {
461
+ return;
462
+ }
463
+ else
464
+ {
465
+ if(util.type.isFunction(params))
466
+ {
467
+ cb = params;
468
+ params = {};
469
+ }
470
+
471
+ sendMessage(cmd, params, cb);
472
+ }
473
+ },
474
+
475
+ bindEvent: function(eventName, cb)
476
+ {
477
+ sendMessage('placementBindEvent', {event: eventName}, cb);
478
+ }
479
+ };
480
+
481
+ BX24.loadScript = function(script, callback)
482
+ {
483
+ if (!isReady)
484
+ {
485
+ var _args = arguments;
486
+ BX24.ready(function() {
487
+ BX24.loadScript.apply(this, _args);
488
+ });
489
+ return;
490
+ }
491
+
492
+ if (util.type.isString(script))
493
+ script = [script];
494
+ var _callback = function()
495
+ {
496
+ return (callback && util.type.isFunction(callback)) ? callback() : null
497
+ }
498
+ var load_js = function(ind)
499
+ {
500
+ if(ind >= script.length)
501
+ return _callback();
502
+
503
+ if(!!script[ind])
504
+ {
505
+ var oHead = document.getElementsByTagName("HEAD")[0] || document.documentElement;
506
+ var oScript = document.createElement('SCRIPT');
507
+ oScript.setAttribute('charset', 'UTF-8');
508
+
509
+ oScript.src = script[ind];
510
+
511
+ var bLoaded = false;
512
+ oScript.onload = oScript.onreadystatechange = function()
513
+ {
514
+ if (!bLoaded && (!oScript.readyState || oScript.readyState == "loaded" || oScript.readyState == "complete"))
515
+ {
516
+ bLoaded = true;
517
+ setTimeout(function (){load_js(++ind);}, 50);
518
+
519
+ oScript.onload = oScript.onreadystatechange = null;
520
+ if (oHead && oScript.parentNode)
521
+ {
522
+ oHead.removeChild(oScript);
523
+ }
524
+ }
525
+ }
526
+
527
+ return oHead.insertBefore(oScript, oHead.firstChild);
528
+ }
529
+ else
530
+ {
531
+ load_js(++ind);
532
+ }
533
+ }
534
+
535
+ load_js(0);
536
+ };
537
+
538
+ BX24.userOption = BX24.appOption = {
539
+ get:function(){},set:function(){}
540
+ };
541
+
542
+ BX24.init(function(){
543
+ BX24.userOption = {
544
+ get: function(name)
545
+ {
546
+ return PARAMS.USER_OPTIONS[name];
547
+ },
548
+ set: function(name, value)
549
+ {
550
+ PARAMS.USER_OPTIONS[name] = value;
551
+ sendMessage('setUserOption', {name:name,value:value});
552
+ }
553
+ };
554
+
555
+ BX24.appOption = {
556
+ get: function(name)
557
+ {
558
+ return PARAMS.APP_OPTIONS[name];
559
+ },
560
+ set: BX24.isAdmin() ? function(name,value,cb)
561
+ {
562
+ PARAMS.APP_OPTIONS[name] = value;
563
+ sendMessage('setAppOption', {name:name,value:value}, cb);
564
+ } : util.blank
565
+ };
566
+ });
567
+ /*************** private section ***********************/
568
+
569
+ // utility
570
+ var util = {
571
+ blank: function(){},
572
+ init: function()
573
+ {
574
+ var f = function(data)
575
+ {
576
+ if(!PARAMS.DOMAIN)
577
+ PARAMS.DOMAIN = data.DOMAIN;
578
+ if(!PARAMS.PATH)
579
+ PARAMS.PATH = data.PATH;
580
+ if(!PARAMS.LANG)
581
+ PARAMS.LANG = data.LANG;
582
+ if(!PARAMS.PLACEMENT)
583
+ PARAMS.PLACEMENT = data.PLACEMENT;
584
+
585
+ PARAMS.PROTOCOL = data.PROTOCOL;
586
+ PARAMS.DOMAIN = PARAMS.DOMAIN.replace(/\\:(80|443)$/, '');
587
+
588
+ if(!!data.AUTH_ID)
589
+ {
590
+ PARAMS.AUTH_ID = data.AUTH_ID;
591
+ PARAMS.REFRESH_ID = data.REFRESH_ID;
592
+ PARAMS.AUTH_EXPIRES = (new Date()).valueOf()+data.AUTH_EXPIRES*1000;
593
+ PARAMS.IS_ADMIN = !!data.IS_ADMIN;
594
+ PARAMS.MEMBER_ID = data.MEMBER_ID||'';
595
+ }
596
+
597
+ if(!PARAMS.USER_OPTIONS)
598
+ PARAMS.USER_OPTIONS = data.USER_OPTIONS;
599
+
600
+ if(!PARAMS.APP_OPTIONS)
601
+ PARAMS.APP_OPTIONS = data.APP_OPTIONS;
602
+
603
+ if(!PARAMS.PLACEMENT_OPTIONS)
604
+ PARAMS.PLACEMENT_OPTIONS = data.PLACEMENT_OPTIONS;
605
+
606
+ isInit = true;
607
+
608
+ var doInit = function()
609
+ {
610
+ BX24.init = function(fn)
611
+ {
612
+ util.defer(fn).call(document);
613
+ }
614
+
615
+ if(!data.INSTALL)
616
+ {
617
+ BX24.installFinish = util.blank;
618
+ }
619
+
620
+ var fn, i = 0;
621
+ while (initList && (fn = initList[i++]))
622
+ {
623
+ BX24.init(fn);
624
+ }
625
+ }
626
+
627
+ if(!!data.FIRST_RUN && installList.length > 0)
628
+ {
629
+ util.install(doInit);
630
+ }
631
+ else
632
+ {
633
+ doInit();
634
+ }
635
+ }
636
+
637
+ if(!PARAMS.DOMAIN||!PARAMS.LANG||!PARAMS.AUTH_ID)
638
+ {
639
+ sendMessage('getInitData', f);
640
+ }
641
+ else
642
+ {
643
+ f(PARAMS);
644
+ }
645
+
646
+ util.init = util.blank;
647
+ },
648
+
649
+ install: function(cb)
650
+ {
651
+ var installer = null,
652
+ installFinish = function()
653
+ {
654
+ util.install(cb);
655
+ };
656
+
657
+ installer = installList.shift();
658
+ if(!!installer)
659
+ {
660
+ if(util.type.isFunction(installer))
661
+ {
662
+ try
663
+ {
664
+ BX24.installFinish = installFinish;
665
+ installer.call(document); // no defer!
666
+ }
667
+ catch(e)
668
+ {
669
+ alert('Installation failed!');
670
+ console.log(e);
671
+ }
672
+ }
673
+ else
674
+ {
675
+ BX24.loadScript(installer, function(){
676
+ BX24.installFinish = installFinish;
677
+ });
678
+ }
679
+ }
680
+ else
681
+ {
682
+ BX24.installFinish = util.install = util.blank;
683
+ sendMessage('setInstall', {install:true});
684
+
685
+ util.defer(cb).call(document);
686
+ }
687
+ },
688
+
689
+ ready: function()
690
+ {
691
+ if (document.readyState === "complete")
692
+ {
693
+ return util.runReady();
694
+ }
695
+
696
+ var __readyHandler;
697
+ if (document.addEventListener)
698
+ {
699
+ __readyHandler = function()
700
+ {
701
+ document.removeEventListener("DOMContentLoaded", __readyHandler, false);
702
+ util.runReady();
703
+ }
704
+ document.addEventListener("DOMContentLoaded", __readyHandler, false);
705
+ window.addEventListener("load", util.runReady, false);
706
+ }
707
+ else if (document.attachEvent)
708
+ {
709
+ __readyHandler = function()
710
+ {
711
+ if (document.readyState === "complete")
712
+ {
713
+ document.detachEvent("onreadystatechange", __readyHandler);
714
+ util.runReady();
715
+ }
716
+ }
717
+ document.attachEvent("onreadystatechange", __readyHandler);
718
+ window.attachEvent("onload", util.runReady);
719
+ }
720
+
721
+ util.ready = util.blank;
722
+
723
+ return null;
724
+ },
725
+
726
+ runReady: function()
727
+ {
728
+ if (!isReady)
729
+ {
730
+ if (!document.body)
731
+ return setTimeout(util.runReady, 15);
732
+
733
+ isReady = true;
734
+
735
+ BX24.ready = function(handler)
736
+ {
737
+ if (util.type.isFunction(handler))
738
+ {
739
+ util.defer(handler).call(document);
740
+ }
741
+ };
742
+
743
+ if (readyList && readyList.length > 0)
744
+ {
745
+ var fn, i = 0;
746
+ while (readyList && (fn = readyList[i++]))
747
+ {
748
+ BX24.ready(fn);
749
+ }
750
+
751
+ readyList = null;
752
+ }
753
+ }
754
+
755
+ return null;
756
+ },
757
+
758
+ delegate: function (func, thisObject)
759
+ {
760
+ if (!func || !thisObject)
761
+ return func;
762
+
763
+ return function() {
764
+ var cur = proxyContext;
765
+ proxyContext = this;
766
+ var res = func.apply(thisObject, arguments);
767
+ proxyContext = cur;
768
+ return res;
769
+ }
770
+ },
771
+
772
+ initObjectProxy: function(thisObject)
773
+ {
774
+ if (typeof thisObject['__proxy_id_' + proxySalt] == 'undefined')
775
+ {
776
+ thisObject['__proxy_id_' + proxySalt] = proxyList.length;
777
+ proxyList[thisObject['__proxy_id_' + proxySalt]] = {};
778
+ }
779
+ },
780
+
781
+ defer: function(fn,t)
782
+ {
783
+ return function(){
784
+ var arg = arguments;
785
+ setTimeout(function(){fn.apply(this,arg)}, t||10);
786
+ };
787
+ },
788
+
789
+ split: function(s,ss)
790
+ {
791
+ var r = s.split(ss);
792
+ return [r[0],r.slice(1).join(ss)];
793
+ },
794
+
795
+ clone: function(obj, bCopyObj)
796
+ {
797
+ var _obj, i, l;
798
+ if (bCopyObj !== false)
799
+ bCopyObj = true;
800
+
801
+ if (obj === null)
802
+ return null;
803
+
804
+ if (util.type.isDomNode(obj))
805
+ {
806
+ _obj = obj.cloneNode(bCopyObj);
807
+ }
808
+ else if (typeof obj == 'object')
809
+ {
810
+ if (util.type.isArray(obj))
811
+ {
812
+ _obj = [];
813
+ for (i=0,l=obj.length;i<l;i++)
814
+ {
815
+ if (typeof obj[i] == "object" && bCopyObj)
816
+ _obj[i] = util.clone(obj[i], bCopyObj);
817
+ else
818
+ _obj[i] = obj[i];
819
+ }
820
+ }
821
+ else
822
+ {
823
+ _obj = {};
824
+ if (obj.constructor)
825
+ {
826
+ if (obj.constructor === Date)
827
+ _obj = new Date(obj);
828
+ else
829
+ _obj = new obj.constructor();
830
+ }
831
+
832
+ for (i in obj)
833
+ {
834
+ if (typeof obj[i] == "object" && bCopyObj)
835
+ _obj[i] = util.clone(obj[i], bCopyObj);
836
+ else
837
+ _obj[i] = obj[i];
838
+ }
839
+ }
840
+
841
+ }
842
+ else
843
+ {
844
+ _obj = obj;
845
+ }
846
+
847
+ return _obj;
848
+ },
849
+
850
+ uniqid: function()
851
+ {
852
+ var s = '';
853
+ for (var i = 0; i <32; i++)
854
+ s += charsList[Math.round(Math.random()*(charsList.length-1))];
855
+ return s;
856
+ },
857
+
858
+ // datatype utility
859
+ type: {
860
+ isString: function(item) {
861
+ return item === '' ? true : (item ? (typeof (item) == "string" || item instanceof String) : false);
862
+ },
863
+ isNotEmptyString: function(item) {
864
+ return util.type.isString(item) ? item.length > 0 : false;
865
+ },
866
+ isBoolean: function(item) {
867
+ return item === true || item === false;
868
+ },
869
+ isNumber: function(item) {
870
+ return item === 0 ? true : (item ? (typeof (item) == "number" || item instanceof Number) : false);
871
+ },
872
+ isFunction: function(item) {
873
+ return item === null ? false : (typeof (item) == "function" || item instanceof Function);
874
+ },
875
+ isElementNode: function(item) {
876
+ return item && typeof (item) == "object" && "nodeType" in item && item.nodeType == 1 && item.tagName && item.tagName.toUpperCase() != 'SCRIPT' && item.tagName.toUpperCase() != 'STYLE' && item.tagName.toUpperCase() != 'LINK';
877
+ },
878
+ isDomNode: function(item) {
879
+ return item && typeof (item) == "object" && "nodeType" in item;
880
+ },
881
+ isObject: function(item) {
882
+ return item && (typeof (item) == "object" || item instanceof Object) ? true : false;
883
+ },
884
+ isArray: function(item) {
885
+ return item && Object.prototype.toString.call(item) == "[object Array]";
886
+ },
887
+ isDate : function(item) {
888
+ return item && Object.prototype.toString.call(item) == "[object Date]";
889
+ }
890
+ }
891
+ };
892
+
893
+ // communication with parent frame utility
894
+ var sendMessage = function(cmd, params, cb)
895
+ {
896
+ if(util.type.isFunction(params))
897
+ {
898
+ cb = params; params = null;
899
+ }
900
+
901
+ if (cmd.indexOf(':') >= 0)
902
+ {
903
+ parent.postMessage(
904
+ {
905
+ method: cmd,
906
+ params: !!params ? params : '',
907
+ callback: sendMessage.setCallback(cb),
908
+ appSid: PARAMS.APP_SID
909
+ },
910
+ 'http'+(PARAMS.PROTOCOL?'s':'')+'://' + PARAMS.DOMAIN
911
+ );
912
+ }
913
+ else
914
+ {
915
+ /* TODO: delete after rest 22.0.0 */
916
+ cmd += ':' + (!!params ? JSON.stringify(params) : '')
917
+ + ':' + sendMessage.setCallback(cb)
918
+ + (!!PARAMS.APP_SID ? (':' + PARAMS.APP_SID) : '');
919
+
920
+ parent.postMessage(cmd, 'http'+(PARAMS.PROTOCOL?'s':'')+'://' + PARAMS.DOMAIN);
921
+ }
922
+ };
923
+
924
+ sendMessage.setCallback = function(cb)
925
+ {
926
+ var cbId = '';
927
+ if(!!cb)
928
+ {
929
+ cbId = util.uniqid();
930
+ sendMessage[cbId] = cb;
931
+ }
932
+
933
+ return cbId;
934
+ };
935
+
936
+ sendMessage.runCallback = function(e)
937
+ {
938
+ e = e || window.event;
939
+
940
+ if(e.origin != 'http'+(PARAMS.PROTOCOL?'s':'')+'://'+PARAMS.DOMAIN)
941
+ return;
942
+
943
+ if(!!e.data)
944
+ {
945
+ var cmd = util.split(e.data,':',2),
946
+ args = [];
947
+
948
+ if(!!sendMessage[cmd[0]])
949
+ {
950
+ if(!!cmd[1])
951
+ args = JSON.parse(cmd[1]);
952
+
953
+ sendMessage[cmd[0]].apply(window, [args]);
954
+ }
955
+ }
956
+ };
957
+
958
+ var ajax = function(config)
959
+ {
960
+ RestrictionManager.check(function(){
961
+ ajax.call(config);
962
+ });
963
+ }
964
+
965
+ ajax.call = function(config)
966
+ {
967
+ if(!isInit)
968
+ {
969
+ BX24.init(function(){
970
+ ajax.call(config);
971
+ });
972
+ }
973
+ else if(PARAMS.AUTH_EXPIRES < (new Date()).valueOf())
974
+ {
975
+ ajax.refreshAuth(config);
976
+ }
977
+ else
978
+ {
979
+ var xhr = ajax.xhr(),
980
+ url = 'http'+(PARAMS.PROTOCOL?'s':'')+'://' + PARAMS.DOMAIN + PARAMS.PATH + '/' + ajax.escape(config.method) + '.json';
981
+
982
+ xhr.open('POST', url);
983
+
984
+ var bRequestCompleted = false;
985
+
986
+ // IE fix
987
+ xhr.onprogress = function(){};
988
+ xhr.ontimeout = function(){};
989
+ xhr.timeout = 0;
990
+
991
+ xhr.onload = function()
992
+ {
993
+ if (bRequestCompleted)
994
+ return;
995
+
996
+ xhr.onload = util.blank;
997
+
998
+ var bSuccess = ajax.isSuccess(xhr);
999
+
1000
+ if(bSuccess)
1001
+ {
1002
+ var data = xhr.responseText;
1003
+
1004
+ if(data.length > 0)
1005
+ {
1006
+ try{
1007
+ data = JSON.parse(data);
1008
+ }catch(e){bSuccess = false;}
1009
+ }
1010
+ else
1011
+ {
1012
+ data = {result:{}};
1013
+ }
1014
+ }
1015
+
1016
+ var s = xhr.status;
1017
+
1018
+ xhr = null;
1019
+
1020
+ if(bSuccess)
1021
+ {
1022
+ if(data.error && data.error == 'expired_token')
1023
+ {
1024
+ ajax.refreshAuth(config);
1025
+ }
1026
+ else if(!!config.callback && util.type.isFunction(config.callback))
1027
+ {
1028
+ var res = new ajaxResult(data, config, s);
1029
+ config.callback.apply(window, [res]);
1030
+ }
1031
+ }
1032
+ else
1033
+ {
1034
+ throw('Query error!');
1035
+ }
1036
+ };
1037
+
1038
+ xhr.onerror = function()
1039
+ {
1040
+ throw('Query error!');
1041
+ };
1042
+
1043
+ var query_data = 'auth=' + PARAMS.AUTH_ID;
1044
+
1045
+ if(typeof config.start != 'undefined')
1046
+ {
1047
+ query_data += '&start=' + parseInt(config.start);
1048
+ }
1049
+
1050
+ if(!!config.data)
1051
+ {
1052
+ if(!!config.data['start'])
1053
+ {
1054
+ delete config.data['start'];
1055
+ }
1056
+
1057
+ ajax.prepareData(config.data, '', function(res){
1058
+ query_data += '&' + res;
1059
+ util.defer(xhr.send.bind(xhr))(query_data);
1060
+ });
1061
+ }
1062
+ else
1063
+ {
1064
+ util.defer(xhr.send.bind(xhr))(query_data);
1065
+ }
1066
+
1067
+ return xhr;
1068
+ }
1069
+ };
1070
+
1071
+ ajax.batch = function(calls, callback, bHaltOnError)
1072
+ {
1073
+ return ajax({
1074
+ method: 'batch',
1075
+ data: {halt:!!bHaltOnError?1:0, cmd:calls},
1076
+ callback: function(res, config, status){
1077
+ if(!!callback)
1078
+ {
1079
+ var data = res.data(),
1080
+ result = util.type.isArray(calls) ? [] : {};
1081
+
1082
+ for(var i in calls)
1083
+ {
1084
+ if(!!calls[i] && calls.hasOwnProperty(i))
1085
+ {
1086
+ if(typeof data.result[i] !== 'undefined' || typeof data.result_error[i] !== 'undefined')
1087
+ {
1088
+ if(util.type.isString(calls[i]))
1089
+ {
1090
+ var q = calls[i].split('?');
1091
+ }
1092
+ else
1093
+ {
1094
+ q = [
1095
+ util.type.isArray(calls[i]) ? calls[i][0] : calls[i].method,
1096
+ util.type.isArray(calls[i]) ? calls[i][1] : calls[i].data,
1097
+ ];
1098
+ }
1099
+
1100
+ result[i] = new ajaxResult({
1101
+ result: typeof data.result[i] !== 'undefined' ? data.result[i] : {},
1102
+ error: data.result_error[i]||undefined,
1103
+ total: data.result_total[i],
1104
+ next: data.result_next[i]
1105
+ }, {
1106
+ method: q[0],
1107
+ data:q[1],
1108
+ callback: callback
1109
+ }, res.status);
1110
+ }
1111
+ }
1112
+ }
1113
+
1114
+ callback.apply(window, [result]);
1115
+ }
1116
+ }
1117
+ });
1118
+ };
1119
+
1120
+ ajax.refreshAuth = function(config)
1121
+ {
1122
+ BX24.refreshAuth(function(){
1123
+ ajax(config)
1124
+ });
1125
+ };
1126
+
1127
+ ajax.xhr = function()
1128
+ {
1129
+ if(!!window.XDomainRequest)
1130
+ return new XDomainRequest();
1131
+ else
1132
+ return new XMLHttpRequest();
1133
+ };
1134
+
1135
+ ajax.escape = function(str)
1136
+ {
1137
+ return encodeURIComponent(str);
1138
+ };
1139
+
1140
+ ajax.prepareData = function(arData, prefix, callback)
1141
+ {
1142
+ var data = '', objects = [];
1143
+ if (util.type.isString(arData) || arData == null)
1144
+ {
1145
+ callback.call(document, arData||'');
1146
+ }
1147
+ else
1148
+ {
1149
+ for(var i in arData)
1150
+ {
1151
+ if (!arData.hasOwnProperty(i))
1152
+ {
1153
+ continue;
1154
+ }
1155
+
1156
+ var name = ajax.escape(i);
1157
+
1158
+ if(prefix)
1159
+ name = prefix + '[' + name + ']';
1160
+
1161
+ if(typeof arData[i] == 'object')
1162
+ {
1163
+ objects.push([name,arData[i]]);
1164
+ }
1165
+ else
1166
+ {
1167
+ if (data.length > 0)
1168
+ {
1169
+ data += '&';
1170
+ }
1171
+
1172
+ data += name + '=' + ajax.escape(arData[i])
1173
+ }
1174
+ }
1175
+
1176
+ var cnt = objects.length;
1177
+ if(cnt > 0)
1178
+ {
1179
+ var cb = function(str)
1180
+ {
1181
+ data += (!!str ? '&' : '') + str;
1182
+ if(--cnt <= 0)
1183
+ {
1184
+ callback.call(document, data)
1185
+ }
1186
+ }
1187
+
1188
+ var cnt1 = cnt;
1189
+ for(var i = 0; i < cnt1; i++)
1190
+ {
1191
+ if(util.type.isDomNode(objects[i][1]))
1192
+ {
1193
+ if(objects[i][1].tagName.toUpperCase() == 'INPUT' && objects[i][1].type == 'file')
1194
+ {
1195
+ if(fileReader.canUse())
1196
+ {
1197
+ fileReader(objects[i][1], (function(name){
1198
+ return function(result){
1199
+ if(util.type.isArray(result)&&result.length>0)
1200
+ {
1201
+ cb(name + '[0]=' + ajax.escape(result[0]) + '&' + name + '[1]=' + ajax.escape(result[1]));
1202
+ }
1203
+ else
1204
+ {
1205
+ cb(name+'=');
1206
+ }
1207
+ }
1208
+ })(objects[i][0]));
1209
+ }
1210
+ }
1211
+ else if(typeof objects[i][1].value != 'undefined')
1212
+ {
1213
+ cb(objects[i][0] + '=' + ajax.escape(objects[i][1].value));
1214
+ }
1215
+ else
1216
+ {
1217
+ cb('');
1218
+ }
1219
+ }
1220
+ else if(util.type.isDate(objects[i][1]))
1221
+ {
1222
+ cb(objects[i][0] + '=' + ajax.escape(objects[i][1].toJSON()));
1223
+ }
1224
+ else if(util.type.isArray(objects[i][1]) && objects[i][1].length <= 0)
1225
+ {
1226
+ cb(objects[i][0] + '=');
1227
+ }
1228
+ else
1229
+ {
1230
+ ajax.prepareData(objects[i][1], objects[i][0], cb);
1231
+ }
1232
+ }
1233
+ }
1234
+ else
1235
+ {
1236
+ callback.call(document, data)
1237
+ }
1238
+ }
1239
+ };
1240
+
1241
+ ajax.isSuccess = function(xhr)
1242
+ {
1243
+ return typeof xhr.status == 'undefined' || (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || xhr.status >= 400 && xhr.status < 500 || xhr.status === 1223 || xhr.status === 0;
1244
+ };
1245
+
1246
+ var ajaxResult = function(answer, query, status)
1247
+ {
1248
+ this.answer = answer;
1249
+ this.query = util.clone(query);
1250
+ this.status = status;
1251
+
1252
+ if(typeof this.answer.next != 'undefined')
1253
+ {
1254
+ this.answer.next = parseInt(this.answer.next);
1255
+ }
1256
+
1257
+ if(typeof this.answer.error != 'undefined')
1258
+ {
1259
+ this.answer.ex = new ajaxError(this.status, typeof this.answer.error == 'string' ? this.answer : this.answer.error)
1260
+ }
1261
+ };
1262
+
1263
+ ajaxResult.prototype.data = function()
1264
+ {
1265
+ return this.answer.result;
1266
+ };
1267
+
1268
+ ajaxResult.prototype.error = function()
1269
+ {
1270
+ return this.answer.ex;
1271
+ };
1272
+
1273
+ ajaxResult.prototype.error_description = function()
1274
+ {
1275
+ return this.answer.error_description;
1276
+ };
1277
+
1278
+ ajaxResult.prototype.more = function()
1279
+ {
1280
+ return !isNaN(this.answer.next);
1281
+ };
1282
+
1283
+ ajaxResult.prototype.total = function()
1284
+ {
1285
+ return parseInt(this.answer.total);
1286
+ };
1287
+
1288
+ ajaxResult.prototype.next = function(cb)
1289
+ {
1290
+ if(this.more())
1291
+ {
1292
+ this.query.start = this.answer.next;
1293
+
1294
+ if(!!cb && util.type.isFunction(cb))
1295
+ {
1296
+ this.query.callback = cb;
1297
+ }
1298
+
1299
+ return ajax(this.query);
1300
+ }
1301
+
1302
+ return false;
1303
+ };
1304
+
1305
+ var ajaxError = function(status, ex)
1306
+ {
1307
+ this.status = status;
1308
+ this.ex = ex;
1309
+ };
1310
+
1311
+ ajaxError.prototype.getError = function()
1312
+ {
1313
+ return this.ex;
1314
+ };
1315
+
1316
+ ajaxError.prototype.getStatus = function()
1317
+ {
1318
+ return this.status;
1319
+ };
1320
+
1321
+ ajaxError.prototype.toString = function()
1322
+ {
1323
+ return this.ex.error + (
1324
+ !!this.ex.error_description
1325
+ ? ': ' + this.ex.error_description
1326
+ : ''
1327
+ ) + ' ('+this.status+')';
1328
+ };
1329
+
1330
+
1331
+ var fileReader = function(fileInput, cb)
1332
+ {
1333
+ if(fileReader.canUse())
1334
+ {
1335
+ var files = fileInput.files,
1336
+ len = 0,
1337
+ result = fileInput.multiple ? [] : null;
1338
+
1339
+ for (var i = 0, f; f = files[i]; i++)
1340
+ {
1341
+ var reader = new window.FileReader();
1342
+
1343
+ reader.BXFILENAME = files[i].name;
1344
+
1345
+ reader.onload = function(e){
1346
+ e = e||window.event;
1347
+
1348
+ var res = [this.BXFILENAME,btoa(e.target.result)];
1349
+
1350
+ if(result === null)
1351
+ result = res;
1352
+ else
1353
+ result.push(res);
1354
+
1355
+ if(--len <= 0)
1356
+ {
1357
+ cb(result);
1358
+ }
1359
+ };
1360
+
1361
+ reader.readAsBinaryString(f);
1362
+ }
1363
+ len = i;
1364
+ if(len <= 0)
1365
+ {
1366
+ cb(result);
1367
+ }
1368
+ }
1369
+ };
1370
+
1371
+ fileReader.canUse = function()
1372
+ {
1373
+ return !!window.FileReader;
1374
+ };
1375
+
1376
+ var RestrictionManager = function()
1377
+ {
1378
+ var _ = this;
1379
+
1380
+ this.param = {
1381
+ SLEEP: 1000,
1382
+ ALLOWED_SPEED: 0.002,
1383
+ ALLOWED_AMOUNT: 90
1384
+ };
1385
+
1386
+ this.storage = {
1387
+ lastDecrement: 0,
1388
+ currentAmount: 0
1389
+ };
1390
+
1391
+ this.wait = function(callback)
1392
+ {
1393
+ return util.defer(function()
1394
+ {
1395
+ return _.check(callback);
1396
+ }, this.param.SLEEP);
1397
+ };
1398
+ };
1399
+
1400
+ RestrictionManager.prototype.check = function(callback)
1401
+ {
1402
+ this.decrementStorage();
1403
+
1404
+ if(!this.checkStorage())
1405
+ {
1406
+ this.wait(callback)();
1407
+ }
1408
+ else
1409
+ {
1410
+ this.incrementStorage();
1411
+
1412
+ this.run(callback);
1413
+ }
1414
+ };
1415
+
1416
+ RestrictionManager.prototype.run = function(callback)
1417
+ {
1418
+ callback();
1419
+ }
1420
+
1421
+ RestrictionManager.prototype.decrementStorage = function()
1422
+ {
1423
+ if(this.storage.lastDecrement > 0)
1424
+ {
1425
+ this.storage.currentAmount -= ((new Date()).valueOf() - this.storage.lastDecrement) * this.param.ALLOWED_SPEED;
1426
+
1427
+ if(this.storage.currentAmount < 0)
1428
+ {
1429
+ this.storage.currentAmount = 0;
1430
+ }
1431
+ }
1432
+
1433
+ this.storage.lastDecrement = (new Date()).valueOf();
1434
+ };
1435
+
1436
+ RestrictionManager.prototype.checkStorage = function()
1437
+ {
1438
+ return this.storage.currentAmount < this.param.ALLOWED_AMOUNT;
1439
+ };
1440
+
1441
+ RestrictionManager.prototype.incrementStorage = function()
1442
+ {
1443
+ this.storage.currentAmount++;
1444
+ };
1445
+
1446
+ /***************** exec ********************************/
1447
+
1448
+ // AUTH_ID can also be set via GET, but it's not recommended due to security reasons
1449
+
1450
+ var PARAMS = {
1451
+ DOMAIN: '',
1452
+ PROTOCOL: 1,
1453
+ APP_SID: false,
1454
+ PATH: '',
1455
+ LANG: '',
1456
+ AUTH_ID: '',
1457
+ REFRESH_ID: null,
1458
+ MEMBER_ID: null,
1459
+ PLACEMENT: null,
1460
+ IS_ADMIN: false,
1461
+ AUTH_EXPIRES: 0,
1462
+ USER_OPTIONS: null,
1463
+ APP_OPTIONS: null,
1464
+ PLACEMENT_OPTIONS: null
1465
+ };
1466
+
1467
+ if(!!window.name)
1468
+ {
1469
+ var q = window.name.split('|');
1470
+ PARAMS.DOMAIN = q[0].replace(/\\:(80|443)$/, '');
1471
+ PARAMS.PROTOCOL = parseInt(q[1])||0;
1472
+ PARAMS.APP_SID = q[2];
1473
+ }
1474
+
1475
+ if(!PARAMS.DOMAIN||!PARAMS.APP_SID)
1476
+ {
1477
+ BX24 = null;
1478
+ throw new Error('Unable to initialize Bitrix24 JS library!');
1479
+ }
1480
+
1481
+ /* bindings */
1482
+ BX24.bind(window, 'message', sendMessage.runCallback);
1483
+
1484
+ util.ready();
1485
+ util.init();
1486
+
1487
+ RestrictionManager = new RestrictionManager();
1488
+
1489
+ })();`},Symbol.toStringTag,{value:"Module"}));T.BX24_REMOTE_SOURCES=_e,T.BX24_SOURCE_TIMEOUT_MS=ae,T.BackgroundWorker=tn,T.Batch=K,T.Bx24EnvironmentError=oe,T.BxBoot=Ke,T.BxHelper=ne,T.BxLogger=ge,T.DEFAULT_BACKGROUND_WORKER_TIMING=z,T.loadBx24=Se,T.resolveBackgroundWorkerTiming=Ee,T.tempus=yt,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})});