szdl-utils-kit 0.2.30 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Readme.md +206 -140
- package/dist/index.js +1435 -928
- package/dist/index.umd.cjs +2 -2
- package/dist/types/background-worker.d.ts +81 -0
- package/dist/types/batch.d.ts +121 -55
- package/dist/types/bx-boot.d.ts +109 -154
- package/dist/types/bx-helper.d.ts +14 -20
- package/dist/types/bx-logger.d.ts +32 -35
- package/dist/types/index.d.ts +3 -2
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):s(JSON.parse(m.responseText))):l&&l(m))},m.open("GET",t,!1),m.send()},w={"%d":{format:function(t){return r(t.day()||i.MIN_DAY,2)},parse:function(t){var s=Number(t);return{day:isNaN(s)?e:s}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return r(t.month()||i.MIN_MONTH,2)},parse:function(t){var s=Number(t);return{month:isNaN(s)?e:s}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return r(t.year()||i.MIN_YEAR,4)},parse:function(t){var s=Number(t);return{year:isNaN(s)?e:s}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||i.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var s=t.dayOfWeek();return x[s!==e?s:i.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var s=t.dayOfWeek();return q[s!==e?s:i.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var s=i.options("monthFromZero")?t.month():t.month()-1;return v[s!==e?s:i.MIN_MONTH]},parse:function(t){var s=i.monthNames().indexOf(t)+(i.options("monthFromZero")?0:1);return{month:s!==-1?s:e}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var s=i.options("monthFromZero")?t.month():t.month()-1;return L[s!==e?s:i.MIN_MONTH]},parse:function(t){var s=i.monthNames(!0).indexOf(t)+(i.options("monthFromZero")?0:1);return{month:s!==-1?s:e}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return r(t.hours()||i.MIN_HOURS,2)},parse:function(t){var s=Number(t);return{hours:isNaN(s)?e:s}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return r(t.minutes()||i.MIN_MINUTES,2)},parse:function(t){var s=Number(t);return{minutes:isNaN(s)?e:s}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return r(t.seconds()||i.MIN_SECONDS,2)},parse:function(t){var s=Number(t);return{seconds:isNaN(s)?e:s}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:i(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return r(t.year()||i.MIN_YEAR,4)+"-"+r(t.month()||i.MIN_MONTH,2)+"-"+r(t.day()||i.MIN_DAY,2)},parse:function(t){var s=Number(t.slice(0,4)),l=Number(t.slice(5,7)),m=Number(t.slice(8,10));return{year:s,month:l,day:m}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return r(t.month()||i.MIN_MONTH,2)+"/"+r(t.day()||i.MIN_DAY,2)+"/"+r(t.year()||i.MIN_YEAR,4)},parse:function(t){var s=Number(t.slice(0,2)),l=Number(t.slice(3,5)),m=Number(t.slice(6,10));return{year:m,month:s,day:l}},minLength:10,maxLength:10,type:"string"}},ut={useMilliseconds:!1,monthFromZero:!1},R;R=function(t,s,l){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==e&&this.set(t,s,l),this},R.fn=R.prototype,R.fn.dayCount=function(){var t=this.month(),s=i.MAX_DAY_IN_MONTHS[t-(i.options("monthFromZero")?0:1)];return this.leapYear()&&t===(i.options("monthFromZero")?1:2)&&(s+=1),s},R.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=i.MIN_YEAR&&Number(t)<=i.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(i.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},R.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=i.MIN_MONTH&&Number(t)<=i.MAX_MONTH?(this._d.setMonth(i.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(i.options("monthFromZero")?i.MIN_MONTH:i.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?i.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},R.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=i.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(i.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},R.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=i.MIN_HOURS&&Number(t)<=i.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(i.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},R.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=i.MIN_MINUTES&&Number(t)<=i.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(i.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},R.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=i.MIN_SECONDS&&Number(t)<=i.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(i.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},R.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=i.MIN_MILLISECONDS&&Number(t)<=i.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(i.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},R.fn.week=function(){var t=new Date(this.year(),0,1),s=i(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((s-t.getTime())/864e5+t.getDay()+1)/7)},R.fn.set=function(t,s,l){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===e)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(i.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(i.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(i.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var m,M=[],E,S,J=[],I=0,C=0,D,Q,Y={},U;if(t===e)return E=o(this,l),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;for(s===e&&(s=i.detectFormat(t));I<s.length;){if(s.charAt(I)==="%"){if(S=s.charAt(I)+s.charAt(I+1),w[S]!==e){switch(D=0,Q="",w[S].type){case"number":for(;D<w[S].maxLength&&C+D<t.length&&!isNaN(Number(t.charAt(C+D)));)Q+=t.charAt(C+D),D+=1;break;case"word":for(;D<w[S].maxLength&&C+D<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(C+D));)Q+=t.charAt(C+D),D+=1;break;case"string":for(;D<w[S].maxLength&&C+D<t.length;)Q+=t.charAt(C+D),D+=1;break}if(D<w[S].minLength)return E=o(this,l),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;M.push(S),J.push(Q),D-=1,C+=D,I+=1}}else if(t.charAt(C)!==s.charAt(I))return E=o(this,l),E===e&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),E;I+=1,C+=1}for(m in M)M.hasOwnProperty(m)&&w.hasOwnProperty(M[m])&&(U=w[M[m]].parse(J[m]),Y={year:U.year!==e?U.year:Y.year,month:U.month!==e?U.month:Y.month,day:U.day!==e?U.day:Y.day,hours:U.hours!==e?U.hours:Y.hours,minutes:U.minutes!==e?U.minutes:Y.minutes,seconds:U.seconds!==e?U.seconds:Y.seconds});this.day(i.MIN_DAY),this.year(Y.year),this.month(Y.month),this.day(Y.day),this.hours(Y.hours),this.minutes(Y.minutes),this.seconds(Y.seconds),this.milliseconds(Y.milliseconds)}return this},R.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},R.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(i.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):i.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},R.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(i.options("useMilliseconds")?1:1e3)),this):i.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},R.fn.dayOfWeek=function(t){if(t==="long")return q[this._d.getDay()];if(t==="short")return x[this._d.getDay()];if(t===e)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},R.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},R.fn.get=function(t){switch(t){case"Date":return new Date(this.year(),this.month()-(i.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()-(i.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()}}},R.fn.format=function(t){for(var s=0,l="",m;s<t.length;)t.charAt(s)==="%"?(m=t.charAt(s)+t.charAt(s+1),w[m]!==e?(l+=w[m].format(this),s+=1):l+="%"):l+=t.charAt(s),s+=1;return l},R.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},R.fn.errors=function(){return this._i},R.fn.between=function(t,s){var l=this.timestamp(),m=t.timestamp();switch(s){case"year":return Math.floor((m-l)/31556952);case"month":return Math.floor((m-l)/2629746);case"day":return Math.floor((m-l)/86400);case"hours":return Math.floor((m-l)/3600);case"minutes":return Math.floor((m-l)/60);case"seconds":return m-l;default:return e}},R.fn.calc=function(t){return t.year!==e&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==e&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==e&&this._d.setDate(this._d.getDate()+t.day),t.hours!==e&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==e&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==e&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==e&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},i=function(t,s,l){return new R(t,s,l)},i.MIN_YEAR=1e3,i.MAX_YEAR=3e3,i.MIN_MONTH=1,i.MAX_MONTH=12,i.MIN_DAY=1,i.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],i.MIN_DAY_OF_WEEK=0,i.MAX_DAY_OF_WEEK=6,i.MIN_HOURS=0,i.MAX_HOURS=23,i.MIN_MINUTES=0,i.MAX_MINUTES=59,i.MIN_SECONDS=0,i.MAX_SECONDS=59,i.MIN_MILLISECONDS=0,i.MAX_MILLISECONDS=999,i.VERSION="0.2.18",i.options=function(t,s){if(t===e)return ut;if(ut.hasOwnProperty(t)){if(s===e)return ut[t];ut[t]=s,t==="monthFromZero"&&(i.MIN_MONTH=s?0:1,i.MAX_MONTH=s?11:12)}return e},i.noConflict=function(){return n.tempus=c,i},i.generate=function(t){var s,l,m,M,E,S,J,I;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof R?s=t.dateFrom.utc():s=i(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof R?l=t.dateTo.utc():l=i(t.dateTo,t.formatTo!==e?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?E={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?E={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(E={year:t.period.year!==e?t.period.year:0,month:t.period.month!==e?t.period.month:0,day:t.period.day!==e?t.period.day:0,hours:t.period.hours!==e?t.period.hours:0,minutes:t.period.minutes!==e?t.period.minutes:0,seconds:t.period.seconds!==e?t.period.seconds:0}),t.groupBy===e?S=t.asObject===!0?{}:[]:(S=[],S.push([]),J=i(s).get()[t.groupBy]),I=function(Q,Y,U){return t.asObject===!0?t.format!==e?Q[i(Y).format(t.format)]={}:Q[i(Y).format("%F %H:%M:%S")]={}:t.format!==e?Q.push(U?null:i(Y).format(t.format)):Q.push(U?null:i(Y)),Q},t.groupBy!==e&&t.fillNulls){var C={year:E.year?-E.year:e,month:E.month?-E.month:e,day:E.day?-E.day:e,hours:E.hours?-E.hours:e,minutes:E.minutes?-E.minutes:e,seconds:E.seconds?-E.seconds:e,milliseconds:E.milliseconds?-E.milliseconds:e};for(m=i(s).calc(C).utc();i(m).get()[t.groupBy]===J;)I(S[S.length-1],m,!0),m=i(m).calc(C).utc();if(t.groupBy==="week"){var D=i(s).dayOfWeek();for(m=i(s).dayOfWeek(0).utc();S[0].length<D&&m<s;)I(S[S.length-1],m,!0),m=i(m).calc(E).utc()}}for(;s<=l;)t.groupBy===e?I(S,s):i(s).get()[t.groupBy]===J?I(S[S.length-1],s):(S.push([]),I(S[S.length-1],s),J=i(s).get()[t.groupBy]),s=i(s).calc(E).utc();if(t.groupBy!==e&&t.fillNulls)for(M=i(l).calc(E).utc();i(M).get()[t.groupBy]===J;)I(S[S.length-1],M,!0),M=i(M).calc(E).utc();return S},i.monthNames=function(t){switch(t){case"long":return L;default:return v}},i.dayNames=function(t){switch(t){case"long":return q;default:return x}},i.lang=function(t){if(t!==e)u=t,N[u]===e&&(u="en"),L=B(),v=X(),q=P(),x=H();else return u;return e},i.availableLangs=function(){return Object.keys(N)},i.registerFormat=function(t,s,l,m,M,E){w[t]={format:s,parse:l,minLength:m,maxLength:M,type:E}},i.unregisterFormat=function(t){delete w[t]},i.detectFormat=function(t){var s,l,m;return s=f(t,0),s!==""&&(m=10),l=t.charAt(m),(l==="T"||l===" ")&&(s+=l,m+=1),s+=a(t,m),s},d={TempusDate:R},i.classes=function(t,s){if(s===e)return d[t];d[t]=s},i.loadTranslations=function(t){typeof t=="object"?N=t:typeof t=="string"&&mt(t,function(s){N=s},function(s){})},u=(y.language||y.systemLanguage||y.userLanguage||"en").substr(0,2).toLowerCase(),N[u]===e&&(u="en"),L=B(),v=X(),q=P(),x=H(),j.exports&&(A=j.exports=i),A.tempus=i}).call(p)})(ft,ft.exports);var Te=ft.exports;const Tt=b(Te);class Z{constructor(A,e={}){O(this,Nt);O(this,Ot);O(this,St);O(this,_t);O(this,pt);O(this,Mt);O(this,Lt);O(this,Ct);O(this,kt);O(this,bt);O(this,Dt);O(this,Ht);O(this,yt);O(this,Yt);O(this,Ft);O(this,ht);O(this,dt);O(this,gt);O(this,Pt);O(this,tt,null);O(this,Rt,null);O(this,et,[]);O(this,G,{});O(this,V,50);O(this,z,50);O(this,At,!0);O(this,st,null);O(this,k,null);O(this,$,null);O(this,wt,100);O(this,at,"no");O(this,F,!1);O(this,it,!1);O(this,ot,!1);W(this,"errors",{});W(this,"answerData",{});W(this,"timeLimit",!1);g(this,tt,A),g(this,Rt,e)}get serial(){return h(this,F)}get limitCommandSerial(){return h(this,z)}set limitCommandSerial(A){if(A<10)throw new Error("limitCommandSerial не может быть меньше 10");A>=10&&A<50&&(g(this,V,A),g(this,z,A)),g(this,z,A)}setSerial(){g(this,F,!0),g(this,it,!0),g(this,ot,!1)}setParallel(){g(this,F,!1),g(this,it,!1),g(this,ot,!0)}stop(){g(this,At,!1)}async batch(A,e){h(this,$)&&_(this,Ot,zt).call(this),e&&g(this,st,e),h(this,it)===!1&&g(this,F,!1),Object.keys(A).length>h(this,z)&&g(this,F,!0),g(this,At,!0),g(this,et,[]),g(this,G,{}),this.errors={},this.answerData={};const n=_(this,_t,Kt).call(this,A);if(Object.keys(A).length<h(this,z)){const r=n.map((o,a)=>_(this,pt,se).call(this,o,n[a]));return Promise.allSettled(r).then(o=>{let a={};for(let f of o)f.status==="fulfilled"&&(a={...a,...f.value});return a})}else{let r={},o=0,a=1,f=Object.keys(A).length||1,c=i=>{o+=Object.keys(i).length,a=Math.round(o/f*100)};for(let[i,d]of Object.entries(n)){let y=await _(this,pt,se).call(this,d,n[i],!0);c(d),e&&e({percent:a}),r={...r,...y}}return r}}async batchUpdateField(A,e){h(this,$)&&_(this,Ot,zt).call(this),e&&g(this,st,e),h(this,it)===!1&&g(this,F,!1),Object.keys(A).length>h(this,z)&&g(this,F,!0),g(this,At,!0),g(this,et,[]),g(this,G,{}),this.errors={},this.answerData={};const n=_(this,_t,Kt).call(this,A);if(Object.keys(A).length<h(this,z)){let r={};for(let[o,a]of Object.entries(n)){let f=await _(this,Mt,ie).call(this,a,n[o]);r={...r,...f}}return r}else{let r={},o=0,a=1,f=Object.keys(A).length||1,c=i=>{o+=Object.keys(i).length,a=Math.round(o/f*100)};for(let[i,d]of Object.entries(n)){let y=await _(this,Mt,ie).call(this,d,n[i],!0);c(d),e&&e({percent:a}),r={...r,...y},this.timeLimit&&(console.log("Был достигнут лимит operating time - сделана остановка на 2 минуты, timeLimit = ",this.timeLimit),await new Promise(u=>setTimeout(u,12e4)),this.timeLimit=!1,console.log("Остановка в 2 минуты по лимиту operating time закончена, timeLimit = ",this.timeLimit))}return r}}async batchTotalCount(A,e){g(this,G,{}),this.errors={};let n=1,r=0,o=Object.keys(A).length||1,a=c=>{r+=Object.keys(c).length,n=Math.round(r/o*100)};e&&e({percent:n});const f=_(this,_t,Kt).call(this,A);if(h(this,ot)){const c=f.map(i=>_(this,Lt,re).call(this,i).then(d=>(a(i),e&&e({percent:n}),d)));return Promise.allSettled(c).then(i=>{let d={};for(let y of i)y.status==="fulfilled"&&(d={...d,...y.value});return d})}else{let c={};for(let i of f){let d=await _(this,Lt,re).call(this,i);a(i),e&&e({percent:n}),c={...c,...d}}return c}}}tt=new WeakMap,Rt=new WeakMap,et=new WeakMap,G=new WeakMap,V=new WeakMap,z=new WeakMap,At=new WeakMap,st=new WeakMap,k=new WeakMap,$=new WeakMap,wt=new WeakMap,at=new WeakMap,F=new WeakMap,it=new WeakMap,ot=new WeakMap,Nt=new WeakSet,Vt=function(){let A=0;if(!h(this,k))return Math.round(A);let e=0,n=0;return Object.values(h(this,k)).forEach(r=>{const{total:o,count:a}=r;e+=o??0,n+=a??0}),e?A=n/e*100:A=100,{percent:Math.round(A),allCount:n,allTotal:e}},Ot=new WeakSet,zt=function(){clearInterval(h(this,$)),g(this,$,""),g(this,k,""),g(this,st,""),g(this,at,"no")},St=new WeakSet,Ae=function({key:A,value:e}){const n=_(this,ht,Ut).call(this,e.data()),r=Array.isArray(n)?n.length:0,o=_(this,dt,qt).call(this,e.total(),r);let a=1;n&&(a=r),h(this,st)&&(h(this,k)||g(this,k,{}),h(this,k)[A]&&h(this,k)[A].count&&(a+=h(this,k)[A].count),h(this,k)[A]={total:o,count:a},h(this,$)||g(this,$,setInterval(()=>{const{percent:f,allCount:c,allTotal:i}=h(this,Nt,Vt);(h(this,at)==="no"||h(this,at)<h(this,Nt,Vt).percent)&&(h(this,st).call(this,{data:h(this,k),percent:f,allCount:c,allTotal:i}),g(this,at,h(this,Nt,Vt).percent)),f===100&&_(this,Ot,zt).call(this)},h(this,wt))))},_t=new WeakSet,Kt=function(A){const e=[],n=Object.entries(A);for(let r=0;r<n.length;r+=h(this,V)){const o=n.slice(r,r+h(this,V));e.push(Object.fromEntries(o))}return e},pt=new WeakSet,se=function(A,e,n){return new Promise(r=>{const o=_(this,Yt,he).call(this,e),a=[];let f=0,c=0;h(this,tt).call(this,A,i=>{Object.entries(i).forEach(([d,y])=>{let u={};const N=y.error();if(N){let{query:{method:H},answer:L}=y;this.errors[d]={error:N,method:H},f+=1}if(y!=null&&y.answer&&Object.keys(y.answer).length){for(let[H,L]of Object.entries(y.answer))H!="result"&&L&&(u[H]=L);Object.keys(u).length&&(this.answerData[d]=u)}const B=_(this,ht,Ut).call(this,y.data()),X=Array.isArray(B)?B.length:0,P=_(this,dt,qt).call(this,y.total(),X);if(Array.isArray(B)?h(this,G)[d]=B:typeof B=="object"&&B!==null&&Object.keys(B).length===0?h(this,G)[d]=[]:h(this,G)[d]=B,c+=P,n||_(this,St,Ae).call(this,{key:d,value:y}),P>h(this,V)&&P>X){const H=Math.ceil(P/h(this,V))-1,L=Array.from({length:H});a.push([d,o[d],L])}}),c>5e3&&h(this,it)===!1&&h(this,ot)===!1&&g(this,F,!0),f>0&&_(this,gt,$t).call(this),a.length?(_(this,Ct,me).call(this,a),_(this,kt,ue).call(this).then(()=>r(_(this,yt,vt).call(this)))):r(_(this,yt,vt).call(this))})})},Mt=new WeakSet,ie=function(A,e,n){let r=_(this,Pt,Ne).call(this,A);return new Promise(o=>{let a=0;h(this,tt).call(this,"batch",r,f=>{var y,u,N,B,X,P;let c=((u=(y=f==null?void 0:f.answer)==null?void 0:y.result)==null?void 0:u.result)??null,i=((B=(N=f==null?void 0:f.answer)==null?void 0:N.result)==null?void 0:B.result_error)??null,d=((P=(X=f==null?void 0:f.answer)==null?void 0:X.result)==null?void 0:P.result_time)??null;(c||Object.keys(c).length)&&Object.entries(c).forEach(([H,L])=>{this.answerData[H]=L}),(i||Object.keys(i).length)&&Object.entries(i).forEach(([H,L])=>{var x,mt;let v=((x=A[H])==null?void 0:x.method)??null,q=((mt=A[H])==null?void 0:mt.params)??null;this.errors[H]={error:L,method:v,params:q},a+=1}),(d||Object.keys(d).length)&&Object.entries(d).forEach(([H,L])=>{((L==null?void 0:L.operating)??0)>=475&&(this.timeLimit=!0)}),a>0&&_(this,gt,$t).call(this),o(this.answerData)})})},Lt=new WeakSet,re=function(A){return new Promise(e=>{const n=_(this,Yt,he).call(this,A);let r=0;h(this,tt).call(this,n,o=>{Object.entries(o).forEach(([a,f])=>{const c=f.error();c&&(this.errors[a]=c,r+=1);const i=_(this,ht,Ut).call(this,f.data()),d=Array.isArray(i)?i.length:0,y=_(this,dt,qt).call(this,f.total(),d);h(this,G)[a]=y}),r>0&&_(this,gt,$t).call(this),e(_(this,yt,vt).call(this))})})},Ct=new WeakSet,me=function(A){let e=[];A.forEach(([n,r,o])=>{o.forEach((a,f)=>{const c=f+1,i=h(this,V)*c,y=[[n,c].join("_"),_(this,Ft,fe).call(this,r,i)];e.length===h(this,V)?(h(this,et).push(e),e=[y]):e.push(y)})}),e.length&&h(this,et).push(e)},kt=new WeakSet,ue=function(){const A=[],e=[],n=r=>{Object.entries(r).forEach(([o,a])=>{const[f]=o.split("_"),c=_(this,ht,Ut).call(this,a.data());Array.isArray(c)&&h(this,G)[f].push(...c),_(this,St,Ae).call(this,{key:f,value:a})})};return h(this,et).forEach((r,o)=>{const a=Object.fromEntries(r),f=()=>new Promise(c=>h(this,tt).call(this,a,i=>{h(this,F)?n(i):e[o]=i,c()}));A.push(f)}),h(this,F)?_(this,Dt,ae).call(this,A):_(this,Ht,oe).call(this,A).then(()=>{e.forEach(n)})},bt=new WeakSet,ne=function(){return new Promise(A=>setTimeout(A,500))},Dt=new WeakSet,ae=function(A){if(!A.length)return Promise.resolve();const e=A.shift();return Promise.allSettled([e(),_(this,bt,ne).call(this)]).then(()=>h(this,At)?_(this,Dt,ae).call(this,A):Promise.resolve())},Ht=new WeakSet,oe=function(A){if(!A.length)return Promise.resolve();const e=A.shift();return _(this,bt,ne).call(this).then(()=>e()).then(()=>h(this,At)?_(this,Ht,oe).call(this,A):Promise.resolve())},yt=new WeakSet,vt=function(){return Object.entries(h(this,Rt)).forEach(([A,e])=>{h(this,G)[A]&&(h(this,G)[A]=e(h(this,G)[A]))}),h(this,G)},Yt=new WeakSet,he=function(A){return Object.entries(A).reduce((e,[n,r])=>{if(Array.isArray(r)){const[o,a={}]=r;e[n]=[o,a]}else{const{method:o,params:a={}}=r;e[n]=[o,a]}return e},{})},Ft=new WeakSet,fe=function(A,e){const[n,r]=A;return[n,{start:e,...r}]},ht=new WeakSet,Ut=function(A){return((A==null?void 0:A.items)||(A==null?void 0:A.documents)||(A==null?void 0:A.tasks))??A},dt=new WeakSet,qt=function(A,e){return A!==A&&(A=0),A===0&&e===0?0:A||e},gt=new WeakSet,$t=function(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([A,e])=>{console.info(`[${A}]`,e)}),console.groupEnd()},Pt=new WeakSet,Ne=function(A){var n,r,o,a,f,c,i,d,y,u,N,B,X,P,H,L,v,q,x,mt,w,ut,R,t;let e={halt:0,cmd:{}};for(let s in A){const l=s;let m=(n=A[s])!=null&&n.method?(r=A[s])==null?void 0:r.method:"",M="",E="",S="";const J=(a=(o=A[s])==null?void 0:o.params)==null?void 0:a.fields;if((c=(f=A[s])==null?void 0:f.params)!=null&&c.entityTypeId?(M=`?entityTypeId=${parseInt((d=(i=A[s])==null?void 0:i.params)==null?void 0:d.entityTypeId)}`,(u=(y=A[s])==null?void 0:y.params)!=null&&u.id&&(E=`&id=${(B=(N=A[s])==null?void 0:N.params)==null?void 0:B.id}`),(P=(X=A[s])==null?void 0:X.params)!=null&&P.ID&&(E=`&ID=${(L=(H=A[s])==null?void 0:H.params)==null?void 0:L.ID}`)):((q=(v=A[s])==null?void 0:v.params)!=null&&q.id&&(E=`?id=${(mt=(x=A[s])==null?void 0:x.params)==null?void 0:mt.id}`),(ut=(w=A[s])==null?void 0:w.params)!=null&&ut.ID&&(E=`?ID=${(t=(R=A[s])==null?void 0:R.params)==null?void 0:t.ID}`)),Object.keys(J).length>0)for(let I in J)S+=`&fields[${I}]=${J[I]}`;e.cmd[l]=`${m}${M}${E}${S}`.trim()}return e};class te{constructor(){O(this,lt,{})}get hash(){return this.createHash(8)}createHash(A){let e="abcdefghijklmnopqrstuvwxyz0123456789",n="";A=A||6;for(let r=0;r<A;r++)n+=e.charAt(Math.floor(Math.random()*e.length));return n}actionFilter({keyTimer:A,duration:e=10,action:n}){h(this,lt)[A]&&(clearTimeout(h(this,lt)[A]),h(this,lt)[A]=null),n&&(h(this,lt)[A]=setTimeout(()=>{n()},e))}async noSleep(){let A=document.createElement("video");A.classList.add("no-sleep"),A.addEventListener("loadeddata",()=>{A.style.position="fixed",A.style.left="-9999px",document.querySelector("body").append(A),A.play()}),A.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>A.play()})}),A.src="data:video/mp4;base64,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"}downloadFileJson(A,e){let n=new Blob([JSON.stringify(A)],{type:"application/json"}),r=URL.createObjectURL(n),o=document.createElement("a");o.style.display="none",o.href=r,o.download=`${e}.json`,document.body.appendChild(o),o.click(),setTimeout(()=>{document.body.removeChild(o),URL.revokeObjectURL(r)},200)}}lt=new WeakMap;const Gt=new te;class ce{constructor(){O(this,jt);O(this,Bt);O(this,Jt);O(this,Xt);O(this,xt);O(this,K,"logger");O(this,rt,!1);O(this,Wt,2e3);O(this,ct,new Map);O(this,It,{});O(this,nt,null);O(this,Et,!1);W(this,"periodClear",3);_(this,jt,Oe).call(this)}async init(){let A=new Z(BX24.callBatch),{entityList:e}=await A.batch({entityList:{method:"entity.get"}});if(e&&Array.isArray(e))if(e.find(r=>r.ENTITY==h(this,K)))g(this,rt,!0);else{let{entityAdd:r}=await A.batch({entityAdd:{method:"entity.add",params:{ENTITY:h(this,K),NAME:h(this,K),ACCESS:{AU:"X"}}}});r&&g(this,rt,!0)}return _(this,Xt,ye).call(this),h(this,rt)}start({type:A,data:e}){if(!h(this,rt)){_(this,Bt,le).call(this,"entity");return}const n=Gt.hash;return h(this,ct).set(n,{type:A,data:e,userInfo:h(this,It),errorList:[],status:"",answer:null,date:new Date().getTime()}),n}stop({key:A,errorList:e,status:n,answer:r}){if(!h(this,rt)){_(this,Bt,le).call(this,"entity");return}let o=h(this,ct).get(A);e&&(o.errorList=e),n&&(o.status=n),r&&(o.answer=r),Gt.actionFilter({keyTimer:"add.entity.items",duration:h(this,Wt),action:async()=>{var a;await _(this,Jt,_e).call(this),(a=o==null?void 0:o.data)!=null&&a.updateList&&g(this,Et,!0)}})}async getEntityList(A){var r;if((r=h(this,nt))!=null&&r.length&&!h(this,Et))return h(this,nt);let e=new Z(BX24.callBatch),{entityList:n}=await e.batch({entityList:{method:"entity.item.get",params:{ENTITY:h(this,K),SORT:{ID:"DESC"}}}},A);return n=n.map(o=>{const{ID:a,DATE_CREATE:f,DETAIL_TEXT:c}=o;return{...JSON.parse(c),id:a,dateCreate:f}}),g(this,Et,!1),n}async downAllEntityJson(){let A=await this.getEntityList(),e=Tt().format("%Y-%m-%d");Gt.downloadFileJson(A,`sdklogger-entity-data__${e}`)}}K=new WeakMap,rt=new WeakMap,Wt=new WeakMap,ct=new WeakMap,It=new WeakMap,nt=new WeakMap,Et=new WeakMap,jt=new WeakSet,Oe=async function(){const A=new Z(BX24.callBatch),e=BX24.isAdmin(),{curUser:n}=await A.batch({curUser:{method:"user.current"}});g(this,It,{isAdmin:e,curUser:n})},Bt=new WeakSet,le=function(A){A=="entity"&&Gt.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},Jt=new WeakSet,_e=async function(){let A={},e=new Z(BX24.callBatch);for(let[n,r]of h(this,ct).entries())r.status&&(A[n]={method:"entity.item.add",params:{ENTITY:h(this,K),NAME:h(this,K),DETAIL_TEXT:JSON.stringify(r)}});if(Object.keys(A).length){let n=await e.batch(A),{errors:r}=e;for(let[o,a]of Object.entries({...n,...r}))h(this,ct).delete(o);return!0}},Xt=new WeakSet,ye=async function(){let A=new Z(BX24.callBatch),{serverTime:e}=await A.batch({serverTime:{method:"server.time"}});h(this,nt)||g(this,nt,await this.getEntityList());let n=h(this,nt).filter(r=>{let{dateCreate:o}=r;return Tt(new Date(o)).between(Tt(new Date(e)),"month")>=this.periodClear});_(this,xt,de).call(this,n)},xt=new WeakSet,de=async function(A){let e=new Z(BX24.callBatch),n=A.map(r=>{let{id:o}=r;return{method:"entity.item.delete",params:{ENTITY:h(this,K),ID:o}}});return await e.batch(n)};class Re{constructor(A){O(this,Qt);O(this,Zt);W(this,"domain","");W(this,"isAdmin",!1);W(this,"appInfo",null);W(this,"appConst",null);W(this,"userInfo",null);W(this,"placeData",null);W(this,"placeInfo",null);W(this,"logger",new ce);this.appConst=A}init(){return new Promise(A=>{let e=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(e),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),await this.logger.init();const[n,r]=await Promise.all([_(this,Qt,ge).call(this),_(this,Zt,Ee).call(this)]);this.appInfo=n,this.userInfo=r,new te().noSleep(),A(!0)})},100)})}userOption(A,e){return e?BX24.userOption.set(A,e):BX24.userOption.get(A)}call({method:A,params:e,updateList:n}){let r=this.logger.start({type:"call",data:{method:A,params:e,updateList:n}});return new Promise(o=>{e||(e={}),BX24.callMethod(A,e,a=>{let f={};if(a!=null&&a.answer)for(let[c,i]of Object.entries(a.answer))c!="result"&&i&&(f[c]=i);if(a.error()){let c=a.error();console.error(c),this.logger.stop({answer:f,key:r,status:"fail",errorList:[c.toString()]}),o(!1)}else{let c=a.data();c!=null&&c.items&&(c=c.items),this.logger.stop({answer:f,key:r,status:"success"}),o(c)}})})}async batch(A,e,{updateList:n,errorCall:r,limitCommandSerial:o}={}){let a=new Z(BX24.callBatch),f=this.logger.start({type:"batch",data:{commandList:A,updateList:n}});o&&(a.limitCommandSerial=o);try{let c=await a.batch(A,e);if(Object.keys(a.errors).length){let i=Object.entries(a.errors).map(([d,y])=>{var u;return{key:d,error:`${y==null?void 0:y.method} ${(u=y==null?void 0:y.error)==null?void 0:u.toString()}`.trim()}});r&&r(a.errors),this.logger.stop({key:f,status:"fail",errorList:i,answer:a.answerData})}else this.logger.stop({key:f,status:"success",answer:a.answerData});return c}catch(c){let i=c==null?void 0:c.toString();return this.logger.stop({key:f,status:"fail-runtime",errorList:[i],answer:a.answerData}),console.error(c),!1}}async batchUpdateField(A,e,{updateList:n,errorCall:r,limitCommandSerial:o}={}){let a=new Z(BX24.callMethod),f=this.logger.start({type:"callMethod-batch",data:{commandList:A,updateList:n}});o&&(a.limitCommandSerial=o);try{let c=await a.batchUpdateField(A,e);if(Object.keys(a.errors).length){let i=Object.entries(a.errors).map(([d,y])=>{var u;return{key:d,error:`${y==null?void 0:y.method} ${(u=y==null?void 0:y.error)==null?void 0:u.toString()}`.trim()}});r&&r(a.errors),this.logger.stop({key:f,status:"fail",errorList:i,answer:a.answerData})}else this.logger.stop({key:f,status:"success",answer:a.answerData});return c}catch(c){let i=c==null?void 0:c.toString();return this.logger.stop({key:f,status:"fail-runtime",errorList:[i],answer:a.answerData}),console.error(c),!1}}async batchTotalCount(A,e){let n=new Z(BX24.callBatch),r=this.logger.start({type:"batch",data:{commandList:A}});try{let o=await n.batchTotalCount(A,e);if(Object.keys(n.errors).length){let a=Object.entries(n.errors).map(([f,c])=>({key:f,error:c.toString()}));this.logger.stop({key:r,status:"fail",errorList:a})}else this.logger.stop({key:r,status:"success"});return o}catch(o){return this.logger.stop({key:r,status:"fail",errorList:[o.toString()]}),console.error(o),!1}}getPlacement(){return this.call({method:"placement.get"}).then(A=>(this.placeData||(this.placeData=A),A))}async placementBind(A){this.placeData||(this.placeData=await this.getPlacement());const{appName:e,pathApp:n}=this.appConst,r=this.placeData.map(a=>a.placement);let o=this.placeData.find(a=>a.placement==A);r.includes(A)?o.handler!=n&&await this.placementUnBind(A,o.handler).then(()=>{this.placementBind(A)}):this.call({method:"placement.bind",params:{PLACEMENT:A,HANDLER:n,LANG_ALL:{ru:{TITLE:e}}}}).then(a=>{a?console.info("Приложение успешно встроено в",A):console.warn("Приложение не может быть встроено в",A)})}async placementUnBind(A,e){const{pathApp:n,appName:r}=this.appConst;return await this.call({method:"placement.unbind",params:{PLACEMENT:A,HANDLER:e??n,LANG_ALL:{ru:{TITLE:r}}}}).then(o=>(console.log("Встройка отвязана",A),o))}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(A=>{let e=Object.values(A);return console.log("chat-bot list:",e),e})}regBot({code:A,type:e,name:n}){const{appName:r,pathApp:o,chatBotLogo:a}=this.appConst,f=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:A??this.appInfo.CODE,TYPE:e??"O",EVENT_HANDLER:o,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${n??r} - бот #${f}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:Tt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:a??""}}}).then(c=>(console.log("Чат-бот добавлен",c),c))}unRegBot(A){return this.call({method:"imbot.unregister",params:{BOT_ID:A}}).then(e=>(console.log("чат-бот удален",e),e))}getLoggerList(A){return this.logger.getEntityList(A)}}Qt=new WeakSet,ge=function(){return this.call({method:"app.info"})},Zt=new WeakSet,Ee=function(){return this.call({method:"user.current"})},T.Batch=Z,T.BxBoot=Re,T.BxHelper=te,T.BxLogger=ce,T.tempus=Tt,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
var bt=Object.defineProperty;var St=(N,E,b)=>E in N?bt(N,E,{enumerable:!0,configurable:!0,writable:!0,value:b}):N[E]=b;var M=(N,E,b)=>(St(N,typeof E!="symbol"?E+"":E,b),b),mt=(N,E,b)=>{if(!E.has(N))throw TypeError("Cannot "+b)};var _=(N,E,b)=>(mt(N,E,"read from private field"),b?b.call(N):E.get(N)),Y=(N,E,b)=>{if(E.has(N))throw TypeError("Cannot add the same private member more than once");E instanceof WeakSet?E.add(N):E.set(N,b)},J=(N,E,b,$)=>(mt(N,E,"write to private field"),$?$.call(N,b):E.set(N,b),b);var Q=(N,E,b)=>(mt(N,E,"access private method"),b);(function(N,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(N=typeof globalThis<"u"?globalThis:N||self,E(N["szdl-utils-kit"]={}))})(this,function(N){var V,j,Z,K,tt,G,q,et,nt,Nt,st,dt,At,Ot,ot,pt,at,_t,ht,yt,lt,Et;"use strict";var E=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function b(W){return W&&W.__esModule&&Object.prototype.hasOwnProperty.call(W,"default")?W.default:W}var $={exports:{}};(function(W,e){(function(r){Array.prototype.indexOf||(Array.prototype.indexOf=function(t,n){var l,f;for(l=n||0,f=this.length;l<f;l+=1)if(this[l]===t)return l;return-1});var i=this,A=function(t,n){for(var l=t.toString();l.length<n;)l="0"+l;return l},o=function(t,n){return n!==r?(t.year(n.year()||n.year),t.month(n.month()||n.month),t.day(n.day()||n.day),t.hours(n.hours()||n.hours),t.minutes(n.minutes()||n.minutes),t.seconds(n.seconds()||n.seconds),t.milliseconds(n.milliseconds()||n.milliseconds),t):r},h=function(t,n){var l,f="";return l=t.slice(n,n+1),l!==""&&!isNaN(Number(l))&&(f+="%H"),l=t.charAt(n+2),l!==""&&l===":"&&(f+=l),l=t.slice(n+3,n+4),l!==""&&!isNaN(Number(l))&&(f+="%M"),l=t.charAt(n+5),l!==""&&l===":"&&(f+=l),l=t.slice(n+6,n+7),l!==""&&!isNaN(Number(l))&&(f+="%S"),f},m=function(t,n){var l,f=[t.slice(n,n+1),t.charAt(n+2),t.slice(n+3,n+4),t.charAt(n+5),t.slice(n+6,n+9)],S;return!isNaN(Number(f[0]))&&!isNaN(Number(f[2]))&&!isNaN(Number(f[4]))?(f[1]==="."&&f[3]==="."?l="%d.%m.%Y":f[1]==="-"&&f[3]==="-"?l="%m-%d-%Y":f[1]==="/"&&f[3]==="/"&&(l="%m/%d/%Y"),l):(S=[t.slice(n,n+3),t.charAt(n+4),t.slice(n+5,n+6),t.charAt(n+7),t.slice(n+8,n+9)],!isNaN(Number(S[0]))&&!isNaN(Number(S[2]))&&!isNaN(Number(S[4]))?(S[1]==="-"&&S[3]==="-"&&(l="%Y-%m-%d"),l):"")},u=i.tempus,s,d,g=i.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"}},y=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]},L=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]},F=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]},x,U,k,B,it=function(t,n,l){var f;i.XMLHttpRequest?f=new XMLHttpRequest:f=new ActiveXObject("Microsoft.XMLHTTP"),f.onreadystatechange=function(){f.readyState===4&&(f.status===200?n&&(i.JSON===r?alert(`Please, include json2 into your project if you want use old browsers!
|
|
2
|
+
https://github.com/douglascrockford/JSON-js/blob/master/json2.js`):n(JSON.parse(f.responseText))):l&&l(f))},f.open("GET",t,!1),f.send()},H={"%d":{format:function(t){return A(t.day()||s.MIN_DAY,2)},parse:function(t){var n=Number(t);return{day:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%m":{format:function(t){return A(t.month()||s.MIN_MONTH,2)},parse:function(t){var n=Number(t);return{month:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%Y":{format:function(t){return A(t.year()||s.MIN_YEAR,4)},parse:function(t){var n=Number(t);return{year:isNaN(n)?r:n}},minLength:4,maxLength:4,type:"number"},"%w":{format:function(t){return t.dayOfWeek()||s.MIN_DAY_OF_WEEK},parse:function(){return{}},minLength:1,maxLength:1,type:"number"},"%a":{format:function(t){var n=t.dayOfWeek();return B[n!==r?n:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%A":{format:function(t){var n=t.dayOfWeek();return k[n!==r?n:s.MIN_DAY_OF_WEEK]},parse:function(){return{}},minLength:1,maxLength:999,type:"word"},"%b":{format:function(t){var n=s.options("monthFromZero")?t.month():t.month()-1;return U[n!==r?n:s.MIN_MONTH]},parse:function(t){var n=s.monthNames().indexOf(t)+(s.options("monthFromZero")?0:1);return{month:n!==-1?n:r}},minLength:1,maxLength:999,type:"word"},"%B":{format:function(t){var n=s.options("monthFromZero")?t.month():t.month()-1;return x[n!==r?n:s.MIN_MONTH]},parse:function(t){var n=s.monthNames(!0).indexOf(t)+(s.options("monthFromZero")?0:1);return{month:n!==-1?n:r}},minLength:1,maxLength:999,type:"word"},"%H":{format:function(t){return A(t.hours()||s.MIN_HOURS,2)},parse:function(t){var n=Number(t);return{hours:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%M":{format:function(t){return A(t.minutes()||s.MIN_MINUTES,2)},parse:function(t){var n=Number(t);return{minutes:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%S":{format:function(t){return A(t.seconds()||s.MIN_SECONDS,2)},parse:function(t){var n=Number(t);return{seconds:isNaN(n)?r:n}},minLength:2,maxLength:2,type:"number"},"%s":{format:function(t){return t.timestamp()},parse:function(t){return isNaN(Number(t))?{}:s(Number(t)).get()},minLength:1,maxLength:20,type:"number"},"%F":{format:function(t){return A(t.year()||s.MIN_YEAR,4)+"-"+A(t.month()||s.MIN_MONTH,2)+"-"+A(t.day()||s.MIN_DAY,2)},parse:function(t){var n=Number(t.slice(0,4)),l=Number(t.slice(5,7)),f=Number(t.slice(8,10));return{year:n,month:l,day:f}},minLength:10,maxLength:10,type:"string"},"%D":{format:function(t){return A(t.month()||s.MIN_MONTH,2)+"/"+A(t.day()||s.MIN_DAY,2)+"/"+A(t.year()||s.MIN_YEAR,4)},parse:function(t){var n=Number(t.slice(0,2)),l=Number(t.slice(3,5)),f=Number(t.slice(6,10));return{year:f,month:n,day:l}},minLength:10,maxLength:10,type:"string"}},ct={useMilliseconds:!1,monthFromZero:!1},T;T=function(t,n,l){return this._d=new Date,this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t!==r&&this.set(t,n,l),this},T.fn=T.prototype,T.fn.dayCount=function(){var t=this.month(),n=s.MAX_DAY_IN_MONTHS[t-(s.options("monthFromZero")?0:1)];return this.leapYear()&&t===(s.options("monthFromZero")?1:2)&&(n+=1),n},T.fn.year=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_YEAR&&Number(t)<=s.MAX_YEAR?(this._d.setFullYear(Number(t)),this._i.year=!1):this._i.year=Number(t):(this._d.setFullYear(s.MIN_YEAR),this._i.year=!1);else return this._i.year===!1?this._d.getFullYear():this._i.year;return this},T.fn.month=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MONTH&&Number(t)<=s.MAX_MONTH?(this._d.setMonth(s.options("monthFromZero")?Number(t):Number(t)-1),this._i.month=!1):this._i.month=Number(t):(this._d.setMonth(s.options("monthFromZero")?s.MIN_MONTH:s.MIN_MONTH-1),this._i.month=!1);else return this._i.month===!1?s.options("monthFromZero")?this._d.getMonth():this._d.getMonth()+1:this._i.month;return this},T.fn.day=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_DAY&&Number(t)<=this.dayCount()?(this._d.setDate(Number(t)),this._i.day=!1):this._i.day=Number(t):(this._d.setDate(s.MIN_DAY),this._i.day=!1);else return this._i.day===!1?this._d.getDate():this._i.day;return this},T.fn.hours=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_HOURS&&Number(t)<=s.MAX_HOURS?(this._d.setHours(Number(t)),this._i.hours=!1):this._i.hours=Number(t):(this._d.setHours(s.MIN_HOURS),this._i.hours=!1);else return this._i.hours===!1?this._d.getHours():this._i.hours;return this},T.fn.minutes=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MINUTES&&Number(t)<=s.MAX_MINUTES?(this._d.setMinutes(Number(t)),this._i.minutes=!1):this._i.minutes=Number(t):(this._d.setMinutes(s.MIN_MINUTES),this._i.minutes=!1);else return this._i.minutes===!1?this._d.getMinutes():this._i.minutes;return this},T.fn.seconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_SECONDS&&Number(t)<=s.MAX_SECONDS?(this._d.setSeconds(Number(t)),this._i.seconds=!1):this._i.seconds=Number(t):(this._d.setSeconds(s.MIN_SECONDS),this._i.seconds=!1);else return this._i.seconds===!1?this._d.getSeconds():this._i.seconds;return this},T.fn.milliseconds=function(t){if(arguments.length!==0)(typeof t=="number"||typeof t=="string")&&!isNaN(Number(t))?Number(t)>=s.MIN_MILLISECONDS&&Number(t)<=s.MAX_MILLISECONDS?(this._d.setMilliseconds(Number(t)),this._i.milliseconds=!1):this._i.milliseconds=Number(t):(this._d.setMilliseconds(s.MIN_MILLISECONDS),this._i.milliseconds=!1);else return this._i.milliseconds===!1?this._d.getMilliseconds():this._i.milliseconds;return this},T.fn.week=function(){var t=new Date(this.year(),0,1),n=s(this.utc()).hours(0).minutes(0).seconds(0).milliseconds(0).utc()*1e3;return Math.ceil(((n-t.getTime())/864e5+t.getDay()+1)/7)},T.fn.set=function(t,n,l){if(this._i={year:!1,month:!1,day:!1,hours:!1,minutes:!1,seconds:!1,milliseconds:!1},t===r)return this._d=new Date,this;if(t instanceof Date)return this._d=t,this;if(typeof t=="number")return this._d=new Date(t*(s.options("useMilliseconds")?1:1e3)),this;if(typeof t=="object"&&(t instanceof Array?(this.day(s.MIN_DAY),this.year(t[0]),this.month(t[1]),this.day(t[2]),this.hours(t[3]),this.minutes(t[4]),this.seconds(t[5]),this.milliseconds(t[6])):(this.day(s.MIN_DAY),this.year(t.year),this.month(t.month),this.day(t.day),this.hours(t.hours),this.minutes(t.minutes),this.seconds(t.seconds),this.milliseconds(t.milliseconds))),typeof t=="string"){var f,S=[],p,R,z=[],C=0,P=0,D,X,I={},w;if(t===r)return p=o(this,l),p===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),p;for(n===r&&(n=s.detectFormat(t));C<n.length;){if(n.charAt(C)==="%"){if(R=n.charAt(C)+n.charAt(C+1),H[R]!==r){switch(D=0,X="",H[R].type){case"number":for(;D<H[R].maxLength&&P+D<t.length&&!isNaN(Number(t.charAt(P+D)));)X+=t.charAt(P+D),D+=1;break;case"word":for(;D<H[R].maxLength&&P+D<t.length&&/^[\u00BF-\u1FFF\u2C00-\uD7FF\w]+$/.test(t.charAt(P+D));)X+=t.charAt(P+D),D+=1;break;case"string":for(;D<H[R].maxLength&&P+D<t.length;)X+=t.charAt(P+D),D+=1;break}if(D<H[R].minLength)return p=o(this,l),p===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),p;S.push(R),z.push(X),D-=1,P+=D,C+=1}}else if(t.charAt(P)!==n.charAt(C))return p=o(this,l),p===r&&(this._i={year:-1,month:-1,day:-1,hours:-1,minutes:-1,seconds:-1,milliseconds:-1}),p;C+=1,P+=1}for(f in S)S.hasOwnProperty(f)&&H.hasOwnProperty(S[f])&&(w=H[S[f]].parse(z[f]),I={year:w.year!==r?w.year:I.year,month:w.month!==r?w.month:I.month,day:w.day!==r?w.day:I.day,hours:w.hours!==r?w.hours:I.hours,minutes:w.minutes!==r?w.minutes:I.minutes,seconds:w.seconds!==r?w.seconds:I.seconds});this.day(s.MIN_DAY),this.year(I.year),this.month(I.month),this.day(I.day),this.hours(I.hours),this.minutes(I.minutes),this.seconds(I.seconds),this.milliseconds(I.milliseconds)}return this},T.fn.leapYear=function(){var t=this.year();return t%4===0?t%100===0?t%400===0:!0:!1},T.fn.timestamp=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)+this._d.getTimezoneOffset()*6e4),this):s.options("useMilliseconds")?this._d.getTime()-this._d.getTimezoneOffset()*6e4:Math.floor(this._d.getTime()/1e3)-this._d.getTimezoneOffset()*60},T.fn.utc=function(t){return arguments.length!==0?(this._d=new Date(Number(t)*(s.options("useMilliseconds")?1:1e3)),this):s.options("useMilliseconds")?this._d.getTime():Math.floor(this._d.getTime()/1e3)},T.fn.dayOfWeek=function(t){if(t==="long")return k[this._d.getDay()];if(t==="short")return B[this._d.getDay()];if(t===r)return this._d.getDay();if(t===0||t==="Sunday")return this.calc({day:-this.dayOfWeek()});if(t===1||t==="Monday")return this.calc({day:(this.dayOfWeek()===0?-6:1)-this.dayOfWeek()});if(t===2||t==="Tuesday")return this.calc({day:(this.dayOfWeek()===0?-5:2)-this.dayOfWeek()});if(t===3||t==="Wednesday")return this.calc({day:(this.dayOfWeek()===0?-4:3)-this.dayOfWeek()});if(t===4||t==="Thursday")return this.calc({day:(this.dayOfWeek()===0?-3:4)-this.dayOfWeek()});if(t===5||t==="Friday")return this.calc({day:(this.dayOfWeek()===0?-2:5)-this.dayOfWeek()});if(t===6||t==="Saturday")return this.calc({day:(this.dayOfWeek()===0?-1:6)-this.dayOfWeek()})},T.fn.timezone=function(t){switch(t){case"hours":return Math.floor(this._d.getTimezoneOffset()/60);case"minutes":return this._d.getTimezoneOffset();default:return this._d.getTimezoneOffset()*60}},T.fn.get=function(t){switch(t){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()}}},T.fn.format=function(t){for(var n=0,l="",f;n<t.length;)t.charAt(n)==="%"?(f=t.charAt(n)+t.charAt(n+1),H[f]!==r?(l+=H[f].format(this),n+=1):l+="%"):l+=t.charAt(n),n+=1;return l},T.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},T.fn.errors=function(){return this._i},T.fn.between=function(t,n){var l=this.timestamp(),f=t.timestamp();switch(n){case"year":return Math.floor((f-l)/31556952);case"month":return Math.floor((f-l)/2629746);case"day":return Math.floor((f-l)/86400);case"hours":return Math.floor((f-l)/3600);case"minutes":return Math.floor((f-l)/60);case"seconds":return f-l;default:return r}},T.fn.calc=function(t){return t.year!==r&&this._d.setFullYear(this._d.getFullYear()+t.year),t.month!==r&&this._d.setMonth(this._d.getMonth()+t.month),t.day!==r&&this._d.setDate(this._d.getDate()+t.day),t.hours!==r&&this._d.setHours(this._d.getHours()+t.hours),t.minutes!==r&&this._d.setMinutes(this._d.getMinutes()+t.minutes),t.seconds!==r&&this._d.setSeconds(this._d.getSeconds()+t.seconds),t.milliseconds!==r&&this._d.setMilliseconds(this._d.getMilliseconds()+t.milliseconds),this},s=function(t,n,l){return new T(t,n,l)},s.MIN_YEAR=1e3,s.MAX_YEAR=3e3,s.MIN_MONTH=1,s.MAX_MONTH=12,s.MIN_DAY=1,s.MAX_DAY_IN_MONTHS=[31,28,31,30,31,30,31,31,30,31,30,31],s.MIN_DAY_OF_WEEK=0,s.MAX_DAY_OF_WEEK=6,s.MIN_HOURS=0,s.MAX_HOURS=23,s.MIN_MINUTES=0,s.MAX_MINUTES=59,s.MIN_SECONDS=0,s.MAX_SECONDS=59,s.MIN_MILLISECONDS=0,s.MAX_MILLISECONDS=999,s.VERSION="0.2.18",s.options=function(t,n){if(t===r)return ct;if(ct.hasOwnProperty(t)){if(n===r)return ct[t];ct[t]=n,t==="monthFromZero"&&(s.MIN_MONTH=n?0:1,s.MAX_MONTH=n?11:12)}return r},s.noConflict=function(){return i.tempus=u,s},s.generate=function(t){var n,l,f,S,p,R,z,C;if(typeof t.dateFrom!="number"&&(t.dateFrom instanceof T?n=t.dateFrom.utc():n=s(t.dateFrom,t.formatFrom).utc()),typeof t.dateTo!="number"&&(t.dateTo instanceof T?l=t.dateTo.utc():l=s(t.dateTo,t.formatTo!==r?t.formatTo:t.formatFrom).utc()),typeof t.period=="number"?p={year:0,month:0,day:0,hours:0,minutes:0,seconds:t.period}:typeof t.period=="string"?p={year:t.period==="year"?1:0,month:t.period==="month"?1:0,day:t.period==="day"?1:0,hours:t.period==="hours"?1:0,minutes:t.period==="minutes"?1:0,seconds:t.period==="seconds"?1:0}:typeof t.period=="object"&&(p={year:t.period.year!==r?t.period.year:0,month:t.period.month!==r?t.period.month:0,day:t.period.day!==r?t.period.day:0,hours:t.period.hours!==r?t.period.hours:0,minutes:t.period.minutes!==r?t.period.minutes:0,seconds:t.period.seconds!==r?t.period.seconds:0}),t.groupBy===r?R=t.asObject===!0?{}:[]:(R=[],R.push([]),z=s(n).get()[t.groupBy]),C=function(X,I,w){return t.asObject===!0?t.format!==r?X[s(I).format(t.format)]={}:X[s(I).format("%F %H:%M:%S")]={}:t.format!==r?X.push(w?null:s(I).format(t.format)):X.push(w?null:s(I)),X},t.groupBy!==r&&t.fillNulls){var P={year:p.year?-p.year:r,month:p.month?-p.month:r,day:p.day?-p.day:r,hours:p.hours?-p.hours:r,minutes:p.minutes?-p.minutes:r,seconds:p.seconds?-p.seconds:r,milliseconds:p.milliseconds?-p.milliseconds:r};for(f=s(n).calc(P).utc();s(f).get()[t.groupBy]===z;)C(R[R.length-1],f,!0),f=s(f).calc(P).utc();if(t.groupBy==="week"){var D=s(n).dayOfWeek();for(f=s(n).dayOfWeek(0).utc();R[0].length<D&&f<n;)C(R[R.length-1],f,!0),f=s(f).calc(p).utc()}}for(;n<=l;)t.groupBy===r?C(R,n):s(n).get()[t.groupBy]===z?C(R[R.length-1],n):(R.push([]),C(R[R.length-1],n),z=s(n).get()[t.groupBy]),n=s(n).calc(p).utc();if(t.groupBy!==r&&t.fillNulls)for(S=s(l).calc(p).utc();s(S).get()[t.groupBy]===z;)C(R[R.length-1],S,!0),S=s(S).calc(p).utc();return R},s.monthNames=function(t){switch(t){case"long":return x;default:return U}},s.dayNames=function(t){switch(t){case"long":return k;default:return B}},s.lang=function(t){if(t!==r)a=t,c[a]===r&&(a="en"),x=y(),U=O(),k=L(),B=F();else return a;return r},s.availableLangs=function(){return Object.keys(c)},s.registerFormat=function(t,n,l,f,S,p){H[t]={format:n,parse:l,minLength:f,maxLength:S,type:p}},s.unregisterFormat=function(t){delete H[t]},s.detectFormat=function(t){var n,l,f;return n=m(t,0),n!==""&&(f=10),l=t.charAt(f),(l==="T"||l===" ")&&(n+=l,f+=1),n+=h(t,f),n},d={TempusDate:T},s.classes=function(t,n){if(n===r)return d[t];d[t]=n},s.loadTranslations=function(t){typeof t=="object"?c=t:typeof t=="string"&&it(t,function(n){c=n},function(n){})},a=(g.language||g.systemLanguage||g.userLanguage||"en").substr(0,2).toLowerCase(),c[a]===r&&(a="en"),x=y(),U=O(),k=L(),B=F(),W.exports&&(e=W.exports=s),e.tempus=s}).call(E)})($,$.exports);var Tt=$.exports;const rt=b(Tt);class v{constructor(e){this.callBatch=e,this.result={},this.errors={},this.limit=50,this.canContinue=!0,this.progressCall="",this.limitCall="",this.progressData="",this.progressTimer="",this.progressDelay=100,this.oldPercent="no",this.chunkRate=1,this.totalProgress=0,this.skipList=new Set}getData(e){return(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}get progressPercent(){let e=0;if(!this.progressData)return{percent:Math.round(e),allCount:0,allTotal:0};let r=0,i=0;return Object.values(this.progressData).forEach(A=>{const{total:o,count:h}=A;r+=o??0,i+=h??0}),r?e=i/r*100*this.chunkRate+this.totalProgress:i===0&&r===0?e=100*this.chunkRate+this.totalProgress:e=100,{percent:Math.round(e),allCount:i,allTotal:r}}setProgressData({key:e,value:r,type:i}){const A=this.getData(r.data()),o=Array.isArray(A)?A.length:0;let h=r.total()||o;i==="count"&&(h=o);let m=1;A&&(m=o),this.progressCall&&(this.progressData||(this.progressData={}),this.progressData[e]&&this.progressData[e].count&&(m+=this.progressData[e].count),this.progressData[e]?this.progressData[e].count=m:this.progressData[e]={total:h,count:m},this.progressTimer||(this.progressTimer=setInterval(()=>{const{percent:u,allCount:s,allTotal:d}=this.progressPercent;(this.oldPercent==="no"||this.oldPercent<this.progressPercent.percent)&&(this.progressCall({data:this.progressData,percent:u,allCount:s,allTotal:d}),this.oldPercent=this.progressPercent.percent),u>=100&&this.clearProgressData()},this.progressDelay)))}delay(){return new Promise(e=>setTimeout(e,500))}stop(){this.canContinue=!1}clearProgressData(){clearInterval(this.progressTimer),this.progressTimer="",this.progressData="",this.progressCall="",this.limitCall="",this.oldPercent="no"}async batch(e,r,i){this.progressTimer&&this.clearProgressData(),r&&(this.progressCall=r),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const A={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let o={},h=0;for(const[m,u]of Object.entries(e)){if(!this.canContinue)break;const s=this.arrayChunk(u);if(!s){h++;continue}o[m]=s,(Object.keys(o).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(o),Object.entries(this.result).forEach(([d,g])=>{A[d]=g}),this.totalProgress=Math.round(h/Object.keys(e).length*100),o={}),h++}return Object.entries(this.errors).length&&(A.errorsList=this.errors),r&&r({percent:100}),Promise.resolve(A)}async batchTotalCount(e,r,i){this.progressTimer&&this.clearProgressData(),r&&(this.progressCall=r),i&&(this.limitCall=i),this.canContinue=!0,this.result={},this.errors={};const A={};this.chunkRate=(1/Math.ceil(Object.keys(e).length/this.limit)).toFixed(5);let o={},h=0;for(const[m,u]of Object.entries(e)){if(!this.canContinue)break;const s=this.arrayChunk(u);if(!s){h++;continue}o[m]=s,(Object.keys(o).length>=50||h+1===Object.keys(e).length)&&(await this.batchChunk(o,"count"),Object.entries(this.result).forEach(([d,g])=>{A[d]=g}),this.totalProgress=Math.round(h/Object.keys(e).length*100),o={}),h++}return Object.entries(this.errors).length&&(A.errorsList=this.errors),r&&r({percent:100}),Promise.resolve(A)}arrayChunk(e){let r="",i={};if(Array.isArray(e)?[r]=e:(r=e.method,i=e.params),this.skipList.has(r))return!1;if((r.includes("list")||r==="user.get")&&r!=="task.item.list"){if(!i)i={order:{ID:"ASC",id:"ASC"}};else{r==="tasks.task.list"?(i.order||(i.order={}),i.order.ID="asc"):r==="user.get"?(i.sort||(i.sort="ID"),i.order||(i.order="ASC")):i.order={ID:"ASC",id:"ASC"},Array.isArray(i.select)&&!i.select.includes("ID")&&i.select.push("ID");const A=r==="user.get"?i.FILTER:i.filter;typeof A=="object"&&A!==null&&!Array.isArray(A)&&Object.entries(A).forEach(([o,h])=>{(i.start===void 0||i.start!==-1)&&["id","ID"].includes(o)&&(typeof h=="string"||Array.isArray(h)&&h.length<=50)&&(i.start=-1)})}r==="crm.type.list"&&i.order&&delete i.order.ID}if(r==="task.item.list")if(!i)i=[{ID:"ASC"},[""],[""],["ID"]];else{Array.isArray(i[0])&&(i[0]={});const[A,o,h,m]=i;A.ID="ASC",m[0]!==""&&m.includes("ID")||m.push("ID")}return{method:r,params:i}}async batchChunk(e,r){return new Promise(i=>{const A=[];let o;this.callBatch(e,async h=>{var m,u,s,d,g,a,c;for(const[y,O]of Object.entries(h)){if(!this.canContinue)return;if(O.error())switch(this.errors[y]=((u=(m=O.error())==null?void 0:m.ex)==null?void 0:u.error)??((d=(s=O.error())==null?void 0:s.ex)==null?void 0:d.error_description)??((g=O.error())==null?void 0:g.toString())??"Неизвестная ошибка",o=!0,((c=(a=O.error())==null?void 0:a.ex)==null?void 0:c.error)??""){case"OPERATION_TIME_LIMIT":this.skipList.add(e[y].method),this.limitCall&&this.limitCall(y);break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":this.skipList.add(e[y].method);break}const L=this.getData(O.data()),F=Array.isArray(L)?L.length:0,x=typeof O.total=="function"&&O.total()!==void 0,U=x?O.total():F;r==="count"?this.result[y]?this.result[y]+=F:this.result[y]=U:this.result[y]=L,this.setProgressData({key:y,value:O,type:r});const k=r==="count"?!x&&F===this.limit:U>this.limit&&U>F;if(!this.canContinue||k){let B=e[y];if(Array.isArray(B)){const[it,H={}]=B;B=[it,H]}else{const{method:it,params:H={}}=B;B=[it,H]}A.push([y,B,U])}}o>0&&this.errorLogger(),A.length?await this.batchPayload(A,r).then(()=>i(this.result)):i(this.result)})})}async batchPayload(e,r){const i=new Map,A=(u,s,d,g)=>{let a="ID";this.result[u][this.result[u].length-1].ID||(a="id");let c=`${a}`;if(JSON.stringify(g[1]).toLocaleLowerCase().includes('"id":"desc"')?c="<"+c:c=">"+c,s===1||d.length===0)return{field:c,id:this.result[u][this.result[u].length-1][a]};let O="";const[L,F]=g;return(L==="tasks.task.list"||L==="task.item.list")&&(O="[tasks]"),["crm.item.list","crm.stagehistory.list"].includes(L)&&(O="[items]"),L==="crm.type.list"&&(O="[types]"),L==="socialnetwork.api.workgroup.list"&&(O="[workgroups]"),{field:c,id:`$result[${[u,s-1].join("__")}]${O}[49][${a}]`}},o=(u,s)=>{const[d,g]=u;let a=JSON.parse(JSON.stringify(g)),c;if(d==="task.item.list"){a=[...a];const[y,O,L,F]=a;return O[s.field]=s.id,[d,a]}return["user.get"].includes(d)||a.FILTER?(a.FILTER||(a.FILTER={}),c=a.FILTER):(a.filter||(a.filter={}),c=a.filter),["socialnetwork.api.workgroup.list","tasks.task.list"].includes(d)?c[">ID"]=s.id:c[s.field]=s.id,[d,{...a,start:-1}]},h=u=>{Object.entries(u).forEach(([s,d])=>{var c,y,O,L,F,x,U;const[g]=s.split("__"),a=this.getData(d.data());if(Array.isArray(a)&&(r==="count"?this.result[g]+=a.length:this.result[g].push(...a)),d.error()){this.errors[g]=((y=(c=d.error())==null?void 0:c.ex)==null?void 0:y.error)??((L=(O=d.error())==null?void 0:O.ex)==null?void 0:L.error_description)??((F=d.error())==null?void 0:F.toString())??"Неизвестная ошибка";const k=((U=(x=d.error())==null?void 0:x.ex)==null?void 0:U.error)??"";if(k==="OPERATION_TIME_LIMIT"){this.limitCall&&this.limitCall(g);const B=i.get(g);switch(k){case"OPERATION_TIME_LIMIT":B&&(this.skipList.add(B),this.limitCall&&this.limitCall(g));break;case"QUERY_LIMIT_EXCEEDED":this.canContinue=!1;break;case"ACCESS_DENIED":this.skipList.add(B);break}}}this.setProgressData({key:g,value:d,type:r})})};let m=[];for await(const[u,s,d]of e){if(!this.canContinue)return;const[g]=s;if(i.set(u,g),this.skipList.has(g))continue;let a=1;for(;d>a*50&&!this.skipList.has(g);){const c=[u,a].join("__"),y=A(u,a,m,s);m.push([c,o(s,y)]),m.length%50===0&&(await new Promise(O=>this.callBatch(Object.fromEntries(m),L=>{h(L),O()})),m=[],await this.delay()),a++}}m.length&&(await new Promise(u=>this.callBatch(Object.fromEntries(m),s=>{h(s),u()})),await this.delay())}errorLogger(){console.group(`${this.constructor.name}: Ошибки в методах!`),Object.entries(this.errors).forEach(([e,r])=>{r&&console.log(`[${e}]`,r.toString())}),console.groupEnd()}}class ut{constructor(){Y(this,V,{})}get hash(){return this.createHash(8)}createHash(e){let r="abcdefghijklmnopqrstuvwxyz0123456789",i="";e=e||6;for(let A=0;A<e;A++)i+=r.charAt(Math.floor(Math.random()*r.length));return i}actionFilter({keyTimer:e,duration:r=10,action:i}){_(this,V)[e]&&(clearTimeout(_(this,V)[e]),_(this,V)[e]=null),i&&(_(this,V)[e]=setTimeout(()=>{i()},r))}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(r=>{console.warn("noSleep: autoplay prevented",r)})}),e.addEventListener("ended",()=>{this.actionFilter({keyTimer:"no-sleep",duration:5e3,action:()=>{e.play().catch(r=>{console.warn("noSleep: replay prevented",r)})}})}),e.src="data:video/mp4;base64,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"}downloadFileJson(e,r){let i=new Blob([JSON.stringify(e)],{type:"application/json"}),A=URL.createObjectURL(i),o=document.createElement("a");o.style.display="none",o.href=A,o.download=`${r}.json`,document.body.appendChild(o),o.click(),setTimeout(()=>{document.body.removeChild(o),URL.revokeObjectURL(A)},200)}}V=new WeakMap;const ft=new ut;class gt{constructor(){Y(this,nt);Y(this,st);Y(this,At);Y(this,ot);Y(this,at);Y(this,j,"logger");Y(this,Z,!1);Y(this,K,new Map);Y(this,tt,{});Y(this,G,null);Y(this,q,!1);Y(this,et,!1);M(this,"periodClear",3);Q(this,nt,Nt).call(this)}async init(){try{let e=new v(BX24.callBatch),{entityList:r}=await e.batch({entityList:{method:"entity.get"}});if(r&&Array.isArray(r))if(r.find(A=>A.ENTITY==_(this,j)))J(this,Z,!0);else{let{entityAdd:A}=await e.batch({entityAdd:{method:"entity.add",params:{ENTITY:_(this,j),NAME:_(this,j),ACCESS:{AU:"X"}}}});A&&J(this,Z,!0)}return Q(this,ot,pt).call(this).catch(i=>{console.error("Ошибка при проверке периода очистки:",i)}),_(this,Z)}catch(e){return console.error("Ошибка при инициализации логера:",e),!1}}start({type:e,data:r}){if(!_(this,Z))return Q(this,st,dt).call(this,"entity"),null;if(!e||!r)return console.error("Невалидные данные для логирования:",{type:e,data:r}),null;const i=ft.hash,A={type:e,data:r,userInfo:_(this,tt),errorList:{},status:"",answer:null,date:new Date().getTime()};return _(this,K).set(i,A),J(this,et,!0),i}async stop({key:e,errorList:r,status:i,answer:A}){var h;if(!_(this,et))return;if(!_(this,Z)){Q(this,st,dt).call(this,"entity");return}let o=_(this,K).get(e);if(!o){console.error(`Не найдены данные логирования для ключа: ${e}`);return}r&&(o.errorList=r),i&&(o.status=i),A&&(o.answer=A),await Q(this,At,Ot).call(this),(h=o==null?void 0:o.data)!=null&&h.updateList&&J(this,q,!0),J(this,et,!1)}async getEntityList(e){var r;try{if((r=_(this,G))!=null&&r.length&&!_(this,q))return _(this,G);let i=new v(BX24.callBatch),{entityList:A}=await i.batch({entityList:{method:"entity.item.get",params:{ENTITY:_(this,j),SORT:{ID:"DESC"}}}},e);return!A||!Array.isArray(A)?(console.warn("Получен невалидный список записей"),[]):(A=A.map(o=>{try{const{ID:h,DATE_CREATE:m,DETAIL_TEXT:u}=o;return{...JSON.parse(u),id:h,dateCreate:m}}catch(h){return console.error(`Ошибка парсинга записи ${o.ID}:`,h),null}}).filter(o=>o!==null),J(this,q,!1),J(this,G,A),A)}catch(i){return console.error("Ошибка при получении списка записей:",i),[]}}async downAllEntityJson(){try{if(_(this,G)||await this.getEntityList(),!_(this,G)||_(this,G).length===0)return console.warn("Нет данных для выгрузки"),!1;let e=rt().format("%Y-%m-%d");return ft.downloadFileJson(_(this,G),`sdklogger-entity-data__${e}`),!0}catch(e){return console.error("Ошибка при выгрузке данных в JSON:",e),!1}}}j=new WeakMap,Z=new WeakMap,K=new WeakMap,tt=new WeakMap,G=new WeakMap,q=new WeakMap,et=new WeakMap,nt=new WeakSet,Nt=async function(){try{const e=new v(BX24.callBatch),r=BX24.isAdmin(),{curUser:i}=await e.batch({curUser:{method:"user.current"}});J(this,tt,{isAdmin:r,curUser:i})}catch(e){console.error("Ошибка при получении информации о пользователе:",e),J(this,tt,{isAdmin:!1,curUser:null})}},st=new WeakSet,dt=function(e){e=="entity"&&ft.actionFilter({keyTimer:"error.logger.entity",duration:500,action:()=>{console.error("Хранилище для логгера не инициализировано")}})},At=new WeakSet,Ot=async function(){try{let e={},r=new v(BX24.callBatch);for(let[i,A]of _(this,K).entries())if(A.status){const o=JSON.stringify(A);e[i]={method:"entity.item.add",params:{ENTITY:_(this,j),NAME:_(this,j),DETAIL_TEXT:o}}}if(Object.keys(e).length){let i=await r.batch(e),{errors:A}=r;for(let[o,h]of Object.entries({...i,...A}))_(this,K).delete(o);return!0}return!1}catch(e){return console.error("Ошибка при добавлении записей в хранилище:",e),!1}},ot=new WeakSet,pt=async function(){try{let e=new v(BX24.callBatch),{serverTime:r}=await e.batch({serverTime:{method:"server.time"}});if(!r){console.error("Не удалось получить время сервера");return}if(_(this,G)||await this.getEntityList(),!_(this,G)||_(this,G).length===0)return;let i=_(this,G).filter(A=>{try{let{dateCreate:o}=A;return o?rt(new Date(o)).between(rt(new Date(r)),"month")>=this.periodClear:!1}catch(o){return console.error("Ошибка при проверке даты записи:",o),!1}});i.length>0&&(console.log(`Найдено ${i.length} записей для очистки (старше ${this.periodClear} месяцев)`),await Q(this,at,_t).call(this,i))}catch(e){console.error("Ошибка при проверке периода очистки:",e)}},at=new WeakSet,_t=async function(e){try{if(!e||e.length===0)return!1;let r=new v(BX24.callBatch),i=e.filter(o=>o&&o.id).map(o=>{let{id:h}=o;return{method:"entity.item.delete",params:{ENTITY:_(this,j),ID:h}}});if(i.length===0)return!1;const A=await r.batch(i);return console.log(`Успешно удалено ${i.length} записей`),J(this,q,!0),A}catch(r){return console.error("Ошибка при очистке устаревших записей:",r),!1}};class Rt{constructor(e){Y(this,ht);Y(this,lt);M(this,"domain","");M(this,"isAdmin",!1);M(this,"appInfo",null);M(this,"appConst",null);M(this,"userInfo",null);M(this,"placeData",null);M(this,"placeInfo",null);M(this,"logger",!1);this.appConst=e}init(){return new Promise((e,r)=>{let A=setInterval(()=>{window.BX24&&BX24.init(async()=>{console.info("init BX24"),clearInterval(A),clearTimeout(o),this.domain=BX24.getDomain(),this.isAdmin=BX24.isAdmin(),this.placeInfo=BX24.placement.info(),this.logger?(this.logger=new gt,await this.logger.init()):this.logger={start:()=>{},stop:()=>{},getEntityList:()=>{}};const[h,m]=await Promise.all([Q(this,ht,yt).call(this),Q(this,lt,Et).call(this)]);this.appInfo=h,this.userInfo=m;let u=new ut;try{u.noSleep()}catch(s){console.warn("Failed to initialize noSleep:",s)}e(!0)})},100);const o=setTimeout(()=>{clearInterval(A);const h=new Error("BX24 initialization timeout: BX24 object not found within 30 seconds");console.error(h),r(h)},3e4)})}userOption(e,r){if(typeof BX24>"u"||!BX24.userOption){console.warn("BX24.userOption is not available. Make sure BX24 is initialized.");return}return r!==void 0?BX24.userOption.set(e,r):BX24.userOption.get(e)}appOption(e,r){if(typeof BX24>"u"||!BX24.appOption){console.warn("BX24.appOption is not available. Make sure BX24 is initialized.");return}return r!==void 0?BX24.appOption.set(e,r):BX24.appOption.get(e)}async call({method:e,params:r,updateList:i}){let A;if(i&&(A=this.logger.start({type:"call",data:{method:e,params:r,updateList:i}})),r||(r={}),typeof BX24>"u"||!BX24.callMethod){const o=new Error("BX24 is not initialized");throw console.error(o),o}return new Promise((o,h)=>{BX24.callMethod(e,r,async m=>{let u={};if(m!=null&&m.answer)for(let[s,d]of Object.entries(m.answer))s!=="result"&&d&&(u[s]=d);if(m.error()){let s=m.error();if(console.error(s),A)try{await this.logger.stop({answer:u,key:A,status:"fail",errorList:{0:s.toString()}})}catch(d){console.error("Logger error:",d)}o(!1)}else{let s=m.data();if(s!=null&&s.items&&(s=s.items),A)try{await this.logger.stop({answer:u,key:A,status:"success"})}catch(d){console.error("Logger error:",d)}o(s)}})})}async batch(e,r,{errorCall:i,limitCommandSerial:A,updateList:o,limitCall:h}={}){if(typeof BX24>"u"||!BX24.callBatch){const s=new Error("BX24 is not initialized");return console.error(s),!1}let m=new v(BX24.callBatch),u;o&&(u=this.logger.start({type:"batch",data:{commandList:e,updateList:o}})),A&&console.warn("limitCommandSerial is deprecated and not used in current Batch implementation");try{let s=await m.batch(e,r,h);if(Object.keys(m.errors).length){if(i&&i(m.errors),u)try{await this.logger.stop({key:u,status:"fail",errorList:m.errors})}catch(d){console.error("Logger error:",d)}}else if(u)try{await this.logger.stop({key:u,status:"success"})}catch(d){console.error("Logger error:",d)}return s}catch(s){if(u)try{await this.logger.stop({key:u,status:"fail-runtime",errorList:{0:s==null?void 0:s.toString()}})}catch(d){console.error("Logger error:",d)}return console.error(s),!1}}async batchTotalCount(e,r,{errorCall:i,updateList:A,limitCall:o}={}){if(typeof BX24>"u"||!BX24.callBatch){const u=new Error("BX24 is not initialized");return console.error(u),!1}let h=new v(BX24.callBatch),m;A&&(m=this.logger.start({type:"batch-total-count",data:{commandList:e}}));try{let u=await h.batchTotalCount(e,r,o);if(Object.keys(h.errors).length){if(i&&i(h.errors),m)try{await this.logger.stop({key:m,status:"fail",errorList:h.errors})}catch(s){console.error("Logger error:",s)}}else if(m)try{await this.logger.stop({key:m,status:"success"})}catch(s){console.error("Logger error:",s)}return u}catch(u){if(m)try{await this.logger.stop({key:m,status:"fail-runtime",errorList:{0:u==null?void 0:u.toString()}})}catch(s){console.error("Logger error:",s)}return console.error(u),!1}}async getPlacement(){return await this.call({method:"placement.get"}).then(e=>(this.placeData||(this.placeData=e),e))}async placementBind(e,r=!0){var d;if(!this.isAdmin)return;r&&await this.placementCheck();let i=[];if(Array.isArray(e)?i=e.map(g=>typeof g=="string"?{placement:g}:g):typeof e=="string"?i=[{placement:e}]:i=[e],this.placeData=await this.getPlacement(),!this.placeData)return;const{appName:A,pathApp:o}=this.appConst;let h=A;this.domain==="szdl.bitrix24.ru"&&((d=this.appInfo)!=null&&d.ID)&&(h=`${A}: #${this.appInfo.ID}`);const m=h.replace(" CRM",""),u={},s=[];for(let g=0;g<i.length;g++){const a=i[g],c=a.placement,y=a.userId;let O=o,L=c;if(c==="PAGE_BACKGROUND_WORKER"){if(!y){console.warn(`placementBind: userId is required for PAGE_BACKGROUND_WORKER, skipping ${c}`);continue}O=`${o}?USER_ID=${y}/`}if(c==="PAGE_BACKGROUND_WORKER_ALL"&&(L="PAGE_BACKGROUND_WORKER"),this.placeData.find(k=>k.placement===L&&k.handler===O))continue;let x=this.placeData.find(k=>k.placement===L&&k.handler!==O);x&&s.push({placement:L,handler:x.handler});const U={PLACEMENT:L,HANDLER:O,LANG_ALL:{ru:{TITLE:L==="USER_PROFILE_TOOLBAR"?m:h}},OPTIONS:{errorHandlerUrl:O}};c==="PAGE_BACKGROUND_WORKER"&&y&&(U.USER_ID=y),u[`bind_${g}`]={method:"placement.bind",params:U}}s.length>0&&await this.placementUnBind(s),Object.keys(u).length>0&&await this.batch(u),Object.keys(u).length>0&&(this.placeData=await this.getPlacement(),Object.values(u).forEach(g=>{console.log("Приложение успешно встроено в",g.params.PLACEMENT)}))}async placementUnBind(e){let r=[];Array.isArray(e)?r=e.map(A=>typeof A=="string"?{placement:A}:A):typeof e=="string"?r=[{placement:e}]:r=[e];const i={};for(let A=0;A<r.length;A++){const o=r[A],h=o.placement,m=o.handler,u={PLACEMENT:h};m&&(u.HANDLER=m),i[`unbind_${A}`]={method:"placement.unbind",params:u}}Object.keys(i).length>0&&(await this.batch(i),r.forEach(A=>{console.log("Встройка отвязана",A.placement)}))}async placementCheck(){if(this.placeData=await this.getPlacement(),!this.placeData)return;const{pathApp:e}=this.appConst,r=[],i=[];for(const A of this.placeData){if(!A.handler||A.handler.includes(e))continue;const{placement:o,handler:h,userId:m}=A;r.push({placement:o,handler:h}),i.push({placement:o,userId:m})}r.length>0&&await this.placementUnBind(r),i.length>0&&await this.placementBind(i,!1)}getBotList(){return this.call({method:"imbot.bot.list",params:{}}).then(e=>{let r=Object.values(e);return console.log("chat-bot list:",r),r})}regBot({code:e,type:r,name:i}){const{appName:A,pathApp:o,chatBotLogo:h}=this.appConst,m=this.appInfo.ID;return this.call({method:"imbot.register",params:{CODE:e??this.appInfo.CODE,TYPE:r??"O",EVENT_HANDLER:o,OPENLINE:"Y",CLIENT_ID:"",PROPERTIES:{NAME:`${i??A} - бот #${m}`,LAST_NAME:"",COLOR:"GREEN",EMAIL:"",PERSONAL_BIRTHDAY:rt().format("%Y-%m-%d"),WORK_POSITION:"Почтальон",PERSONAL_WWW:"",PERSONAL_GENDER:"M",PERSONAL_PHOTO:h??""}}}).then(u=>(console.log("Чат-бот добавлен",u),u))}unRegBot(e){return this.call({method:"imbot.unregister",params:{BOT_ID:e}}).then(r=>(console.log("чат-бот удален",r),r))}getLoggerList(e){return this.logger.getEntityList(e)}}ht=new WeakSet,yt=function(){return this.call({method:"app.info"})},lt=new WeakSet,Et=function(){return this.call({method:"user.current"})};class Lt{constructor(e){M(this,"entityName","tabs");M(this,"maxTabs",5);M(this,"interval");M(this,"id",0);M(this,"tabList",[]);M(this,"random",this.getRandomNum());M(this,"continueCondition");M(this,"defaultContinueBackground",()=>!0);M(this,"activeMaxPause",60*1e3*5+this.random);M(this,"activeMinPause",60*1e3*3+this.random);if(!e){console.error("В бек-воркер не переданы настройки, отмена вызова"),console.log("BackgroundWorker: Отмена конструктора - отсутствуют опции");return}const{appFunc:r,bx:i,users:A,continueBackground:o}=e;this.bx=i,this.appPath=i.appConst.pathApp??"",this.appName=i.appConst.appName??"",this.appInit=r,this.users=A,this.start=new Date,this.continueCondition=typeof o=="function"?o:this.defaultContinueBackground}async init(){if(!this.appInit){console.error("Функция-запуск не передана в appInit, отмена инициализации бекворкера"),console.log("BackgroundWorker: Отмена init - не передана appInit");return}if(!this.bx){console.error("Не передан экземпляр bxBoot"),console.log("BackgroundWorker: Отмена init - отсутствует bx");return}if(await this.bx.placementBind(["PAGE_BACKGROUND_WORKER"]),!await this.continueBackground()){console.log("BackgroundWorker: Отмена init - условие запуска не выполнено");return}await this.checkEntity(),this.tabList=await this.getFilteredTabList(),this.id=await this.addTab(),console.log("tabId",this.id),this.interval=setInterval(()=>{this.backgroundPolling().catch(e=>{console.error("BackgroundWorker: backgroundPolling failed",e)})},this.activeMinPause)}async checkEntity(){var i;const e=await this.bx.call({method:"entity.get"});((i=e==null?void 0:e.find)==null?void 0:i.call(e,A=>A.ENTITY===this.entityName))||await this.bx.call({method:"entity.add",params:{ENTITY:this.entityName,NAME:this.entityName,ACCESS:{AU:"X"}}})}async getTabs(){var r;const e=await this.bx.call({method:"entity.item.get",params:{ENTITY:this.entityName,FILTER:{NAME:(r=this.bx.userInfo)==null?void 0:r.ID},SORT:{DATE_CREATE:"DESC"}}});return e!=null&&e.length?e.map(i=>{if(!i)return{id:void 0,data:void 0};try{return{id:i.ID,data:{...JSON.parse(i.DETAIL_TEXT)}}}catch(A){return console.log(A),{id:i.ID,data:void 0}}}):[]}async addTab(){var r;const e={lastActive:new Date().toISOString(),duration:new Date().getTime()-this.start.getTime(),start:!1};return this.tabList.length<this.maxTabs&&await this.bx.call({method:"entity.item.add",params:{ENTITY:this.entityName,NAME:(r=this.bx.userInfo)==null?void 0:r.ID,DETAIL_TEXT:JSON.stringify(e)}})||0}async updateTab(e){var i;const r={lastActive:new Date().toISOString(),duration:new Date().getTime()-this.start.getTime(),start:e};await this.bx.call({method:"entity.item.update",params:{ENTITY:this.entityName,ID:this.id,NAME:(i=this.bx.userInfo)==null?void 0:i.ID,DETAIL_TEXT:JSON.stringify(r)}})}async deleteTabs(e=[]){if(!e.length)return;const r=e.map(i=>({method:"entity.item.delete",params:{ENTITY:this.entityName,ID:i.id}}));r.length&&await this.bx.batch(r)}getRandomNum(){const e=Math.round(Number(Math.random().toFixed(2))*30);return Math.round(Math.random())?e:-e}async continueBackground(){try{const r=!!await Promise.resolve(this.continueCondition(this));return console.log(r?"BackgroundWorker: Условие продолжения выполнено":"BackgroundWorker: Отмена continueBackground - внешнее условие вернуло false"),r}catch(e){return console.error("BackgroundWorker: Ошибка при выполнении условия продолжения",e),console.log("BackgroundWorker: Отмена continueBackground - исключение в условии запуска"),!1}}async getFilteredTabList(){const e=[],r=[],i=await this.getTabs();for(const A of i){if(!(A!=null&&A.data)){e.push(A);continue}new Date().getTime()-new Date(A.data.lastActive).getTime()>this.activeMaxPause?e.push(A):r.push(A)}return await this.deleteTabs(e),r}async backgroundPolling(){if(!await this.continueBackground()){this.interval&&(clearInterval(this.interval),this.interval=void 0),console.log("BackgroundWorker: Остановка backgroundPolling - условие continueBackground не выполнено");return}if(this.tabList=await this.getFilteredTabList(),!this.id){this.id=await this.addTab();return}let e=this.checkOtherTabs();e&&(await this.pause(Math.round(Number(Math.random().toFixed(2))*1e4)),this.tabList=await this.getFilteredTabList(),e=this.checkOtherTabs(),e&&await this.startBackground())}checkOtherTabs(){var A,o;let e=!1,r=new Date().getTime()-new Date(this.start).getTime();for(const h of this.tabList)if(+h.id!==this.id&&((A=h.data)!=null&&A.start&&(e=!0),((o=h.data)==null?void 0:o.duration)>r)){r=!1;break}const i=!e&&!!r;return this.updateTab(i).catch(h=>{console.error("BackgroundWorker: updateTab failed",h)}),console.log(`BackgroundWorker: Проверка вкладок - можно запускать приложение? ${i}`),i}async startBackground(){this.interval&&(clearInterval(this.interval),this.interval=void 0),this.interval=setInterval(()=>{this.updateTab(!0).catch(e=>{console.error("BackgroundWorker: periodic updateTab failed",e)})},this.activeMinPause),await this.appInit(),this.interval&&(clearInterval(this.interval),this.interval=void 0),this.id&&(await this.deleteTabs([{id:this.id}]),this.id=0)}async setBackgroundWorkerAll(){var d,g;if(!((d=this.bx)!=null&&d.isAdmin)){console.log("BackgroundWorker: Отмена setBackgroundWorkerAll - пользователь не админ");return}(g=this.users)!=null&&g.length||await this.getEntityData();const e=await this.bx.getPlacement(),r=new Map;let i=null;e.forEach(a=>{a.placement==="PAGE_BACKGROUND_WORKER"&&(a.userId?r.set(+a.userId,a):i=a)}),console.log(`setBackgroundWorkerAll: Найдено ${r.size} индивидуальных и ${i?1:0} общих привязок PAGE_BACKGROUND_WORKER`);const A=await this.getAdminsList(),o=await this.getEligibleUsersForBackgroundWorker(A);o.sort((a,c)=>{const y=a.LAST_LOGIN?new Date(a.LAST_LOGIN):new Date(0);return(c.LAST_LOGIN?new Date(c.LAST_LOGIN):new Date(0))-y}),console.log(`setBackgroundWorkerAll: Найдено ${o.length} подходящих пользователей (админы и руководители)`);const h=[];!i&&this.appPath&&(h.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}/`}}}),console.log("setBackgroundWorkerAll: Добавлен в очередь создание общего бэк-воркера"));const m=10,u=o.slice(0,m),s=[];for(const[a]of r)o.find(y=>+y.ID===a)||s.push(a);for(const a of s)this.appPath&&(h.push({method:"placement.unbind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${a}/`}}),console.log(`setBackgroundWorkerAll: Добавлена в очередь отвязка бэк-воркера от пользователя ${a}`));for(const a of u)r.has(+a.ID)||!this.appPath||h.push({method:"placement.bind",params:{PLACEMENT:"PAGE_BACKGROUND_WORKER",HANDLER:`${this.appPath}?USER_ID=${a.ID}/`,LANG_ALL:{ru:{TITLE:this.appName}},OPTIONS:{errorHandlerUrl:`${this.appPath}?USER_ID=${a.ID}/`},USER_ID:a.ID}});h.length?(console.log(`setBackgroundWorkerAll: Выполняем ${h.length} операций через batch`),await this.bx.batch(h),console.log("setBackgroundWorkerAll: Все операции batch выполнены успешно")):console.log("setBackgroundWorkerAll: Нет операций для выполнения")}async getEligibleUsersForBackgroundWorker(e=[]){return(this.users??[]).filter(i=>i.ACTIVE==="Y"||i.ACTIVE===!0).filter(i=>{const A=+i.ID;return e.includes(A)})}async updateAdminsList(){var e,r,i;try{const A=BX24.appOption.get("adminsList");let o=[];if(A)try{o=JSON.parse(A)}catch{console.log("updateAdminsList: Ошибка парсинга существующего списка админов, создаем новый"),o=[]}const h=+(((e=this.bx.userInfo)==null?void 0:e.ID)??0);(r=this.bx)!=null&&r.isAdmin&&h&&!o.includes(h)&&(o.push(h),console.log(`updateAdminsList: Добавлен новый админ ${h}`)),!((i=this.bx)!=null&&i.isAdmin)&&h&&o.includes(h)&&(o=o.filter(s=>s!==h),console.log(`updateAdminsList: Удален из списка админов пользователь ${h} (больше не админ)`));const m=new Set((this.users??[]).filter(s=>s.ACTIVE==="Y"||s.ACTIVE===!0).map(s=>+s.ID)),u=o.filter(s=>m.has(s));return u.length!==o.length&&(console.log(`updateAdminsList: Удалено ${o.length-u.length} неактивных админов`),o=u),BX24.appOption.set("adminsList",JSON.stringify(o)),console.log(`BackgroundWorker: Список админов обновлен: ${o.length} админов`),o}catch(A){return console.error("BackgroundWorker: Ошибка при обновлении списка админов:",A),[]}}async getAdminsList(){try{const e=BX24.appOption.get("adminsList");return e?JSON.parse(e):[]}catch(e){return console.error("getAdminsList: Ошибка при получении списка админов:",e),[]}}async getEntityData(){const e={users:{method:"user.get",params:{filter:{ACTIVE:"Y"}}}},{users:r}=await this.bx.batch(e).then(i=>i?(Array.isArray(i.users)||(i.users=[]),i):{users:[]});this.users=r}pause(e=500,r){return new Promise(i=>{setTimeout(()=>{r&&r(),i(!0)},e)})}}N.BackgroundWorker=Lt,N.Batch=v,N.BxBoot=Rt,N.BxHelper=ut,N.BxLogger=gt,N.tempus=rt,Object.defineProperty(N,Symbol.toStringTag,{value:"Module"})});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type BxBoot from "./bx-boot";
|
|
2
|
+
|
|
3
|
+
/** Флаг активности пользователя из Bitrix24 */
|
|
4
|
+
type Booleanish = boolean | 'Y' | 'N';
|
|
5
|
+
|
|
6
|
+
/** Краткая информация о пользователе, используемая воркером */
|
|
7
|
+
type BackgroundWorkerUser = {
|
|
8
|
+
ID: string | number;
|
|
9
|
+
ACTIVE?: Booleanish;
|
|
10
|
+
LAST_LOGIN?: string | null;
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/** Служебные данные таба, сохраненные в HL-подобном хранилище */
|
|
15
|
+
type BackgroundWorkerTab = {
|
|
16
|
+
id?: number;
|
|
17
|
+
data?: Record<string, unknown>;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
type BackgroundWorkerOptions = {
|
|
21
|
+
bx: BxBoot;
|
|
22
|
+
appFunc?: () => void | Promise<void>;
|
|
23
|
+
users?: BackgroundWorkerUser[];
|
|
24
|
+
continueBackground?: (worker: BackgroundWorker) => boolean | Promise<boolean>;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
declare class BackgroundWorker {
|
|
28
|
+
constructor(options: BackgroundWorkerOptions);
|
|
29
|
+
|
|
30
|
+
/** Имя сущности для хранения данных о табах */
|
|
31
|
+
readonly entityName: string;
|
|
32
|
+
/** Максимальное количество параллельных табов */
|
|
33
|
+
readonly maxTabs: number;
|
|
34
|
+
/** Ссылка на используемый экземпляр BxBoot */
|
|
35
|
+
readonly bx?: BxBoot;
|
|
36
|
+
|
|
37
|
+
/** Инициализация воркера: регистрация в placement и создание записи таба */
|
|
38
|
+
init(): Promise<void>;
|
|
39
|
+
/** Проверка существования сущности хранения и создание при необходимости */
|
|
40
|
+
checkEntity(): Promise<void>;
|
|
41
|
+
/** Получение актуального списка табов для текущего пользователя */
|
|
42
|
+
getTabs(): Promise<BackgroundWorkerTab[]>;
|
|
43
|
+
/** Добавление новой записи таба для текущего окна */
|
|
44
|
+
addTab(): Promise<number>;
|
|
45
|
+
/** Обновление статуса текущего таба */
|
|
46
|
+
updateTab(start: boolean): Promise<void>;
|
|
47
|
+
/** Удаление списка табов */
|
|
48
|
+
deleteTabs(tabList?: BackgroundWorkerTab[]): Promise<void>;
|
|
49
|
+
/** Генерация случайной дельты для смещения таймеров */
|
|
50
|
+
getRandomNum(): number;
|
|
51
|
+
/** Проверка, пришло ли время запускать фоновые задачи */
|
|
52
|
+
continueBackground(): Promise<boolean>;
|
|
53
|
+
/** Получение списка табов с фильтрацией устаревших записей */
|
|
54
|
+
getFilteredTabList(): Promise<BackgroundWorkerTab[]>;
|
|
55
|
+
/** Основной цикл фоновой проверки условий запуска приложения */
|
|
56
|
+
backgroundPolling(): Promise<void>;
|
|
57
|
+
/** Проверка остальных табов на предмет запущенного процесса */
|
|
58
|
+
checkOtherTabs(): boolean;
|
|
59
|
+
/** Запуск фонового процесса и очистка текущей записи */
|
|
60
|
+
startBackground(): Promise<void>;
|
|
61
|
+
/** Массовая привязка фонового воркера к пользователям */
|
|
62
|
+
setBackgroundWorkerAll(): Promise<void>;
|
|
63
|
+
/** Возвращает список пользователей, имеющих право запускать бэкворкер */
|
|
64
|
+
getEligibleUsersForBackgroundWorker(adminsList?: number[]): Promise<BackgroundWorkerUser[]>;
|
|
65
|
+
/** Обновляет список администраторов приложения */
|
|
66
|
+
updateAdminsList(): Promise<number[]>;
|
|
67
|
+
/** Получает список администраторов приложения */
|
|
68
|
+
getAdminsList(): Promise<number[]>;
|
|
69
|
+
/** Загружает из Bitrix24 пользователей и подразделения */
|
|
70
|
+
getEntityData(): Promise<void>;
|
|
71
|
+
/** Пауза с опциональным колбэком после ожидания */
|
|
72
|
+
pause(duration?: number, call?: () => void): Promise<boolean>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type {
|
|
76
|
+
BackgroundWorkerOptions,
|
|
77
|
+
BackgroundWorkerUser,
|
|
78
|
+
BackgroundWorkerTab,
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
export default BackgroundWorker;
|
package/dist/types/batch.d.ts
CHANGED
|
@@ -1,72 +1,138 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Параметры объекта команды batch-запроса.
|
|
3
|
+
*/
|
|
4
|
+
type TCommandObjectParams =
|
|
5
|
+
| Record<string, unknown>
|
|
6
|
+
| {
|
|
7
|
+
select?: string[];
|
|
8
|
+
filter?: Record<string, string | string[]>;
|
|
9
|
+
}
|
|
10
|
+
| {
|
|
11
|
+
id?: string;
|
|
12
|
+
params?: Record<string, string>;
|
|
13
|
+
fields?: Record<string, unknown>;
|
|
14
|
+
};
|
|
12
15
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
*/
|
|
18
|
-
constructor(callBatch: ()=>void);
|
|
16
|
+
/**
|
|
17
|
+
* Описание команды batch-запроса: либо объект, либо массив (устаревшие форматы некоторых методов).
|
|
18
|
+
*/
|
|
19
|
+
type TCommand = { method: string; params?: TCommandObjectParams } | [string, ...unknown[]];
|
|
19
20
|
|
|
20
|
-
|
|
21
|
-
* Флаг режима передачи
|
|
22
|
-
*/
|
|
23
|
-
get serial(): boolean;
|
|
21
|
+
type TCommandList = Record<string, TCommand> | TCommand[];
|
|
24
22
|
|
|
25
|
-
|
|
26
|
-
* лимит команд при котором происходит переключение батча в последовательный режим по дефолту 50
|
|
27
|
-
*/
|
|
28
|
-
limitCommandSerial: number
|
|
23
|
+
type TBatchResult = Record<string, unknown>;
|
|
29
24
|
|
|
30
|
-
|
|
31
|
-
|
|
25
|
+
type TBatchProgress = {
|
|
26
|
+
percent: number;
|
|
27
|
+
allCount: number;
|
|
28
|
+
allTotal: number;
|
|
29
|
+
data?: Record<string, { total: number; count: number }>;
|
|
30
|
+
};
|
|
32
31
|
|
|
33
|
-
|
|
34
|
-
answerData: Record<string, any>;
|
|
32
|
+
type TBatchProgressCallback = (payload: TBatchProgress) => void;
|
|
35
33
|
|
|
36
|
-
|
|
37
|
-
* Установить последовательный режим
|
|
38
|
-
*/
|
|
39
|
-
setSerial(): void;
|
|
34
|
+
type TBatchLimitCallback = (key: string) => void;
|
|
40
35
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
36
|
+
type TCallBatch = (
|
|
37
|
+
commandList: Record<string, TCommand>,
|
|
38
|
+
callback: (result: Record<string, any>) => void
|
|
39
|
+
) => void;
|
|
45
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Класс-обертка над BX24.callBatch с дополнительной логикой пагинации,
|
|
43
|
+
* логированием и трекингом прогресса выполнения.
|
|
44
|
+
*/
|
|
45
|
+
declare class Batch {
|
|
46
46
|
/**
|
|
47
|
-
*
|
|
47
|
+
* @param callBatch - проксированный метод BX24.callBatch
|
|
48
48
|
*/
|
|
49
|
+
constructor(callBatch: TCallBatch);
|
|
50
|
+
|
|
51
|
+
/** Сохраненная ссылка на callBatch */
|
|
52
|
+
private callBatch: TCallBatch;
|
|
53
|
+
|
|
54
|
+
/** Объект с результатами, где ключ совпадает с ключом исходного запроса */
|
|
55
|
+
result: Record<string, unknown>;
|
|
56
|
+
/** Объект ошибок, где ключ совпадает с ключом чанка, а значение описывает ошибку */
|
|
57
|
+
errors: Record<string, string>;
|
|
58
|
+
/** Лимит команд в одном запросе (по умолчанию 50) */
|
|
59
|
+
limit: number;
|
|
60
|
+
/** Флаг продолжения выполнения запросов */
|
|
61
|
+
canContinue: boolean;
|
|
62
|
+
/** Callback прогресса выполнения batch */
|
|
63
|
+
progressCall?: TBatchProgressCallback;
|
|
64
|
+
/** Callback при достижении лимитов/ошибок времени выполнения */
|
|
65
|
+
limitCall?: TBatchLimitCallback;
|
|
66
|
+
/** Хранилище промежуточных данных прогресса */
|
|
67
|
+
progressData: Record<string, { total: number; count: number }> | '';
|
|
68
|
+
/** Таймер для обновления прогресса */
|
|
69
|
+
progressTimer: ReturnType<typeof setInterval> | '';
|
|
70
|
+
/** Задержка между отправкой прогресса (мс) */
|
|
71
|
+
progressDelay: number;
|
|
72
|
+
/** Предыдущее значение процента прогресса */
|
|
73
|
+
oldPercent: number | 'no';
|
|
74
|
+
/** Коэффициент чанков (используется при вычислении прогресса) */
|
|
75
|
+
chunkRate: number | string;
|
|
76
|
+
/** Общий прогресс выполнения в процентах */
|
|
77
|
+
totalProgress: number;
|
|
78
|
+
/** Список методов, которые нужно пропустить (например, при ошибках) */
|
|
79
|
+
skipList: Set<string>;
|
|
80
|
+
|
|
81
|
+
/** Вычисление текущего прогресса выполнения batch-запросов */
|
|
82
|
+
get progressPercent(): TBatchProgress;
|
|
83
|
+
|
|
84
|
+
/** Нормализация данных ответа */
|
|
85
|
+
getData<T = unknown>(data: T): T;
|
|
86
|
+
/** Обновление данных прогресса */
|
|
87
|
+
setProgressData(params: { key: string; value: any; type?: 'count' }): void;
|
|
88
|
+
/** Задержка между запросами (используется при повторной пагинации) */
|
|
89
|
+
delay(): Promise<void>;
|
|
90
|
+
|
|
91
|
+
/** Принудительная остановка выполнения запросов */
|
|
49
92
|
stop(): void;
|
|
93
|
+
/** Очистка данных прогресса */
|
|
94
|
+
clearProgressData(): void;
|
|
95
|
+
|
|
96
|
+
/** Подготовка команды к выполнению: приводит объекты/массивы к единому виду */
|
|
97
|
+
arrayChunk(data: TCommand): { method: string; params?: TCommandObjectParams } | false;
|
|
50
98
|
|
|
51
|
-
/**
|
|
52
|
-
* Пакетный запрос данных
|
|
53
|
-
* @param commandList - лист команд можно передавать как в виде объекта, так и в виде массива команд
|
|
54
|
-
* @param progressCall - принимает callback в который передается статус загрузки данных в процентах
|
|
55
|
-
*/
|
|
56
99
|
batch(
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
100
|
+
commandList: TCommandList,
|
|
101
|
+
progressCall?: TBatchProgressCallback,
|
|
102
|
+
limitCall?: TBatchLimitCallback
|
|
103
|
+
): Promise<TBatchResult>;
|
|
60
104
|
|
|
61
|
-
/**
|
|
62
|
-
* Пакетный запрос количества элементов по запрощенным сущностям
|
|
63
|
-
* @param commandList - лист команд можно передавать как в виде объекта, так и в виде массива команд
|
|
64
|
-
* @param progressCall - принимает callback в который передается статус загрузки данных в процентах
|
|
65
|
-
*/
|
|
66
105
|
batchTotalCount(
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
106
|
+
commandList: TCommandList,
|
|
107
|
+
progressCall?: TBatchProgressCallback,
|
|
108
|
+
limitCall?: TBatchLimitCallback
|
|
109
|
+
): Promise<TBatchResult>;
|
|
110
|
+
|
|
111
|
+
/** Выполнение одного чанка запросов */
|
|
112
|
+
batchChunk(
|
|
113
|
+
commandList: Record<string, TCommand>,
|
|
114
|
+
type?: 'count'
|
|
115
|
+
): Promise<Record<string, unknown>>;
|
|
116
|
+
|
|
117
|
+
/** Рекурсивная пагинация для списочных методов */
|
|
118
|
+
batchPayload(
|
|
119
|
+
payloadList: Array<[string, TCommand, number]>,
|
|
120
|
+
type?: 'count'
|
|
121
|
+
): Promise<void>;
|
|
122
|
+
|
|
123
|
+
/** Вывод ошибок в консоль */
|
|
124
|
+
errorLogger(): void;
|
|
70
125
|
}
|
|
71
126
|
|
|
72
|
-
export default Batch;
|
|
127
|
+
export default Batch;
|
|
128
|
+
|
|
129
|
+
export type {
|
|
130
|
+
TCommandObjectParams,
|
|
131
|
+
TCommand,
|
|
132
|
+
TCommandList,
|
|
133
|
+
TBatchResult,
|
|
134
|
+
TBatchProgress,
|
|
135
|
+
TBatchProgressCallback,
|
|
136
|
+
TBatchLimitCallback,
|
|
137
|
+
TCallBatch,
|
|
138
|
+
};
|