@bxshefby/b24jssdk
Version:
Bitrix24 REST API JavaScript SDK
70 lines • 448 kB
JavaScript
/**
* @package @bxshefby/b24jssdk
* @version 3.3.0
* @copyright (c) 2026 Bitrix24
* @license MIT
* @see https://github.com/bx-shef/b24-js-sdk
* @see https://b24-js-sdk.bx-shef.by/
*/(function(A,W){typeof exports=="object"&&typeof module<"u"?W(exports):typeof define=="function"&&define.amd?define(["exports"],W):(A=typeof globalThis<"u"?globalThis:A||self,W(A.B24Js={}))})(this,(function(A){"use strict";var W=(r=>(r[r.DEBUG=0]="DEBUG",r[r.INFO=1]="INFO",r[r.NOTICE=2]="NOTICE",r[r.WARNING=3]="WARNING",r[r.ERROR=4]="ERROR",r[r.CRITICAL=5]="CRITICAL",r[r.ALERT=6]="ALERT",r[r.EMERGENCY=7]="EMERGENCY",r))(W||{});const hu=["MMMMM","LLLLL","EEEEE","ccccc","yyyy","MMMM","LLLL","EEEE","cccc","MMM","LLL","EEE","ccc","SSS","ooo","uuu","ZZZ","yy","MM","LL","dd","HH","hh","mm","ss","qq","uu","ZZ","y","M","L","d","H","h","m","s","S","a","E","c","q","o","u","x","X","Z"];function du(r,e){if(!(r instanceof Date)||Number.isNaN(r.getTime()))return"Invalid DateTime";const t=(u,l=2)=>String(Math.trunc(Math.abs(u))).padStart(l,"0"),s=u=>new Intl.DateTimeFormat("en-US",u).format(r),n=u=>{const l=-r.getTimezoneOffset(),h=l<0?"-":"+",d=Math.trunc(Math.abs(l)/60),f=Math.abs(l)%60;return u==="short"?f?`${h}${d}:${t(f)}`:`${h}${d}`:u==="colon"?`${h}${t(d)}:${t(f)}`:`${h}${t(d)}${t(f)}`},i=r.getHours()%12||12,o=Math.round((Date.UTC(r.getFullYear(),r.getMonth(),r.getDate())-Date.UTC(r.getFullYear(),0,1))/864e5)+1,a={yyyy:()=>t(r.getFullYear(),4),yy:()=>t(r.getFullYear()%100),y:()=>String(r.getFullYear()),MMMMM:()=>s({month:"narrow"}),LLLLL:()=>s({month:"narrow"}),EEEEE:()=>s({weekday:"narrow"}),ccccc:()=>s({weekday:"narrow"}),MMMM:()=>s({month:"long"}),MMM:()=>s({month:"short"}),MM:()=>t(r.getMonth()+1),M:()=>String(r.getMonth()+1),LLLL:()=>s({month:"long"}),LLL:()=>s({month:"short"}),LL:()=>t(r.getMonth()+1),L:()=>String(r.getMonth()+1),dd:()=>t(r.getDate()),d:()=>String(r.getDate()),EEEE:()=>s({weekday:"long"}),EEE:()=>s({weekday:"short"}),cccc:()=>s({weekday:"long"}),ccc:()=>s({weekday:"short"}),HH:()=>t(r.getHours()),H:()=>String(r.getHours()),hh:()=>t(i),h:()=>String(i),mm:()=>t(r.getMinutes()),m:()=>String(r.getMinutes()),ss:()=>t(r.getSeconds()),s:()=>String(r.getSeconds()),SSS:()=>t(r.getMilliseconds(),3),S:()=>String(r.getMilliseconds()),a:()=>r.getHours()<12?"AM":"PM",E:()=>String(r.getDay()||7),c:()=>String(r.getDay()||7),qq:()=>t(Math.floor(r.getMonth()/3)+1),q:()=>String(Math.floor(r.getMonth()/3)+1),ooo:()=>t(o,3),o:()=>String(o),uuu:()=>String(Math.floor(r.getMilliseconds()/100)),uu:()=>t(Math.floor(r.getMilliseconds()/10)),u:()=>t(r.getMilliseconds(),3),x:()=>String(r.getTime()),X:()=>String(Math.floor(r.getTime()/1e3)),ZZZ:()=>n("plain"),ZZ:()=>n("colon"),Z:()=>n("short")};let c="";for(let u=0;u<e.length;){if(e[u]==="'"){const h=e.indexOf("'",u+1);if(h===u+1){c+="'",u+=2;continue}c+=h===-1?e.slice(u+1):e.slice(u+1,h),u=h===-1?e.length:h+1;continue}const l=hu.find(h=>e.startsWith(h,u));if(l){c+=a[l](),u+=l.length;continue}c+=e[u],u++}return c}class Ws{dateFormat;constructor(e="YYYY-MM-DD HH:mm:ss"){this.dateFormat=e}_formatTimestamp(e){return Math.floor((e instanceof Date?e.getTime():Number.NaN)/1e3).toFixed(0)}_formatDate(e){return du(e,this.dateFormat.replace(/YYYY/g,"yyyy").replace(/YY/g,"yy").replace(/DD/g,"dd").replace(/D/g,"d"))}}class fu extends Ws{constructor(e="YYYY-MM-DD HH:mm:ss"){super(e)}format(e){return JSON.stringify({channel:e.channel,levelName:e.levelName,message:e.message,context:e.context,extra:e.extra,timestamp:this._formatTimestamp(e.timestamp),date:this._formatDate(e.timestamp)})}}class ts extends Ws{formatString;constructor(e="[{channel}] {levelName}: {message} {context} {extra} {date}",t="YYYY-MM-DD HH:mm:ss"){super(t),this.formatString=e}format(e){let t=this.formatString;const s={"{channel}":e.channel,"{levelName}":e.levelName,"{message}":e.message,"{context}":JSON.stringify(e.context),"{extra}":JSON.stringify(e.extra),"{timestamp}":this._formatTimestamp(e.timestamp),"{date}":this._formatDate(e.timestamp)};for(const[n,i]of Object.entries(s))t=t.replace(n,i);return t}}const pu=new Set(["_","*","`","["]);class zs extends Ws{parseMode;maxMessageLength;constructor(e=!0,t="YYYY-MM-DD HH:mm:ss",s=4096){super(t),this.parseMode=e?"HTML":"Markdown",this.maxMessageLength=s}format(e){let t=this._formatBaseMessage(e);const s=this._formatAdditionalInfo(e);return s&&(t+=`
${s}`),t.length>this.maxMessageLength&&(t=this._truncate(t)),t}_truncate(e){const t=this.parseMode==="MarkdownV2"?"\\.\\.\\.":"...",s=this.parseMode==="HTML"?0:4;let n=e.substring(0,this.maxMessageLength-t.length-s);return this.parseMode==="HTML"?(n=n.replace(/&[#a-z0-9]{0,7}$/i,""),n+t):((/\\+$/.exec(n)?.[0].length??0)%2===1&&(n=n.slice(0,-1)),n=n.replace(/(?<!`)`{1,2}$/,""),(n.match(/```/g)?.length??0)%2===1?`${n}
\`\`\`${t}`:n+t)}_formatBaseMessage(e){const t=String(this._formatDate(e.timestamp)),s=String(e.levelName),n=String(e.channel),i=String(e.message);return this.parseMode==="HTML"?`<b>${this._escapeHtml(s)}</b> | <code>${this._escapeHtml(n)}</code>
<i>Time:</i> ${this._escapeHtml(t)}
<i>Message:</i>
${this._escapeHtml(i)}`:`*${this._escapeText(s)}* \`${this._escapeCode(n)}\`
_Time:_ \`${this._escapeCode(t)}\`
_Message:_
${this._escapeText(i)}`}_formatAdditionalInfo(e){const t=[];return e.context&&Object.keys(e.context).length>0&&t.push(this._formatJsonBlock("Context",JSON.stringify(e.context,null,2))),e.extra&&Object.keys(e.extra).length>0&&t.push(this._formatJsonBlock("Extra",JSON.stringify(e.extra,null,2))),t.join(`
`)}_formatJsonBlock(e,t){return this.parseMode==="HTML"?`<i>${e}:</i>
<pre><code class="language-json">${this._escapeHtml(t)}</code></pre>`:`_${e}:_
\`\`\`json
${this._escapeCode(t)}
\`\`\``}_escapeText(e){return this.parseMode==="MarkdownV2"?this._escapeMarkdownV2(e):Array.from(e,t=>pu.has(t)?`\\${t}`:t).join("")}_escapeCode(e){return this.parseMode==="MarkdownV2"?e.replace(/[\\`]/g,"\\$&"):e.replace(/`/g,"'")}_escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}_escapeMarkdownV2(e){return e.replace(/[\\_*[\]()~`>#+\-=|{}.!]/g,"\\$&")}setUseHtml(e){return this.parseMode=e?"HTML":"Markdown",this}setParseMode(e){return this.parseMode=e,this}setMaxMessageLength(e){return this.maxMessageLength=e,this}}const gu=r=>(r.extra.pid="?",typeof process<"u"&&process.pid&&(r.extra.pid=process.pid),r),mu=r=>(r.extra.memoryUsage="?",typeof process<"u"&&process.memoryUsage&&(r.extra.memoryUsage=Math.round(process.memoryUsage().heapUsed/1024/1024)+"MB"),r);class Yt{level;formatter=null;bubble=!0;constructor(e=W.DEBUG,t){this.level=e,t!==void 0&&(this.bubble=t)}isHandling(e){return e>=this.level}shouldBubble(){return this.bubble}setFormatter(e){this.formatter=e}getFormatter(){return this.formatter}}class zi extends Yt{_styles=new Map;_useStyles;constructor(e=W.DEBUG,t){const s={useStyles:!0,...t};super(e,s.bubble),this._useStyles=s.useStyles,this._initStyles(),this.setFormatter(new ts)}_initStyles(){const e="color: _color_; background: _bg_; padding: 2px 6px; border-radius: 3px; font-size: 11px;";this._styles.set(W.DEBUG,["%cDEBUG",e.replace("_color_","#666666").replace("_bg_","#F0F0F0")]),this._styles.set(W.INFO,["%cINFO",e.replace("_color_","white").replace("_bg_","#2196F3")]),this._styles.set(W.NOTICE,["%cNOTICE",e.replace("_color_","white").replace("_bg_","#213BF3")]),this._styles.set(W.WARNING,["%cWARN",e.replace("_color_","white").replace("_bg_","#FF9800")]),this._styles.set(W.ERROR,["%cERROR",e.replace("_color_","white").replace("_bg_","#F44336")]),this._styles.set(W.CRITICAL,["%cCRITICAL",e.replace("_color_","white").replace("_bg_","#9C27B0")])}async handle(e){const t=this.getFormatter().format(e);let s=this._getConsoleMethod(e.level);e.context.needTrace===!0&&(s="trace");const n=[];if(this._useStyles&&this._styles.has(e.level)){const i=this._styles.get(e.level);n.push(i[0],i[1])}return n.push(t),console[s](...n.filter(Boolean)),!0}_getConsoleMethod(e){switch(e){case W.INFO:case W.NOTICE:return"info";case W.WARNING:return"warn";case W.ERROR:case W.CRITICAL:case W.ALERT:case W.EMERGENCY:return"error";default:return"log"}}}class Js extends zi{constructor(e=W.DEBUG,t){super(e,t),this.setFormatter(new ts("[{channel}]: {message}"))}async handle(e){const t=this.getFormatter().format(e);let s=this._getConsoleMethod(e.level);e.context.needTrace===!0&&(s="trace");const n=e.context&&Object.keys(e.context).length>0?e.context:void 0,i=e.extra&&Object.keys(e.extra).length>0?e.extra:void 0,o=[];if(this._useStyles&&this._styles.has(e.level)){const a=this._styles.get(e.level);o.push(a[0],a[1])}return o.push(t),o.push(n),o.push(i),console[s](...o.filter(Boolean)),!0}}class yu extends Yt{records=[];limit;constructor(e=W.DEBUG,t){const s={bubble:!0,limit:1e3,...t};super(e,s.bubble),this.limit=s.limit}async handle(e){return this.records.push(e),this.records.length>this.limit&&this.records.shift(),!0}getRecords(){return[...this.records]}clear(){this.records=[]}}class _u extends Yt{stream;constructor(e=W.DEBUG,t){const s={bubble:!0,...t};super(e,s.bubble),this.stream=s.stream,this.setFormatter(new ts)}async handle(e){try{const t=this.getFormatter().format(e)+`
`;this.stream.write(t)}catch(t){return console.error(`StreamHandler write error: ${t}`),!1}return!0}async close(){if(typeof this.stream.end=="function")return new Promise((e,t)=>{this.stream.end(s=>{s?t(s):e()})})}}class wu extends Yt{consolaInstance;constructor(e=W.DEBUG,t){const s={bubble:!0,...t};super(e,s.bubble),this.consolaInstance=s.consolaInstance}setFormatter(e){}getFormatter(){return null}async handle(e){const t=`[${e.channel}] ${e.levelName}: ${e.message}`,s={...e.context,...e.extra,timestamp:e.timestamp};switch(e.level){case W.DEBUG:this.consolaInstance.log(t,s);break;case W.INFO:this.consolaInstance.info(t,s);break;case W.NOTICE:this.consolaInstance.success(t,s);break;case W.WARNING:this.consolaInstance.warn(t,s);break;case W.ERROR:case W.CRITICAL:case W.ALERT:case W.EMERGENCY:this.consolaInstance.error(t,s);break;default:this.consolaInstance.log(t,s)}return!0}}class bu extends Yt{winstonLogger;constructor(e=W.DEBUG,t){const s={bubble:!0,...t};super(e,s.bubble),this.winstonLogger=s.winstonLogger}setFormatter(e){}getFormatter(){return null}async handle(e){const t={DEBUG:"debug",INFO:"info",NOTICE:"notice",WARNING:"warn",ERROR:"error",CRITICAL:"error",ALERT:"error",EMERGENCY:"error"},s=t[e.levelName]||t.INFO;return this.winstonLogger.log({level:s,channel:e.channel,message:e.message,context:e.context,extra:e.extra,timestamp:e.timestamp}),!0}}var Ks=(r=>(r.UNKNOWN="unknown",r.BROWSE="browser",r.WORKER="worker",r.NODE="node",r))(Ks||{});function Su(){try{const r=globalThis.WorkerGlobalScope;return typeof r>"u"?!1:globalThis instanceof r}catch{return!1}}function Gs(){return typeof window<"u"&&typeof window.document<"u"?"browser":typeof process<"u"&&process.versions&&process.versions.node?"node":Su()?"worker":"unknown"}function br(){const r=Gs();return r==="browser"||r==="worker"}class Eu extends Yt{botToken;chatId;parseMode;disableNotification;disableWebPagePreview;environment;isBrowserLike;warnInBrowser;constructor(e=W.ERROR,t){if(super(e,t.bubble),!t.botToken)throw new Error("botToken is required for TelegramHandler");if(!t.chatId)throw new Error("chatId is required for TelegramHandler");this.botToken=t.botToken,this.chatId=t.chatId,this.parseMode=t.parseMode||"HTML",this.disableNotification=t.disableNotification||!1,this.disableWebPagePreview=t.disableWebPagePreview||!0,this.environment=Gs(),this.isBrowserLike=br(),this.warnInBrowser=t.warnInBrowser!==!1,this.setFormatter(new zs().setParseMode(this.parseMode))}async handle(e){const t=this.getFormatter();if(!t)return console.error("TelegramHandler: No formatter set"),!1;const s=t.format(e);return this.isBrowserLike?this._handleInBrowser(s,e):this.environment===Ks.NODE?this._handleInNode(s,e):(console.warn("TelegramHandler: Unknown environment, using fallback"),this._handleFallback(s))}async _handleInBrowser(e,t){if(this.warnInBrowser){const s=`\u26A0\uFE0F TelegramHandler: Cannot send logs to Telegram from a browser-like environment.
This would expose your bot token. Consider disabling this handler in browser.
Log message: ${t.message}
If you need to send logs from browser, use a proxy server.`;console.warn(s),console.log("%cTelegram Handler Warning","color: #FF9800; background: #FFF3E0; padding: 8px; border: 1px solid #FFB74D; border-radius: 4px;",s)}return!1}async _handleInNode(e,t){try{const s=`https://api.telegram.org/bot${this.botToken}/sendMessage`,n=JSON.stringify({chat_id:this.chatId,text:e,parse_mode:this.parseMode,disable_notification:this.disableNotification,disable_web_page_preview:this.disableWebPagePreview}),i=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:n})).json();return i.ok?!0:(console.error("TelegramHandler: Failed to send message",i),!1)}catch(s){return console.error("TelegramHandler: Error sending message",s),!1}}async _handleFallback(e){return console.log("TelegramHandler (fallback):",e),!1}updateSettings(e){if(e.botToken&&(this.botToken=e.botToken),e.chatId&&(this.chatId=e.chatId),e.parseMode){this.parseMode=e.parseMode;const t=this.getFormatter();t instanceof zs&&t.setParseMode(e.parseMode)}return e.disableNotification!==void 0&&(this.disableNotification=e.disableNotification),e.disableWebPagePreview!==void 0&&(this.disableWebPagePreview=e.disableWebPagePreview),e.warnInBrowser!==void 0&&(this.warnInBrowser=e.warnInBrowser),this}getEnvironment(){return this.environment}async testConnection(){if(this.isBrowserLike)return console.warn("TelegramHandler: Cannot test connection in a browser-like environment"),!1;try{const e=`https://api.telegram.org/bot${this.botToken}/getMe`;return(await(await fetch(e)).json()).ok===!0}catch(e){return console.error("TelegramHandler: Test connection failed",e),!1}}}class Ys{async debug(e,t){return this.log(W.DEBUG,e,t)}async info(e,t){return this.log(W.INFO,e,t)}async notice(e,t){return this.log(W.NOTICE,e,t)}async warning(e,t){return this.log(W.WARNING,e,t)}async error(e,t){return this.log(W.ERROR,e,t)}async critical(e,t){return this.log(W.CRITICAL,e,t)}async alert(e,t){return this.log(W.ALERT,e,t)}async emergency(e,t){return this.log(W.EMERGENCY,e,t)}}class Sr extends Ys{static create(){return new Sr}async log(e,t,s){}}class Er extends Ys{channel;handlers=[];processors=[];constructor(e){super(),this.channel=e}static create(e){return new Er(e)}pushHandler(e){return this.handlers.push(e),this}popHandler(){return this.handlers.pop()||null}setHandlers(e){return this.handlers=e,this}pushProcessor(e){return this.processors.push(e),this}async log(e,t,s){let n={channel:this.channel,level:e,levelName:W[e],message:t,context:s??{},extra:{},timestamp:new Date};for(const i of this.processors)try{n=i(n)}catch(o){this.reportLoggingFailure(i,o)}for(const i of this.handlers)try{if(!i.isHandling(e))continue;if(await i.handle(n)&&!i.shouldBubble())break}catch(o){this.reportLoggingFailure(i,o)}}reportLoggingFailure(e,t){const s=e?.constructor?.name??"processor";console.warn(`[b24jssdk] logger channel "${this.channel}": ${s} failed; the record was skipped. Logging continues through the remaining handlers, and the operation being logged is unaffected.`,t)}}class oe{static createNullLogger(){return Sr.create()}static createForBrowser(e,t=!1){return t?oe.createForBrowserDevelopment(e):oe.createForBrowserProduction(e)}static createForBrowserDevelopment(e,t=W.DEBUG){const s=new Er(e),n=new Js(t);return s.pushHandler(n),s}static createForBrowserProduction(e,t=W.ERROR){const s=new Er(e),n=new Js(t);return s.pushHandler(n),s}static async forcedLog(e,t,s,n){if(!(typeof globalThis<"u"&&"vitest"in globalThis)){if(e instanceof Sr)switch(t){case"debug":console.log(s,n);return;case"info":case"notice":console.info(s,n);return;case"warning":console.warn(s,n);return;default:console.error(s,n);return}return e[t](s,n)}}}var Ji=(r=>(r.undefined="undefined",r.any="any",r.integer="integer",r.boolean="boolean",r.double="double",r.date="date",r.datetime="datetime",r.string="string",r.text="text",r.file="file",r.array="array",r.object="object",r.user="user",r.location="location",r.crmCategory="crm_category",r.crmStatus="crm_status",r.crmCurrency="crm_currency",r))(Ji||{});const Tu=Function.prototype.toString.call(Object);let vu=class{getTag(e){return Object.prototype.toString.call(e)}isString(e){return typeof e=="string"||e instanceof String}isStringFilled(e){return this.isString(e)&&e!==""}isFunction(e){return e===null?!1:typeof e=="function"||e instanceof Function}isObject(e){return!!e&&(typeof e=="object"||typeof e=="function")}isObjectLike(e){return!!e&&typeof e=="object"}isPlainObject(e){if(!this.isObjectLike(e)||this.getTag(e)!=="[object Object]")return!1;const t=Object.getPrototypeOf(e);if(t===null)return!0;const s=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof s=="function"&&Function.prototype.toString.call(s)===Tu}isJsonRpcRequest(e){return typeof e=="object"&&e&&"jsonrpc"in e&&this.isStringFilled(e.jsonrpc)&&"method"in e&&this.isStringFilled(e.method)}isJsonRpcResponse(e){return typeof e=="object"&&e&&"jsonrpc"in e&&this.isStringFilled(e.jsonrpc)&&"id"in e&&("result"in e||"error"in e)}isBoolean(e){return e===!0||e===!1}isNumber(e){return typeof e=="number"&&!Number.isNaN(e)}isInteger(e){return Number.isInteger(e)}isFloat(e){return this.isNumber(e)&&!this.isInteger(e)}isNil(e){return e==null}isArray(e){return!this.isNil(e)&&Array.isArray(e)}isArrayFilled(e){return this.isArray(e)&&e.length>0}isArrayLike(e){return!this.isNil(e)&&!this.isFunction(e)&&e.length>-1&&e.length<=Number.MAX_SAFE_INTEGER}isDate(e){return e instanceof Date}isDomNode(e){return this.isObjectLike(e)&&!this.isPlainObject(e)&&"nodeType"in e}isElementNode(e){return this.isDomNode(e)&&e.nodeType===Node.ELEMENT_NODE}isTextNode(e){return this.isDomNode(e)&&e.nodeType===Node.TEXT_NODE}isMap(e){return this.isObjectLike(e)&&this.getTag(e)==="[object Map]"}isSet(e){return this.isObjectLike(e)&&this.getTag(e)==="[object Set]"}isWeakMap(e){return this.isObjectLike(e)&&this.getTag(e)==="[object WeakMap]"}isWeakSet(e){return this.isObjectLike(e)&&this.getTag(e)==="[object WeakSet]"}isPrototype(e){return(typeof(e&&e.constructor)=="function"&&e.constructor.prototype||Object.prototype)===e}isRegExp(e){return this.isObjectLike(e)&&this.getTag(e)==="[object RegExp]"}isNull(e){return e===null}isUndefined(e){return typeof e>"u"}isArrayBuffer(e){return this.isObjectLike(e)&&this.getTag(e)==="[object ArrayBuffer]"}isTypedArray(e){const t=/^\[object (?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)Array\]$/;return this.isObjectLike(e)&&t.test(this.getTag(e))}isBlob(e){return this.isObjectLike(e)&&this.isNumber(e.size)&&this.isString(e.type)&&this.isFunction(e.slice)}isFile(e){return this.isBlob(e)&&this.isString(e.name)&&(this.isNumber(e.lastModified)||this.isObjectLike(e.lastModifiedDate))}isFormData(e){return typeof FormData<"u"&&e instanceof FormData?!0:this.isObjectLike(e)&&this.getTag(e)==="[object FormData]"}clone(e,t=!0){let s,n,i;if(this.isNil(e)||typeof e!="object")return e;if(this.isDomNode(e))s=e.cloneNode(t);else if(typeof e=="object")if(this.isArray(e))for(s=[],n=0,i=e.length;n<i;n++)typeof e[n]=="object"&&t?s[n]=this.clone(e[n],t):s[n]=e[n];else{s={},e.constructor&&(this.isDate(e)?s=new Date(e):s=new e.constructor);for(n in e)Object.prototype.hasOwnProperty.call(e,n)&&(typeof e[n]=="object"&&t?s[n]=this.clone(e[n],t):s[n]=e[n])}else s=e;return s}};const L=new vu;function Ou(r,e){const t={};for(const s of e)t[s]=r[s];return t}function Ki(r,e){const t={...r};for(const s of e)delete t[s];return t}function Au(r){return Array.isArray(r[0])}function Iu(r,e){return Object.values(r).includes(e)?e:void 0}class Ft extends Error{}class ku extends Ft{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Ru extends Ft{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class Cu extends Ft{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Zt extends Ft{}class Gi extends Ft{constructor(e){super(`Invalid unit ${e}`)}}class Me extends Ft{}class It extends Ft{constructor(){super("Zone is an abstract class")}}const M="numeric",st="short",Je="long",rs={year:M,month:M,day:M},Yi={year:M,month:st,day:M},Nu={year:M,month:st,day:M,weekday:st},Zi={year:M,month:Je,day:M},Xi={year:M,month:Je,day:M,weekday:Je},Qi={hour:M,minute:M},eo={hour:M,minute:M,second:M},to={hour:M,minute:M,second:M,timeZoneName:st},ro={hour:M,minute:M,second:M,timeZoneName:Je},so={hour:M,minute:M,hourCycle:"h23"},no={hour:M,minute:M,second:M,hourCycle:"h23"},io={hour:M,minute:M,second:M,hourCycle:"h23",timeZoneName:st},oo={hour:M,minute:M,second:M,hourCycle:"h23",timeZoneName:Je},ao={year:M,month:M,day:M,hour:M,minute:M},co={year:M,month:M,day:M,hour:M,minute:M,second:M},lo={year:M,month:st,day:M,hour:M,minute:M},uo={year:M,month:st,day:M,hour:M,minute:M,second:M},Du={year:M,month:st,day:M,weekday:st,hour:M,minute:M},ho={year:M,month:Je,day:M,hour:M,minute:M,timeZoneName:st},fo={year:M,month:Je,day:M,hour:M,minute:M,second:M,timeZoneName:st},po={year:M,month:Je,day:M,weekday:Je,hour:M,minute:M,timeZoneName:Je},go={year:M,month:Je,day:M,weekday:Je,hour:M,minute:M,second:M,timeZoneName:Je};class Tr{get type(){throw new It}get name(){throw new It}get ianaName(){return this.name}get isUniversal(){throw new It}offsetName(e,t){throw new It}formatOffset(e,t){throw new It}offset(e){throw new It}equals(e){throw new It}get isValid(){throw new It}}let Zs=null;class ss extends Tr{static get instance(){return Zs===null&&(Zs=new ss),Zs}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Uo(e,t,s)}formatOffset(e,t){return Ir(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Xs=new Map;function Lu(r){let e=Xs.get(r);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Xs.set(r,e)),e}const Mu={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Pu(r,e){const t=r.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,n,i,o,a,c,u,l]=s;return[o,n,i,a,c,u,l]}function xu(r,e){const t=r.formatToParts(e),s=[];for(let n=0;n<t.length;n++){const{type:i,value:o}=t[n],a=Mu[i];i==="era"?s[a]=o:H(a)||(s[a]=parseInt(o,10))}return s}const Qs=new Map;class yt extends Tr{static create(e){let t=Qs.get(e);return t===void 0&&Qs.set(e,t=new yt(e)),t}static resetCache(){Qs.clear(),Xs.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=yt.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Uo(e,t,s,this.name)}formatOffset(e,t){return Ir(this.offset(e),t)}offset(e){if(!this.valid)return NaN;const t=new Date(e);if(isNaN(t))return NaN;const s=Lu(this.name);let[n,i,o,a,c,u,l]=s.formatToParts?xu(s,t):Pu(s,t);a==="BC"&&(n=-Math.abs(n)+1);const d=cs({year:n,month:i,day:o,hour:c===24?0:c,minute:u,second:l,millisecond:0});let f=+t;const p=f%1e3;return f-=p>=0?p:1e3+p,(d-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let mo={};function Fu(r,e={}){const t=JSON.stringify([r,e]);let s=mo[t];return s||(s=new Intl.ListFormat(r,e),mo[t]=s),s}const en=new Map;function tn(r,e={}){const t=JSON.stringify([r,e]);let s=en.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(r,e),en.set(t,s)),s}const rn=new Map;function Bu(r,e={}){const t=JSON.stringify([r,e]);let s=rn.get(t);return s===void 0&&(s=new Intl.NumberFormat(r,e),rn.set(t,s)),s}const sn=new Map;function $u(r,e={}){const{base:t,...s}=e,n=JSON.stringify([r,s]);let i=sn.get(n);return i===void 0&&(i=new Intl.RelativeTimeFormat(r,e),sn.set(n,i)),i}let vr=null;function ju(){return vr||(vr=new Intl.DateTimeFormat().resolvedOptions().locale,vr)}const nn=new Map;function yo(r){let e=nn.get(r);return e===void 0&&(e=new Intl.DateTimeFormat(r).resolvedOptions(),nn.set(r,e)),e}const on=new Map;function Uu(r){let e=on.get(r);if(!e){const t=new Intl.Locale(r);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={..._o,...e}),on.set(r,e)}return e}function Vu(r){const e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));const t=r.indexOf("-u-");if(t===-1)return[r];{let s,n;try{s=tn(r).resolvedOptions(),n=r}catch{const c=r.substring(0,t);s=tn(c).resolvedOptions(),n=c}const{numberingSystem:i,calendar:o}=s;return[n,i,o]}}function qu(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}function Hu(r){const e=[];for(let t=1;t<=12;t++){const s=V.utc(2009,t,1);e.push(r(s))}return e}function Wu(r){const e=[];for(let t=1;t<=7;t++){const s=V.utc(2016,11,13+t);e.push(r(s))}return e}function ns(r,e,t,s){const n=r.listingMode();return n==="error"?null:n==="en"?t(e):s(e)}function zu(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||yo(r.locale).numberingSystem==="latn"}class Ju{constructor(e,t,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:n,floor:i,...o}=s;if(!t||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=Bu(e,a)}}format(e){if(this.inf){const t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{const t=this.floor?Math.floor(e):gn(e,3);return Se(t,this.padTo)}}}class Ku{constructor(e,t,s){this.opts=s,this.originalZone=void 0;let n;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&yt.create(a).valid?(n=a,this.dt=e):(n="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,n=e.zone.name):(n="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const i={...this.opts};i.timeZone=i.timeZone||n,this.dtf=tn(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:s}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class Gu{constructor(e,t,s){this.opts={style:"long",...s},!t&&Fo()&&(this.rtf=$u(e,s))}format(e,t){return this.rtf?this.rtf.format(e,t):yh(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}}const _o={firstDay:1,minimalDays:4,weekend:[6,7]};class ne{static fromOpts(e){return ne.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,s,n,i=!1){const o=e||ge.defaultLocale,a=o||(i?"en-US":ju()),c=t||ge.defaultNumberingSystem,u=s||ge.defaultOutputCalendar,l=fn(n)||ge.defaultWeekSettings;return new ne(a,c,u,l,o)}static resetCache(){vr=null,en.clear(),rn.clear(),sn.clear(),nn.clear(),on.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:n}={}){return ne.create(e,t,s,n)}constructor(e,t,s,n,i){const[o,a,c]=Vu(e);this.locale=o,this.numberingSystem=t||a||null,this.outputCalendar=s||c||null,this.weekSettings=n,this.intl=qu(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=zu(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:ne.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,fn(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return ns(this,e,Ho,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");t&=!s;const n=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,n).format():a=>this.extract(a,n,"month");this.monthsCache[i][e]=Hu(o)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return ns(this,e,Jo,()=>{const s=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},n=t?"format":"standalone";return this.weekdaysCache[n][e]||(this.weekdaysCache[n][e]=Wu(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[n][e]})}meridiems(){return ns(this,void 0,()=>Ko,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return ns(this,e,Go,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const n=this.dtFormatter(e,t),i=n.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new Ju(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new Ku(e,this.intl,t)}relFormatter(e={}){return new Gu(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Fu(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||yo(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Bo()?Uu(this.locale):_o}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let an=null;class je extends Tr{static get utcInstance(){return an===null&&(an=new je(0)),an}static instance(e){return e===0?je.utcInstance:new je(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new je(ls(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Ir(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Ir(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return Ir(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class Yu extends Tr{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function kt(r,e){if(H(r)||r===null)return e;if(r instanceof Tr)return r;if(rh(r)){const t=r.toLowerCase();return t==="default"?e:t==="local"||t==="system"?ss.instance:t==="utc"||t==="gmt"?je.utcInstance:je.parseSpecifier(t)||yt.create(r)}else return Rt(r)?je.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new Yu(r)}const cn={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},wo={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Zu=cn.hanidec.replace(/[\[|\]]/g,"").split("");function Xu(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){const s=r.charCodeAt(t);if(r[t].search(cn.hanidec)!==-1)e+=Zu.indexOf(r[t]);else for(const n in wo){const[i,o]=wo[n];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const ln=new Map;function Qu(){ln.clear()}function nt({numberingSystem:r},e=""){const t=r||"latn";let s=ln.get(t);s===void 0&&(s=new Map,ln.set(t,s));let n=s.get(e);return n===void 0&&(n=new RegExp(`${cn[t]}${e}`),s.set(e,n)),n}let bo=()=>Date.now(),So="system",Eo=null,To=null,vo=null,Oo=60,Ao,Io=null;class ge{static get now(){return bo}static set now(e){bo=e}static set defaultZone(e){So=e}static get defaultZone(){return kt(So,ss.instance)}static get defaultLocale(){return Eo}static set defaultLocale(e){Eo=e}static get defaultNumberingSystem(){return To}static set defaultNumberingSystem(e){To=e}static get defaultOutputCalendar(){return vo}static set defaultOutputCalendar(e){vo=e}static get defaultWeekSettings(){return Io}static set defaultWeekSettings(e){Io=fn(e)}static get twoDigitCutoffYear(){return Oo}static set twoDigitCutoffYear(e){Oo=e%100}static get throwOnInvalid(){return Ao}static set throwOnInvalid(e){Ao=e}static resetCaches(){ne.resetCache(),yt.resetCache(),V.resetCache(),Qu()}}class it{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const ko=[0,31,59,90,120,151,181,212,243,273,304,334],Ro=[0,31,60,91,121,152,182,213,244,274,305,335];function Qe(r,e){return new it("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function un(r,e,t){const s=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const n=s.getUTCDay();return n===0?7:n}function Co(r,e,t){return t+(Or(r)?Ro:ko)[e-1]}function No(r,e){const t=Or(r)?Ro:ko,s=t.findIndex(i=>i<e),n=e-t[s];return{month:s+1,day:n}}function hn(r,e){return(r-e+7)%7+1}function is(r,e=4,t=1){const{year:s,month:n,day:i}=r,o=Co(s,n,i),a=hn(un(s,n,i),t);let c=Math.floor((o-a+14-e)/7),u;return c<1?(u=s-1,c=Ar(u,e,t)):c>Ar(s,e,t)?(u=s+1,c=1):u=s,{weekYear:u,weekNumber:c,weekday:a,...hs(r)}}function Do(r,e=4,t=1){const{weekYear:s,weekNumber:n,weekday:i}=r,o=hn(un(s,1,e),t),a=Qt(s);let c=n*7+i-o-7+e,u;c<1?(u=s-1,c+=Qt(u)):c>a?(u=s+1,c-=Qt(s)):u=s;const{month:l,day:h}=No(u,c);return{year:u,month:l,day:h,...hs(r)}}function dn(r){const{year:e,month:t,day:s}=r,n=Co(e,t,s);return{year:e,ordinal:n,...hs(r)}}function Lo(r){const{year:e,ordinal:t}=r,{month:s,day:n}=No(e,t);return{year:e,month:s,day:n,...hs(r)}}function Mo(r,e){if(!H(r.localWeekday)||!H(r.localWeekNumber)||!H(r.localWeekYear)){if(!H(r.weekday)||!H(r.weekNumber)||!H(r.weekYear))throw new Zt("Cannot mix locale-based week fields with ISO-based week fields");return H(r.localWeekday)||(r.weekday=r.localWeekday),H(r.localWeekNumber)||(r.weekNumber=r.localWeekNumber),H(r.localWeekYear)||(r.weekYear=r.localWeekYear),delete r.localWeekday,delete r.localWeekNumber,delete r.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function eh(r,e=4,t=1){const s=os(r.weekYear),n=et(r.weekNumber,1,Ar(r.weekYear,e,t)),i=et(r.weekday,1,7);return s?n?i?!1:Qe("weekday",r.weekday):Qe("week",r.weekNumber):Qe("weekYear",r.weekYear)}function th(r){const e=os(r.year),t=et(r.ordinal,1,Qt(r.year));return e?t?!1:Qe("ordinal",r.ordinal):Qe("year",r.year)}function Po(r){const e=os(r.year),t=et(r.month,1,12),s=et(r.day,1,as(r.year,r.month));return e?t?s?!1:Qe("day",r.day):Qe("month",r.month):Qe("year",r.year)}function xo(r){const{hour:e,minute:t,second:s,millisecond:n}=r,i=et(e,0,23)||e===24&&t===0&&s===0&&n===0,o=et(t,0,59),a=et(s,0,59),c=et(n,0,999);return i?o?a?c?!1:Qe("millisecond",n):Qe("second",s):Qe("minute",t):Qe("hour",e)}function H(r){return typeof r>"u"}function Rt(r){return typeof r=="number"}function os(r){return typeof r=="number"&&r%1===0}function rh(r){return typeof r=="string"}function sh(r){return Object.prototype.toString.call(r)==="[object Date]"}function Fo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Bo(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function nh(r){return Array.isArray(r)?r:[r]}function $o(r,e,t){if(r.length!==0)return r.reduce((s,n)=>{const i=[e(n),n];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}function ih(r,e){return e.reduce((t,s)=>(t[s]=r[s],t),{})}function Xt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function fn(r){if(r==null)return null;if(typeof r!="object")throw new Me("Week settings must be an object");if(!et(r.firstDay,1,7)||!et(r.minimalDays,1,7)||!Array.isArray(r.weekend)||r.weekend.some(e=>!et(e,1,7)))throw new Me("Invalid week settings");return{firstDay:r.firstDay,minimalDays:r.minimalDays,weekend:Array.from(r.weekend)}}function et(r,e,t){return os(r)&&r>=e&&r<=t}function oh(r,e){return r-e*Math.floor(r/e)}function Se(r,e=2){const t=r<0;let s;return t?s="-"+(""+-r).padStart(e,"0"):s=(""+r).padStart(e,"0"),s}function Ct(r){if(!(H(r)||r===null||r===""))return parseInt(r,10)}function Bt(r){if(!(H(r)||r===null||r===""))return parseFloat(r)}function pn(r){if(!(H(r)||r===null||r==="")){const e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function gn(r,e,t="round"){const s=10**e;switch(t){case"expand":return r>0?Math.ceil(r*s)/s:Math.floor(r*s)/s;case"trunc":return Math.trunc(r*s)/s;case"round":return Math.round(r*s)/s;case"floor":return Math.floor(r*s)/s;case"ceil":return Math.ceil(r*s)/s;default:throw new RangeError(`Value rounding ${t} is out of range`)}}function Or(r){return r%4===0&&(r%100!==0||r%400===0)}function Qt(r){return Or(r)?366:365}function as(r,e){const t=oh(e-1,12)+1,s=r+(e-t)/12;return t===2?Or(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function cs(r){let e=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return r.year<100&&r.year>=0&&(e=new Date(e),e.setUTCFullYear(r.year,r.month-1,r.day)),+e}function jo(r,e,t){return-hn(un(r,1,e),t)+e-1}function Ar(r,e=4,t=1){const s=jo(r,e,t),n=jo(r+1,e,t);return(Qt(r)-s+n)/7}function mn(r){return r>99?r:r>ge.twoDigitCutoffYear?1900+r:2e3+r}function Uo(r,e,t,s=null){const n=new Date(r),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,o).formatToParts(n).find(c=>c.type.toLowerCase()==="timezonename");return a?a.value:null}function ls(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,n=t<0||Object.is(t,-0)?-s:s;return t*60+n}function Vo(r){const e=Number(r);if(typeof r=="boolean"||r===""||!Number.isFinite(e))throw new Me(`Invalid unit value ${r}`);return e}function us(r,e){const t={};for(const s in r)if(Xt(r,s)){const n=r[s];if(n==null)continue;t[e(s)]=Vo(n)}return t}function Ir(r,e){const t=Math.trunc(Math.abs(r/60)),s=Math.trunc(Math.abs(r%60)),n=r>=0?"+":"-";switch(e){case"short":return`${n}${Se(t,2)}:${Se(s,2)}`;case"narrow":return`${n}${t}${s>0?`:${s}`:""}`;case"techie":return`${n}${Se(t,2)}${Se(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function hs(r){return ih(r,["hour","minute","second","millisecond"])}const ah=["January","February","March","April","May","June","July","August","September","October","November","December"],qo=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ch=["J","F","M","A","M","J","J","A","S","O","N","D"];function Ho(r){switch(r){case"narrow":return[...ch];case"short":return[...qo];case"long":return[...ah];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const Wo=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],zo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],lh=["M","T","W","T","F","S","S"];function Jo(r){switch(r){case"narrow":return[...lh];case"short":return[...zo];case"long":return[...Wo];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Ko=["AM","PM"],uh=["Before Christ","Anno Domini"],hh=["BC","AD"],dh=["B","A"];function Go(r){switch(r){case"narrow":return[...dh];case"short":return[...hh];case"long":return[...uh];default:return null}}function fh(r){return Ko[r.hour<12?0:1]}function ph(r,e){return Jo(e)[r.weekday-1]}function gh(r,e){return Ho(e)[r.month-1]}function mh(r,e){return Go(e)[r.year<0?0:1]}function yh(r,e,t="always",s=!1){const n={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&i){const h=r==="days";switch(e){case 1:return h?"tomorrow":`next ${n[r][0]}`;case-1:return h?"yesterday":`last ${n[r][0]}`;case 0:return h?"today":`this ${n[r][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),c=a===1,u=n[r],l=s?c?u[1]:u[2]||u[1]:c?n[r][0]:r;return o?`${a} ${l} ago`:`in ${a} ${l}`}function Yo(r,e){let t="";for(const s of r)s.literal?t+=s.val:t+=e(s.val);return t}const _h={D:rs,DD:Yi,DDD:Zi,DDDD:Xi,t:Qi,tt:eo,ttt:to,tttt:ro,T:so,TT:no,TTT:io,TTTT:oo,f:ao,ff:lo,fff:ho,ffff:po,F:co,FF:uo,FFF:fo,FFFF:go};class Pe{static create(e,t={}){return new Pe(e,t)}static parseFormat(e){let t=null,s="",n=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||n)&&i.push({literal:n||/^\s+$/.test(s),val:s===""?"'":s}),t=null,s="",n=!n):n||a===t?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,t=a)}return s.length>0&&i.push({literal:n||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return _h[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,s=void 0){if(this.opts.forceSimple)return Se(e,t);const n={...this.opts};return t>0&&(n.padTo=t),s&&(n.signDisplay=s),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){const s=this.loc.listingMode()==="en",n=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,p)=>this.loc.extract(e,f,p),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?fh(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(f,p)=>s?gh(e,f):i(p?{month:f}:{month:f,day:"numeric"},"month"),u=(f,p)=>s?ph(e,f):i(p?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),l=f=>{const p=Pe.macroTokenToFormatOpts(f);return p?this.formatWithSystemDefault(e,p):f},h=f=>s?mh(e,f):i({era:f},"era"),d=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return n?i({day:"numeric"},"day"):this.num(e.day);case"dd":return n?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("narrow",!1);case"L":return n?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return n?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return n?i({month:"numeric"},"month"):this.num(e.month);case"MM":return n?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return n?i({year:"numeric"},"year"):this.num(e.year);case"yy":return n?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return n?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return n?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return h("short");case"GG":return h("long");case"GGGGG":return h("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return l(f)}};return Yo(Pe.parseFormat(t),d)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,n=l=>{switch(l[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(l,h)=>d=>{const f=n(d);if(f){const p=h.isNegativeDuration&&f!==h.largestUnit?s:1;let g;return this.opts.signMode==="negativeLargestOnly"&&f!==h.largestUnit?g="never":this.opts.signMode==="all"?g="always":g="auto",this.num(l.get(f)*p,d.length,g)}else return d},o=Pe.parseFormat(t),a=o.reduce((l,{literal:h,val:d})=>h?l:l.concat(d),[]),c=e.shiftTo(...a.map(n).filter(l=>l)),u={isNegativeDuration:c<0,largestUnit:Object.keys(c.values)[0]};return Yo(o,i(c,u))}}const Zo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function er(...r){const e=r.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function tr(...r){return e=>r.reduce(([t,s,n],i)=>{const[o,a,c]=i(e,n);return[{...t,...o},a||s,c]},[{},null,1]).slice(0,2)}function rr(r,...e){if(r==null)return[null,null];for(const[t,s]of e){const n=t.exec(r);if(n)return s(n)}return[null,null]}function Xo(...r){return(e,t)=>{const s={};let n;for(n=0;n<r.length;n++)s[r[n]]=Ct(e[t+n]);return[s,null,t+n]}}const Qo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,wh=`(?:${Qo.source}?(?:\\[(${Zo.source})\\])?)?`,yn=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ea=RegExp(`${yn.source}${wh}`),_n=RegExp(`(?:[Tt]${ea.source})?`),bh=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Sh=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Eh=/(\d{4})-?(\d{3})/,Th=Xo("weekYear","weekNumber","weekDay"),vh=Xo("year","ordinal"),Oh=/(\d{4})-(\d\d)-(\d\d)/,ta=RegExp(`${yn.source} ?(?:${Qo.source}|(${Zo.source}))?`),Ah=RegExp(`(?: ${ta.source})?`);function sr(r,e,t){const s=r[e];return H(s)?t:Ct(s)}function Ih(r,e){return[{year:sr(r,e),month:sr(r,e+1,1),day:sr(r,e+2,1)},null,e+3]}function nr(r,e){return[{hours:sr(r,e,0),minutes:sr(r,e+1,0),seconds:sr(r,e+2,0),milliseconds:pn(r[e+3])},null,e+4]}function kr(r,e){const t=!r[e]&&!r[e+1],s=ls(r[e+1],r[e+2]),n=t?null:je.instance(s);return[{},n,e+3]}function Rr(r,e){const t=r[e]?yt.create(r[e]):null;return[{},t,e+1]}const kh=RegExp(`^T?${yn.source}$`),Rh=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Ch(r){const[e,t,s,n,i,o,a,c,u]=r,l=e[0]==="-",h=c&&c[0]==="-",d=(f,p=!1)=>f!==void 0&&(p||f&&l)?-f:f;return[{years:d(Bt(t)),months:d(Bt(s)),weeks:d(Bt(n)),days:d(Bt(i)),hours:d(Bt(o)),minutes:d(Bt(a)),seconds:d(Bt(c),c==="-0"),milliseconds:d(pn(u),h)}]}const Nh={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function wn(r,e,t,s,n,i,o){const a={year:e.length===2?mn(Ct(e)):Ct(e),month:qo.indexOf(t)+1,day:Ct(s),hour:Ct(n),minute:Ct(i)};return o&&(a.second=Ct(o)),r&&(a.weekday=r.length>3?Wo.indexOf(r)+1:zo.indexOf(r)+1),a}const Dh=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Lh(r){const[,e,t,s,n,i,o,a,c,u,l,h]=r,d=wn(e,n,s,t,i,o,a);let f;return c?f=Nh[c]:u?f=0:f=ls(l,h),[d,new je(f)]}function Mh(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Ph=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,xh=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Fh=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function ra(r){const[,e,t,s,n,i,o,a]=r;return[wn(e,n,s,t,i,o,a),je.utcInstance]}function Bh(r){const[,e,t,s,n,i,o,a]=r;return[wn(e,a,t,s,n,i,o),je.utcInstance]}const $h=er(bh,_n),jh=er(Sh,_n),Uh=er(Eh,_n),Vh=er(ea),sa=tr(Ih,nr,kr,Rr),qh=tr(Th,nr,kr,Rr),Hh=tr(vh,nr,kr,Rr),Wh=tr(nr,kr,Rr);function zh(r){return rr(r,[$h,sa],[jh,qh],[Uh,Hh],[Vh,Wh])}function Jh(r){return rr(Mh(r),[Dh,Lh])}function Kh(r){return rr(r,[Ph,ra],[xh,ra],[Fh,Bh])}function Gh(r){return rr(r,[Rh,Ch])}const Yh=tr(nr);function Zh(r){return rr(r,[kh,Yh])}const Xh=er(Oh,Ah),Qh=er(ta),ed=tr(nr,kr,Rr);function td(r){return rr(r,[Xh,sa],[Qh,ed])}const na="Invalid Duration",ia={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},rd={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...ia},tt=146097/400,ir=146097/4800,sd={years:{quarters:4,months:12,weeks:tt/7,days:tt,hours:tt*24,minutes:tt*24*60,seconds:tt*24*60*60,milliseconds:tt*24*60*60*1e3},quarters:{months:3,weeks:tt/28,days:tt/4,hours:tt*24/4,minutes:tt*24*60/4,seconds:tt*24*60*60/4,milliseconds:tt*24*60*60*1e3/4},months:{weeks:ir/7,days:ir,hours:ir*24,minutes:ir*24*60,seconds:ir*24*60*60,milliseconds:ir*24*60*60*1e3},...ia},$t=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],nd=$t.slice(0).reverse();function _t(r,e,t=!1){const s={values:t?e.values:{...r.values,...e.values||{}},loc:r.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||r.conversionAccuracy,matrix:e.matrix||r.matrix};return new Z(s)}function oa(r,e){let t=e.milliseconds??0;for(const s of nd.slice(1))e[s]&&(t+=e[s]*r[s].milliseconds);return t}function aa(r,e){const t=oa(r,e)<0?-1:1;$t.reduceRight((s,n)=>{if(H(e[n]))return s;if(s){const i=e[s]*t,o=r[n][s],a=Math.floor(i/o);e[n]+=a*t,e[s]-=a*o*t}return n},null),$t.reduce((s,n)=>{if(H(e[n]))return s;if(s){const i=e[s]%1;e[s]-=i,e[n]+=i*r[s][n]}return n},null)}function ca(r){const e={};for(const[t,s]of Object.entries(r))s!==0&&(e[t]=s);return e}class Z{constructor(e){const t=e.conversionAccuracy==="longterm"||!1;let s=t?sd:rd;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||ne.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return Z.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new Me(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new Z({values:us(e,Z.normalizeUnit),loc:ne.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(Rt(e))return Z.fromMillis(e);if(Z.isDuration(e))return e;if(typeof e=="object")return Z.fromObject(e);throw new Me(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=Gh(e);return s?Z.fromObject(s,t):Z.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=Zh(e);return s?Z.fromObject(s,t):Z.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new Me("need to specify a reason the Duration is invalid");const s=e instanceof it?e:new it(e,t);if(ge.throwOnInvalid)throw new Cu(s);return new Z({invalid:s})}static normalizeUnit(e){const t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new Gi(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){const s={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?Pe.create(this.loc,s).formatDurationFromString(this,e):na}toHuman(e={}){if(!this.isValid)return na;const t=e.showZeros!==!1,s=$t.map(n=>{const i=this.values[n];return H(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(i)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=gn(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},V.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?oa(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=Z.fromDurationLike(e),s={};for(const n of $t)(Xt(t.values,n)||Xt(this.values,n))&&(s[n]=t.get(n)+this.get(n));return _t(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=Z.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;const t={};for(const s of Object.keys(this.values))t[s]=Vo(e(this.values[s],s));return _t(this,{values:t},!0)}get(e){return this[Z.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...us(e,Z.normalizeUnit)};return _t(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:s,matrix:n}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:n,conversionAccuracy:s};return _t(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return aa(this.matrix,e),_t(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=ca(this.normalize().shiftToAll().toObject());return _t(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>Z.normalizeUnit(o));const t={},s={},n=this.toObject();let i;for(const o of $t)if(e.indexOf(o)>=0){i=o;let a=0;for(const u in s)a+=this.matrix[u][o]*s[u],s[u]=0;Rt(n[o])&&(a+=n[o]);const c=Math.trunc(a);t[o]=c,s[o]=(a*1e3-c*1e3)/1e3}else Rt(n[o])&&(s[o]=n[o]);for(const o in s)s[o]!==0&&(t[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return aa(this.matrix,t),_t(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return _t(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=ca(this.values);return _t(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(s,n){return s===void 0||s===0?n===void 0||n===0:s===n}for(const s of $t)if(!t(this.values[s],e.values[s]))return!1;return!0}}const or="Invalid Interval";function id(r,e){return!r||!r.isValid?me.invalid("missing or invalid start"):!e||!e.isValid?me.invalid("missing or invalid end"):e<r?me.invalid("end before start",`The end of an interval must be after its start, but you had start=${r.toISO()} and end=${e.toISO()}`):null}class me{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new Me("need to specify a reason the Interval is invalid");const s=e instanceof it?e:new it(e,t);if(ge.throwOnInvalid)throw new Ru(s);return new me({invalid:s})}static fromDateTimes(e,t){const s=Dr(e),n=Dr(t),i=id(s,n);return i??new me({start:s,end:n})}static after(e,t){const s=Z.fromDurationLike(t),n=Dr(e);return me.fromDateTimes(n,n.plus(s))}static before(e,t){const s=Z.fromDurationLike(t),n=Dr(e);return me.fromDateTimes(n.minus(s),n)}static fromISO(e,t){const[s,n]=(e||"").split("/",2);if(s&&n){let i,o;try{i=V.fromISO(s,t),o=i.isValid}catch{o=!1}let a,c;try{a=V.fromISO(n,t),c=a.isValid}catch{c=!1}if(o&&c)return me.fromDateTimes(i,a);if(o){const u=Z.fromISO(n,t);if(u.isValid)return me.after(i,u)}else if(c){const u=Z.fromISO(s,t);if(u.isValid)return me.before(a,u)}}return me.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;const s=this.start.startOf(e,t);let n;return t?.useLocaleWeeks?n=this.end.reconfigure({locale:s.locale}):n=this.end,n=n.startOf(e,t),Math.floor(n.diff(s,e).get(e))+(n.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?me.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];const t=e.map(Dr).filter(o=>this.contains(o)).sort((o,a)=>o.toMillis()-a.toMillis()),s=[];let{s:n}=this,i=0;for(;n<this.e;){const o=t[i]||this.e,a=+o>+this.e?this.e:o;s.push(me.fromDateTimes(n,a)),n=a,i+=1}return s}splitBy(e){const t=Z.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s}=this,n=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(t.mapUnits(c=>c*n));i=+a>+this.e?this.e:a,o.push(me.fromDateTimes(s,i)),s=i,n+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const t=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return t>=s?null:me.fromDateTimes(t,s)}union(e){if(!this.isValid)return this;const t=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return me.fromDateTimes(t,s)}static merge(e){const[t,s]=e.sort((n,i)=>n.s-i.s).reduce(([n,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[n,i.union(o)]:[n.concat([i]),o]:[n,o],[[],null]);return s&&t.push(s),t}static xor(e){let t=null,s=0;const n=[],i=e.map(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((c,u)=>c.time-u.time);for(const c of a)s+=c.type==="s"?1:-1,s===1?t=c.time:(t&&+t!=+c.time&&n.push(me.fromDateTimes(t,c.time)),t=null);return me.merge(n)}difference(...e){return me.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:or}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=rs,t={}){return this.isValid?Pe.create(this.s.loc.clone(t),e).formatInterval(this):or}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:or}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:or}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:or}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:or}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):Z.invalid(this.invalidReason)}mapEndpoints(e){return me.fromDateTimes(e(this.s),e(this.e))}}class ds{static hasDST(e=ge.defaultZone){const t=V.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return yt.isValidZone(e)}static normalizeZone(e){return kt(e,ge.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||ne.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||ne.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||ne.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null,outputCalendar:i="gregory"}={}){return(n||ne.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null,outputCalendar:i="gregory"}={}){return(n||ne.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null}={}){return(n||ne.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:n=null}={}){return(n||ne.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ne.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return ne.create(t,null,"gregory").eras(e)}static features(){return{relative:Fo(),localeWeek:Bo()}}}function la(r,e){const t=n=>n.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(r);return Math.floor(Z.fromMillis(s).as("days"))}function od(r,e,t){const s=[["years",(c,u)=>u.year-c.year],["quarters",(c,u)=>u.quarter-c.quarter+(u.year-c.year)*4],["months",(c,u)=>u.month-c.month+(u.year-c.year)*12],["weeks",(c,u)=>{const l=la(c,u);return(l-l%7)/7}],["days",la]],n={},i=r;let o,a;for(const[c,u]of s)t.indexOf(c)>=0&&(o=c,n[c]=u(r,e),a=i.plus(n),a>e?(n[c]--,r=i.plus(n),r>e&&(a=r,n[c]--,r=i.plus(n))):r=a);return[r,n,a,o]}function ad(r,e,t,s){let[n,i,o,a]=od(r,e,t);const c=e-n,u=t.filter(h=>["hours","minutes","seconds","milliseconds"].indexOf(h)>=0);u.length===0&&(o<e&&(o=n.plus({[a]:1})),o!==n&&(i[a]=(i[a]||0)+c/(o-n)));const l=Z.fromObject(i,s);return u.length>0?Z.fromMillis(c,s).shiftTo(...u).plus(l):l}const cd="missing Intl.DateTimeFormat.formatToParts support";function te(r,e=t=>t){return{regex:r,deser:([t])=>e(Xu(t))}}const ua="[ \xA0]",ha=new RegExp(ua,"g");function ld(r){return r.replace(/\./g,"\\.?").replace(ha,ua)}function da(r){return r.replace(/\./g,"").replace(ha," ").toLowerCase()}function ot(r,e){return r===null?null:{regex:RegExp(r.map(ld).join("|")),deser:([t])=>r.findIndex(s=>da(t)===da(s))+e}}function fa(r,e){return{regex:r,deser:([,t,s])=>ls(t,s),groups:e}}function fs(r){return{regex:r,deser:([e])=>e}}function ud(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hd(r,e){const t=nt(e),s=nt(e,"{2}"),n=nt(e,"{3}"),i=nt(e,"{4}"),o=nt(e,"{6}"),a=nt(e,"{1,2}"),c=nt(e,"{1,3}"),u=nt(e,"{1,6}"),l=nt(e,"{1,9}"),h=nt(e,"{2,4}"),d=nt(e,"{4,6}"),f=y=>({regex:RegExp(ud(y.val)),deser:([w])=>w,literal:!0}),g=(y=>{if(r.literal)return f(y);switch(y.val){case"G":return ot(e.eras("short"),0);case"GG":return ot(e.eras("long"),0);case"y":return te(u);case"yy":return te(h,mn);case"yyyy":return te(i);case"yyyyy":return te(d);case"yyyyyy":return te(o);case"M":return te(a);case"MM":return te(s);case"MMM":return ot(e.months("short",!0),1);case"MMMM":return ot(e.months("long",!0),1);case"L":return te(a);case"LL":return te(s);case"LLL":return ot(e.months("short",!1),1);case"LLLL":return ot(e.months("long",!1),1);case"d":return te(a);case"dd":return te(s);case"o":return te(c);case"ooo":return te(n);case"HH":return te(s);case"H":return te(a);case"hh":return te(s);case"h":return te(a);case"mm":return te(s);case"m":return te(a);case"q":return te(a);case"qq":return te(s);case"s":return te(a);case"ss":return te(s);case"S":return te(c);case"SSS":return te(n);case"u":return fs(l);case"uu":return fs(a);case"uuu":return te(t);case"a":return ot(e.meridiems(),0);case"kkkk":return te(i);case"kk":return te(h,mn);case"W":return te(a);case"WW":return te(s);case"E":case"c":return te(t);case"EEE":return ot(e.weekdays("short",!1),1);case"EEEE":return ot(e.weekdays("long",!1),1);case"ccc":return ot(e.weekdays("short",!0),1);case"cccc":return ot(e.weekdays("long",!0),1);case"Z":case"ZZ":return fa(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return fa(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return fs(/[a-z_+-/]{1,256}?/i);case" ":return fs(/[^\S\n\r]/);default:return f(y)}})(r)||{invalidReason:cd};return g.token=r,g}const dd={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function fd(r,e,t){const{type:s,value:n}=r;if(s==="literal"){const c=/^\s+$/.test(n);return{literal:!c,val:c?" ":n}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=t.hour12?"hour12":"hour24");let a=dd[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function pd(r){return[`^${r.map(t=>t.regex).reduce((t,s)=>`${t}(${s.source})`,"")}$`,r]}function gd(r,e,t){const s=r.match(e);if(s){const n={};let i=1;for(const o in t)if(Xt(t,o)){const a=t[o],c=a.groups?a.groups+1:1;!a.literal&&a.token&&(n[a.token.val[0]]=a.deser(s.slice(i,i+c))),i+=c}return[s,n]}else return[s,{}]}function md(r){const e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let t=null,s;return H(r.z)||(t=yt.create(r.z)),H(r.Z)||(t||(t=new je(r.Z)),s=r.Z),H(r.q)||(r.M=(r.q-1)*3+1),H(r.h)||(r.h<12&&r.a===1?r.h+=12:r.h===12&&r.a===0&&(r.h=0)),r.G===0&&r.y&&(r.y=-r.y),H(r.u)||(r.S=pn(r.u)),[Object.keys(r).reduce((i,o)=>{const a=e(o);return a&&(i[a]=r[o]),i},{}),t,s]}let bn=null;function yd(){return bn||(bn=V.fromMillis(1555555555555)),bn}function _d(r,e){if(r.literal)return r;const t=Pe.macroTokenToFormatOpts(r.val),s=ya(t,e);return s==null||s.includes(void 0)?r:s}function pa(r,e){return Array.prototype.concat(...r.map(t=>_d(t,e)))}class ga{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=pa(Pe.parseFormat(t),e),this.units=this.tokens.map(s=>hd(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,n]=pd(this.units);this.regex=RegExp(s,"i"),this.handlers=n}}explainFromTokens(e){if(this.isValid){const[t,s]=gd(e,this.regex,this.handlers),[n,i,o]=s?md(s):[null,null,void 0];if(Xt(s,"a")&&Xt(s,"H"))throw new Zt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:s,result:n,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function ma(r,e,t){return new ga(r,t).explainFromTokens(e)}function wd(r,e,t){const{result:s,zone:n,specificOffset:i,invalidReason:o}=ma(r,e,t);return[s,n,i,o]}function ya(r,e){if(!r)return null;const s=Pe.create(e,r).dtFormatter(yd()),n=s.formatToParts(),i=s.resolvedOptions();return n.map(o=>fd(o,r,i))}const Sn="Invalid DateTime",_a=864e13;function Cr(r){return new it("unsupported zone",`the zone "${r.name}" is not supported`)}function En(r){return r.weekData===null&&(r.weekData=is(r.c)),r.weekData}function Tn(r){return r.localWeekData===null&&(r.localWeekData=is(r.c,r.loc.getMinDaysInFirstWeek(),r.loc.getStartOfWeek())),r.localWeekData}function jt(r,e){const t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new V({...t,...e,old:t})}function wa(r,e,t){let s=r-e*60*1e3;const n=t.offset(s);if(e===n)return[s,e];s-=(n-e)*60*1e3;const i=t.offset(s);return n===i?[s,n]:[r-Math.min(n,i)*60*1e3,Math.max(n,i)]}function ps(r,e){r+=e*60*1e3;const t=new Date(r);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function gs(r,e,t){return wa(cs(r),e,t)}function ba(r,e){const t=r.o,s=r.c.year+Math.trunc(e.years),n=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...r.c,year:s,month:n,day:Math.min(r.c.day,as(s,n))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=Z.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=cs(i);let[c,u]=wa(a,t,r.zone);return o!==0&&(c+=o,u=r.zone.offset(c)),{ts:c,o:u}}function ar(r,e,t,s,n,i){const{setZone:o,zone:a}=t;if(r&&Object.keys(r).length!==0||e){const c=e||a,u=V.fromObject(r,{...t,zone:c,specificOffset:i});return o?u:u.setZone(a)}else return V.invalid(new it("unparsable",`the input "${n}" can't be parsed as ${s}`))}function ms(r,e,t=!0){return r.isValid?Pe.create(ne.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}function vn(r,e,t){const s=r.c.year>9999||r.c.year<0;let n="";if(s&&r.c.year>=0&&(n+="+"),n+=Se(r.c.year,s?6:4),t==="year")return n;if(e){if(n+="-",n+=Se(r.c.month),t==="month")return n;n+="-"}else if(n+=Se(r.c.month),t==="month")return n;return n+=Se(r.c.day),n}function Sa(r,e,t,s,n,i,o){let a=!t||r.c.millisecond!==0||r.c.second!==0,c="";switch(o){case"day":case"month":case"year":break;default:if(c+=Se(r.c.hour),o==="hour")break;if(e){if(c+=":",c+=Se(r.c.minute),o==="minute")break;a&&(c+=":",c+=Se(r.c.second))}else{if(c+=Se(r.c.minute),o==="minute")break;a&&(c+=Se(r.c.second))}if(o==="second")break;a&&(!s||r.c.millisecond!==0)&&(c+=".",c+=Se(r.c.millisecond,3))}return n&&(r.isOffsetFixed&&r.offset===0&&!i?c+="Z":r.o<0?(c+="-",c+=Se(Math.trunc(-r.o/60)),c+=":",c+=Se(Math.trunc(-r.o%60))):(c+="+",c+=Se(Math.trunc(r.o/60)),c+=":",c+=Se(Math.trunc(r.o%60)))),i&&(c+="["+r.zone.ianaName+"]"),c}const Ea={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},bd={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Sd={ordinal:1,hour:0,minute:0,second:0,millisecond:0},ys=["year","month","day","hour","minute","second","millisecond"],Ed=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Td=["year","ordinal","hour","minute","second","millisecond"];function _s(r){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[r.toLowerCase()];if(!e)throw new Gi(r);return e}function Ta(r){switch(r.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return _s(r)}}function vd(r){if(Nr===void 0&&(Nr=ge.now()),r.type!=="iana")return r.offset(Nr);const e=r.name;let t=On.get(e);return t===void 0&&(t=r.offset(Nr),On.set(e,t)),t}function va(r,e){const t=kt(e.zone,ge.defaultZone);if(!t.isValid)return V.invalid(Cr(t));const s=ne.fromObject(e);let n,i;if(H(r.year))n=ge.now();else{for(const c of ys)H(r[c])&&(r[c]=Ea[c]);const o=Po(r)||xo(r);if(o)return V.invalid(o);const a=vd(t);[n,i]=gs(r,a,t)}return new V({ts:n,zone:t,loc:s,o:i})}function Oa(r,e,t){const s=H(t.round)?!0:t.round,n=H(t.rounding)?"trunc":t.rounding,i=(a,c)=>(a=gn(a,s||t.calendary?0:2,t.calendary?"round":n),e.loc.clone(t).relFormatter(t).format(a,c)),o=a=>t.calendary?e.hasSame(r,a)?0:e.startOf(a).diff(r.startOf(a),a).get(a):e.diff(r,a).get(a);if(t.unit)return i(o(t.unit),t.unit);for(const a of t.units){const c=o(a);if(Math.abs(c)>=1)return i(c,a)}return i(r>e?-0:0,t.units[t.units.length-1])}function Aa(r){let e={},t;return r.length>0&&typeof r[r.length-1]=="object"?(e=r[r.length-1],t=Array.from(r).slice(0,r.length-1)):t=Array.from(r),[e,t]}let Nr;const On=new Map;class V{constructor(e){const t=e.zone||ge.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new it("invalid input"):null)||(t.isValid?null:Cr(t));this.ts=H(e.ts)?ge.now():e.ts;let n=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[n,i]=[e.old.c,e.old.o];else{const a=Rt(e.o)&&!e.old?e.o:t.offset(this.ts);n=ps(this.ts,a),s=Number.isNaN(n.year)?new it("invalid input"):null,n=s?null:n,i=s?null:a}this._zone=t,this.loc=e.loc||ne.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=n,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,t]=Aa(arguments),[s,n,i,o,a,c,u]=t;return va({year:s,month:n,day:i,hour:o,minute:a,second:c,millisecond:u},e)}static utc(){const[e,t]=Aa(arguments),[s,n,i,o,a,c,u]=t;return e.zone=je.utcInstance,va({year:s,month:n,day:i,hour:o,minute:a,second:c,millisecond:u},e)}static fromJSDate(e,t={}){const s=sh(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const n=kt(t.zone,ge.defaultZone);return n.isValid?new V({ts:s,zone:n,loc:ne.fromObject(t)}):V.invalid(Cr(n))}static fromMillis(e,t={}){if(Rt(e))return e<-_a||e>_a?V.invalid("Timestamp out of range"):new V({ts:e,zone:kt(t.zone,ge.defaultZone),loc:ne.fromObject(t)});throw new Me(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(Rt(e))return new V({ts:e*1e3,zone:kt(t.zone,ge.defaultZone),loc:ne.fromObject(t)});throw new Me("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=kt(t.zone,ge.defaultZone);if(!s.isValid)return V.invalid(Cr(s));const n=ne.fromObject(t),i=us(e,Ta),{minDaysInFirstWeek:o,startOfWeek:a}=Mo(i,n),c=ge.now(),u=H(t.specificOffset)?s.offset(c):t.specificOffset,l=!H(i.ordinal),h=!H(i.year),d=!H(i.month)||!H(i.day),f=h||d,p=i.weekYear||i.weekNumber;if((f||l)&&p)throw new Zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(d&&l)throw new Zt("Can't mix ordinal dates with month/day");const g=p||i.weekday&&!f;let y,w,_=ps(c,u);g?(y=Ed,w=bd,_=is(_,o,a)):l?(y=Td,w=Sd,_=dn(_)):(y=ys,w=Ea);let S=!1;for(const D of y){const z=i[D];H(z)?S?i[D]=w[D]:i[D]=_[D]:S=!0}const m=g?eh(i,o,a):l?th(i):Po(i),T=m||xo(i);if(T)return V.invalid(T);const E=g?Do(i,o,a):l?Lo(i):i,[v,I]=gs(E,u,s),P=new V({ts:v,zone:s,o:I,loc:n});return i.weekday&&f&&e.weekday!==P.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${P.toISO()}`):P.isValid?P:V.invalid(P.invalid)}static fromISO(e,t={}){const[s,n]=zh(e);return ar(s,n,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,n]=Jh(e);return ar(s,n,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,n]=Kh(e);return ar(s,n,t,"HTTP",t)}static fromFormat(e,t,s={}){if(H(e)||H(t))throw new Me("fromFormat requires an input string and a format");const{locale:n=null,numberingSystem:i=null}=s,o=ne.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0}),[a,c,u,l]=wd(o,e,t);return l?V.invalid(l):ar(a,c,s,`format ${t}`,e,u)}static fromString(e,t,s={}){return V.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,n]=td(e);return ar(s,n,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new Me("need to specify a reason the DateTime is invalid");const s=e instanceof it?e:new it(e,t);if(ge.throwOnInvalid)throw new ku(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=ya(e,ne.fromObject(t));return s?s.map(n=>n?n.val:null).join(""):null}static expandFormat(e,t={}){return pa(Pe.parseFormat(e),ne.fromObject(t)).map(n=>n.val).join("")}static resetCache(){Nr=void 0,On.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?En(this).weekYear:NaN}get weekNumber(){return this.isValid?En(this).weekNumber:NaN}get weekday(){return this.isValid?En(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Tn(this).weekday:NaN}get localWeekNumber(){return this.isValid?Tn(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Tn(this).weekYear:NaN}get ordinal(){return this.isValid?dn(this.c).ordinal:NaN}get monthShort(){return this.isValid?ds.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?ds.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?ds.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?ds.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=cs(this.c),n=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-n*t),a=this.zone.offset(s-i*t);if(o===a)return[this];const c=s-o*t,u=s-a*t,l=ps(c,o),h=ps(u,a);return l.hour===h.hour&&l.minute===h.minute&&l.second===h.second&&l.millisecond===h.millisecond?[jt(this,{ts:c}),jt(this,{ts:u})]:[this]}get isInLeapYear(){return Or(this.year)}get daysInMonth(){return as(this.year,this.month)}get daysInYear(){return this.isValid?Qt(this.year):NaN}get weeksInWeekYear(){return this.isValid?Ar(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Ar(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:n}=Pe.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:n}}toUTC(e=0,t={}){return this.setZone(je.instance(e),t)}toLocal(){return this.setZone(ge.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=kt(e,ge.defaultZone),e.equals(this.zone))return this;if(e.isValid){let n=this.ts;if(t||s){const i=e.offset(this.ts),o=this.toObject();[n]=gs(o,i,e)}return jt(this,{ts:n,zone:e})}else return V.invalid(Cr(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const n=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return jt(this,{loc:n})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=us(e,Ta),{minDaysInFirstWeek:s,startOfWeek:n}=Mo(t,this.loc),i=!H(t.weekYear)||!H(t.weekNumber)||!H(t.weekday),o=!H(t.ordinal),a=!H(t.year),c=!H(t.month)||!H(t.day),u=a||c,l=t.weekYear||t.weekNumber;if((u||o)&&l)throw new Zt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&o)throw new Zt("Can't mix ordinal dates with month/day");let h;i?h=Do({...is(this.c,s,n),...t},s,n):H(t.ordinal)?(h={...this.toObject(),...t},H(t.day)&&(h.day=Math.min(as(h.year,h.month),h.day))):h=Lo({...dn(this.c),...t});const[d,f]=gs(h,this.o,this.zone);return jt(this,{ts:d,o:f})}plus(e){if(!this.isValid)return this;const t=Z.fromDurationLike(e);return jt(this,ba(this,t))}minus(e){if(!this.isValid)return this;const t=Z.fromDurationLike(e).negate();return jt(this,ba(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},n=Z.normalizeUnit(e);switch(n){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(n==="weeks")if(t){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(n==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?Pe.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):Sn}toLocaleString(e=rs,t={}){return this.isValid?Pe.create(this.loc.clone(t),e).formatDateTime(this):Sn}toLocaleParts(e={}){return this.isValid?Pe.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:s=!1,includeOffset:n=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=_s(o);const a=e==="extended";let c=vn(this,a,o);return ys.indexOf(o)>=3&&(c+="T"),c+=Sa(this,a,t,s,n,i,o),c}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?vn(this,e==="extended",_s(t)):null}toISOWeekDate(){return ms(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:n=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=_s(a),(n&&ys.indexOf(a)>=3?"T":"")+Sa(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return ms(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return ms(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?vn(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:s=!0}={}){let n="HH:mm:ss.SSS";return(t||e)&&(s&&(n+=" "),t?n+="z":e&&(n+="ZZ")),ms(this,n,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Sn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",s={}){if(!this.isValid||!e.isValid)return Z.invalid("created by diffing an invalid DateTime");const n={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=nh(t).map(Z.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,c=o?e:this,u=ad(a,c,i,n);return o?u.negate():u}diffNow(e="milliseconds",t={}){return this.diff(V.now(),e,t)}until(e){return this.isValid?me.fromDateTimes(this,e):this}hasSame(e,t,s){if(!this.isValid)return!1;const n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,s)<=n&&n<=i.endOf(t,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const t=e.base||V.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let n=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(n=e.unit,i=void 0),Oa(t,this.plus(s),{...e,numeric:"always",units:n,unit:i})}toRelativeCalendar(e={}){return this.isValid?Oa(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new Me("min requires all arguments be DateTimes");return $o(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new Me("max requires all arguments be DateTimes");return $o(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:n=null,numberingSystem:i=null}=s,o=ne.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});return ma(o,e,t)}static fromStringExplain(e,t,s={}){return V.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:n=null}=t,i=ne.fromOpts({locale:s,numberingSystem:n,defaultToEN:!0});return new ga(i,e)}static fromFormatParser(e,t,s={}){if(H(e)||H(t))throw new Me("fromFormatParser requires an input string and a format parser");const{locale:n=null,numberingSystem:i=null}=s,o=ne.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new Me(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:c,specificOffset:u,invalidReason:l}=t.explainFromTokens(e);return l?V.invalid(l):ar(a,c,s,`format ${t.format}`,e,u)}static get DATE_SHORT(){return rs}static get DATE_MED(){return Yi}static get DATE_MED_WITH_WEEKDAY(){return Nu}static get DATE_FULL(){return Zi}static get DATE_HUGE(){return Xi}static get TIME_SIMPLE(){return Qi}static get TIME_WITH_SECONDS(){return eo}static get TIME_WITH_SHORT_OFFSET(){return to}static get TIME_WITH_LONG_OFFSET(){return ro}static get TIME_24_SIMPLE(){return so}static get TIME_24_WITH_SECONDS(){return no}static get TIME_24_WITH_SHORT_OFFSET(){return io}static get TIME_24_WITH_LONG_OFFSET(){return oo}static get DATETIME_SHORT(){return ao}static get DATETIME_SHORT_WITH_SECONDS(){return co}static get DATETIME_MED(){return lo}static get DATETIME_MED_WITH_SECONDS(){return uo}static get DATETIME_MED_WITH_WEEKDAY(){return Du}static get DATETIME_FULL(){return ho}static get DATETIME_FULL_WITH_SECONDS(){return fo}static get DATETIME_HUGE(){return po}static get DATETIME_HUGE_WITH_SECONDS(){return go}}function Dr(r){if(V.isDateTime(r))return r;if(r&&r.valueOf&&Rt(r.valueOf()))return V.fromJSDate(r);if(r&&typeof r=="object")return V.fromObject(r);throw new Me(`Unknown datetime argument: ${r}, of type ${typeof r}`)}const De=[];for(let r=0;r<256;++r)De.push((r+256).toString(16).slice(1));function Od(r,e,t,s){return()=>{r|=0,e|=0,t|=0,s|=0;const n=(r+e|0)+s|0;return s=s+1|0,r=e^e>>>9,e=t+(t<<3)|0,t=(t<<21|t>>>11)+n|0,n>>>0}}function Ad(){const r=new Uint8Array(16),e=BigInt(Date.now()),t=BigInt(Math.floor(performance.now()*1e3)%65535),s=e<<16n|t;r[0]=Number(s>>40n&0xFFn),r[1]=Number(s>>32n&0xFFn),r[2]=Number(s>>24n&0xFFn),r[3]=Number(s>>16n&0xFFn),r[4]=Number(s>>8n&0xFFn),r[5]=Number(s&0xFFn);const n=(Math.random()*4294967295^Date.now()^performance.now())>>>0,i=Od(2654435769,608135816,3084996962,n),o=new DataView(r.buffer);return o.setUint32(6,i()),o.setUint32(10,i()),o.setUint16(14,i()),r[6]=112|r[6]&15,r[8]=128|r[8]&63,(De[r[0]]+De[r[1]]+De[r[2]]+De[r[3]]+"-"+De[r[4]]+De[r[5]]+"-"+De[r[6]]+De[r[7]]+"-"+De[r[8]]+De[r[9]]+"-"+De[r[10]]+De[r[11]]+De[r[12]]+De[r[13]]+De[r[14]]+De[r[15]]).toLowerCase()}function ie(r=new Date){const e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}-${e(r.getMonth()+1)}-${e(r.getDate())} ${e(r.getHours())}:${e(r.getMinutes())}:${e(r.getSeconds())}`}function Ia(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.trunc(Math.random()*16);return(r==="x"?e:e&3|8).toString(16)})}function An(){return Ad()}function In(r){const e=Number.parseFloat(r);return L.isNumber(e)?e:0}function pt(r){return In(Number.parseInt(r,10))}function ws(r,e=[]){const t=L.isString(r)?r.toLowerCase():r;return["true","y","1",1,!0,...e].includes(t)}function ka(r){return L.isStringFilled(r)?r[0].toUpperCase()+r.slice(1):r}function kn(r){if(L.isNil(r))return"";const e=[];for(const[t,s]of Object.entries(r))L.isArray(s)?s.forEach((n,i)=>{e.push(`${encodeURIComponent(`${t}[${i}]`)}=${encodeURIComponent(n)}`)}):e.push(`${encodeURIComponent(t)}=${encodeURIComponent(s)}`);return e.join("&")}const Id=/[&<>'"]/g,kd=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34)/g,Rd={"&":"&","<":"<",">":">","'":"'",'"':"""},Cd={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","&apos":"'","'":"'",""":'"',""":'"'};let Nd=class{getRandom(e=8){return Array.from({length:e}).map(()=>Math.trunc(Math.random()*36).toString(36)).join("")}getUniqId(){return Ia()}getUuidRfc4122(){return An()}encode(e){return L.isString(e)?e.replace(Id,t=>Rd[t]):e}decode(e){return L.isString(e)?e.replace(kd,t=>Cd[t]):e}toNumber(e){return In(e)}toInteger(e){return pt(e)}toBoolean(e,t=[]){return ws(e,t)}toCamelCase(e){if(!L.isStringFilled(e))return e;const t=/[-_\s]+(.)?/g;if(!t.test(e))return/^[A-Z]+$/.test(e)?e.toLowerCase():e[0].toLowerCase()+e.slice(1);const s=e.toLowerCase().replace(t,(n,i)=>i?i.toUpperCase():"");return s[0].toLowerCase()+s.slice(1)}toPascalCase(e){return L.isStringFilled(e)?this.capitalize(this.toCamelCase(e)):e}toKebabCase(e){if(!L.isStringFilled(e))return e;const t=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+\d*|\b)|[A-Z]?[a-z]+\d*|[A-Z]|\d+/g);return t?t.map(s=>s.toLowerCase()).join("-"):e}capitalize(e){return ka(e)}numberFormat(e,t=0,s=".",n=","){const i=Number.isFinite(e)?e:0,o=Number.isFinite(t)?Math.abs(t):0,a=(o?((c,u)=>{const l=10**u;return Math.round(c*l)/l})(i,o):Math.round(i)).toString().split(".");return a[0]&&a[0].length>3&&(a[0]=a[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,n)),(a[1]||"").length<o&&(a[1]=(a[1]||"").padEnd(o,"0")),a.join(s)}toDateTime(e,t,s){return L.isStringFilled(t)?V.fromFormat(e,t,s):V.fromISO(e,s)}toB24Format(e){return typeof e=="string"?e:e instanceof Date?this.toB24Format(V.fromJSDate(e)):e.toFormat("yyyy-MM-dd'T'HH:mm:ssZZ")}getDateForLog(){return ie()}buildQueryString(e){return kn(e)}};const bs=new Nd;let ke="";try{ke=navigator?.userAgent.toLowerCase()}catch{ke="?"}let Dd=class{isOpera(){return ke.includes("opera")}isIE(){return"attachEvent"in document&&!this.isOpera()}isIE6(){return ke.includes("msie 6")}isIE7(){return ke.includes("msie 7")}isIE8(){return ke.includes("msie 8")}isIE9(){return"documentMode"in document&&document?.documentMode>=9}isIE10(){return"documentMode"in document&&document?.documentMode>=10}isSafari(){return ke.includes("safari")&&!ke.includes("chrome")}isFirefox(){return ke.includes("firefox")}isChrome(){return ke.includes("chrome")}detectIEVersion(){if(this.isOpera()||this.isSafari()||this.isFirefox()||this.isChrome())return-1;let e=-1;if(window.MSStream&&!window.ActiveXObject&&"ActiveXObject"in window?e=11:this.isIE10()?e=10:this.isIE9()?e=9:this.isIE()&&(e=8),e===-1||e===8){if(navigator.appName==="Microsoft Internet Explorer"){const t=/MSIE (\d[.0-9]*)/,s=navigator.userAgent.match(t);L.isArrayLike(s)&&s.length>0&&(e=Number.parseFloat(s[1]))}if(navigator.appName==="Netscape"){e=11;const t=/Trident\/.*rv:(\d[.0-9]*)/;if(t.exec(navigator.userAgent)!=null){const s=navigator.userAgent.match(t);L.isArrayLike(s)&&s.length>0&&(e=Number.parseFloat(s[1]))}}}return e}isIE11(){return this.detectIEVersion()>=11}isMac(){return ke.includes("macintosh")}isWin(){return ke.includes("windows")}isLinux(){return ke.includes("linux")&&!this.isAndroid()}isAndroid(){return ke.includes("android")}isIPad(){return ke.includes("ipad;")||this.isMac()&&this.isTouchDevice()}isIPhone(){return ke.includes("iphone;")}isIOS(){return this.isIPad()||this.isIPhone()}isMobile(){return this.isIPhone()||this.isIPad()||this.isAndroid()||ke.includes("mobile")||ke.includes("touch")}isRetina(){return(window.devicePixelRatio&&window.devicePixelRatio>=2)===!0}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}isDoctype(e){const t=e||document;return t.compatMode?t.compatMode==="CSS1Compat":t.documentElement&&t.documentElement.clientHeight}isLocalStorageSupported(){try{return localStorage.setItem("test","test"),localStorage.removeItem("test"),!0}catch{return!1}}detectAndroidVersion(){const e=/Android (\d[.0-9]*)/;if(e.exec(navigator.userAgent)!=null){const t=navigator.userAgent.match(e);if(L.isArrayLike(t)&&t.length>0)return Number.parseFloat(t[1])}return 0}};const Ra=new Dd;var K=(r=>(r.v3="v3",r.v2="v2",r))(K||{}),Ca=(r=>(r.undefined="UNDEFINED",r.lead="CRM_LEAD",r.deal="CRM_DEAL",r.contact="CRM_CONTACT",r.company="CRM_COMPANY",r.oldInvoice="CRM_INVOICE",r.invoice="CRM_SMART_INVOICE",r.quote="CRM_QUOTE",r.requisite="CRM_REQUISITE",r.order="ORDER",r))(Ca||{}),at=(r=>(r[r.undefined=0]="undefined",r[r.lead=1]="lead",r[r.deal=2]="deal",r[r.contact=3]="contact",r[r.company=4]="company",r[r.oldInvoice=5]="oldInvoice",r[r.invoice=31]="invoice",r[r.quote=7]="quote",r[r.requisite=8]="requisite",r[r.order=14]="order",r))(at||{}),Rn=(r=>(r.undefined="?",r.lead="L",r.deal="D",r.contact="C",r.company="CO",r.oldInvoice="I",r.invoice="SI",r.quote="Q",r.requisite="RQ",r.order="O",r))(Rn||{});function Ld(r){const e=at[r];return Rn[e]||"?"}var Na=(r=>(r[r.undefined=0]="undefined",r[r.absolute=1]="absolute",r[r.percentage=2]="percentage",r))(Na||{}),Da=(r=>(r[r.undefined=0]="undefined",r[r.product=1]="product",r[r.service=7]="service",r[r.sku=3]="sku",r[r.skuEmpty=6]="skuEmpty",r[r.offer=4]="offer",r[r.offerEmpty=5]="offerEmpty",r))(Da||{}),La=(r=>(r.undefined="UNDEFINED",r.detail="DETAIL_PICTURE",r.preview="PREVIEW_PICTURE",r.morePhoto="MORE_PHOTO",r))(La||{}),Ma=(r=>(r[r.undefined=0]="undefined",r[r.mathematical=1]="mathematical",r[r.roundingUp=2]="roundingUp",r[r.roundingDown=4]="roundingDown",r))(Ma||{}),Pa=(r=>(r.undefined="undefined",r.b24="b24",r.box="box",r))(Pa||{}),xa=(r=>(r.undefined="undefined",r.crm="crm",r.disk="disk",r.lists="lists",r))(xa||{}),Fa=(r=>(r.undefined="undefined",r.lead="CCrmDocumentLead",r.company="CCrmDocumentCompany",r.contact="CCrmDocumentContact",r.deal="CCrmDocumentDeal",r.invoice="Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice",r.quote="Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote",r.order="Bitrix\\Crm\\Integration\\BizProc\\Document\\Order",r.dynamic="Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic",r.disk="Bitrix\\Disk\\BizProcDocument",r.lists="BizprocDocument",r.listsList="Bitrix\\Lists\\BizprocDocumentLists",r))(Fa||{});function Md(r){switch(r){case"CCrmDocumentLead":return at.lead;case"CCrmDocumentCompany":return at.company;case"CCrmDocumentContact":return at.contact;case"CCrmDocumentDeal":return at.deal;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice":return at.invoice;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote":return at.quote;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Order":return at.order}return at.undefined}function Cn(r,e){let t="",s="undefined";switch(r){case"CCrmDocumentLead":s="crm",t="LEAD";break;case"CCrmDocumentCompany":s="crm",t="COMPANY";break;case"CCrmDocumentContact":s="crm",t="CONTACT";break;case"CCrmDocumentDeal":s="crm",t="DEAL";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice":s="crm",t="SMART_INVOICE";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote":s="crm",t="QUOTE";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Order":s="crm",t="ORDER";break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic":if(s="crm",t=`DYNAMIC_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break;case"Bitrix\\Disk\\BizProcDocument":if(s="disk",t=`STORAGE_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break;case"BizprocDocument":if(s="lists",t=`iblock_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break;case"Bitrix\\Lists\\BizprocDocumentLists":if(s="lists",t=`iblock_${e||0}`,(e||0)<1)throw new Error("Need set entityId");break}return[s,r,t]}function Pd(r,e,t){let s="";const n=Cn(r,1);switch(r){case"CCrmDocumentLead":s=`LEAD_${e}`;break;case"CCrmDocumentCompany":s=`COMPANY_${e}`;break;case"CCrmDocumentContact":s=`CONTACT_${e}`;break;case"CCrmDocumentDeal":s=`DEAL_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice":s=`SMART_INVOICE_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote":s=`QUOTE_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Order":s=`ORDER_${e}`;break;case"Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic":if(s=`DYNAMIC_${t||0}_${e}`,(t||0)<1)throw new Error("Need set dynamicId");break;case"Bitrix\\Disk\\BizProcDocument":s=`${e}`;break;case"BizprocDocument":s=`${e}`;break;case"Bitrix\\Lists\\BizprocDocumentLists":s=`${e}`;break}return[n[0],n[1],s]}function xd(r){const e=Cn(r,1);return[e[0],e[1]]}var de=(r=>(r.App="app",r.Profile="profile",r.Currency="currency",r.AppOptions="appOptions",r.UserOptions="userOptions",r))(de||{});const wt={Free:"F",Demo:"D",Trial:"T",Paid:"P",Local:"L",Subscription:"S"},Ba={[wt.Free]:"Free",[wt.Demo]:"Demo",[wt.Trial]:"Trial",[wt.Paid]:"Paid",[wt.Local]:"Local",[wt.Subscription]:"Subscription"},Ut={MainSettings:"MainSettings",UfList:"UfList",UfPage:"UfPage"};var bt=(r=>(r.NotSet="notSet",r.JsonArray="jsonArray",r.JsonObject="jsonObject",r.FloatVal="float",r.IntegerVal="integer",r.BoolYN="boolYN",r.StringVal="string",r))(bt||{}),he=(r=>(r.Undefined="undefined",r.WebSocket="webSocket",r.LongPolling="longPolling",r))(he||{}),Ve=(r=>(r.PullConfig="bx-pull-config",r.WebsocketBlocked="bx-pull-websocket-blocked",r.LongPollingBlocked="bx-pull-longpolling-blocked",r.LoggingEnabled="bx-pull-logging-enabled",r))(Ve||{}),Ke=(r=>(r.Online="online",r.Offline="offline",r.Connecting="connect",r))(Ke||{}),Ss=(r=>(r[r.Unknown=0]="Unknown",r[r.Client=1]="Client",r[r.Backend=2]="Backend",r))(Ss||{}),Ge=(r=>(r.Server="server",r.Client="client",r.Online="online",r.Status="status",r.Revision="revision",r))(Ge||{}),xe=(r=>(r[r.NORMAL_CLOSURE=1e3]="NORMAL_CLOSURE",r[r.SERVER_DIE=1001]="SERVER_DIE",r[r.CONFIG_REPLACED=3e3]="CONFIG_REPLACED",r[r.CHANNEL_EXPIRED=3001]="CHANNEL_EXPIRED",r[r.SERVER_RESTARTED=3002]="SERVER_RESTARTED",r[r.CONFIG_EXPIRED=3003]="CONFIG_EXPIRED",r[r.MANUAL=3004]="MANUAL",r[r.STUCK=3005]="STUCK",r[r.WRONG_CHANNEL_ID=4010]="WRONG_CHANNEL_ID",r[r.NO_PUBLIC_CHANNEL_ID=4012]="NO_PUBLIC_CHANNEL_ID",r[r.WRONG_REQUEST_DATA=4013]="WRONG_REQUEST_DATA",r[r.REQUEST_COMMAND_NOT_ALLOWED=4014]="REQUEST_COMMAND_NOT_ALLOWED",r[r.WRONG_REQUEST_COMMAND=4015]="WRONG_REQUEST_COMMAND",r[r.TOO_MANY_MESSAGES=4016]="TOO_MANY_MESSAGES",r[r.NO_CHANNELS_FOUND=4017]="NO_CHANNELS_FOUND",r[r.TOO_MANY_CHANNELS=4018]="TOO_MANY_CHANNELS",r[r.INVALID_CHANNEL_ID=4019]="INVALID_CHANNEL_ID",r[r.PRIVATE_CHANNEL_NOT_ALLOWED=4020]="PRIVATE_CHANNEL_NOT_ALLOWED",r[r.INVALID_CHANNEL_SIGNATURE=4021]="INVALID_CHANNEL_SIGNATURE",r[r.TOO_MANY_CONNECTIONS=4029]="TOO_MANY_CONNECTIONS",r))(xe||{});function Fd(r){return Bd.has(r)}const Bd=new Set([4013,4014,4015,4016,4017,4018,4019,4020,4021]);var Lr=(r=>(r.CHANNEL_EXPIRE="CHANNEL_EXPIRE",r.CONFIG_EXPIRE="CONFIG_EXPIRE",r.SERVER_RESTART="SERVER_RESTART",r))(Lr||{}),Nn=(r=>(r.Shared="shared",r.Personal="personal",r))(Nn||{});const Dn={Parse:{code:-32700,message:"Parse error"},InvalidRequest:{code:-32600,message:"Invalid Request"},MethodNotFound:{code:-32601,message:"Method not found"},InvalidParams:{code:-32602,message:"Invalid params"},Internal:{code:-32603,message:"Internal error"}};var gt=(r=>(r.Publish="publish",r.GetUsersLastSeen="getUsersLastSeen",r.Ping="ping",r.ListChannels="listChannels",r.SubscribeStatusChange="subscribeStatusChange",r.UnsubscribeStatusChange="unsubscribeStatusChange",r))(gt||{}),Ln=(r=>(r.ru="ru",r.id="id",r.ms="ms",r.de="de",r.en="en",r.la="la",r.fr="fr",r.in="in",r.it="it",r.pl="pl",r.br="br",r.vn="vn",r.tr="tr",r.kz="kz",r.ua="ua",r.ar="ar",r.th="th",r.sc="sc",r.tc="tc",r.ja="ja",r))(Ln||{});const $d={ru:"ru-RU",id:"id-ID",ms:"ms-MY",de:"de-DE",en:"en-EN",la:"es-ES",fr:"fr-FR",in:"hi-IN",it:"it-IT",pl:"pl-PL",br:"pt-BR",vn:"vi-VN",tr:"tr-TR",kz:"kk",ua:"uk-UA",ar:"ar-SA",th:"th-TH",sc:"zh-CN",tc:"zh-TW",ja:"ja-JP"};class Oe{_errors;_data;constructor(e){this._errors=new Map,this._data=e??null}get isSuccess(){return this._errors.size===0}get errors(){return this._errors}setData(e){return this._data=e,this}getData(){return this._data}addError(e,t){const s=t??An(),n=typeof e=="string"?new Error(e):e;return this._errors.set(s,n),this}addErrors(e){for(const t of e)this.addError(t);return this}getErrors(){return this._errors.values()}hasError(e){return this._errors.has(e)}getErrorMessages(){return Array.from(this._errors.values(),e=>e.message)}getErrorsByKey(){return Object.fromEntries(this._errors)}getErrorMessagesByKey(){return Object.fromEntries(Array.from(this._errors,([e,t])=>[e,t.message]))}toString(){const e=this.isSuccess?"success":"failure",t=this.safeStringify(this._data);return this.isSuccess?`Result(${e}): ${t}`:`Result(${e}): ${t}
Errors: ${this.getErrorMessages().join(", ")}`}safeStringify(e){try{return JSON.stringify(e,this.replacer,2)}catch{return"[Unable to serialize data]"}}replacer(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack}:t}static ok(e){return new Oe(e)}static fail(e,t){return new Oe().addError(e,t)}}class R extends Error{code;_status;timestamp;constructor(e){const t=R.formatErrorMessage(e);super(t),this.name="SdkError",this.code=e.code,this._status=e.status,Object.defineProperty(this,"originalError",{value:e.originalError,enumerable:!1,writable:!1,configurable:!0}),this.timestamp=new Date,this.cleanErrorStack()}get status(){return this._status}static fromException(e,t){return e instanceof R?e:new R({code:t?.code||"JSSDK_INTERNAL_ERROR",status:t?.status||500,description:e instanceof Error?e.message:`${e}`,originalError:e})}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this._status,timestamp:this.timestamp.toISOString(),stack:this.stack}}toString(){let e=`[${this.name}] ${this.code} (${this._status}): ${this.message}`;return this.stack&&(e+=`
Stack trace:
${this.stack}`),e}static formatErrorMessage(e){return e?.description?`${e.description}`:"Internal error"}cleanErrorStack(){typeof this.stack=="string"&&(this.stack=this.stack.split(`
`).filter(e=>!e.includes("SdkError.constructor")).join(`
`))}}const Mn=["auth","password","token","secret","access_token","refresh_token","client_secret","application_token","sessid","key","signature"],Mr="***REDACTED***",jd=new RegExp(`([?&]|^)(${Mn.join("|")})=[^&#;]*`,"gi"),Ud=/(\/rest\/(?:api\/)?\d+\/)[\w-]{8,}(?=[/?#]|$)/gi;function $a(r){return r.replace(Ud,`$1${Mr}`)}function ja(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ua(r){return r.includes("=")?r.replace(jd,(e,t,s)=>`${t}${s}=${Mr}`):r}function Vd(r){return $a(Ua(r))}function Pn(r,e){return typeof r=="string"?Vd(r):e<=0?r:ja(r)?Va(r,e-1):Array.isArray(r)?r.map(t=>Pn(t,e)):r}function Va(r,e){const t={...r};for(const s of Object.keys(t)){if(Mn.includes(s.toLowerCase())){t[s]=Mr;continue}t[s]=Pn(t[s],e)}return t}const qa=2;function qe(r){return ja(r)?Va(r,qa):Pn(r,qa)}function qd(r,e=[]){if(typeof r!="string")return r;const t=$a(r);if(!t.includes("="))return t;if(e.length===0)return Ua(t);const s=e.map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")),n=new RegExp(`([?&]|^)(${[...Mn,...s].join("|")})=[^&#;]*`,"gi");return t.replace(n,(i,o,a)=>`${o}${a}=${Mr}`)}class ye extends R{requestInfo;validation;isV3Envelope;constructor(e){(e.code==="AUTHORIZE_ERROR"||e.code==="WRONG_AUTH_TYPE")&&(e.status=403),e.description=ye.formatErrorMessage(e),super(e),this.name="AjaxError",this.isV3Envelope=e.isV3Envelope,this.validation=e.validation?.length?Object.freeze(e.validation.map(t=>qe(t))):void 0,this.requestInfo=e.requestInfo?{...e.requestInfo,...e.requestInfo.params!==void 0?{params:qe(e.requestInfo.params)}:{}}:void 0,this.cleanErrorStack()}static fromResponse(e){return new ye({code:e.data?.error||"JSSDK_INTERNAL_AJAX_ERROR",description:e.data?.error_description,status:e.status,requestInfo:e.config})}static fromException(e,t){return e instanceof ye?e:new ye({code:t?.code||"JSSDK_INTERNAL_AJAX_ERROR",status:t?.status||500,description:e instanceof Error?e.message:String(e),requestInfo:t?.requestInfo,originalError:e})}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this._status,timestamp:this.timestamp.toISOString(),requestInfo:this.requestInfo,...this.validation?{validation:this.validation}:{},stack:this.stack}}toString(){let e=`[${this.name}] ${this.code} (${this._status}): ${this.message}`;return this.requestInfo&&(e+=`
Request: ${this.requestInfo?.requestId?`[${this.requestInfo.requestId}] `:""}${this.requestInfo.method}`),this.stack&&(e+=`
Stack trace:
${this.stack}`),e}static formatErrorMessage(e){return e?.description?`${e.description}`:e.requestInfo?.method?`${e.code} (on ${e.requestInfo.method})`:"Internal ajax error"}cleanErrorStack(){typeof this.stack=="string"&&(this.stack=this.stack.split(`
`).filter(e=>!e.includes("AjaxError.constructor")).join(`
`))}}function Ha(r,e,t){if(!r||typeof r!="object"||!("error"in r))return;const s=r;if(s.error&&typeof s.error=="object"&&"code"in s.error){const n=s.error;let i=String(n.message??"").trimEnd();if(n.validation&&n.validation.length>0){const o=n.validation.map(a=>a?.message||JSON.stringify(a)).filter(a=>a!==void 0&&a!=="");o.length>0&&(i.length>0&&(i.endsWith(".")||(i+="."),i+=" "),i+=o.join(" "))}return{code:n.code,description:i,isV3Envelope:!0,...n.validation?{validation:Object.freeze([...n.validation])}:{}}}if(s.error&&typeof s.error=="string")return{code:s.error!=="0"?s.error:e,description:s?.error_description??t,isV3Envelope:!1}}class Pr extends Oe{_status;_query;_idempotency;_data;constructor(e){super(),this._data=e.answer?Object.freeze(e.answer):void 0,this._query=Object.freeze(structuredClone(e.query)),this._status=e.status,this._idempotency=e.idempotency?Object.freeze({...e.idempotency}):void 0,e.error?this.addError(e.error,"base-error"):this.#t()}get isSuccess(){return this.#e()}#e(){return this._errors.size===0}getData(){if(!this.isSuccess)return;const e=this._data;return e!==null&&typeof e=="object"&&"result"in e?Object.freeze({result:e.result,time:e.time}):Object.freeze({result:e,time:e?.time})}#t(){const e=Ha(this._data,"JSSDK_RESPONSE_ERROR","Some error in response");e!==void 0&&this.addError(this.#s({code:e.code,description:e.description,status:this._status,validation:e.validation,isV3Envelope:e.isV3Envelope}),"base-error")}#s(e){return new ye({code:e.code,description:e.description,status:e.status,validation:e.validation,isV3Envelope:e.isV3Envelope,requestInfo:{method:this._query.method,params:this._query.params,requestId:this._query.requestId}})}hasMore(){return this.isMore()}isMore(){if(!this.isSuccess)return!1;const e=this._data,t="next"in e?e.next:void 0;return L.isNumber(t)}getTotal(){if(!this.isSuccess)return 0;const e=this._data,t="total"in e?e.total:void 0;return pt(t)}getStatus(){return this._status}isIdempotentReplay(){return this._idempotency?.replayed??!1}getIdempotencyKey(){return this._idempotency?.key}getQuery(){return this._query}async fetchNext(e){const t=await this.getNext(e);return t===!1?null:t}async getNext(e){if(e.apiVersion===K.v3)throw new R({code:"JSSDK_CORE_METHOD_NOT_SUPPORT_IN_API_V3",description:"restApi:v3 not support method getNext",status:500});if(!this.isSuccess||!this.isMore())return!1;const t=this.#r();return e.call(t.method,t.params)}#r(){const e=this._data,t="next"in e?e.next:void 0;return{...this._query,params:{...this._query.params,start:pt(t)}}}setData(){throw new ReferenceError("AjaxResult does not allow data modification")}}class xr{static getDefault(){return{rateLimit:{burstLimit:50,drainRate:2,adaptiveEnabled:!0},operatingLimit:{windowMs:6e5,limitMs:48e4,heavyPercent:80},adaptiveConfig:{enabled:!0,thresholdPercent:80,coefficient:.01,maxDelay:7e3},maxRetries:3,retryDelay:1e3,retryOnNetworkError:!0}}static getEnterprise(){return{...this.getDefault(),rateLimit:{burstLimit:250,drainRate:5,adaptiveEnabled:!0}}}static getBatchProcessing(){return{...this.getDefault(),rateLimit:{burstLimit:30,drainRate:1,adaptiveEnabled:!0},operatingLimit:{windowMs:6e5,limitMs:48e4,heavyPercent:50},adaptiveConfig:{enabled:!0,thresholdPercent:50,coefficient:.015,maxDelay:1e4},maxRetries:5}}static getRealtime(){return{...this.getDefault(),adaptiveConfig:{enabled:!1,thresholdPercent:100,coefficient:.001,maxDelay:48e4},maxRetries:1}}static fromTariffPlan(e){return e.toLowerCase()==="enterprise"?this.getEnterprise():this.getDefault()}}class Wa{#e;#t;#s;#r;#i=[];#n;#o=5;#a=20;#h=.5;#d=5;#c=[];#l=[];_logger;constructor(e){this._logger=oe.createNullLogger(),this.#r=e,this.#n={...e},this.#e=e.burstLimit,this.#t=Date.now(),this.#s=1e3/e.drainRate}getTitle(){return"rateLimiter"}setLogger(e){this._logger=e}getLogger(){return this._logger}async canProceed(e,t,s){await this.#u(e);try{const n=Date.now(),i=(n-this.#t)*this.#r.drainRate/1e3;return this.#e=Math.min(this.#r.burstLimit,this.#e+i),this.#t=n,this.#e>=1}finally{this.#f()}}async waitIfNeeded(e,t,s){await this.#u(e);try{const n=Date.now(),i=(n-this.#t)*this.#r.drainRate/1e3;if(this.#e=Math.min(this.#r.burstLimit,this.#e+i),this.#t=n,this.#e>=1)return this.#e-=1,0;const o=1-this.#e;return Math.ceil(o*this.#s)}finally{this.#f()}}async handleExceeded(e){await this.#u(e);try{return this.#w(),this.#r.adaptiveEnabled&&this.#p()&&this.#_(e),this.#e=0,this.#s+1e3}finally{this.#f()}}async updateStats(e,t,s){await this.#u(e);try{this.#b(),this.#r.adaptiveEnabled&&this.#O(e),this.#r.adaptiveEnabled&&this.#g()&&this.#m(e)}finally{this.#f()}}async reset(){await this.#u("reset");try{this.#e=this.#r.burstLimit,this.#t=Date.now(),this.#c=[],this.#l=[],this.#r.drainRate=this.#n.drainRate,this.#r.burstLimit=this.#n.burstLimit,this.#s=1e3/this.#r.drainRate}finally{this.#f()}}getStats(){return{tokens:this.#e,burstLimit:this.#r.burstLimit,originalBurstLimit:this.#n.burstLimit,drainRate:this.#r.drainRate,originalDrainRate:this.#n.drainRate,refillIntervalMs:this.#s,lastRefill:this.#t,pendingRequests:this.#i.length,recentErrors:this.#c.length,recentSuccesses:this.#l.length}}async setConfig(e){await this.#u("setConfig");try{this.#r=e,this.#n={...e},this.#s=1e3/this.#r.drainRate,e.burstLimit>this.#e&&(this.#e=Math.min(e.burstLimit,this.#e)),this.#c=[],this.#l=[]}finally{this.#f()}}async#u(e){return new Promise(t=>{const s=this.#i.push(t);s>1&&this.#v(e,s),this.#i.length===1&&t()})}#f(){if(this.#i.shift(),this.#i.length>0){const e=this.#i[0];e()}}#p(){return this.#c.length>=this.#o}#g(){return this.#l.length>=this.#a&&this.#c.length<this.#o/2&&(this.#r.drainRate<this.#n.drainRate||this.#r.burstLimit<this.#n.burstLimit)}#_(e){const t=Math.max(this.#h,Number.parseFloat((this.#r.drainRate*.8).toFixed(2))),s=Math.max(this.#d,Number.parseFloat((this.#r.burstLimit*.8).toFixed(2)));this.#r.drainRate=t,this.#r.burstLimit=s,this.#s=1e3/t,this.#E(e,t,s),this.#c=[],this.#l=[]}#m(e){if(this.#r.drainRate===this.#n.drainRate&&this.#r.burstLimit===this.#n.burstLimit)return;const t=Math.min(this.#n.drainRate,Number.parseFloat((this.#r.drainRate*1.1).toFixed(2))),s=Math.min(this.#n.burstLimit,Number.parseFloat((this.#r.burstLimit*1.1).toFixed(2)));this.#r.drainRate=t,this.#r.burstLimit=s,this.#s=1e3/t,this.#T(e,t,s),this.#c=[],this.#l=[]}#w(){const e=Date.now();this.#c.push(e),this.#l=[],this.#y(e)}#y(e){const t=e-6e4;this.#c=this.#c.filter(s=>s>t)}#b(){const e=Date.now();this.#l.push(e),this.#S(),this.#y(e)}#S(){this.#l=this.#l.slice(-1*this.#a)}#E(e,t,s){const n=this.#n.drainRate,i=t<n,o=this.#n.burstLimit,a=s<o;this.getLogger().warning(`${this.getTitle()} is lowering limits due to frequent errors`,{requestId:e,drainRate:{current:t,original:n,condition:i,formatted:`(${t} < ${n}) ${i}`},burstLimit:{current:s,original:o,condition:a,formatted:`(${s} < ${o}) ${a}`}}).catch(()=>{})}#T(e,t,s){const n=this.#n.drainRate,i=t<n,o=this.#n.burstLimit,a=s<o;this.getLogger().warning(`${this.getTitle()} increases limits during stable operation`,{requestId:e,drainRate:{current:t,original:n,condition:i,formatted:`(${t} < ${n}) ${i}`},burstLimit:{current:s,original:o,condition:a,formatted:`(${s} < ${o}) ${a}`}}).catch(()=>{})}#v(e,t){this.getLogger().debug(`${this.getTitle()} request in queue`,{requestId:e,queueLength:t}).catch(()=>{})}#O(e){const t=this.#l.length,s=this.#a,n=t>=s,i=this.#c.length,o=this.#o,a=i<o/2,c=this.#r.drainRate,u=this.#n.drainRate,l=c<u,h=this.#r.burstLimit,d=this.#n.burstLimit,f=h<d;this.getLogger().debug(`${this.getTitle()} state`,{requestId:e,success:{count:t,threshold:s,condition:n,formatted:`(${t} >= ${s}) ${n}`},fail:{count:i,threshold:o/2,condition:a,formatted:`(${i} < ${o/2}) ${a}`},drainRate:{current:c,original:u,condition:l,formatted:`(${c} < ${u}) ${l}`},burstLimit:{current:h,original:d,condition:f,formatted:`(${h} < ${d}) ${f}`}}).catch(()=>{})}}class za{#e;#t=new Map;#s={heavyRequestCount:0};_logger;getTitle(){return"operatingLimiter"}constructor(e){this._logger=oe.createNullLogger(),this.#e=e}setLogger(e){this._logger=e}getLogger(){return this._logger}get limitMs(){return this.#e.limitMs}getMethodStat(e){const t=this.#t.get(e);if(t)return t}async canProceed(e,t,s){return await this.getTimeToFree(e,t,s)===0}async waitIfNeeded(e,t,s){return this.getTimeToFree(e,t,s)}async getTimeToFree(e,t,s,n){this.#r();const i=this.#t.get(t);if(!i)return 0;const o=Math.max(1e3,this.#e.limitMs-5e3);if(i.operating>=o){const a=Date.now();return i.operating_reset_at>a?i.operating_reset_at-a+1e3:5e3}return 0}async updateStats(e,t,s){if(!s)return;this.#r();const{operating:n,operating_reset_at:i}=s;if(n==null)return;this.#t.has(t)||this.#t.set(t,{operating:0,operating_reset_at:0,lastUpdated:Date.now()});const o=this.#t.get(t);o.operating=n*1e3,i!==void 0&&(o.operating_reset_at=i*1e3),o.lastUpdated=Date.now();const a=o.operating/this.#e.limitMs*100;a>this.#e.heavyPercent&&(this.#s.heavyRequestCount++,this.#i(e,t,a,o.operating))}#r(){const e=Date.now(),t=this.#e.windowMs+1e4;for(const[s,n]of this.#t.entries())e-n.lastUpdated>t&&this.#t.delete(s)}async reset(){this.#t.clear(),this.#s={heavyRequestCount:0}}getStats(){const e={};for(const[t,s]of this.#t.entries())e[t]=Number.parseFloat((s.operating/1e3).toFixed(2));return{...this.#s,operatingStats:e}}async setConfig(e){this.#e=e}#i(e,t,s,n){this.getLogger().debug(`${this.getTitle()} detected limit for method ${t}`,{requestId:e,method:t,operating:{percent:Number.parseFloat(s.toFixed(2)),current:Number.parseFloat((n/1e3).toFixed(0)),max:Number.parseFloat((this.#e.limitMs/1e3).toFixed(0))}}).catch(()=>{})}}class Ja{#e;#t;#s={adaptiveDelays:0,totalAdaptiveDelay:0};_logger;getTitle(){return"adaptiveDelayer"}constructor(e,t){this._logger=oe.createNullLogger(),this.#e=e,this.#t=t}setLogger(e){this._logger=e}getLogger(){return this._logger}async canProceed(e,t,s){return!0}async waitIfNeeded(e,t,s){if(!this.#e.enabled)return 0;const n=this.#r(e,t);return n>0&&(this.incrementAdaptiveDelays(),this.#s.totalAdaptiveDelay+=n),n}#r(e,t){const s=this.#t.getMethodStat(t);if(typeof s>"u")return 0;const n=s.operating/this.#t.limitMs*100;if(n>this.#e.thresholdPercent){let i=0;const o=Date.now();s.operating_reset_at>o?i+=(s.operating_reset_at-o)*this.#e.coefficient:i+=7e3;const a=Number.parseInt(Math.min(i,this.#e.maxDelay).toFixed(0));return this.#i(e,t,n,i,a),a}return 0}async updateStats(e,t,s){}async reset(){this.#s={adaptiveDelays:0,totalAdaptiveDelay:0}}getStats(){return{...this.#s,adaptiveDelayAvg:this.#s.adaptiveDelays>0?this.#s.totalAdaptiveDelay/this.#s.adaptiveDelays:0}}async setConfig(e){this.#e=e}incrementAdaptiveDelays(){this.#s.adaptiveDelays++}#i(e,t,s,n,i){this.getLogger().debug(`${this.getTitle()} state for method ${t}`,{requestId:e,method:t,percent:Number.parseFloat(s.toFixed(2)),delays:{calculated:n,actual:i}}).catch(()=>{})}}const Ka=["burstLimit","drainRate","adaptiveEnabled"],Ga=["windowMs","limitMs","heavyPercent"],Ya=["thresholdPercent","coefficient","maxDelay","enabled"];function Za(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}function xn(r){return{...r,...r.rateLimit?{rateLimit:{...r.rateLimit}}:{},...r.operatingLimit?{operatingLimit:{...r.operatingLimit}}:{},...r.adaptiveConfig?{adaptiveConfig:{...r.adaptiveConfig}}:{},...r.hardErrorCodes?{hardErrorCodes:[...r.hardErrorCodes]}:{},...r.softErrorCodes?{softErrorCodes:[...r.softErrorCodes]}:{}}}function cr(r,e,t){if(r===void 0)return;const s=r,n=s===null?[...t]:t.filter(i=>s[i]===void 0);if(n.length!==0)throw new R({code:"JSSDK_LIMITER_INVALID_CONFIG_BLOCK",description:`setRestrictionManagerParams: \`${e}\` is replaced whole, not merged, so it must carry every field. Missing: ${n.join(", ")}. Spread the current block if you mean to change one value.`,status:500})}class lr{#e;#t;#s;#r;#i={retries:0,consecutiveErrors:0,limitHits:0};#n=new Map;_logger;constructor(e){this._logger=oe.createNullLogger();const t=Za(e);cr(t.rateLimit,"rateLimit",Ka),cr(t.operatingLimit,"operatingLimit",Ga),cr(t.adaptiveConfig,"adaptiveConfig",Ya),this.#r=xn({...xr.getDefault(),...t}),this.#e=new Wa(this.#r.rateLimit),this.#t=new za(this.#r.operatingLimit),this.#s=new Ja(this.#r.adaptiveConfig,this.#t)}setLogger(e){this._logger=e,this.#e.setLogger(this._logger),this.#t.setLogger(this._logger),this.#s.setLogger(this._logger)}getLogger(){return this._logger}async applyOperatingLimits(e,t,s){const n=await this.#t.waitIfNeeded(e,t,s);if(n>0)this.incrementStats("limitHits"),this.#g(this.#t.getTitle(),e,t,n),await this.#p(n);else{const i=await this.#s.waitIfNeeded(e,t,s);i>0&&(this.incrementStats("limitHits"),this.#g(this.#s.getTitle(),e,t,i),await this.#p(i))}}async checkRateLimit(e,t){let s,n=1;do s=await this.#e.waitIfNeeded(e,t),s>0&&(this.incrementStats("limitHits"),this.#_(this.#e.getTitle(),e,t,s,n),await this.#p(s),n++);while(s>0)}async updateStats(e,t,s){await this.#t.updateStats(e,t,s),await this.#s.updateStats(e,t,s),await this.#e.updateStats(e,t,s)}async handleError(e,t,s,n,i){if(this.#o(n)){const o=await this.#a(e)*Math.pow(1.5,i);return this.#m(this.#e.getTitle(),e,"QUERY_LIMIT_EXCEEDED",n.message,t,o),o}if(this.#h(n)){const o=Math.max(1e4,await this.#d(e,t,s,n));return this.#m(this.#t.getTitle(),e,"OPERATION_TIME_LIMIT",n.message,t,o),o}if(this.#c(n))return this.#y(e,n?.code?`${n.code}`:"?",n?.message??"",t,Number(n?.status??0)),0;if(!this.#l(n)){const o=await this.#f(e),a=Math.max(3e4,o),c=Math.min(a,o*Math.pow(2,i)),u=c*.1*(Math.random()*2-1),l=Math.max(100,c+u);return this.#w(e,n?.code?`${n.code}`:"?",n.message,t,l),l}return 0}#o(e){return e.status===503||e.code==="QUERY_LIMIT_EXCEEDED"}async#a(e){return this.#e.handleExceeded(e)}#h(e){return e.status===429||e.code==="OPERATION_TIME_LIMIT"}async#d(e,t,s,n){return this.#t.getTimeToFree(e,t,s,n)}#c(e){const t=Number(e?.status??0);return Number.isNaN(t)?!1:t>=400&&t<500&&t!==408&&t!==429}#l(e){const t={code:e?.code??"-1",description:e?.message??""};return[...this.exceptionCodeForHard,...this.exceptionCodeForSoft].includes(t.code)||(t.description??"").includes("Could not find value for parameter")}static BUILT_IN_HARD_ERROR_CODES=["ERR_BAD_REQUEST","JSSDK_UNKNOWN_ERROR","100","INTERNAL_SERVER_ERROR","ERROR_UNEXPECTED_ANSWER","PORTAL_DELETED","ERROR_BATCH_METHOD_NOT_ALLOWED","ERROR_BATCH_LENGTH_EXCEEDED","NO_AUTH_FOUND","INVALID_REQUEST","OVERLOAD_LIMIT","expired_token","invalid_token","ACCESS_DENIED","INVALID_CREDENTIALS","user_access_error","insufficient_scope","BITRIX_REST_V3_EXCEPTION_INSUFFICIENTSCOPEEXCEPTION","JSSDK_HTTP_REDIRECT_BLOCKED","ERROR_MANIFEST_IS_NOT_AVAILABLE","allowed_only_intranet_user","NOT_FOUND","INVALID_ARG_VALUE"];static BUILT_IN_SOFT_ERROR_CODES=["ERROR_ENTITY_NOT_FOUND","BITRIX_REST_V3_EXCEPTION_ACCESSDENIEDEXCEPTION","BITRIX_REST_V3_EXCEPTION_INVALIDJSONEXCEPTION","BITRIX_REST_V3_EXCEPTION_INVALIDFILTEREXCEPTION","BITRIX_REST_V3_EXCEPTION_INVALIDSELECTEXCEPTION","BITRIX_REST_V3_EXCEPTION_ENTITYNOTFOUNDEXCEPTION","BITRIX_REST_V3_EXCEPTION_METHODNOTFOUNDEXCEPTION","BITRIX_REST_V3_EXCEPTION_UNKNOWNDTOPROPERTYEXCEPTION","BITRIX_REST_V3_EXCEPTION_VALIDATION_REQUESTVALIDATIONEXCEPTION","BITRIX_REST_V3_EXCEPTION_VALIDATION_DTOVALIDATIONEXCEPTION"];get exceptionCodeForHard(){const e=[...lr.BUILT_IN_HARD_ERROR_CODES];return this.#r.retryOnNetworkError===!1&&e.push("NETWORK_ERROR","REQUEST_TIMEOUT"),this.#r.hardErrorCodes&&this.#r.hardErrorCodes.length>0&&e.push(...this.#r.hardErrorCodes),e}get exceptionCodeForSoft(){const e=[...lr.BUILT_IN_SOFT_ERROR_CODES];return this.#r.softErrorCodes&&this.#r.softErrorCodes.length>0&&e.push(...this.#r.softErrorCodes),e}static#u=[401,408,429];isSoftError(e){const t=e?.code,s=typeof t=="string"?t:"";if(this.exceptionCodeForHard.includes(s))return!1;if(this.exceptionCodeForSoft.includes(s))return!0;if(e?.isV3Envelope!==!0)return!1;const n=Number(e?.status??0);return Number.isInteger(n)&&n>=400&&n<500&&!lr.#u.includes(n)}async#f(e){return this.#r.retryDelay??xr.getDefault().retryDelay}incrementError(e){const t=this.#n.get(e)||0;this.#n.set(e,t+1),this.incrementStats("consecutiveErrors")}resetErrors(e){this.#n.delete(e),this.#i.consecutiveErrors=0}incrementStats(e){this.#i[e]++}getStats(){return{...this.#i,...this.#e.getStats(),...this.#s.getStats(),...this.#t.getStats(),errorCounts:Object.fromEntries(this.#n)}}async reset(){await this.#e.reset(),await this.#t.reset(),await this.#s.reset(),this.#n.clear(),this.#i={retries:0,consecutiveErrors:0,limitHits:0}}async setConfig(e){const t=Za(e);cr(t.rateLimit,"rateLimit",Ka),cr(t.operatingLimit,"operatingLimit",Ga),cr(t.adaptiveConfig,"adaptiveConfig",Ya),this.#r=xn({...this.#r,...t}),t.rateLimit!==void 0&&await this.#e.setConfig({...t.rateLimit}),t.operatingLimit!==void 0&&await this.#t.setConfig({...t.operatingLimit}),t.adaptiveConfig!==void 0&&await this.#s.setConfig({...t.adaptiveConfig})}getParams(){return xn(this.#r)}async#p(e){return new Promise(t=>setTimeout(t,e))}async waiteDelay(e){return this.#p(e)}#g(e,t,s,n){this.getLogger().notice(`${e} blocked method ${s}`,{requestId:t,method:s,wait:n,limiter:e}).catch(()=>{})}#_(e,t,s,n,i){this.getLogger().notice(`${e} blocked method ${s} | ${i} times`,{requestId:t,method:s,times:i,wait:n,limiter:e}).catch(()=>{})}#m(e,t,s,n,i,o){this.getLogger().error(`${e} recognized the ${s} error for the ${i} method`,{requestId:t,method:i,wait:o,limiter:e,error:{code:s,message:n}}).catch(()=>{})}#w(e,t,s,n,i){this.getLogger().error(`recognized the ${t} error for the ${n} method`,{requestId:e,method:n,wait:i,error:{code:t,message:s}}).catch(()=>{})}#y(e,t,s,n,i){this.getLogger().error(`client error ${i} (${t}) for the ${n} method is not retryable`,{requestId:e,method:n,status:i,error:{code:t,message:s}}).catch(()=>{})}}const ur=class cu{static create(){return new cu}getAllApiVersions(){return[K.v3,K.v2]}isSupport(e,t){return!0}automaticallyObtainApiVersion(e){return K.v2}automaticallyObtainApiVersionForBatch(e){return K.v2}}.create(),Hd=["log","debug","info","notice","warning","error","critical","alert","emergency"];function Wd(r,e){if(r===null||typeof r!="object"){console.warn(`[b24jssdk] ${e}: the value passed to setLogger() is not an object. Expected an implementation of LoggerInterface.`);return}const t=Hd.filter(s=>typeof r[s]!="function");t.length>0&&console.warn(`[b24jssdk] ${e}: the logger passed to setLogger() is missing ${t.join(", ")}. LoggerInterface declares every level as Promise<void>; the SDK calls them fire-and-forget, so a missing or non-promise method raises a TypeError at the callsite.`)}class ct{_b24;_logger;constructor(e,t){this._b24=e,this._logger=t}_warnMisplacedOptions(e,t,s){if(!e)return;const n=t.filter(i=>Object.hasOwn(e,i));n.length!==0&&this._logger.warning(`[b24jssdk] ${n.join(", ")} passed at the top level ${n.length===1?"is":"are"} ignored \u2014 ${n.length===1?"it belongs":"they belong"} in \`${s}\`. Write \`${s}: { ${n.join(", ")} }\`.`).catch(()=>{})}}class zd extends ct{async make(e){const t=e.params||{};return this._b24.getHttpClient(K.v2).call(e.method,t,e.requestId)}}const Xa=1e4;function Fn(r,e){if(e===void 0)return Xa;if(!Number.isInteger(e)||e<1)throw new R({code:"JSSDK_ACTION_INVALID_MAX_PAGES",description:`${r}: \`maxPages\` must be a positive integer \u2014 it is the number of pages the walk may read before it gives up. Omit it to use the default of ${Xa}.`,status:400});return e}function Bn(r,e,t){return new R({code:"JSSDK_ACTION_MAX_PAGES_EXCEEDED",description:`${r}: stopped after ${t} pages of \`${e}\` without reaching the end of the data. Either the read is genuinely larger than the ceiling \u2014 raise \`maxPages\` \u2014 or the walk is not making progress, which happens when the page condition is not applied and the cursor repeats values whose order the SDK cannot judge (a cursor that demonstrably moves backwards is reported earlier, as JSSDK_ACTION_CURSOR_WENT_BACKWARDS). The eager helpers (callList / callTail) return the pages they did read, with this error attached \u2014 so check \`isSuccess\` rather than assuming a returned list is whole. A streaming helper (fetchList / fetchTail) has already yielded every page it read, and throws this instead.`,status:500})}function Jd(r,e){return new R({code:"JSSDK_ACTION_ABORTED",description:`${r}: the walk over \`${e}\` was aborted through its \`signal\`. The eager helpers (callList / callTail) return the pages they did read, with this error attached; a streaming helper (fetchList / fetchTail) has already yielded every page it read, and throws this instead.`,status:400})}function Fr(r,e,t){if(r?.aborted===!0)throw Jd(e,t)}const Kd=new Set(["JSSDK_ACTION_MAX_PAGES_EXCEEDED","JSSDK_ACTION_ABORTED"]);function $n(r){return r instanceof R&&Kd.has(r.code)}function jn(r,e){return new R({code:"JSSDK_ACTION_CURSOR_STALLED",description:`${r}: the cursor did not move \u2014 the server answered with the same page again, so this walk can never finish. ${e} Stopping instead of looping for ever. Note that a streaming helper (fetchList / fetchTail) has already yielded every page it read, including the repeated one, so a consumer that persisted them has to undo that.`,status:500})}const hr="Check `idKey` \u2014 the id field as the response spells it \u2014 against `cursorIdKey`, the field name the request sorts and filters by. When the two differ, the page condition is written with a name the server does not match, and it is dropped: on `restApi:v2` `tasks.task.list` the response carries a lowercase `id` while the filter accepts an uppercase `ID`, so that walk needs `idKey: 'id', cursorIdKey: 'ID'`. The v3 method spells it lowercase both ways and needs no override.",Qa="Check `cursorField`: it must name the field the server actually pages by, it must be readable in the response (include it in `select`), and its values must advance from page to page \u2014 a block of rows sharing one value is enough to stall the walk, so prefer a unique field. With `order: 'DESC'`, check `initialValue` too.";function Un(r,e){return new R({code:"JSSDK_ACTION_CURSOR_WENT_BACKWARDS",description:`${r}: the cursor moved backwards \u2014 the server answered with a page it had already passed, so this walk can never finish. ${e} A server that alternates between two pages produces exactly this, and the "did not move" check cannot see it: the value differs from the one just sent, it is simply one the walk had already used. Stopping instead of looping for ever. Note that a streaming helper (fetchList / fetchTail) has already yielded every page it read, so a consumer that persisted them has to undo that.`,status:500})}const ec=/^\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2}(?:\.\d+)?(Z|[+-]\d{2}:?\d{2})$/,tc=/^\d+$/;function rc(r){return Vn.test(r)?"DESC":"ASC"}const Vn=/desc/i;function Gd(r,e){if(typeof r=="number"&&typeof e=="number")return Number.isFinite(r)&&Number.isFinite(e);if(typeof r=="string"&&typeof e=="string"){if(r.length!==e.length)return!1;if(tc.test(r)&&tc.test(e))return!0;const t=ec.exec(r),s=ec.exec(e);return t!==null&&s!==null&&t[1]===s[1]&&t[2]===s[2]}return!1}function qn(r,e,t){return r===e?!1:Gd(r,e)?t==="DESC"?r<e:r>e:!0}const Yd=["filter","order","start"],Zd={filter:"the `>id` cursor condition that advances the walk",order:"the ordering by the cursor field, which cursor paging depends on",start:"the `start: -1` that turns off the portal's own row counting"},Xd={filter:"its conditions are dropped and the request returns rows they should have excluded",order:"it is ignored \u2014 cursor paging must order by the cursor field",start:"it is ignored \u2014 the walker pages by cursor, not by offset"},Qd={filter:"The walk will not advance and will fail as stalled.",order:"Ordering is then unstable across pages, which cursor paging cannot survive.",start:"The walk still advances, but the portal resumes counting rows on every page and an offset skips rows."},sc={filter:"Move the conditions into `filter`, which is merged with the page condition rather than replaced by it",order:"Remove it: cursor paging must order by `cursorIdKey`, and a lowercase `order` is stripped just the same",start:"Remove it: the walker pages by cursor and forces `start: -1`"};function Hn(r,e){return Object.prototype.hasOwnProperty.call(r,e)&&r[e]!==void 0}function nc(r,e,t){oe.forcedLog(r,"warning",`${e}: ${t}`,{code:"JSSDK_ACTION_V2_SHADOWED_PARAM"}).catch(()=>{})}function ic(r,e,t){const s=[],n=Object.keys(e);for(const o of n){if(!Hn(e,o))continue;const a=o.toLowerCase();if(o===a||!Yd.includes(a)||!Hn(e,a))continue;const c=n.indexOf(o)>n.indexOf(a)?`\`${o}\` is sent after the \`${a}\` this walker pages with, and the portal keeps only the later of two top-level keys that differ by case \u2014 so \`${o}\` overwrites ${Zd[a]}. ${Qd[a]} ${sc[a]}, and remove \`${o}\`; writing \`${a}\` while leaving \`${o}\` in place is what produces this.`:`\`${o}\` is not the key this walker pages with. It writes the lowercase \`${a}\`, the portal keeps only the later of two top-level keys that differ by case, and here the injected one is later \u2014 so \`${o}\` never takes effect and ${Xd[a]}. ${sc[a]}.`;s.push({key:o,message:c}),nc(t,r,c)}const i=n.find(o=>o.toLowerCase()==="sort"&&Hn(e,o));if(i!==void 0){const o=`\`${i}\` makes this request fail. The walker replaces \`order\` with an object to page by the cursor, the portal folds that onto \`ORDER\`, and a method that takes \`SORT\` validates \`ORDER\` as a string \u2014 so the call throws ERROR_ARGUMENT ("Order must be a string"). Measured on \`user.get\`. Cursor paging fixes the ordering; drop \`SORT\` and narrow with lowercase \`filter\` instead.`;s.push({key:i,message:o}),nc(t,r,o)}return s}class ef extends ct{async make(e){const t=new Oe,s=e?.idKey??"ID",n=e?.cursorIdKey??s,i=e?.customKeyForResult??null,o=e?.params??{};"order"in o&&o.order&&this._logger.warning("callList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{});const a=`>${n}`,{order:c,...u}=o,l={...u,order:{[n]:"ASC"},filter:{...o.filter||{},[a]:0},start:-1};ic("callList.make",l,this._logger);let h=[],d=0;const f=Fn("callList.make",e?.maxPages);try{for(;;){Fr(e?.signal,"callList.make",e.method);const p=await this._b24.actions.v2.call.make({method:e.method,params:l,requestId:e.requestId});if(!p.isSuccess){this._logger.error("callFastListMethod",{method:e.method,requestId:e.requestId,messages:p.getErrorMessages()}).catch(()=>{});for(const[m,T]of p.errors)t.addError(T,m);break}const g=p.getData();if(!g)break;const y=i===null?g.result:g.result[i];if(y.length===0)break;h=[...h,...y],d+=1,e.progress?.({pages:d,rows:h.length});const w=y.length<50,_=y[y.length-1],S=_?Number.parseInt(_[s],10):Number.NaN;if(Number.isFinite(S)){if(S===l.filter[a])throw jn("callList.make",hr);if(!qn(S,l.filter[a],"ASC"))throw Un("callList.make",hr);if(w)break;if(l.filter[a]=S,d>=f)throw Bn("callList.make",e.method,f)}else{w||this._logger.warning(`callList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${s}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`).catch(()=>{});break}}}catch(p){if($n(p))t.addError(p);else throw p}return t.setData(h)}}class tf extends ct{async*make(e){const t=e?.idKey??"ID",s=e?.cursorIdKey??t,n=e?.customKeyForResult??null,i=e?.params??{};"order"in i&&i.order&&this._logger.warning("fetchList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{});const o=`>${s}`,{order:a,...c}=i,u={...c,order:{[s]:"ASC"},filter:{...i.filter||{},[o]:0},start:-1};ic("fetchList.make",u,this._logger);let l=0;const h=Fn("fetchList.make",e?.maxPages);for(;;){Fr(e?.signal,"fetchList.make",e.method);const d=await this._b24.actions.v2.call.make({method:e.method,params:u,requestId:e.requestId});if(!d.isSuccess)throw this._logger.error("fetchList.make",{method:e.method,requestId:e.requestId,messages:d.getErrorMessages()}).catch(()=>{}),new R({code:"JSSDK_CORE_B24_FETCH_LIST_METHOD_API_V2",description:`API Error: ${d.getErrorMessages().join("; ")}`,status:500});const f=d.getData();if(!f)break;const p=n===null?f.result:f.result[n];if(p.length===0)break;l+=1,yield p,Fr(e?.signal,"fetchList.make",e.method);const g=p.length<50,y=p[p.length-1],w=y?Number.parseInt(y[t],10):Number.NaN;if(Number.isFinite(w)){if(w===u.filter[o])throw jn("fetchList.make",hr);if(!qn(w,u.filter[o],"ASC"))throw Un("fetchList.make",hr);if(g)break;if(u.filter[o]=w,l>=h)throw Bn("fetchList.make",e.method,h)}else{g||this._logger.warning(`fetchList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${t}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`).catch(()=>{});break}}}}class Es extends ct{_addBatchErrorsIfAny(e,t){if(!e.isSuccess)for(const[s,n]of e.errors)t.addError(n,s)}_processBatchResponse(e,t,s){const n=Array.isArray(t);return s.returnAjaxResult?this._createBatchResultWithAjax(e,n):this._createBatchResultSimple(e,n)}_createBatchResultWithAjax(e,t){return t?this._createBatchArrayResult(e):this._createBatchObjectResult(e)}_createBatchArrayResult(e){const t=new Oe;this._addBatchErrorsIfAny(e,t);const s=[];for(const[n,i]of e.getData().result)s.push(i);return t.setData(s)}_createBatchObjectResult(e){const t=new Oe;this._addBatchErrorsIfAny(e,t);const s={};for(const[n,i]of e.getData().result)s[n]=i;return t.setData(s)}_createBatchResultSimple(e,t){const s=new Oe;return this._addBatchErrorsIfAny(e,s),s.setData(this._extractBatchSimpleData(e,t))}_extractBatchSimpleData(e,t){if(t){const s=[];for(const[n,i]of e.getData().result)i.isSuccess&&s.push(i.getData().result);return s}else{const s={};for(const[n,i]of e.getData().result)i.isSuccess&&(s[n]=i.getData().result);return s}}chunkArray(e,t=50){const s=[];for(let n=0;n<e.length;n+=t){const i=e.slice(n,n+t);s.push(i)}return s}}class rf extends Es{async make(e){this._warnMisplacedOptions(e,["isHaltOnError","returnAjaxResult","requestId"],"options");const t={...e.options,apiVersion:K.v2},s=await this._b24.getHttpClient(K.v2).batch(e.calls,t);return this._processBatchResponse(s,e.calls,t)}}class sf extends Es{async make(e){this._warnMisplacedOptions(e,["isHaltOnError","requestId"],"options");const t=50,s={...e.options,returnAjaxResult:!1,apiVersion:K.v2},n=new Oe,i=[],o=this.chunkArray(e.calls,t);for(const a of o){const c=await this._b24.getHttpClient(K.v2).batch(a,s);c.isSuccess||this._addBatchErrorsIfAny(c,n);for(const[u,l]of c.getData().result)l.isSuccess&&i.push(l.getData().result)}return n.setData(i)}}const Wn=Symbol("call_V2"),zn=Symbol("callList_V2"),Jn=Symbol("fetchList_V2"),Kn=Symbol("batch_V2"),Gn=Symbol("batchByChunk_V2");class nf{_b24;_logger;_mapActions;constructor(e){this._b24=e,this._logger=oe.createNullLogger(),this._mapActions=new Map}setLogger(e){this._logger=e}getLogger(){return this._logger}get call(){return this._mapActions.has(Wn)||this._mapActions.set(Wn,new zd(this._b24,this._logger)),this._mapActions.get(Wn)}get callList(){return this._mapActions.has(zn)||this._mapActions.set(zn,new ef(this._b24,this._logger)),this._mapActions.get(zn)}get fetchList(){return this._mapActions.has(Jn)||this._mapActions.set(Jn,new tf(this._b24,this._logger)),this._mapActions.get(Jn)}get batch(){return this._mapActions.has(Kn)||this._mapActions.set(Kn,new rf(this._b24,this._logger)),this._mapActions.get(Kn)}get batchByChunk(){return this._mapActions.has(Gn)||this._mapActions.set(Gn,new sf(this._b24,this._logger)),this._mapActions.get(Gn)}}class of extends ct{async make(e){const t=e.params||{};return this._b24.getHttpClient(K.v3).call(e.method,t,e.requestId,e.idempotencyKey===void 0?void 0:{idempotencyKey:e.idempotencyKey})}}function oc(r,e){if(!(r===void 0||Array.isArray(r)))throw new R({code:"JSSDK_ACTION_V3_LIST_FILTER_NOT_ARRAY",description:ac(r)?`${e}: \`filter\` must be an array here. A logic group is a valid v3 filter \u2014 the portal accepts one on its own \u2014 but this action appends its page condition to \`filter\` on every request, and only an array can be extended. Wrap it: filter: [FilterV3.or(...)].`:`${e}: \`filter\` must be the restApi:v3 array form, e.g. [['id', '>', 100]] or FilterV3.build(...). The restApi:v2 object dialect ({ '>id': 100 }) is not accepted by the portal: a filter element carrying none of type/logic/conditions/negative is read positionally, so a map keyed by an operator prefix matches no condition it knows.`,status:500})}const af=["type","logic","conditions","negative"];function ac(r){return typeof r!="object"||r===null||Array.isArray(r)?!1:af.some(e=>e in r)}const cf=32;function cc(r,e,t=cf){return Yn(r,e,t,new WeakMap)}function Yn(r,e,t,s){if(t<=0)return!1;if(typeof r=="object"&&r!==null){const n=s.get(r);if(n!==void 0&&n>=t)return!1;s.set(r,t)}return Array.isArray(r)?typeof r[0]=="string"?r[0]===e:r.some(n=>Yn(n,e,t-1,s)):typeof r=="object"&&r!==null&&"conditions"in r?Yn(r.conditions,e,t-1,s):!1}function lc(r,e){if(!(r===void 0||Array.isArray(r)||ac(r)))throw new R({code:"JSSDK_ACTION_V3_TAIL_FILTER_INVALID",description:`${e}: \`filter\` must be the restApi:v3 array form, e.g. [['id', '>', 100]] or FilterV3.build(...), or a logic group from FilterV3.or() / and() / not(). The restApi:v2 object dialect ({ '>id': 100 }) is not accepted by the portal: a filter element carrying none of type/logic/conditions/negative is read positionally, so a map keyed by an operator prefix matches no condition it knows. Rejected here rather than one round trip later, where the server reports it in wording that never mentions the dialect.`,status:500})}class Br extends Error{errors;messages;constructor(e,t){super(t.join("; ")),this.name="KeysetPaginationError",this.errors=e,this.messages=t}}async function*Ts(r,e,t){let s=t.initialCursor,n=0,i=0;const o=Fn(t.actionLabel,t.maxPages);for(;;){Fr(t.signal,t.actionLabel,t.method);const a=await r.actions.v3.call.make({method:t.method,params:t.buildParams(s),requestId:t.requestId});if(!a.isSuccess)throw e.error(t.errorLabel,{method:t.method,requestId:t.requestId,messages:a.getErrorMessages()}).catch(()=>{}),new Br(a.errors,a.getErrorMessages());const c=a.getData();if(!c)break;const u=c.result[t.customKeyForResult];if(!Array.isArray(u)||u.length===0)break;i+=1,yield u,Fr(t.signal,t.actionLabel,t.method),n=Math.max(n,u.length);const l=u.length<n,h=u[u.length-1],d=h?t.readNextCursor(h):null;if(typeof d!="number"&&typeof d!="string"){l||e.warning(t.noCursorWarning).catch(()=>{});break}if(d===s)throw jn(t.actionLabel,t.stalledCursorHint);if(!qn(d,s,t.cursorDirection))throw Un(t.actionLabel,t.stalledCursorHint);if(l)break;if(i>=o)throw Bn(t.actionLabel,t.method,o);s=d}}class lf extends ct{async make(e){const t=e?.limit??50,s=new Oe,n=e?.idKey??"id",i=e?.cursorIdKey??n,o=e?.customKeyForResult??null,a=e?.params??{};"order"in a&&a.order&&this._logger.warning("callList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{}),oc(a.filter,"callList.make");const{order:c,...u}=a,l={...u,order:{[i]:"ASC"},filter:[...a.filter??[]],pagination:{page:0,limit:t}},h=[];let d=0;try{for await(const f of Ts(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:o,initialCursor:0,buildParams:p=>({...l,filter:[...l.filter,[i,">",p]]}),readNextCursor:p=>{const g=Number.parseInt(p[n],10);return Number.isFinite(g)?g:null},noCursorWarning:`callList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${n}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`,errorLabel:"callFastListMethod",actionLabel:"callList.make",stalledCursorHint:hr,cursorDirection:"ASC",maxPages:e?.maxPages,signal:e?.signal})){for(const p of f)h.push(p);d+=1,e.progress?.({pages:d,rows:h.length})}}catch(f){if(f instanceof Br)for(const[p,g]of f.errors)s.addError(g,p);else if($n(f))s.addError(f);else throw f}return s.setData(h)}}class uf extends ct{async*make(e){const t=e?.limit??50,s=e?.idKey??"id",n=e?.cursorIdKey??s,i=e?.customKeyForResult??null,o=e?.params??{};"order"in o&&o.order&&this._logger.warning("fetchList.make: user-provided `order` parameter is ignored because cursor-based pagination requires ordering by cursorIdKey. Use `filter` to narrow results instead.").catch(()=>{}),oc(o.filter,"fetchList.make");const{order:a,...c}=o,u={...c,order:{[n]:"ASC"},filter:[...o.filter??[]],pagination:{page:0,limit:t}};try{yield*Ts(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:i,initialCursor:0,buildParams:l=>({...u,filter:[...u.filter,[n,">",l]]}),readNextCursor:l=>{const h=Number.parseInt(l[s],10);return Number.isFinite(h)?h:null},noCursorWarning:`fetchList.make: pagination stops here \u2014 no numeric id could be read from the returned items via idKey "${s}". Make sure idKey matches the id field in the response; if the sortable field name differs from it, also set cursorIdKey (e.g. idKey: 'id', cursorIdKey: 'ID').`,errorLabel:"fetchList.make",actionLabel:"fetchList.make",stalledCursorHint:hr,cursorDirection:"ASC",maxPages:e?.maxPages,signal:e?.signal})}catch(l){throw l instanceof Br?new R({code:"JSSDK_CORE_B24_FETCH_LIST_METHOD_API_V3",description:`API Error: ${l.messages.join("; ")}`,status:500}):l}}}class hf extends ct{async make(e){const t=e?.limit??50,s=new Oe,n=e?.cursorField??"id",i=e?.order??"ASC",o=e?.customKeyForResult??"items",a=e?.params??{};if(lc(a.filter,"callTail.make"),Vn.test(i)&&e?.initialValue===void 0)throw new R({code:"JSSDK_CORE_B24_CALL_TAIL_DESC_REQUIRES_INITIAL_VALUE",description:'callTail.make: order "DESC" requires an explicit `initialValue` (the server pages by `field < value`, so the default 0 returns nothing). Pass `initialValue` set to the type maximum / newest value.',status:500});cc(a.filter,n)&&this._logger.warning(`callTail.make: the cursor field "${n}" must not appear in \`filter\` \u2014 the server orders and pages by it and will reject a filter on the same field (INVALIDFILTEREXCEPTION). Remove it from \`filter\`.`).catch(()=>{});let c=a.select;Array.isArray(c)?c.includes(n)||(c=[...c,n]):n!=="id"&&this._logger.warning(`callTail.make: no \`select\` provided with a non-default cursorField "${n}" \u2014 make sure it is in the server's default field set, otherwise pass \`select\` including "${n}" so the cursor can advance.`).catch(()=>{});const{select:u,...l}=a,h=[];let d=0;try{for await(const f of Ts(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:o,initialCursor:e?.initialValue??0,buildParams:p=>({...l,...c?{select:c}:{},cursor:{field:n,value:p,order:i,limit:t}}),readNextCursor:p=>p[n]??null,noCursorWarning:`callTail.make: pagination stops here \u2014 no value could be read from the returned items via cursorField "${n}". Make sure cursorField matches a field present in the response (and in \`select\`).`,errorLabel:"callTailMethod",actionLabel:"callTail.make",stalledCursorHint:Qa,cursorDirection:rc(i),maxPages:e?.maxPages,signal:e?.signal})){for(const p of f)h.push(p);d+=1,e.progress?.({pages:d,rows:h.length})}}catch(f){if(f instanceof Br)for(const[p,g]of f.errors)s.addError(g,p);else if($n(f))s.addError(f);else throw f}return s.setData(h)}}class df extends ct{async*make(e){const t=e?.limit??50,s=e?.cursorField??"id",n=e?.order??"ASC",i=e?.customKeyForResult??"items",o=e?.params??{};if(lc(o.filter,"fetchTail.make"),Vn.test(n)&&e?.initialValue===void 0)throw new R({code:"JSSDK_CORE_B24_FETCH_TAIL_DESC_REQUIRES_INITIAL_VALUE",description:'fetchTail.make: order "DESC" requires an explicit `initialValue` (the server pages by `field < value`, so the default 0 returns nothing). Pass `initialValue` set to the type maximum / newest value.',status:500});cc(o.filter,s)&&this._logger.warning(`fetchTail.make: the cursor field "${s}" must not appear in \`filter\` \u2014 the server orders and pages by it and will reject a filter on the same field (INVALIDFILTEREXCEPTION). Remove it from \`filter\`.`).catch(()=>{});let a=o.select;Array.isArray(a)?a.includes(s)||(a=[...a,s]):s!=="id"&&this._logger.warning(`fetchTail.make: no \`select\` provided with a non-default cursorField "${s}" \u2014 make sure it is in the server's default field set, otherwise pass \`select\` including "${s}" so the cursor can advance.`).catch(()=>{});const{select:c,...u}=o;try{yield*Ts(this._b24,this._logger,{method:e.method,requestId:e.requestId,customKeyForResult:i,initialCursor:e?.initialValue??0,buildParams:l=>({...u,...a?{select:a}:{},cursor:{field:s,value:l,order:n,limit:t}}),readNextCursor:l=>l[s]??null,noCursorWarning:`fetchTail.make: pagination stops here \u2014 no value could be read from the returned items via cursorField "${s}". Make sure cursorField matches a field present in the response (and in \`select\`).`,errorLabel:"fetchTailMethod",actionLabel:"fetchTail.make",stalledCursorHint:Qa,cursorDirection:rc(n),maxPages:e?.maxPages,signal:e?.signal})}catch(l){throw l instanceof Br?new R({code:"JSSDK_CORE_B24_FETCH_TAIL_METHOD_API_V3",description:`API Error: ${l.messages.join("; ")}`,status:500}):l}}}const uc=["sum","avg","min","max","count","countDistinct"];class ff extends ct{async make(e){const t=new Oe,s=e?.select??{},n=Object.keys(s);let i=0;for(const l of n){if(!uc.includes(l))throw new R({code:"JSSDK_AGGREGATE_V3_INVALID_FUNCTION",description:`AggregateV3: "${l}" is not an aggregate function \u2014 use one of ${uc.join(" ")}.`,status:400});const h=s[l];if(!Array.isArray(h)&&(typeof h!="object"||h===null))throw new R({code:"JSSDK_AGGREGATE_V3_INVALID_SELECT",description:`AggregateV3: select.${l} must be a string[] (default alias) or a { field: alias } map.`,status:400});i+=Array.isArray(h)?h.length:Object.keys(h).length}if(i===0)throw new R({code:"JSSDK_AGGREGATE_V3_EMPTY_SELECT",description:"AggregateV3: `select` names no field to aggregate, e.g. { count: ['id'] }. The portal answers such a request with a 500 that says nothing, so it is refused here.",status:400});const o={select:s};e?.params?.filter&&(o.filter=e.params.filter);const a=await this._b24.actions.v3.call.make({method:e.method,params:o,requestId:e.requestId});if(!a.isSuccess){this._logger.error("aggregateMethod",{method:e.method,requestId:e.requestId,messages:a.getErrorMessages()}).catch(()=>{});for(const[l,h]of a.errors)t.addError(h,l);return t}const c=a.getData()?.result;let u;return c&&typeof c=="object"&&"result"in c?u=c.result??{}:c&&typeof c=="object"?(this._logger.warning(`aggregate.make: response has no nested 'result.result' envelope, which is what a portal was measured to send and what the v3 reference \xA77 specifies; falling back to the top-level 'result'. method=${e.method}`).catch(()=>{}),u=c):(this._logger.warning(`aggregate.make: response carried no usable 'result' object \u2014 returning empty buckets, which is not the same as an aggregate over no rows (that answers null per function). method=${e.method}`).catch(()=>{}),u={}),t.setData(u)}}class pf extends Es{async make(e){this._warnMisplacedOptions(e,["isHaltOnError","returnAjaxResult","requestId"],"options");const t={...e.options,apiVersion:K.v3},s=await this._b24.getHttpClient(K.v3).batch(e.calls,t);return this._processBatchResponse(s,e.calls,t)}}class gf extends Es{async make(e){this._warnMisplacedOptions(e,["isHaltOnError","requestId"],"options");const t=50,s={...e.options,returnAjaxResult:!1,apiVersion:K.v3},n=new Oe,i=[],o=this.chunkArray(e.calls,t);for(const a of o){const c=await this._b24.getHttpClient(K.v3).batch(a,s);c.isSuccess||this._addBatchErrorsIfAny(c,n);for(const[u,l]of c.getData().result)l.isSuccess&&i.push(l.getData().result)}return n.setData(i)}}class Nt{static getBatchCommand(e,t){if(e){if(typeof e=="object"&&"method"in e&&typeof e.method=="string")return{method:e.method,query:e.params??{},as:e.as??t.asDefaultValue,parallel:e.parallel??t.parallelDefaultValue};if(Array.isArray(e)&&e.length>0&&typeof e[0]=="string")return{method:e[0],query:e[1]??{},as:t.asDefaultValue,parallel:t.parallelDefaultValue}}const{parallelDefaultValue:s,asDefaultValue:n}=t,i=e&&typeof e=="object"?{keys:Object.keys(e).join(", "),...Array.isArray(e)?{length:e.length}:{method:typeof e.method=="string"?e.method:void 0}}:{type:typeof e};throw new R({code:"JSSDK_INTERACTION_BATCH_ROW_FAIL",description:`There were difficulties parsing the command for batch.
${JSON.stringify({row:i,options:{parallelDefaultValue:s,asDefaultValue:n}})}`,status:500})}static getMethodsFromCommands(e){const t=[],s={parallelDefaultValue:!1};return Array.isArray(e)?e.forEach(n=>{const i=Nt.getBatchCommand(n,s);t.push(i.method)}):Object.entries(e).forEach(([n,i])=>{const o=Nt.getBatchCommand(i,{...s,asDefaultValue:n});t.push(o.method)}),t}}const mf=2e3,yf=250,_f=6e5,wf=2147483647;class bf extends ct{async make(e){const t=new Oe;if(this.#s(e.calls),e.signal?.aborted)return t.addError(hc(),"base-error");const s=await this.add(e);if(!s.isSuccess)return this.#n(s,t);const n=s.getData(),i=n.id;this.#i(e.onStatus,n,i);const o=await this.#t(i,e,n.status);if(!o.isSuccess)return o.getData()?.status==="error"&&(this._logger.warning('deferredBatch: the job ended with status "error"',{id:i,errorMessage:o.getData()?.errorMessage}).catch(()=>{}),e.deleteAfter!==!1&&await this.#e(i)),this.#n(o,t);const a=await this.download(i);return a.isSuccess?(e.deleteAfter!==!1&&await this.#e(i),t.setData(a.getData())):this.#n(a,t)}async#e(e){const t=await this.delete(e);t.isSuccess||this._logger.warning("deferredBatch: the job could not be deleted",{id:e,errors:t.getErrorMessages()}).catch(()=>{})}async add(e){const t=this.#s(e.calls);return this.#r("rest.deferredbatch.add",{fields:{commands:t}},s=>s.item,e.requestId,e.idempotencyKey)}async get(e){return this.#r("rest.deferredbatch.get",{id:e},t=>t.item)}async list(){return this.#r("rest.deferredbatch.list",{},e=>Array.isArray(e)?e:Array.isArray(e.items)?e.items:void 0)}async waitFor(e,t={}){return this.#t(e,t,void 0)}async#t(e,t,s){const n=Math.min(wf,Math.max(yf,Sf(t.pollInterval,mf))),i=Math.max(0,typeof t.timeout=="number"&&!Number.isNaN(t.timeout)?t.timeout:_f),o=Date.now()+i,a=new Oe;let c=s;for(;;){if(t.signal?.aborted)return a.addError(hc(e),"base-error");const u=await this.get(e);if(!u.isSuccess)return this.#n(u,a);const l=u.getData();if(l.status!==c&&(c=l.status,this.#i(t.onStatus,l,e)),l.status==="done")return a.setData(l);if(l.status==="error")return a.setData(l),a.addError(new R({code:"JSSDK_DEFERRED_BATCH_FAILED",description:`deferredBatch: job #${e} ended with status "error"; see the job's errorMessage (waitFor / get).`,status:500}),"base-error");if(Date.now()+n>o)return a.addError(new R({code:"JSSDK_DEFERRED_BATCH_TIMEOUT",description:`deferredBatch: job #${e} reached no final status within ${i} ms; it keeps running on the portal.`,status:408}),"base-error");await this.#o(n,t.signal)}}async getDownloadUrl(e){return this.#r("rest.deferredbatch.downloadresult",{id:e},t=>t.downloadUrl)}async download(e){const t=new Oe,s=await this.getDownloadUrl(e);if(!s.isSuccess)return this.#n(s,t);let n;try{const i=await this._b24.getHttpClient(K.v3).ajaxClient.get(s.getData(),{responseType:"arraybuffer",maxRedirects:0});if(!i.status)return t.addError(new R({code:"JSSDK_DEFERRED_BATCH_DOWNLOAD_FAILED",description:"deferredBatch: the result file could not be downloaded (no status: a refused redirect or a dropped connection).",status:0}),"base-error");n=i.data}catch(i){const o=Number(i?.response?.status??0),a=i?.code,c=!o&&typeof a=="string"&&/^[A-Z][A-Z0-9_]{2,39}$/.test(a)?`, ${a}`:"";return t.addError(new R({code:"JSSDK_DEFERRED_BATCH_DOWNLOAD_FAILED",description:`deferredBatch: the result file could not be downloaded (HTTP ${o||"no response"}${c}).`,status:o||500}),"base-error")}try{return t.setData(await this.decode(n))}catch(i){return t.addError(i instanceof Error?i:new Error(String(i)),"base-error")}}async decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e),s=t.length>=2&&t[0]===31&&t[1]===139,n=new TextDecoder().decode(s?await Ef(t):t);let i;try{i=JSON.parse(n)}catch{i=void 0}if(!Array.isArray(i))throw new R({code:"JSSDK_DEFERRED_BATCH_DECODE_FAILED",description:"deferredBatch: the result file is not a JSON array.",status:500});return i}async delete(e){return this.#r("rest.deferredbatch.delete",{id:e},()=>!0,void 0,void 0,!1)}#s(e){if(!Array.isArray(e)||e.length===0)throw new R({code:"JSSDK_DEFERRED_BATCH_EMPTY",description:"deferredBatch: `calls` must be a non-empty array of commands.",status:400});return e.map(t=>{const s=Nt.getBatchCommand(t,{parallelDefaultValue:!1});return{method:s.method,query:s.query??{}}})}async#r(e,t,s,n,i,o=!0){const a=new Oe;let c;try{c=await this._b24.getHttpClient(K.v3).call(e,t,n,i===void 0?void 0:{idempotencyKey:i})}catch(h){return a.addError(h instanceof Error?h:new Error(String(h)),"base-error")}if(!c.isSuccess)return this.#n(c,a);const u=c.getData()?.result,l=u==null&&o?void 0:s(u);return l==null?a.addError(new R({code:"JSSDK_DEFERRED_BATCH_UNEXPECTED_RESPONSE",description:`deferredBatch: ${e} answered without the expected data.`,status:500}),"base-error"):a.setData(l)}#i(e,t,s){const n=i=>{this._logger.warning("deferredBatch: onStatus threw",{id:s,error:String(i)}).catch(()=>{})};try{const i=e?.(t);i&&typeof i.then=="function"&&Promise.resolve(i).catch(n)}catch(i){n(i)}}#n(e,t){for(const[s,n]of e.errors)t.addError(n,s);return t}#o(e,t){return new Promise(s=>{if(t?.aborted){s();return}const n=setTimeout(i,e);function i(){clearTimeout(n),t?.removeEventListener("abort",i),s()}t?.addEventListener("abort",i,{once:!0})})}}function hc(r){return new R({code:"JSSDK_DEFERRED_BATCH_ABORTED",description:r===void 0?"deferredBatch: aborted before anything was added.":`deferredBatch: waiting for job #${r} was aborted; it keeps running on the portal.`,status:499})}function Sf(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}async function Ef(r){if(typeof DecompressionStream!="function")throw new R({code:"JSSDK_DEFERRED_BATCH_GZIP_UNSUPPORTED",description:"deferredBatch: this runtime has no DecompressionStream, so the gzip result file cannot be decoded. Use Node.js 18+ or a current browser.",status:500});try{const e=new Blob([r]).stream().pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(e).arrayBuffer())}catch{throw new R({code:"JSSDK_DEFERRED_BATCH_DECODE_FAILED",description:"deferredBatch: the result file is not valid gzip.",status:500})}}const Zn=Symbol("call_V3"),Xn=Symbol("callList_V3"),Qn=Symbol("fetchList_V3"),ei=Symbol("callTail_V3"),ti=Symbol("fetchTail_V3"),ri=Symbol("aggregate_V3"),si=Symbol("batch_V3"),ni=Symbol("batchByChunk_V3"),ii=Symbol("deferredBatch_V3");class Tf{_b24;_logger;_mapActions;constructor(e){this._b24=e,this._logger=oe.createNullLogger(),this._mapActions=new Map}setLogger(e){this._logger=e}getLogger(){return this._logger}get call(){return this._mapActions.has(Zn)||this._mapActions.set(Zn,new of(this._b24,this._logger)),this._mapActions.get(Zn)}get callList(){return this._mapActions.has(Xn)||this._mapActions.set(Xn,new lf(this._b24,this._logger)),this._mapActions.get(Xn)}get fetchList(){return this._mapActions.has(Qn)||this._mapActions.set(Qn,new uf(this._b24,this._logger)),this._mapActions.get(Qn)}get callTail(){return this._mapActions.has(ei)||this._mapActions.set(ei,new hf(this._b24,this._logger)),this._mapActions.get(ei)}get fetchTail(){return this._mapActions.has(ti)||this._mapActions.set(ti,new df(this._b24,this._logger)),this._mapActions.get(ti)}get aggregate(){return this._mapActions.has(ri)||this._mapActions.set(ri,new ff(this._b24,this._logger)),this._mapActions.get(ri)}get batch(){return this._mapActions.has(si)||this._mapActions.set(si,new pf(this._b24,this._logger)),this._mapActions.get(si)}get batchByChunk(){return this._mapActions.has(ni)||this._mapActions.set(ni,new gf(this._b24,this._logger)),this._mapActions.get(ni)}get deferredBatch(){return this._mapActions.has(ii)||this._mapActions.set(ii,new bf(this._b24,this._logger)),this._mapActions.get(ii)}}const oi=Symbol(K.v2),ai=Symbol(K.v3);class vf{_b24;_logger;_mapActions;constructor(e){this._b24=e,this._logger=oe.createNullLogger(),this._mapActions=new Map}setLogger(e){this._logger=e,this.v2.setLogger(this._logger),this.v3.setLogger(this._logger)}getLogger(){return this._logger}get v2(){return this._mapActions.has(oi)||this._mapActions.set(oi,new nf(this._b24)),this._mapActions.get(oi)}get v3(){return this._mapActions.has(ai)||this._mapActions.set(ai,new Tf(this._b24)),this._mapActions.get(ai)}}class dc{_b24;_logger;constructor(e,t){this._b24=e,this._logger=t}}class Of extends dc{async make(e){const t=Date.now();try{return await this._b24.actions.v2.call.make({method:"server.time",params:{},requestId:e?.requestId}),Date.now()-t}catch{return-1}}}class Af extends dc{async make(e){try{return(await this._b24.actions.v2.call.make({method:"server.time",params:{},requestId:e?.requestId})).isSuccess}catch{return!1}}}const ci=Symbol("ping"),li=Symbol("healthCheck");class If{_b24;_logger;_mapTools;constructor(e){this._b24=e,this._logger=oe.createNullLogger(),this._mapTools=new Map}setLogger(e){this._logger=e}getLogger(){return this._logger}get ping(){return this._mapTools.has(ci)||this._mapTools.set(ci,new Of(this._b24,this._logger)),this._mapTools.get(ci)}get healthCheck(){return this._mapTools.has(li)||this._mapTools.set(li,new Af(this._b24,this._logger)),this._mapTools.get(li)}}class vs{_isInit=!1;_httpV2=null;_httpV3=null;_logger;_actionsManager;_toolsManager;constructor(){this._isInit=!1,this._logger=oe.createNullLogger(),this._actionsManager=new vf(this),this._toolsManager=new If(this)}get isInit(){return this._isInit}async init(){this._isInit=!0}destroy(){}get actions(){return this._ensureInitialized(),this._actionsManager}get tools(){return this._ensureInitialized(),this._toolsManager}getHttpClient(e){switch(this._ensureInitialized(),e){case K.v3:if(this._httpV3===null)throw new R({code:"JSSDK_CORE_B24_HTTP_V3_NOT_INIT",description:"HttpV3 not init",status:500});return this._httpV3;case K.v2:if(this._httpV2===null)throw new R({code:"JSSDK_CORE_B24_HTTP_V2_NOT_INIT",description:"HttpV2 not init",status:500});return this._httpV2}throw new R({code:"JSSDK_CORE_B24_API_WRONG",description:`Wrong Api Version ${e}`,status:500})}setHttpClient(e,t){switch(e){case K.v3:this._httpV3=t;return;case K.v2:this._httpV2=t;return}throw new R({code:"JSSDK_CORE_B24_API_WRONG",description:`Wrong Api Version ${e}`,status:500})}setLogger(e){Wd(e,"B24 client"),this._logger=e,this._actionsManager.setLogger(this._logger),this._toolsManager.setLogger(this._logger),ur.getAllApiVersions().forEach(t=>{this.getHttpClient(t).setLogger(this._logger)})}getLogger(){return this._logger}async setRestrictionManagerParams(e){const t=ur.getAllApiVersions().map(s=>this.getHttpClient(s).setRestrictionManagerParams(e));await Promise.all(t)}_httpOptions=null;_getHttpOptions(){return this._httpOptions}_ensureInitialized(){if(!this._isInit)throw new R({code:"JSSDK_CORE_B24_NOT_INIT",description:"B24 not initialized",status:500})}}function fc(r,e){return function(){return r.apply(e,arguments)}}const{toString:kf}=Object.prototype,{getPrototypeOf:St}=Object,{iterator:$r,toStringTag:pc}=Symbol,Et=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),gc=r=>typeof r=="string"&&(r==="__proto__"||r==="constructor"||r==="prototype"),Os=(r,e,t)=>r===Object.prototype||!t&&e===null,Rf=r=>{if(!Object.isExtensible(r))return!1;const e=Object.getOwnPropertyNames(r);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(r)),e.every(t=>{if(gc(t))return!1;const s=Object.getOwnPropertyDescriptor(r,t);return!!s&&s.configurable&&s.writable===!0})},ui=(r,e)=>{let t=r;const s=[];for(;t!=null;){if(s.indexOf(t)!==-1)return!1;s.push(t);const n=St(t);if(Os(t,n,t===r))return!1;if(Et(t,e))return!0;t=n}return!1},Cf=(r,e)=>r!=null&&ui(r,e)?r[e]:void 0,Nf=r=>{if(r==null||typeof r!="object"&&typeof r!="function")return r;const e=St(r);if(e===null&&Rf(r))return r;const t=Object.create(null),s=Object.create(null),n=[];let i=r;for(;i!=null&&n.indexOf(i)===-1;){n.push(i);const o=i===r?e:St(i);if(Os(i,o,i===r))break;const a=Object.getOwnPropertyNames(i);Object.getOwnPropertySymbols&&a.push(...Object.getOwnPropertySymbols(i));for(const c of a)gc(c)||Et(s,c)||(t[c]=r[c],s[c]=!0);i=o}return t},hi=(r=>e=>{const t=kf.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),rt=r=>(r=r.toLowerCase(),e=>hi(e)===r),As=r=>e=>typeof e===r,{isArray:Vt}=Array,qt=As("undefined");function dr(r){return r!==null&&!qt(r)&&r.constructor!==null&&!qt(r.constructor)&&He(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const mc=rt("ArrayBuffer");function Df(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&mc(r.buffer),e}const Lf=As("string"),He=As("function"),Mf=As("number"),fr=r=>r!==null&&typeof r=="object",Pf=r=>r===!0||r===!1,Is=r=>{if(!fr(r))return!1;const e=St(r);return(e===null||e===Object.prototype||St(e)===null)&&(Os(r,e,!0)||!Et(r,pc)&&!Et(r,$r))},xf=r=>{if(!fr(r)||dr(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},Ff=rt("Date"),Bf=rt("File"),$f=r=>!!(r&&typeof r.uri<"u"),jf=r=>r&&typeof r.getParts<"u",Uf=rt("Blob"),Vf=rt("FileList"),qf=rt("Set"),Hf=r=>fr(r)&&He(r.pipe);function Wf(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const yc=Wf(),_c=typeof yc.FormData<"u"?yc.FormData:void 0,zf=r=>{if(!r)return!1;if(_c&&r instanceof _c)return!0;const e=St(r);if(!e||e===Object.prototype||!He(r.append))return!1;const t=hi(r);return t==="formdata"||t==="object"&&He(r.toString)&&r.toString()==="[object FormData]"},Jf=rt("URLSearchParams"),[Kf,Gf,Yf,Zf]=["ReadableStream","Request","Response","Headers"].map(rt),Xf=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function jr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let s,n;if(typeof r!="object"&&(r=[r]),Vt(r))for(s=0,n=r.length;s<n;s++)e.call(null,r[s],s,r);else{if(dr(r))return;const i=t?Object.getOwnPropertyNames(r):Object.keys(r),o=i.length;let a;for(s=0;s<o;s++)a=i[s],e.call(null,r[a],a,r)}}function Qf(r,e){if(dr(r))return null;e=e.toLowerCase();const t=Object.keys(r);let s=t.length,n;for(;s-- >0;)if(n=t[s],e===n.toLowerCase())return n;return null}const Ht=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,wc=r=>!qt(r)&&r!==Ht;function di(...r){const{caseless:e,skipUndefined:t}=wc(this)&&this||{},s={},n=e?Object.create(null):null,i=(o,a)=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;let c=a;if(n&&typeof a=="string"){const l=a.toLowerCase(),h=n[l];h!==void 0&&Et(s,h)?c=h:n[l]=a}const u=Et(s,c)?s[c]:void 0;Is(u)&&Is(o)?s[c]=di(u,o):Is(o)?s[c]=di({},o):Vt(o)?s[c]=o.slice():(!t||!qt(o))&&(s[c]=o)};for(let o=0,a=r.length;o<a;o++){const c=r[o];if(!c||dr(c)||(jr(c,i),typeof c!="object"||Vt(c)||!Object.getOwnPropertySymbols))continue;const u=Object.getOwnPropertySymbols(c);for(let l=0;l<u.length;l++){const h=u[l];hp.call(c,h)&&i(c[h],h)}}return s}const ep=(r,e,t,{allOwnKeys:s}={})=>(jr(e,(n,i)=>{t&&He(n)?Object.defineProperty(r,i,{__proto__:null,value:fc(n,t),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(r,i,{__proto__:null,value:n,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:s}),r),tp=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),rp=(r,e,t,s)=>{r.prototype=Object.create(e.prototype,s),Object.defineProperty(r.prototype,"constructor",{__proto__:null,value:r,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(r,"super",{__proto__:null,value:e.prototype}),t&&Object.assign(r.prototype,t)},sp=(r,e,t,s)=>{let n,i,o;const a={};if(e=e||{},r==null)return e;do{for(n=Object.getOwnPropertyNames(r),i=n.length;i-- >0;)o=n[i],(!s||s(o,r,e))&&!a[o]&&(e[o]=r[o],a[o]=!0);r=t!==!1&&St(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},np=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const s=r.indexOf(e,t);return s!==-1&&s===t},ip=r=>{if(!r)return null;if(Vt(r))return r;let e=r.length;if(!Number.isSafeInteger(e)||e<0||e>4294967295)return null;const t=new Set,s=new Set;let n=r;for(;n!=null&&t.size<e;){if(s.has(n))return null;s.add(n);const o=St(n);if(Os(n,o,n===r))break;Object.getOwnPropertyNames(n).forEach(a=>{const c=+a;Number.isInteger(c)&&c>=0&&c<e&&String(c)===a&&Et(n,a)&&t.add(c)}),n=o}if(t.size!==e)return null;const i=new Array(e);for(;e-- >0;)i[e]=r[e];return i},op=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&St(Uint8Array)),ap=(r,e)=>{const s=(r&&r[$r]).call(r);let n;for(;(n=s.next())&&!n.done;){const i=n.value;e.call(r,i[0],i[1])}},cp=(r,e)=>{let t;const s=[];for(;(t=r.exec(e))!==null;)s.push(t);return s},lp=rt("HTMLFormElement"),up=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,s,n){return s.toUpperCase()+n}),{propertyIsEnumerable:hp}=Object.prototype,dp=rt("RegExp"),bc=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),s={};jr(t,(n,i)=>{let o;(o=e(n,i,r))!==!1&&(s[i]=o||n)}),Object.defineProperties(r,s)},fp=r=>{bc(r,(e,t)=>{if(He(r)&&["arguments","caller","callee"].includes(t))return!1;const s=r[t];if(He(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},pp=(r,e)=>{const t={},s=n=>{n.forEach(i=>{t[i]=!0})};return Vt(r)?s(r):s(String(r).split(e)),t},gp=()=>{},mp=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function yp(r){return!!(r&&He(r.append)&&r[pc]==="FormData"&&r[$r])}const _p=r=>{const e=new WeakSet,t=s=>{if(fr(s)){if(e.has(s))return;if(dr(s))return s;if(!("toJSON"in s)){e.add(s);let n;if(qf(s)){n=[];for(const i of s){const o=t(i);!qt(o)&&n.push(o)}}else n=Vt(s)?[]:{},jr(s,(i,o)=>{const a=t(i);!qt(a)&&(n[o]=a)});return e.delete(s),n}}return s};return t(r)},wp=rt("AsyncFunction"),bp=r=>r&&(fr(r)||He(r))&&He(r.then)&&He(r.catch),Sc=((r,e)=>r?setImmediate:e?((t,s)=>(Ht.addEventListener("message",({source:n,data:i})=>{n===Ht&&i===t&&s.length&&s.shift()()},!1),n=>{s.push(n),Ht.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",He(Ht.postMessage)),Sp=typeof queueMicrotask<"u"?queueMicrotask.bind(Ht):typeof process<"u"&&process.nextTick||Sc,Ec=r=>r!=null&&He(r[$r]),b={isArray:Vt,isArrayBuffer:mc,isBuffer:dr,isFormData:zf,isArrayBufferView:Df,isString:Lf,isNumber:Mf,isBoolean:Pf,isObject:fr,isPlainObject:Is,isEmptyObject:xf,isReadableStream:Kf,isRequest:Gf,isResponse:Yf,isHeaders:Zf,isUndefined:qt,isDate:Ff,isFile:Bf,isReactNativeBlob:$f,isReactNative:jf,isBlob:Uf,isRegExp:dp,isFunction:He,isStream:Hf,isURLSearchParams:Jf,isTypedArray:op,isFileList:Vf,forEach:jr,merge:di,extend:ep,trim:Xf,stripBOM:tp,inherits:rp,toFlatObject:sp,kindOf:hi,kindOfTest:rt,endsWith:np,toArray:ip,forEachEntry:ap,matchAll:cp,isHTMLForm:lp,hasOwnProperty:Et,hasOwnProp:Et,hasOwnInPrototypeChain:ui,getSafeProp:Cf,toSafeFlatObject:Nf,reduceDescriptors:bc,freezeMethods:fp,toObjectSet:pp,toCamelCase:up,noop:gp,toFiniteNumber:mp,findKey:Qf,global:Ht,isContextDefined:wc,isSpecCompliantForm:yp,toJSONObject:_p,isAsyncFn:wp,isThenable:bp,setImmediate:Sc,asap:Sp,isIterable:Ec,isSafeIterable:r=>r!=null&&ui(r,$r)&&Ec(r)},Ep=b.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Tp=r=>{const e=Object.create(null);let t,s,n;return r&&r.split(`
`).forEach(function(o){n=o.indexOf(":"),t=o.substring(0,n).trim().toLowerCase(),s=o.substring(n+1).trim();const a=b.hasOwnProp(e,t);!t||a&&b.hasOwnProp(Ep,t)||(t==="set-cookie"?a?e[t].push(s):e[t]=[s]:e[t]=a?e[t]+", "+s:s)}),e};function vp(r){let e=0,t=r.length;for(;e<t;){const s=r.charCodeAt(e);if(s!==9&&s!==32)break;e+=1}for(;t>e;){const s=r.charCodeAt(t-1);if(s!==9&&s!==32)break;t-=1}return e===0&&t===r.length?r:r.slice(e,t)}const Op=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Ap=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function fi(r,e){return b.isArray(r)?r.map(t=>fi(t,e)):vp(String(r).replace(e,""))}const Ip=r=>fi(r,Op),kp=r=>fi(r,Ap);function Tc(r){const e=Object.create(null);return b.forEach(r.toJSON(),(t,s)=>{e[s]=kp(t)}),e}const vc=Symbol("internals");function Ur(r){return r&&String(r).trim().toLowerCase()}function ks(r){return r===!1||r==null?r:b.isArray(r)?r.map(ks):Ip(String(r))}function Rp(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=t.exec(r);)e[s[1]]=s[2];return e}const Cp=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function pi(r){let e=0,t=r.length;for(;e<t;){const s=r.charCodeAt(e);if(s!==9&&s!==32)break;e+=1}for(;t>e;){const s=r.charCodeAt(t-1);if(s!==9&&s!==32)break;t-=1}return e===0&&t===r.length?r:r.slice(e,t)}function Np(r){const e=r.length-1;if(e<1||r.charCodeAt(0)!==34||r.charCodeAt(e)!==34)return r;let t="";for(let s=1;s<e;s++){const n=r.charCodeAt(s);if(n===34||n===92&&(s+=1,s>=e))return r;t+=r[s]}return t}function Dp(r){const e=Object.create(null),t=String(r);let s=0,n=!1,i=!1;function o(a){const c=pi(t.slice(s,a)),u=c.indexOf("=");if(u<1)return;const l=pi(c.slice(0,u));if(!Cp.test(l))return;const h=l.toLowerCase();if(h==="__proto__"||h==="constructor"||h==="prototype")return;const d=pi(c.slice(u+1));e[h]=Np(d)}for(let a=0;a<t.length;a++){const c=t.charCodeAt(a);n?i?i=!1:c===92?i=!0:c===34&&(n=!1):c===34?n=!0:(c===44||c===59)&&(o(a),s=a+1)}return o(t.length),e}const Lp=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim()),Mp="__Proto__",Oc=r=>r==="__proto__"?Mp:r;function gi(r,e,t,s,n){if(b.isFunction(s))return s.call(r,e,t);if(n&&(e=t),!!b.isString(e)){if(b.isString(s))return e.indexOf(s)!==-1;if(b.isRegExp(s))return s.test(e)}}function Pp(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,s)=>t.toUpperCase()+s)}function xp(r,e){const t=b.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(r,s+t,{__proto__:null,value:function(n,i,o){return this[s].call(this,e,n,i,o)},configurable:!0})})}let Ae=class{constructor(e){e&&this.set(e)}set(e,t,s){const n=this;function i(a,c,u){const l=Ur(c);if(!l)return;const h=b.findKey(n,l);(!h||n[h]===void 0||u===!0||u===void 0&&n[h]!==!1)&&(n[Oc(h||c)]=ks(a))}const o=(a,c)=>b.forEach(a,(u,l)=>i(u,l,c));if(b.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(b.isString(e)&&(e=e.trim())&&!Lp(e))o(Tp(e),t);else if(b.isObject(e)&&b.isSafeIterable(e)){let a=Object.create(null),c,u;for(const l of e){if(!b.isArray(l))throw new TypeError("Object iterator must return a key-value pair");u=l[0],b.hasOwnProp(a,u)?(c=a[u],a[u]=b.isArray(c)?[...c,l[1]]:[c,l[1]]):a[u]=l[1]}o(a,t)}else e!=null&&i(t,e,s);return this}get(e,t){if(e=Ur(e),e){const s=b.findKey(this,e);if(s){const n=this[s];if(!t)return n;if(t===!0)return Rp(n);if(b.isFunction(t))return t.call(this,n,s);if(b.isRegExp(t))return t.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ur(e),e){const s=b.findKey(this,e);return!!(s&&this[s]!==void 0&&(!t||gi(this,this[s],s,t)))}return!1}delete(e,t){const s=this;let n=!1;function i(o){if(o=Ur(o),o){const a=b.findKey(s,o);a&&(!t||gi(s,s[a],a,t))&&(delete s[a],n=!0)}}return b.isArray(e)?e.forEach(i):i(e),n}clear(e){const t=Object.keys(this);let s=t.length,n=!1;for(;s--;){const i=t[s];(!e||gi(this,this[i],i,e,!0))&&(delete this[i],n=!0)}return n}normalize(e){const t=this,s=Object.create(null);return b.forEach(this,(n,i)=>{const o=b.findKey(s,i);if(o){t[o]=ks(n),delete t[i];return}const a=Oc(e?Pp(i):String(i).trim());a!==i&&delete t[i],t[a]=ks(n),s[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return b.forEach(this,(s,n)=>{s!=null&&s!==!1&&(t[n]=e&&b.isArray(s)?s.join(", "):s)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(`
`)}getSetCookie(){const e=this.get("set-cookie");return b.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return Dp(e)}static concat(e,...t){const s=new this(e);return t.forEach(n=>s.set(n)),s}static accessor(e){const s=(this[vc]=this[vc]={accessors:{}}).accessors,n=this.prototype;function i(o){const a=Ur(o);s[a]||(xp(n,o),s[a]=!0)}return b.isArray(e)?e.forEach(i):i(e),this}};Ae.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),b.reduceDescriptors(Ae.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(s){this[t]=s}}}),b.freezeMethods(Ae);const Rs="[REDACTED ****]";function Fp(r){if(b.hasOwnProp(r,"toJSON"))return!0;let e=Object.getPrototypeOf(r);for(;e&&e!==Object.prototype;){if(b.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function Bp(r,e){const t=new Set(e.map(i=>String(i).toLowerCase())),s=[],n=i=>{if(i===null||typeof i!="object"||b.isBuffer(i))return i;if(s.indexOf(i)!==-1)return;i instanceof Ae&&(i=i.toJSON()),s.push(i);let o;if(b.isArray(i))o=[],i.forEach((a,c)=>{const u=n(a);b.isUndefined(u)||(o[c]=u)});else{if(!b.isPlainObject(i)&&Fp(i))return s.pop(),i;o=Object.create(null);for(const[a,c]of Object.entries(i)){const u=t.has(a.toLowerCase())?Rs:n(c);b.isUndefined(u)||(o[a]=u)}}return s.pop(),o};return n(r)}function Ac(r){try{return String(r)}catch{return""}}function $p(r){return r.errors.map(t=>{try{return t&&t.message?Ac(t.message):Ac(t)}catch{return""}}).filter(Boolean).join("; ")||r.name||"AggregateError"}const jp=`
Caused by: `,mi=Symbol("causeStack");function Up(r,e){const t=b.hasOwnProp(r,mi)&&r[mi];return t&&e.endsWith(t)?e.length-t.length:-1}function Vp(r,e){try{const t=e&&e.stack;if(typeof t!="string"||!t)return;const s=r.stack;if(typeof s!="string"||!s)return;const n=jp+t;r.stack=s+n,Object.defineProperty(r,mi,{__proto__:null,value:n})}catch{}}let C=class lu extends Error{static from(e,t,s,n,i,o){let a=e.message;!a&&b.isArray(e.errors)&&e.errors.length&&(a=$p(e));const c=new lu(a,t||e.code,s,n,i);return Object.defineProperty(c,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),c.name=e.name,Vp(c,e),e.status!=null&&c.status==null&&(c.status=e.status),o&&Object.assign(c,o),c}constructor(e,t,s,n,i){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),s&&(this.config=s),n&&(this.request=n),i&&(this.response=i,this.status=i.status)}toJSON(){const e=this.config,t=e&&b.hasOwnProp(e,"redact")?e.redact:void 0,s=b.isArray(t)&&t.length>0?Bp(e,t):b.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:s,code:this.code,status:this.status}}};C.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",C.ERR_BAD_OPTION="ERR_BAD_OPTION",C.ECONNABORTED="ECONNABORTED",C.ETIMEDOUT="ETIMEDOUT",C.ECONNREFUSED="ECONNREFUSED",C.ERR_NETWORK="ERR_NETWORK",C.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",C.ERR_DEPRECATED="ERR_DEPRECATED",C.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",C.ERR_BAD_REQUEST="ERR_BAD_REQUEST",C.ERR_CANCELED="ERR_CANCELED",C.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",C.ERR_INVALID_URL="ERR_INVALID_URL",C.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const qp=null,Ic=100;function yi(r){return b.isPlainObject(r)||b.isArray(r)}function kc(r){return b.endsWith(r,"[]")?r.slice(0,-2):r}function _i(r,e,t){return r?r.concat(e).map(function(n,i){return n=kc(n),!t&&i?"["+n+"]":n}).join(t?".":""):e}function Hp(r){return b.isArray(r)&&!r.some(yi)}const Wp=b.toFlatObject(b,{},null,function(e){return/^is[A-Z]/.test(e)});function Cs(r,e,t){if(!b.isObject(r))throw new TypeError("target must be an object");e=e||new FormData;const s=(_,S)=>{const m=b.getSafeProp(t,_);return b.isUndefined(m)?S:m},n=s("metaTokens",!0),i=s("visitor")||g,o=s("dots",!1),a=s("indexes",!1),c=s("Blob")||typeof Blob<"u"&&Blob,u=s("maxDepth",Ic),l=c&&b.isSpecCompliantForm(e),h=[];if(!b.isFunction(i))throw new TypeError("visitor must be a function");function d(_){if(_===null)return"";if(b.isDate(_))return _.toISOString();if(b.isBoolean(_))return _.toString();if(!l&&b.isBlob(_))throw new C("Blob is not supported. Use a Buffer instead.");if(b.isArrayBuffer(_)||b.isTypedArray(_)){if(l&&typeof c=="function")return new c([_]);throw new C("Blob is not supported. Use a Buffer instead.",C.ERR_NOT_SUPPORT)}return _}function f(_){if(_>u)throw new C("Object is too deeply nested ("+_+" levels). Max depth: "+u,C.ERR_FORM_DATA_DEPTH_EXCEEDED)}function p(_,S){if(u===1/0)return JSON.stringify(_);const m=[];return JSON.stringify(_,function(E,v){if(!b.isObject(v))return v;for(;m.length&&m[m.length-1]!==this;)m.pop();return m.push(v),f(S+m.length-1),v})}function g(_,S,m){let T=_;if(b.isReactNative(e)&&b.isReactNativeBlob(_))return e.append(_i(m,S,o),d(_)),!1;if(_&&!m&&typeof _=="object"){if(b.endsWith(S,"{}"))S=n?S:S.slice(0,-2),_=p(_,1);else if(b.isArray(_)&&Hp(_)||(b.isFileList(_)||b.endsWith(S,"[]"))&&(T=b.toArray(_)))return S=kc(S),T.forEach(function(v,I){!(b.isUndefined(v)||v===null)&&e.append(a===!0?_i([S],I,o):a===null?S:S+"[]",d(v))}),!1}return yi(_)?!0:(e.append(_i(m,S,o),d(_)),!1)}const y=Object.assign(Wp,{defaultVisitor:g,convertValue:d,isVisitable:yi});function w(_,S,m=0){if(!b.isUndefined(_)){if(f(m),h.indexOf(_)!==-1)throw new Error("Circular reference detected in "+S.join("."));h.push(_),b.forEach(_,function(E,v){(!(b.isUndefined(E)||E===null)&&i.call(e,E,b.isString(v)?v.trim():v,S,y))===!0&&w(E,S?S.concat(v):[v],m+1)}),h.pop()}}if(!b.isObject(r))throw new TypeError("data must be an object");return w(r),e}function Rc(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(r).replace(/[!'()~]|%20/g,function(s){return e[s]})}function wi(r,e){this._pairs=[],r&&Cs(r,this,e)}const Cc=wi.prototype;Cc.append=function(e,t){this._pairs.push([e,t])},Cc.toString=function(e){const t=e?s=>e.call(this,s,Rc):Rc;return this._pairs.map(function(n){return t(n[0])+"="+t(n[1])},"").join("&")};function zp(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Nc(r,e,t){if(!e)return r;r=r||"";const s=b.isFunction(t)?{serialize:t}:t,n=b.getSafeProp(s,"encode")||zp,i=b.getSafeProp(s,"serialize");let o;if(i?o=i(e,s):o=b.isURLSearchParams(e)?e.toString():new wi(e,s).toString(n),o){const a=r.indexOf("#");a!==-1&&(r=r.slice(0,a)),r+=(r.indexOf("?")===-1?"?":"&")+o}return r}const Vr=Symbol("internals");function Dc(r){return r?r.length:0}function Lc(r){if(r)for(;r.length&&r[r.length-1]===null;)r.pop()}function Jp(r){return typeof r=="string"&&r!==""&&String(Number(r))===r?Number(r):r}function qr(r,e){const t=r.handlers,s=Dc(t);t!==e.handlersRef?(e.handlersRef=t,e.handlerEntries.clear()):s!==e.handlersLength&&(s?e.handlerEntries.forEach(function(i,o){t[i.index]!==i.handler&&e.handlerEntries.delete(o)}):e.handlerEntries.clear()),e.handlersLength=s}class Mc{constructor(){this.handlers=[],this[Vr]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,t,s){const n={fulfilled:e,rejected:t,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null},i=this[Vr];this.handlers==null&&(this.handlers=[]),qr(this,i);const o=i.nextId++;return this.handlers.push(n),i.handlerEntries.set(o,{handler:n,index:this.handlers.length-1}),i.handlersLength=this.handlers.length,o}eject(e){const t=this[Vr];qr(this,t);const s=Jp(e),n=t.handlerEntries.get(s);if(n){if(t.handlerEntries.delete(s),this.handlers[n.index]!==n.handler)return;this.handlers[n.index]=null,t.iterationDepth||(Lc(this.handlers),t.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],qr(this,this[Vr]))}forEach(e){const t=this[Vr];qr(this,t),t.iterationDepth++;try{b.forEach(this.handlers,function(n){n!==null&&e(n)})}finally{--t.iterationDepth||(qr(this,t),Lc(this.handlers),t.handlersLength=Dc(this.handlers))}}}const bi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0,encodeBasicAuthUsername:!1},Kp={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:wi,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Si=typeof window<"u"&&typeof document<"u",Ei=typeof navigator=="object"&&navigator||void 0,Gp=Si&&(!Ei||["ReactNative","NativeScript","NS"].indexOf(Ei.product)<0),Yp=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Zp=Si&&window.location.href||"http://localhost",Ee={...{__proto__:null,hasBrowserEnv:Si,hasStandardBrowserEnv:Gp,hasStandardBrowserWebWorkerEnv:Yp,navigator:Ei,origin:Zp},...Kp};function Xp(r,e){return Cs(r,new Ee.classes.URLSearchParams,{visitor:function(t,s,n,i){return Ee.isNode&&b.isBuffer(t)?(this.append(s,t.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...e})}const Pc=Ic;function xc(r){if(r>Pc)throw new C("FormData field is too deeply nested ("+r+" levels). Max depth: "+Pc,C.ERR_FORM_DATA_DEPTH_EXCEEDED)}function Qp(r){const e=[],t=/[^.[\]]+|\[([^.[\]]*)]/g;let s;for(;(s=t.exec(r))!==null;)xc(e.length),e.push(s[0]==="[]"?"":s[1]||s[0]);return e}function Fc(r){const e={},t=Object.keys(r);let s;const n=t.length;let i;for(s=0;s<n;s++)i=t[s],e[i]=r[i];return e}function Bc(r){if(!b.isArray(r))return r;const e=Object.keys(r);return e.length!==r.length||e.some((t,s)=>t!==String(s))?Fc(r):r}function eg(r){const e=[r];for(;e.length;){const t=e.pop();Object.keys(t).forEach(s=>{const n=t[s]=Bc(t[s]);(b.isArray(n)||b.isPlainObject(n))&&e.push(n)})}return r}function $c(r){function e(t,s,n,i){xc(i);let o=t[i++];if(o==="__proto__")return!0;const a=Number.isFinite(+o),c=i>=t.length;return o=!o&&b.isArray(n)?n.length:o,c?(b.hasOwnProp(n,o)?(n[o]=Bc(n[o]),n[o]=b.isArray(n[o])?n[o].concat(s):[n[o],s]):n[o]=s,!a):((!b.hasOwnProp(n,o)||!b.isObject(n[o]))&&(n[o]=[]),e(t,s,n[o],i)&&b.isArray(n[o])&&(n[o]=Fc(n[o])),!a)}if(b.isFormData(r)&&b.isFunction(r.entries)){const t={};return b.forEachEntry(r,(s,n)=>{e(Qp(s),n,t,0)}),eg(t)}return null}const jc=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),pr=(r,e)=>r!=null&&b.hasOwnProp(r,e)?r[e]:void 0;function tg(r,e,t){if(b.isString(r))try{return(e||JSON.parse)(r),b.trim(r)}catch(s){if(s.name!=="SyntaxError")throw s}return(t||JSON.stringify)(r)}const Hr={transitional:bi,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const s=t.getContentType()||"",n=s.indexOf("application/json")>-1,i=b.isObject(e);if(i&&b.isHTMLForm(e)&&(e=new FormData(e)),b.isFormData(e))return n?JSON.stringify($c(e)):e;if(b.isArrayBuffer(e)||b.isBuffer(e)||b.isStream(e)||b.isFile(e)||b.isBlob(e)||b.isReadableStream(e))return e;if(b.isArrayBufferView(e))return e.buffer;if(b.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(i){const c=pr(this,"formSerializer");if(s.indexOf("application/x-www-form-urlencoded")>-1)return Xp(e,c).toString();if((a=b.isFileList(e))||s.indexOf("multipart/form-data")>-1){const u=pr(this,"env"),l=u&&u.FormData;return Cs(a?{"files[]":e}:e,l&&new l,c)}}return i||n?(t.setContentType("application/json",!1),tg(e)):e}],transformResponse:[function(e){const t=pr(this,"transitional")||Hr.transitional,s=t&&t.forcedJSONParsing,n=pr(this,"responseType"),i=n==="json";if(b.isResponse(e)||b.isReadableStream(e))return e;if(e&&b.isString(e)&&(s&&!n||i)){const a=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,pr(this,"parseReviver"))}catch(c){if(a)throw c.name==="SyntaxError"?C.from(c,C.ERR_BAD_RESPONSE,this,null,pr(this,"response")):c}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ee.classes.FormData,Blob:Ee.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};b.forEach(jc,r=>{Hr.headers[r]={}});function Ti(r,e){const t=this||Hr,s=e||t,n=Ae.from(s.headers);let i=s.data;return b.forEach(r,function(a){i=a.call(t,i,n.normalize(),e?e.status:void 0)}),n.normalize(),i}function Uc(r){return!!(r&&r.__CANCEL__)}let Wr=class extends C{constructor(e,t,s){super(e??"canceled",C.ERR_CANCELED,t,s),this.name="CanceledError",this.__CANCEL__=!0}};function Vc(r,e,t){const s=t.config.validateStatus;!t.status||!s||s(t.status)?r(t):e(new C("Request failed with status code "+t.status,t.status>=400&&t.status<500?C.ERR_BAD_REQUEST:C.ERR_BAD_RESPONSE,t.config,t.request,t))}const rg=/[\t\n\r]/g;function qc(r){if(typeof r!="string")return r;let e=0;for(;e<r.length&&r.charCodeAt(e)<=32;)e++;return r.slice(e).replace(rg,"")}function vi(r){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(r);return e&&e[1].toLowerCase()||""}const Hc=r=>{try{return decodeURIComponent(r)}catch{return r}},Wc=Ee.hasStandardBrowserEnv?{write(r,e,t,s,n,i,o){if(typeof document>"u")return;const a=[`${r}=${encodeURIComponent(e)}`];b.isNumber(t)&&a.push(`expires=${new Date(t).toUTCString()}`),b.isString(s)&&a.push(`path=${s}`),b.isString(n)&&a.push(`domain=${n}`),i===!0&&a.push("secure"),b.isString(o)&&a.push(`SameSite=${o}`),document.cookie=a.join("; ")},read(r){if(typeof document>"u")return null;const e=document.cookie;if(!e)return null;const t=e.split(";");for(let s=0;s<t.length;s++){const n=t[s].replace(/^\s+/,""),i=n.indexOf("=");if(i!==-1&&n.slice(0,i)===r)return Hc(n.slice(i+1))}return null},async readAsync(r){try{const e=typeof window<"u"&&window.cookieStore;if(e&&b.isFunction(e.get)){const t=await e.get(r);return t?Hc(t.value):null}}catch{}return this.read(r)},remove(r){this.write(r,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},async readAsync(){return null},remove(){}};function sg(r,e){r=r||10;const t=new Array(r),s=new Array(r);let n=0,i=0,o;return e=e!==void 0?e:1e3,function(c){const u=Date.now(),l=s[i];o||(o=u),t[n]=c,s[n]=u;let h=i,d=0;for(;h!==n;)d+=t[h++],h=h%r;if(n=(n+1)%r,n===i&&(i=(i+1)%r),u-o<e)return;const f=l&&u-l;return f?Math.round(d*1e3/f):void 0}}function ng(r,e){let t=0,s=1e3/e,n,i;const o=(l,h=Date.now())=>{t=h,n=null,i&&(clearTimeout(i),i=null),r(...l)};return[(...l)=>{const h=Date.now(),d=h-t;d>=s?o(l,h):(n=l,i||(i=setTimeout(()=>{i=null,o(n)},s-d)))},()=>n&&o(n),(...l)=>o(l)]}const Ns=(r,e,t=3)=>{let s=0;const n=sg(50,250);return ng(i=>{if(!i||!b.isNumber(i.loaded))return;const o=i.loaded,a=i.lengthComputable?i.total:void 0,c=Math.max(0,a!=null?Math.min(o,a):o),u=Math.max(0,c-s),l=n(u);s=Math.max(s,c);const h={loaded:c,total:a,progress:a?c/a:void 0,bytes:u,rate:l||void 0,estimated:l&&a?(a-c)/l:void 0,event:i,lengthComputable:a!=null,[e?"download":"upload"]:!0};r(h)},t)},zc=(r,e)=>{const t=r!=null;return[s=>e[0]({lengthComputable:t,total:r,loaded:s}),e[1]]},Jc=(r,e=b.asap)=>(...t)=>e(()=>r(...t)),ig=Ee.hasStandardBrowserEnv?(r=>e=>(e=new URL(e,document.baseURI||Ee.origin),r.protocol===e.protocol&&r.host===e.host&&r.port===e.port))(new URL(Ee.origin)):()=>!0;function og(r){return typeof r!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function ag(r,e){if(!e)return r;let t=r.length;for(;t>0&&r.charCodeAt(t-1)===47;)t--;return r.slice(0,t)+"/"+e.replace(/^\/+/,"")}const cg=/^https?:(?!\/\/)/i;function lg(r){return r&&r.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,t,s="")=>`${t}${s}${Rs}`)}function ug(r){const e=r.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${Rs}@`),t=e.indexOf("#"),n=(t===-1?e:e.slice(0,t)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${Rs}`);return t===-1?n:`${n}#${lg(e.slice(t+1))}`}function Kc(r,e){if(typeof r=="string"){const t=qc(r);if(cg.test(t))throw new C(`Invalid URL ${JSON.stringify(ug(t))}: missing "//" after protocol`,C.ERR_INVALID_URL,e)}}function Gc(r,e,t,s){Kc(e,s);let n=!og(e);return r&&(n||t===!1)?(Kc(r,s),ag(r,e)):e}function hg(r){const e=[{value:r}],t=new WeakSet,s=new WeakSet;for(;e.length;){const{value:n,done:i}=e.pop();if(!b.isPlainObject(n)&&!b.isArray(n))continue;if(i){t.delete(n);continue}if(t.has(n))throw new C("Circular reference detected in params",C.ERR_BAD_OPTION_VALUE);if(s.has(n))continue;s.add(n),t.add(n),e.push({value:n,done:!0});const o=Object.keys(n);Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor&&Object.getOwnPropertySymbols(n).forEach(a=>{const c=Object.getOwnPropertyDescriptor(n,a);c&&c.enumerable&&o.push(a)}),o.forEach(a=>{if(a==="__proto__"||a==="constructor"||a==="prototype"){const c=Object.getOwnPropertyDescriptor(n,a);c&&b.hasOwnProp(c,"value")&&e.push({value:c.value})}else e.push({value:n[a]})})}}const Yc=r=>r instanceof Ae?{...r}:r,Oi=r=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(r).concat(Object.getOwnPropertySymbols(r).filter(e=>{const t=Object.getOwnPropertyDescriptor(r,e);return t&&t.enumerable})):Object.keys(r);function dg(r,e){const t=[],s=new WeakMap,n={};function i(a,c){if(!b.isPlainObject(c))return b.isArray(c)?c.slice():c;const u=b.isPlainObject(a)?a:n;let l=s.get(c);if(l||(l=new WeakMap,s.set(c,l)),l.has(u))return l.get(u);const h={};return l.set(u,h),t.push({base:u,source:c,result:h}),h}const o=b.isUndefined(e)?i(void 0,r):i(r,e);for(;t.length;){const{base:a,source:c,result:u}=t.pop(),l=new Set(Oi(a)),h=new Set(Oi(c));new Set([...l,...h]).forEach(f=>{if(f==="__proto__"||f==="constructor"||f==="prototype")return;const p=h.has(f),g=p?c[f]:void 0,y=(!p||b.isPlainObject(g))&&l.has(f)?a[f]:void 0;u[f]=p?i(y,g):i(void 0,y)})}return hg(o),o}function Dt(r,e,t,s){return b.isPlainObject(r)&&b.isPlainObject(e)?b.merge.call({caseless:s},r,e):b.isPlainObject(e)?b.merge({},e):b.isArray(e)?e.slice():e}function Zc(r,e,t,s){if(b.isUndefined(e)){if(!b.isUndefined(r))return Dt(void 0,r,t,s)}else return Dt(r,e,t,s)}function Ai(r,e){if(!b.isUndefined(e))return Dt(void 0,e)}function fe(r,e){if(b.isUndefined(e)){if(!b.isUndefined(r))return Dt(void 0,r)}else return Dt(void 0,e)}function fg(r,e,t){const s=b.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!b.isUndefined(s))if(b.isPlainObject(s)){if(b.hasOwnProp(s,t))return s[t]}else return;const n=b.hasOwnProp(r,"transitional")?r.transitional:void 0;if(b.isPlainObject(n)&&b.hasOwnProp(n,t))return n[t]}function Ii(r,e,t,s,n){if(b.hasOwnProp(n,t))return Dt(r,e);if(b.hasOwnProp(s,t))return Dt(void 0,r)}function pg(r,e,t){return Zc(Yc(r),Yc(e),t,!0)}const gg=Object.freeze({__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0}),Xc={url:Ai,method:Ai,data:Ai,baseURL:fe,transformRequest:fe,transformResponse:fe,params:dg,paramsSerializer:fe,timeout:fe,timeoutErrorMessage:fe,withCredentials:fe,withXSRFToken:fe,adapter:fe,responseType:fe,xsrfCookieName:fe,xsrfHeaderName:fe,onUploadProgress:fe,onDownloadProgress:fe,decompress:fe,maxContentLength:fe,maxBodyLength:fe,beforeRedirect:fe,transport:fe,httpAgent:fe,httpsAgent:fe,cancelToken:fe,socketPath:fe,allowedSocketPaths:fe,responseEncoding:fe,validateStatus:Ii,headers:pg};function Wt(r,e){r=r||{},e=e||{};const t=Object.create(null);Object.defineProperty(t,"hasOwnProperty",gg);const s=Oi({...r,...e});for(let n=0,i=s.length;n<i;n++){const o=s[n];if(o==="__proto__"||o==="constructor"||o==="prototype")continue;const a=b.hasOwnProp(Xc,o)?Xc[o]:Zc,c=b.hasOwnProp(r,o)?r[o]:void 0,u=b.hasOwnProp(e,o)?e[o]:void 0,l=a===Ii?a(c,u,o,r,e):a(c,u,o);b.isUndefined(l)&&a!==Ii||(t[o]=l)}return b.hasOwnProp(e,"validateStatus")&&b.isUndefined(e.validateStatus)&&fg(r,e,"validateStatusUndefinedResolves")===!1&&(b.hasOwnProp(r,"validateStatus")?t.validateStatus=Dt(void 0,r.validateStatus):delete t.validateStatus),t}const mg=["content-type","content-length"];function yg(r,e,t){if(t!=="content-only"){r.set(e);return}Object.entries(e||{}).forEach(([s,n])=>{mg.includes(s.toLowerCase())&&r.set(s,n)})}const Qc=r=>encodeURIComponent(r).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16))),_g=r=>Wc.read(r);function el(r,e=_g){const t=Wt({},r),s=f=>b.hasOwnProp(t,f)?t[f]:void 0,n=s("data");let i=s("withXSRFToken");const o=s("xsrfHeaderName"),a=s("xsrfCookieName");let c=s("headers");const u=s("auth"),l=s("baseURL"),h=s("allowAbsoluteUrls"),d=s("url");if(t.headers=c=Ae.from(c),t.url=Nc(Gc(l,d,h,t),s("params"),s("paramsSerializer")),u){const f=b.getSafeProp(u,"username")||"",p=b.getSafeProp(u,"password")||"",g=s("transitional"),y=g&&b.hasOwnProp(g,"encodeBasicAuthUsername")&&g.encodeBasicAuthUsername===!0;try{c.set("Authorization","Basic "+btoa((y?Qc(f):f)+":"+(p?Qc(p):"")))}catch(w){throw C.from(w,C.ERR_BAD_OPTION_VALUE,r)}}if(b.isFormData(n)){const f=b.getSafeProp(n,"getHeaders");Ee.hasStandardBrowserEnv||Ee.hasStandardBrowserWebWorkerEnv||b.isReactNative(n)?c.setContentType(void 0):b.isFunction(f)&&yg(c,f.call(n),s("formDataHeaderPolicy"))}if(Ee.hasStandardBrowserEnv&&(b.isFunction(i)&&(i=i(t)),i===!0||i==null&&ig(t.url))){const p=o&&a&&e(a);p&&c.set(o,p)}return t}const wg=typeof XMLHttpRequest<"u"&&function(r){return new Promise(function(t,s){let n;try{const I=Ee.hasStandardBrowserEnv&&typeof window<"u"&&window.cookieStore;n=I&&b.isFunction(I.get)}catch{}let i;const o=el(r,n?I=>(i=I,null):void 0);let a=o.data;const c=Ae.from(o.headers).normalize();let{responseType:u,onUploadProgress:l,onDownloadProgress:h}=o,d,f,p,g,y,w,_;function S(){clearTimeout(f);try{y&&y()}catch(I){setTimeout(()=>{throw I})}try{w&&w()}catch(I){setTimeout(()=>{throw I})}m&&(g&&m.removeEventListener("progress",g),m.upload&&(p&&m.upload.removeEventListener("progress",p),y&&m.upload.removeEventListener("loadend",y))),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let m=new XMLHttpRequest;m.open(o.method.toUpperCase(),o.url,!0),m.timeout=o.timeout;function T(I){if(!m)return;if(m.status===0&&(vi(qc(o.url))||vi(Ee.origin))!=="file"&&!(m.responseURL&&m.responseURL.startsWith("file:"))){s(new C("Request aborted",C.ECONNABORTED,r,m)),S(),m=null;return}try{I?_&&_(I):w&&w()}catch(re){setTimeout(()=>{throw re})}if(!m)return;const P=Ae.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),z={data:!u||u==="text"||u==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:P,config:r,request:m};Vc(function($){t($),S()},function($){s($),S()},z),m=null}if("onloadend"in m?m.onloadend=T:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.startsWith("file:"))||setTimeout(T)},m.onabort=function(){m&&(s(new C("Request aborted",C.ECONNABORTED,r,m)),S(),m=null)},m.onerror=function(P){const D=P&&P.message?P.message:"Network Error",z=new C(D,C.ERR_NETWORK,r,m);z.event=P||null,s(z),S(),m=null},m.ontimeout=function(){if(!m)return;let P=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const D=o.transitional||bi;o.timeoutErrorMessage&&(P=o.timeoutErrorMessage),s(new C(P,D.clarifyTimeoutError?C.ETIMEDOUT:C.ECONNABORTED,r,m)),S(),m=null},a===void 0&&c.setContentType(null),b.isUndefined(o.withCredentials)||(m.withCredentials=!!o.withCredentials),u&&u!=="json"&&(m.responseType=o.responseType),h&&([g,w,_]=Ns(h,!0),m.addEventListener("progress",g)),l&&m.upload&&([p,y]=Ns(l),m.upload.addEventListener("progress",p),m.upload.addEventListener("loadend",y)),o.cancelToken||o.signal){if(d=I=>{if(!m)return;s(!I||I.type?new Wr(null,r,m):I);const P=m;S(),m=null,P.abort()},o.cancelToken&&o.cancelToken.subscribe(d),!m)return;o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d))}if(!m)return;const E=vi(o.url);if(E&&!Ee.protocols.includes(E)){s(new C("Unsupported protocol "+E+":",C.ERR_BAD_REQUEST,r)),S();return}const v=()=>{m&&("setRequestHeader"in m&&b.forEach(Tc(c),function(P,D){m.setRequestHeader(D,P)}),m.send(a||null))};if(i){const I=typeof performance<"u"&&b.isFunction(performance.now)?()=>performance.now():Date.now,P=m.timeout>0?I()+Number(m.timeout):void 0,D=()=>{if(!m)return;const z=m;z.ontimeout(),z.abort()};if(P!==void 0){const z=()=>{const re=P-I();re>0?f=setTimeout(z,Math.min(re,2147483647)):D()};z()}Wc.readAsync(i).then(z=>{if(m){if(P!==void 0&&I()>=P){D();return}if(z){const re=b.hasOwnProp(o,"xsrfHeaderName")&&o.xsrfHeaderName;c.set(re,z)}v()}}).catch(z=>{m&&(s(C.from(z,null,r,m)),S(),m=null)})}else v()})},bg=(r,e)=>{if(r=r?r.filter(Boolean):[],!e&&!r.length)return;const t=new AbortController;let s=!1;const n=function(c){if(!s){s=!0,o();const u=c instanceof Error?c:this.reason;t.abort(u instanceof C?u:new Wr(u instanceof Error?u.message:u))}};let i=e&&setTimeout(()=>{i=null,n(new C(`timeout of ${e}ms exceeded`,C.ETIMEDOUT))},e);const o=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(c=>{const u=b.getSafeProp(c,"unsubscribe");b.isFunction(u)?u.call(c,n):c.removeEventListener("abort",n)}),r=null)};r.forEach(c=>{if(!s){if(c.aborted){n.call(c);return}c.addEventListener("abort",n,{once:!0})}});const{signal:a}=t;return a.unsubscribe=()=>b.asap(o),a},Sg=function*(r,e){let t=r.byteLength;if(t<e){yield r;return}let s=0,n;for(;s<t;)n=s+e,yield r.slice(s,n),s=n},Eg=async function*(r,e){for await(const t of Tg(r))yield*Sg(t,e)},Tg=async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const e=r.getReader();try{for(;;){const{done:t,value:s}=await e.read();if(t)break;yield s}}finally{await e.cancel()}},tl=(r,e,t,s)=>{const n=Eg(r,e);let i=0,o,a=c=>{o||(o=!0,s&&s(c))};return new ReadableStream({async pull(c){try{const{done:u,value:l}=await n.next();if(u){a(),c.close();return}let h=l.byteLength;if(t){let d=i+=h;t(d)}c.enqueue(new Uint8Array(l))}catch(u){throw a(u),u}},cancel(c){return a(c),n.return()}},{highWaterMark:2})},Lt=`\r
`,rl=r=>String(r).replace(/\r\n|\r|\n/g,Lt),sl=r=>String(r).replace(/[\r\n"]/g,e=>e==="\r"?"%0D":e===`
`?"%0A":"%22"),zr=(r,e)=>{let t=0;for(let s=0;s<r.length;s++){const n=r.charCodeAt(s);e&&(n===13||n===10)?(n===13&&r.charCodeAt(s+1)===10&&s++,t+=2):n<128?t++:n<2048?t+=2:n>=55296&&n<=56319&&r.charCodeAt(s+1)>=56320&&r.charCodeAt(s+1)<=57343?(t+=4,s++):t+=3}return t};class Ds extends TypeError{constructor(e,t){super(e),this.name="FormDataError",this.reason=t}}function vg(r,e,t,s,n){if(!b.isFunction(e))throw new Ds("Blob is not supported","blob");if(!b.isString(n)||!/^[A-Za-z0-9'()+_,./:=? -]{1,70}$/.test(n)||/ $/.test(n))throw new Ds("Invalid multipart boundary","boundary");const i="--"+n+"--"+Lt;let o=i.length;const a=[],c=l=>{if(o+l>t)throw s()};c(0);for(const[l,h]of r){const d=b.isString(h),f=d?zr(h,!0):h.size;if(!Number.isFinite(f)||f<0)throw new Ds("Unsupported FormData part size","part");c(f+zr(l,!0)+(!d&&h.name?zr(h.name,!1):0)+(!d&&h.type?zr(h.type,!1):0));let p="--"+n+Lt+'Content-Disposition: form-data; name="'+sl(rl(l))+'"';d||(p+='; filename="'+sl(b.isString(h.name)?h.name:"blob")+'"'+Lt+"Content-Type: "+String(h.type||"application/octet-stream").replace(/[\r\n]/g,"")),p+=Lt+Lt;const g=zr(p,!1)+f+Lt.length;c(g),o+=g,a.push({header:p,value:h,isString:d})}const u=[];for(const l of a)u.push(l.header,l.isString?rl(l.value):l.value,Lt);return u.push(i),new e(u,{type:"multipart/form-data; boundary="+n})}function Og(r,e,t,s,n){if(!b.isFunction(e))throw new C("Blob is not supported",C.ERR_NOT_SUPPORT);if(n===void 0)if(b.isFunction(Ee.generateString))n="axios-"+Ee.generateString(36,"0123456789abcdef");else{const i=b.global.crypto;if(!i||!b.isFunction(i.getRandomValues))throw new C("Random byte generation is not supported",C.ERR_NOT_SUPPORT);const o=new Uint8Array(18);i.getRandomValues(o),n="axios-"+Array.from(o,a=>("0"+a.toString(16)).slice(-2)).join("")}try{return vg(r,e,t,s,n)}catch(i){if(i instanceof Ds){const o=i.reason==="boundary"?C.ERR_BAD_OPTION_VALUE:C.ERR_BAD_REQUEST;throw new C(i.message,o)}throw i}}const nl=r=>r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102,il=(r,e,t)=>e+2<t&&nl(r.charCodeAt(e+1))&&nl(r.charCodeAt(e+2)),ol=r=>r<=57?r-48:(r&223)-55,Ag=r=>r>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||r===43||r===47||r===45||r===95,Ig=r=>r===9||r===10||r===12||r===13||r===32,kg=r=>{const e=Math.floor(r/4),t=r%4;return e*3+(t===2?1:t===3?2:0)},Rg=r=>{const e=r.length;let t=0;return e>0&&r.charCodeAt(e-1)===61&&(t++,e>1&&r.charCodeAt(e-2)===61&&t++),Math.floor((e-t)*3/4)},Cg=r=>{const e=r.length;let t=0,s=0,n=!1;for(let i=0;i<e;i++){let o=r.charCodeAt(i);if(o===37&&il(r,i,e)&&(o=ol(r.charCodeAt(i+1))*16+ol(r.charCodeAt(i+2)),i+=2),!Ig(o)){if(o===61){s++;continue}if(!Ag(o)||s>0){n=!0;continue}t++}}return n||s>2||s>0&&(t+s)%4!==0||t%4===1?Rg(r):kg(t)},Ng=(r,e,t)=>{if(!r||typeof r!="string"||!/^data:/i.test(r))return 0;const s=r.indexOf(",");if(s<0)return 0;const n=r.slice(5,s),i=r.slice(s+1);if(t.test(n))return e(i);let a=0;for(let c=0,u=i.length;c<u;c++){const l=i.charCodeAt(c);if(l===37&&il(i,c,u))a+=1,c+=2;else if(l<128)a+=1;else if(l<2048)a+=2;else if(l>=55296&&l<=56319&&c+1<u){const h=i.charCodeAt(c+1);h>=56320&&h<=57343?(a+=4,c++):a+=3}else a+=3}return a};function Dg(r){const e=typeof r=="string"?r.indexOf("#"):-1;return Ng(e===-1?r:r.slice(0,e),Cg,/; *base64[\t\n\f\r ]*$/i)}const ki="1.21.1",al=64*1024,cl={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:Ls}=b,Lg=r=>encodeURIComponent(r).replace(/%([0-9A-F]{2})/gi,(e,t)=>String.fromCharCode(parseInt(t,16))),ll=r=>{if(!b.isString(r))return r;try{return decodeURIComponent(r)}catch{return r}},Ms=(r,...e)=>{try{return!!r(...e)}catch{return!1}},Mg=r=>{const e=r.indexOf("://");let t=r;return e!==-1&&(t=t.slice(e+3)),t.includes("@")||t.includes(":")},Pg=r=>{const e=b.global!==void 0&&b.global!==null?b.global:globalThis,{ReadableStream:t,TextEncoder:s}=e;r=b.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response,Blob:e.Blob},r);const n=b.hasOwnProp(r,"fetch")?r.fetch:void 0,{Request:i,Response:o,Blob:a}=r,c=n?Ls(n):typeof fetch=="function",u=Ls(i),l=Ls(o);if(!c)return!1;const h=c&&Ls(t),d=c&&(typeof s=="function"?(S=>m=>S.encode(m))(new s):async S=>new Uint8Array(await new i(S).arrayBuffer())),f=u&&h&&Ms(()=>{let S=!1;const m=new i(Ee.origin,{body:new t,method:"POST",get duplex(){return S=!0,"half"}}),T=m.headers.has("Content-Type");return m.body!=null&&m.body.cancel(),S&&!T}),p=l&&h&&Ms(()=>b.isReadableStream(new o("").body)),g=Object.assign(Object.create(null),cl);u&&!Ms(()=>new i(Ee.origin,g))&&(delete g.cache,Ms(()=>new i(Ee.origin,g))||(g.cache=cl.cache));const y={stream:p&&(S=>S.body)};c&&["text","arrayBuffer","blob","formData","stream"].forEach(S=>{!y[S]&&(y[S]=(m,T)=>{let E=m&&m[S];if(E)return E.call(m);throw new C(`Response type '${S}' is not supported`,C.ERR_NOT_SUPPORT,T)})});const w=async S=>{if(S==null)return 0;if(b.isBlob(S))return S.size;if(b.isArrayBufferView(S)||b.isArrayBuffer(S))return S.byteLength;if(b.isURLSearchParams(S)&&(S=S+""),b.isString(S))return(await d(S)).byteLength},_=async(S,m)=>{const T=b.toFiniteNumber(S.getContentLength());return T??w(m)};return async S=>{let{url:m,method:T,data:E,signal:v,cancelToken:I,timeout:P,onDownloadProgress:D,onUploadProgress:z,responseType:re,headers:$,withCredentials:ee="same-origin",fetchOptions:U,maxContentLength:le,maxBodyLength:ue,maxRedirects:j}=el(S);const We=b.isNumber(le)&&le>-1,Ze=b.isNumber(ue)&&ue>-1,lt=se=>b.hasOwnProp(S,se)?S[se]:void 0;let J=n||fetch;re=re?(re+"").toLowerCase():"text";let X=bg([v,I&&I.toAbortSignal()],P),G=null;const ae=X&&X.unsubscribe&&(()=>{X.unsubscribe()});let pe,ve=null,q=null;const Xe=()=>new C("Request body larger than maxBodyLength limit",C.ERR_BAD_REQUEST,S,G);try{let se;const Be=lt("auth");if(Be){const Y=b.getSafeProp(Be,"username")||"",Ne=b.getSafeProp(Be,"password")||"";se={username:Y,password:Ne}}let Ue;if(Mg(m)){if(Ue=new URL(m,Ee.origin),!se&&(Ue.username||Ue.password)){const Y=ll(Ue.username),Ne=ll(Ue.password);se={username:Y,password:Ne}}(Ue.username||Ue.password)&&(Ue.username="",Ue.password="",m=Ue.href)}if(se&&($.delete("authorization"),$.set("Authorization","Basic "+btoa(Lg((se.username||"")+":"+(se.password||""))))),We&&Ue&&Ue.protocol==="data:"&&Dg(Ue.href)>le)throw new C("maxContentLength size of "+le+" exceeded",C.ERR_BAD_RESPONSE,S,G);const ut=b.isSpecCompliantForm(E)&&Ae.from(lt("headers")).getContentType();let _r;if(b.isString(ut)&&/^multipart\/form-data(?:\s*;|$)/i.test(ut.trim())){const Y=Ae.parseParameters(ut);b.hasOwnProp(Y,"boundary")&&(_r=Y.boundary)}if(b.isSpecCompliantForm(E)&&T!=="get"&&T!=="head"&&(Ze||z&&f||_r!==void 0)&&(E=Og(E,a,Ze?ue:1/0,Xe,_r),$.setContentType(_r===void 0?E.type:ut),pe=E.size),Ze&&T!=="get"&&T!=="head"){const Y=await w(E);if(typeof Y=="number"&&isFinite(Y)&&(pe=Y,Y>ue))throw Xe()}const wr=Ze&&(b.isReadableStream(E)||b.isStream(E)),qs=(Y,Ne,Le)=>tl(Y,al,ft=>{if(Ze&&ft>ue)throw ve=Xe();Ne&&Ne(ft)},Le);if(f&&T!=="get"&&T!=="head"&&(z||wr)){if(pe=pe??await _($,E),pe!==0||wr){let Y=new i(m,{method:"POST",body:E,duplex:"half"}),Ne;if(b.isFormData(E)&&(Ne=Y.headers.get("content-type"))&&$.setContentType(Ne),Y.body){const[Le,ft]=z&&zc(pe,Ns(Jc(z)))||[];E=qs(Y.body,Le,ft)}}}else if(wr&&!u&&h&&T!=="get"&&T!=="head")E=qs(E);else if(wr&&u&&!f&&T!=="get"&&T!=="head")throw new C("Stream request bodies are not supported by the current fetch implementation",C.ERR_NOT_SUPPORT,S,G);b.isString(ee)||(ee=ee?"include":"omit");const Zr=u&&"credentials"in i.prototype;if(b.isFormData(E)){const Y=$.getContentType();Y&&/^multipart\/form-data/i.test(Y)&&!/boundary=/i.test(Y)&&$.delete("content-type")}$.set("User-Agent","axios/"+ki,!1);const we=U==null?U:Object.assign(Object.create(null),U);we&&(delete we.body,delete we.headers,delete we.method,delete we.signal,delete we.duplex,delete we.credentials);const ht=Object.assign(Object.create(null),we,{signal:X,method:T.toUpperCase(),headers:Tc($.normalize()),body:E,duplex:"half",credentials:Zr?ee:void 0});u&&(b.forEach(g,(Y,Ne)=>{ht[Ne]===void 0&&(ht[Ne]=Y)}),ht.signal===void 0&&(ht.signal=null),ht.body===void 0&&(ht.body=null)),j===0&&(ht.redirect="manual",we&&(we.redirect="manual")),G=u&&new i(m,ht);let $e=await(u?J(G,we):J(m,ht));const Hs=Ae.from($e.headers);if(We){const Y=b.toFiniteNumber(Hs.getContentLength());if(Y!=null&&Y>le)throw new C("maxContentLength size of "+le+" exceeded",C.ERR_BAD_RESPONSE,S,G)}const Xr=p&&(re==="stream"||re==="response");if(p&&$e.body&&(D||We||Xr&&ae)){const Y={};["status","statusText","headers"].forEach(Kt=>{Y[Kt]=$e[Kt]});const Ne=b.toFiniteNumber(Hs.getContentLength()),[Le,ft]=D&&zc(Ne,Ns(Jc(D),!0))||[];let Qr=0;const es=Kt=>{if(We&&(Qr=Kt,Qr>le))throw q=new C("maxContentLength size of "+le+" exceeded",C.ERR_BAD_RESPONSE,S,G);Le&&Le(Kt)};$e=new o(tl($e.body,al,es,()=>{ft&&ft(),ae&&ae()}),Y)}re=re||"text";let dt=await y[b.findKey(y,re)||"text"]($e,S);if(We&&!p&&!Xr){let Y;if(dt!=null&&(typeof dt.byteLength=="number"?Y=dt.byteLength:typeof dt.size=="number"?Y=dt.size:typeof dt=="string"&&(Y=typeof s=="function"?new s().encode(dt).byteLength:dt.length)),typeof Y=="number"&&Y>le)throw new C("maxContentLength size of "+le+" exceeded",C.ERR_BAD_RESPONSE,S,G)}return!Xr&&ae&&ae(),await new Promise((Y,Ne)=>{Vc(Y,Ne,{data:dt,headers:Ae.from($e.headers),status:$e.status,statusText:$e.statusText,config:S,request:G})})}catch(se){if(ae&&ae(),X&&X.aborted&&X.reason instanceof C){const Be=X.reason;throw Be.config=S,G&&(Be.request=G),se!==Be&&Object.defineProperty(Be,"cause",{__proto__:null,value:se,writable:!0,enumerable:!1,configurable:!0}),Be}if(ve)throw G&&!ve.request&&(ve.request=G),ve;if(q)throw q;if(se instanceof C)throw G&&!se.request&&(se.request=G),se;if(se&&se.name==="TypeError"&&/Load failed|fetch/i.test(se.message)){const Be=new C("Network Error",C.ERR_NETWORK,S,G,se&&se.response);throw Object.defineProperty(Be,"cause",{__proto__:null,value:se.cause||se,writable:!0,enumerable:!1,configurable:!0}),Be}throw C.from(se,se&&se.code,S,G,se&&se.response)}}},xg=new Map,ul=r=>{const e=Object.create(null),t=r&&b.hasOwnProp(r,"env")&&r.env;["fetch","Request","Response","Blob"].forEach(f=>{t&&b.hasOwnProp(t,f)&&(e[f]=t[f])});const{fetch:s,Request:n,Response:i,Blob:o}=e,a=[n,i,s,o];let c=a.length,u=c,l,h,d=xg;for(;u--;)l=a[u],h=d.get(l),h===void 0&&d.set(l,h=u?new Map:Pg(e)),d=h;return h};ul();const Ri={http:qp,xhr:wg,fetch:{get:ul}};b.forEach(Ri,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(r,"adapterName",{__proto__:null,value:e})}});const hl=r=>`- ${r}`,Fg=r=>b.isFunction(r)||r===null||r===!1;function Bg(r,e){r=b.isArray(r)?r:[r];const{length:t}=r;let s,n;const i={};for(let o=0;o<t;o++){s=r[o];let a;if(n=s,!Fg(s)&&(n=Ri[(a=String(s)).toLowerCase()],n===void 0))throw new C(`Unknown adapter '${a}'`);if(n&&(b.isFunction(n)||(n=n.get(e))))break;i[a||"#"+o]=n}if(!n){const o=Object.entries(i).map(([c,u])=>`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build"));let a=t?o.length>1?`since :
`+o.map(hl).join(`
`):" "+hl(o[0]):"as no adapter specified";throw new C("There is no suitable adapter to dispatch the request "+a,C.ERR_NOT_SUPPORT)}return n}const dl={getAdapter:Bg,adapters:Ri};function Ci(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Wr(null,r)}function $g(){return typeof performance<"u"&&b.isFunction(performance.now)?()=>performance.now():Date.now}function fl(r,e){return Math.max(0,Math.round(r()-e))}function Ni(r){const e=b.toSafeFlatObject(r);Ci(e),e.headers=Ae.from(b.getSafeProp(e,"headers")),e.data=Ti.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1);const t=dl.getAdapter(e.adapter||Hr.adapter,e),s=$g(),n=s();return t(e).then(function(o){Ci(e),o.duration=fl(s,n),e.response=o;try{o.data=Ti.call(e,e.transformResponse,o)}finally{delete e.response}return o.headers=Ae.from(o.headers),o},function(o){if(!Uc(o)&&(Ci(e),o&&o.response)){o.response.duration=fl(s,n),e.response=o.response;try{o.response.data=Ti.call(e,e.transformResponse,o.response)}finally{delete e.response}o.response.headers=Ae.from(o.response.headers)}return Promise.reject(o)})}const Ps={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{Ps[r]=function(s){return typeof s===r||"a"+(e<1?"n ":" ")+r}});const pl={};Ps.transitional=function(e,t,s){function n(i,o){return"[Axios v"+ki+"] Transitional option '"+i+"'"+o+(s?". "+s:"")}return(i,o,a)=>{if(e===!1)throw new C(n(o," has been removed"+(t?" in "+t:"")),C.ERR_DEPRECATED);return t&&!pl[o]&&(pl[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(i,o,a):!0}},Ps.spelling=function(e){return(t,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)};function jg(r,e,t){if(typeof r!="object"||r===null)throw new C("options must be an object",C.ERR_BAD_OPTION_VALUE);const s=Object.keys(r);let n=s.length;for(;n-- >0;){const i=s[n],o=Object.prototype.hasOwnProperty.call(e,i)?e[i]:void 0;if(o){const a=r[i],c=a===void 0||o(a,i,r);if(c!==!0)throw new C("option "+i+" must be "+c,C.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new C("Unknown option "+i,C.ERR_BAD_OPTION)}}const xs={assertOptions:jg,validators:Ps},Re=xs.validators,Di=r=>{if(r==null||b.isPlainObject(r)||r instanceof Ae)return!0;try{return b.isObject(r)&&b.getSafeProp(r,Symbol.toStringTag)==="AxiosHeaders"&&["toJSON","set","get","has","delete","clear","normalize","concat","toString",Symbol.iterator].every(e=>b.isFunction(b.getSafeProp(r,e)))}catch{return!1}};let zt=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Mc,response:new Mc}}async request(e,t){try{return await this._request(e,t)}catch(s){if(s instanceof Error)try{let n={};Error.captureStackTrace?Error.captureStackTrace(n):n=new Error;const i=n.stack;let o="";if(typeof i=="string"){const a=i.indexOf(`
`);o=a===-1?"":i.slice(a+1)}if(!s.stack)s.stack=o;else if(o){const a=o.indexOf(`
`),c=a===-1?-1:o.indexOf(`
`,a+1),u=c===-1?o:o.slice(c+1),l=String(s.stack),h=Up(s,l),d=h===-1?l:l.slice(0,h),f=h===-1?"":l.slice(h);d.endsWith(u)||(s.stack=d+`
`+o+f)}}catch{}throw s}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Wt(this.defaults,t);const{transitional:s,paramsSerializer:n,headers:i}=t;s!==void 0&&xs.assertOptions(s,{silentJSONParsing:Re.transitional(Re.boolean),forcedJSONParsing:Re.transitional(Re.boolean),clarifyTimeoutError:Re.transitional(Re.boolean),legacyInterceptorReqResOrdering:Re.transitional(Re.boolean),advertiseZstdAcceptEncoding:Re.transitional(Re.boolean),validateStatusUndefinedResolves:Re.transitional(Re.boolean),encodeBasicAuthUsername:Re.transitional(Re.boolean)},!1),n!=null&&(b.isFunction(n)?t.paramsSerializer={serialize:n}:xs.assertOptions(n,{encode:Re.function,serialize:Re.function},!0)),t.allowAbsoluteUrls!==void 0||(b.hasOwnProp(this.defaults,"allowAbsoluteUrls")&&this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),xs.assertOptions(t,{baseUrl:Re.spelling("baseURL"),withXsrfToken:Re.spelling("withXSRFToken")},!0),t.method=(b.getSafeProp(t,"method")||b.getSafeProp(this.defaults,"method")||"get").toLowerCase();const o=b.getSafeProp(i,"common"),a=b.getSafeProp(i,t.method),c=i&&b.merge(Di(o)?o:void 0,Di(a)?a:void 0);i&&b.forEach(jc.concat("common"),y=>{Di(b.getSafeProp(i,y))&&delete i[y]}),t.headers=Ae.concat(c,i);const u=[];let l=!0;this.interceptors.request.forEach(function(w){if(typeof w.runWhen=="function"&&w.runWhen(t)===!1)return;l=l&&w.synchronous;const _=t.transitional||bi;_&&_.legacyInterceptorReqResOrdering?u.unshift(w.fulfilled,w.rejected):u.push(w.fulfilled,w.rejected)});const h=[];this.interceptors.response.forEach(function(w){h.push(w.fulfilled,w.rejected)});let d,f=0,p;if(!l){const y=[Ni.bind(this),void 0];for(y.unshift(...u),y.push(...h),p=y.length,d=Promise.resolve(t);f<p;)d=d.then(y[f++],y[f++]);return d}p=u.length;let g=t;for(;f<p;){const y=u[f++],w=u[f++];try{g=y?y(g):g}catch(_){if(!w){d=Promise.reject(_);break}try{const S=w.call(this,_);b.isThenable(S)&&(d=Promise.resolve(S).then(()=>Ni.call(this,g)))}catch(S){d=Promise.reject(S)}break}}if(!d)try{d=Ni.call(this,g)}catch(y){d=Promise.reject(y)}for(f=0,p=h.length;f<p;)d=d.then(h[f++],h[f++]);return d}getUri(e){e=Wt(this.defaults,e);const t=Gc(e.baseURL,e.url,e.allowAbsoluteUrls,e);return Nc(t,e.params,e.paramsSerializer)}};b.forEach(["delete","get","head","options"],function(e){zt.prototype[e]=async function(t,s){return this.request(Wt(s||{},{method:e,url:t,data:s&&b.hasOwnProp(s,"data")?s.data:void 0}))}}),b.forEach(["post","put","patch","query"],function(e){function t(s){return async function(i,o,a){return this.request(Wt(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}zt.prototype[e]=t(),e!=="query"&&(zt.prototype[e+"Form"]=t(!0))});let Ug=class uu{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(i){t=i});const s=this;this.promise.then(n=>{if(!s._listeners)return;let i=s._listeners.length;for(;i-- >0;)s._listeners[i](n);s._listeners=null}),this.promise.then=n=>{let i;const o=new Promise(a=>{s.subscribe(a),i=a}).then(n);return o.cancel=function(){s.unsubscribe(i)},o},e(function(i,o,a){s.reason||(s.reason=new Wr(i,o,a),t(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=s=>{e.abort(s)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new uu(function(n){e=n}),cancel:e}}};function Vg(r){return function(t){return r.apply(null,t)}}function qg(r){return b.isObject(r)&&r.isAxiosError===!0}const Fs={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Fs).forEach(([r,e])=>{Fs[e]===void 0&&(Fs[e]=r)});function gl(r){const e=new zt(r),t=fc(zt.prototype.request,e);return b.extend(t,zt.prototype,e,{allOwnKeys:!0}),b.extend(t,e,null,{allOwnKeys:!0}),t.create=function(n){return gl(Wt(r,n))},t}const _e=gl(Hr);_e.Axios=zt,_e.CanceledError=Wr,_e.CancelToken=Ug,_e.isCancel=Uc,_e.VERSION=ki,_e.toFormData=Cs,_e.AxiosError=C,_e.Cancel=_e.CanceledError,_e.all=function(e){return Promise.all(e)},_e.spread=Vg,_e.isAxiosError=qg,_e.mergeConfig=Wt,_e.AxiosHeaders=Ae,_e.formToJSON=r=>$c(b.isHTMLForm(r)?new FormData(r):r),_e.getAdapter=dl.getAdapter,_e.HttpStatusCode=Fs,_e.default=_e;const{Axios:Dy,AxiosError:Li,CanceledError:Ly,isCancel:My,CancelToken:Py,VERSION:xy,all:Fy,Cancel:By,isAxiosError:$y,spread:jy,toFormData:Uy,AxiosHeaders:Vy,HttpStatusCode:qy,formToJSON:Hy,getAdapter:Wy,mergeConfig:zy,create:Jy}=_e,Hg="X-Request-ID",Wg="bx24_request_id",zg="bx24_sdk_ver",Jg="bx24_sdk_type";class Kg{getQueryStringParameterName(){return Wg}getQueryStringSdkParameterName(){return zg}getQueryStringSdkTypeParameterName(){return Jg}generate(){return An()}getRequestId(){return this.generate()}getHeaderFieldName(){return Hg}}const ml=["adapter","timeout","timeoutErrorMessage","proxy","httpAgent","httpsAgent","maxRedirects","maxContentLength","maxBodyLength","decompress","withCredentials"];function Gg(r){const e={},t=[];if(!r)return{picked:e,dropped:t};for(const[s,n]of Object.entries(r)){if(ml.includes(s)){e[s]=n;continue}s!=="headers"&&t.push(s)}return{picked:e,dropped:t}}const Yg=300,Zg=100;function Mi(r){const e=typeof r=="string"?r:String(r);return e.length>Yg?e.slice(0,Zg)+"...":e}const yl="Idempotency-Key",Xg="idempotency-key",Qg="idempotent-replayed",em=/^[\u0021-\u007E]{1,255}$/;function tm(r){if(r===null||typeof r!="object")return;let e,t;for(const[s,n]of Object.entries(r)){const i=s.toLowerCase(),o=Array.isArray(n)?n[0]:n;Xg===i&&typeof o=="string"?e=o:Qg===i&&(t=o===!0||String(o).trim().toLowerCase()==="true")}if(!(e===void 0&&t===void 0))return{key:e,replayed:t??!1}}function Pi(){return br()}const _l=new WeakSet;function rm(){return br()?typeof globalThis.fetch=="function"?{adapter:"fetch"}:{}:{}}class wl{_clientAxios;_authActions;_requestIdGenerator;_restrictionManager;_pendingRefresh=null;_logger;_isClientSideWarning=!1;_clientSideWarningMessage="";_version;_metrics={totalRequests:0,successfulRequests:0,failedRequests:0,totalDuration:0,byMethod:new Map,lastErrors:[]};constructor(e,t,s){this._version=K.v2,this._logger=oe.createNullLogger();const n={};this.isServerSide()&&(n["User-Agent"]="b24-js-sdk/3.3.0"),this._authActions=e,this._requestIdGenerator=new Kg;const{picked:i,dropped:o}=Gg(t);this._clientAxios=_e.create({timeout:3e4,timeoutErrorMessage:"Request timeout exceeded",...rm(),...i,headers:{...n,...t?.headers??{}}}),o.length>0&&!_l.has(t)&&(_l.add(t),oe.forcedLog(this._logger,"warning","httpOptions: keys not accepted at construction were dropped",{dropped:o.join(", "),accepted:ml.join(", "),hint:"set them on getHttpClient(version).ajaxClient.defaults instead"}).catch(()=>{}));const a={...xr.getDefault(),...s};this._restrictionManager=new lr(a)}get apiVersion(){return this._version}get ajaxClient(){return this._clientAxios}setLogger(e){this._logger=e,this._restrictionManager.setLogger(this._logger)}getLogger(){return this._logger}async setRestrictionManagerParams(e){await this._restrictionManager.setConfig(e)}getRestrictionManagerParams(){return this._restrictionManager.getParams()}getStats(){return{...this._restrictionManager.getStats(),totalRequests:this._metrics.totalRequests,successfulRequests:this._metrics.successfulRequests,failedRequests:this._metrics.failedRequests,totalDuration:this._metrics.totalDuration,byMethod:this._metrics.byMethod,lastErrors:this._metrics.lastErrors}}async reset(){return this._metrics.totalRequests=0,this._metrics.successfulRequests=0,this._metrics.failedRequests=0,this._metrics.totalDuration=0,this._metrics.byMethod.clear(),this._metrics.lastErrors=[],this._restrictionManager.reset()}_updateMetrics(e,t,s,n){this._metrics.totalRequests++,t?this._metrics.successfulRequests++:(this._metrics.failedRequests++,n instanceof ye&&(this._metrics.lastErrors.push({method:e,error:n.message,timestamp:Date.now()}),this._metrics.lastErrors.length>100&&(this._metrics.lastErrors=this._metrics.lastErrors.slice(-100)))),this._metrics.byMethod.has(e)||this._metrics.byMethod.set(e,{count:0,totalDuration:0});const i=this._metrics.byMethod.get(e);i.count++,i.totalDuration+=s}_validateParams(e,t,s){try{JSON.stringify(s)}catch(n){throw new ye({code:"JSSDK_INVALID_PARAMS",description:"Parameters contain circular references",status:400,requestInfo:{method:t,params:s,requestId:e},originalError:n})}}async call(e,t,s,n){s=s??this._requestIdGenerator.getRequestId();const i=this._restrictionManager.getParams().maxRetries;this._validateParams(s,e,t),this._logRequest(s,e,t);const o=this._prepareRequestConfig(s,e,n);let a=null;const c=Date.now();for(let u=0;u<i;u++)try{this._logAttempt(s,e,u+1,i),await this._restrictionManager.applyOperatingLimits(s,e,t);const l=await this._executeSingleCall(s,e,t,o),h=Date.now()-c;return this._restrictionManager.resetErrors(e),this._updateMetrics(e,!0,h),this._logSuccessfulRequest(s,e,h),l}catch(l){a=this._convertToAjaxError(s,l,e,t);const h=Date.now()-c;if(this._restrictionManager.incrementError(e),this._updateMetrics(e,!1,h,a),this._logFailedRequest(s,e,u+1,i,a),u+1<i){const d=await this._restrictionManager.handleError(s,e,t,a,u);if(d>0){this._restrictionManager.incrementStats("limitHits"),this._logAttemptRetryWaiteDelay(s,e,d,u+1,i),await this._restrictionManager.waiteDelay(d),this._restrictionManager.incrementStats("retries");continue}}if(u+1===i&&this._logAllAttemptsExhausted(s,e,u+1,i),this._restrictionManager.isSoftError(a))return this._createAjaxResultWithErrorFromResponse(a,s,e,t);throw a}throw new ye({code:"JSSDK_CALL_ALL_ATTEMPTS_EXHAUSTED",description:"All attempts exhausted",status:a?.status||500,requestInfo:{method:e,params:t,requestId:s},originalError:a?.originalError||null})}_convertToAjaxError(e,t,s,n){return t instanceof ye?t:t instanceof Li?this._convertAxiosErrorToAjaxError(e,t,s,n):this._convertUnknownErrorToAjaxError(e,t,s,n)}_convertAxiosErrorToAjaxError(e,t,s,n){const i=`${t.code||"JSSDK_AXIOS_ERROR"}`,o=t.message,a=t.response?.status||0;if(i==="ERR_NETWORK")return new ye({code:"NETWORK_ERROR",description:"Network connection failed",status:0,requestInfo:{method:s,params:n,requestId:e},originalError:t});if(i==="ECONNABORTED"||t.message.includes("timeout"))return new ye({code:"REQUEST_TIMEOUT",description:"Request timeout exceeded",status:408,requestInfo:{method:s,params:n,requestId:e},originalError:t});const c=Ha(t.response?.data,i,o);return new ye({code:c?.code??i,description:c?.description??o,status:a,validation:c?.validation,isV3Envelope:c?.isV3Envelope,requestInfo:{method:s,params:n,requestId:e},originalError:t})}_convertUnknownErrorToAjaxError(e,t,s,n){return new ye({code:"JSSDK_UNKNOWN_ERROR",description:t instanceof Error?t.message:String(t),status:0,requestInfo:{method:s,params:n,requestId:e},originalError:t})}async _executeSingleCall(e,t,s,n){this._checkClientSideWarning(e);const i=await this._ensureAuth(e),o=await this._makeRequestWithAuthRetry(e,t,s,i,n);return this._createAjaxResultFromResponse(o,e,t,s)}async _ensureAuth(e){let t=this._authActions.getAuthData();return t===!1&&(this._logRefreshingAuthToken(e),t=await this._refreshAuth()),t}_refreshAuth(){if(this._pendingRefresh)return this._pendingRefresh;const e=this._authActions.refreshAuth();return this._pendingRefresh=e,e.finally(()=>{this._pendingRefresh=null}).catch(()=>{}),e}async _makeRequestWithAuthRetry(e,t,s,n,i){try{return await this._restrictionManager.checkRateLimit(e,t),await this._makeAxiosRequest(e,t,s,n,i)}catch(o){o instanceof Li&&this.getLogger().info("post/catchError",{requestId:e,status:o.status,responseData:Mi(JSON.stringify(qe(o?.response?.data),null,0))}).catch(()=>{});const a=this._convertToAjaxError(e,o,t,s);if(this._isAuthError(a)){this._logAuthErrorDetected(e),this._logRefreshingAuthToken(e);const c=await this._refreshAuth();return await this._restrictionManager.checkRateLimit(e,t),await this._makeAxiosRequest(e,t,s,c,i)}throw a}}async _makeAxiosRequest(e,t,s,n,i){let o=this._prepareMethod(e,t,this.getBaseUrl());const a=K.v3===this._version&&t==="batch"&&Array.isArray(s),c=n.refresh_token==="hook",u=typeof n.access_token=="string"&&n.access_token.trim().length>0,l=K.v3===this._version&&typeof i?.headers?.[yl]=="string",h=(a||l)&&!c&&u,d=h&&!Pi(),f=h&&Pi(),p=a&&(c||d||f),g=p?s:this._prepareParams(n,s);h&&!p&&delete g.auth;const y={"Content-Type":"application/json"},w=d?{maxRedirects:0,...i,headers:{...y,...i?.headers,Authorization:`Bearer ${n.access_token}`}}:f?{maxRedirects:0,...i,headers:{...y,...i?.headers}}:{...i,headers:{...y,...i?.headers}},_=JSON.stringify(qe(g),null,0);if(this.getLogger().info("post/send",{requestId:e,method:t,params:Mi(_)}).catch(()=>{}),f){const E=o.includes("?")?"&":"?";o+=`${E}auth=${encodeURIComponent(n.access_token)}`}const S=await this._clientAxios.post(o,g,w);if((w?.maxRedirects??this._clientAxios.defaults.maxRedirects)===0&&S.status===0)throw new ye({code:"JSSDK_HTTP_REDIRECT_BLOCKED",description:"This request does not follow redirects (`maxRedirects: 0`) and the answer carried no status of its own \u2014 which is what a refused redirect looks like on the fetch adapter, and what a dropped connection can look like too. The SDK sets `maxRedirects: 0` on a `restApi:v3` batch and on a `restApi:v3` call with `idempotencyKey`, both on a non-hook transport, because they carry an access token a redirect would take along. Point the SDK at the final URL instead.",status:0,requestInfo:{method:t,params:s,requestId:e}});const m=JSON.stringify(qe(S.data?.result),null,0);this.getLogger().info("post/response",{requestId:e,result:Mi(m),time:JSON.stringify(S.data?.time,null,0)}).catch(()=>{});const T=tm(S.headers);return{status:S.status,payload:S.data,...T?{idempotency:T}:{}}}_prepareRequestConfig(e,t,s){const n=s?.idempotencyKey;if(n!==void 0){if(!em.test(n))throw new R({code:"JSSDK_HTTP_INVALID_IDEMPOTENCY_KEY",description:"`idempotencyKey` must be 1-255 printable ASCII characters with no whitespace or control characters. A `crypto.randomUUID()` value satisfies this. See https://apidocs.bitrix24.ru/api-reference/rest-v3.html",status:500});if(K.v3===this._version&&Pi())throw new R({code:"JSSDK_HTTP_IDEMPOTENCY_KEY_BROWSER",description:"`idempotencyKey` cannot be used from a browser: the portal's CORS preflight does not allow the `Idempotency-Key` header, so a cross-origin request carrying it is refused. Make idempotent writes from a server. See https://github.com/bitrix24/b24jssdk/issues/573",status:500});return{headers:{[yl]:n}}}}_isAuthError(e){return e instanceof ye?e.status===401&&["expired_token","invalid_token"].includes(e.code):!1}async _createAjaxResultFromResponse(e,t,s,n){const i=new Pr({answer:e.payload,query:{method:s,params:n,requestId:t},status:e.status,idempotency:e.idempotency});if(i.isSuccess){const o=i.getData()?.time;o&&await this._restrictionManager.updateStats(t,s,o)}return i}_createAjaxResultWithErrorFromResponse(e,t,s,n){return new Pr({answer:{error:{code:e.code,message:e.message}},query:{method:s,params:n,requestId:t},status:e.status,error:e})}_prepareMethod(e,t,s){const n=`/${encodeURIComponent(t)}`;if(/^task\./.test(t))return`${s}${n}`;const i=new URLSearchParams({[this._requestIdGenerator.getQueryStringParameterName()]:e,[this._requestIdGenerator.getQueryStringSdkParameterName()]:"3.3.0",[this._requestIdGenerator.getQueryStringSdkTypeParameterName()]:"b24-js-sdk"});return`${s}${n}?${i.toString()}`}_prepareParams(e,t){const s={...t};if(e.refresh_token!=="hook"&&(s.auth=e.access_token),s?.data&&"start"in s.data){const{start:n,...i}=s.data;s.data=i}return s}setClientSideWarning(e,t){this._isClientSideWarning=e,this._clientSideWarningMessage=t}isServerSide(){return!br()}getBaseUrl(){return this._authActions.getTargetOriginWithPath().get(this._version)}_sanitizeParams(e){return qe(e)}_logRequest(e,t,s){this.getLogger().debug("http request starting",{requestId:e,method:t,params:this._sanitizeParams(s),api:this.apiVersion,timestamp:Date.now()}).catch(()=>{})}_logAttempt(e,t,s,n){this.getLogger().info("http request attempt",{requestId:e,method:t,api:this.apiVersion,attempt:{current:s,max:n}}).catch(()=>{})}_logRefreshingAuthToken(e){this.getLogger().info("http refreshing auth token",{requestId:e,api:this.apiVersion}).catch(()=>{})}_logAuthErrorDetected(e){this.getLogger().info("http auth error detected",{requestId:e,api:this.apiVersion}).catch(()=>{})}_logSuccessfulRequest(e,t,s){this.getLogger().debug("http request successful",{requestId:e,method:t,api:this.apiVersion,duration:{ms:s,sec:Number.parseFloat((s/1e3).toFixed(2))}}).catch(()=>{})}_logFailedRequest(e,t,s,n,i){this.getLogger().debug("http request failed",{requestId:e,method:t,api:this.apiVersion,attempt:{current:s,max:n},error:{code:i.code,message:i.message,status:i.status}}).catch(()=>{})}_logAttemptRetryWaiteDelay(e,t,s,n,i){this.getLogger().debug(`http wait ${(s/1e3).toFixed(2)} sec.`,{requestId:e,method:t,api:this.apiVersion,wait:s,attempt:{current:n,max:i}}).catch(()=>{})}_logAllAttemptsExhausted(e,t,s,n){this.getLogger().warning("http all retry attempts exhausted",{requestId:e,method:t,api:this.apiVersion,attempt:{current:s,max:n}}).catch(()=>{})}_logBatchStart(e,t,s){const n=Array.isArray(t)?t.length:Object.keys(t).length;this.getLogger().debug("http batch request starting ",{requestId:e,callCount:n,api:this.apiVersion,isHaltOnError:s.isHaltOnError,timestamp:Date.now()}).catch(()=>{})}_logBatchCompletion(e,t,s){this.getLogger().debug("http batch request completed",{requestId:e,api:this.apiVersion,totalCalls:t,successful:t-s,failed:s,successRate:t>0?((t-s)/t*100).toFixed(1)+"%":"??"}).catch(()=>{})}_checkClientSideWarning(e){this._isClientSideWarning&&!this.isServerSide()&&L.isStringFilled(this._clientSideWarningMessage)&&oe.forcedLog(this.getLogger(),"warning",this._clientSideWarningMessage,{requestId:e,code:"JSSDK_CLIENT_SIDE_WARNING"})}}const bl=["method","params","as","parallel"];class Sl{parallelDefaultValue;requestId;restrictionManager;logger;processingStrategy;_commands=[];constructor(e){this.parallelDefaultValue=e.parallelDefaultValue,this.requestId=e.requestId,this.restrictionManager=e.restrictionManager,this.processingStrategy=e.processingStrategy,this.logger=e.logger}setProcessingStrategy(e){this.processingStrategy=e}get size(){return this._commands.length}get maxSize(){return 0}addCommands(e){if(!this.processingStrategy)throw new R({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});try{this._warnUnreadCommandKeys(e)}catch{}this._commands=this.processingStrategy.prepareCommands(e,{parallelDefaultValue:this.parallelDefaultValue})}_warnUnreadCommandKeys(e){const t=new Set,s=[];for(const[i,o]of Object.entries(e)){if(!o||typeof o!="object"||Array.isArray(o))continue;const a=Object.keys(o).filter(h=>!bl.includes(h)&&o[h]!==void 0);if(a.length===0)continue;const c=o.params,u=c!==null&&typeof c=="object"&&Object.keys(c).length>0,l=a.some(h=>h.toLowerCase()==="query");u&&!l||(a.forEach(h=>t.add(h)),s.push(i))}if(t.size===0)return;const n=[...t];oe.forcedLog(this.logger??oe.createNullLogger(),"warning",`[b24jssdk] batch command: ${n.join(", ")} ${n.length===1?"is":"are"} ignored \u2014 a command's arguments go in \`params\`. Write \`params: { \u2026 }\`. (\`query\` is the portal's own wire spelling on \`restApi:v3\`, which the SDK writes for you; on \`restApi:v2\` the arguments are serialised into the \`cmd\` querystring instead.)`,{code:"JSSDK_BATCH_UNREAD_COMMAND_KEY",unread:n.join(", "),read:bl.join(", "),commands:s.join(", ")}).catch(()=>{})}getCommandsForCall(){if(!this.processingStrategy)throw new R({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});return this.processingStrategy.buildCommands(this._commands)}}const sm=50;class nm extends Sl{get maxSize(){return sm}async prepareResponse(e){if(!this.processingStrategy)throw new R({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});const t={requestId:e.getQuery().requestId,parallelDefaultValue:this.parallelDefaultValue,restrictionManager:this.restrictionManager,response:e},s=await this.processingStrategy.prepareItems(this._commands,t);return this.processingStrategy.handleResults(this._commands,s,t)}}const im=String.prototype.replace,om=/%20/g,El={RFC1738:"RFC1738",RFC3986:"RFC3986"},am={RFC1738:function(r){return im.call(r,om,"+")},RFC3986:function(r){return String(r)}},cm=El.RFC1738,lm=El.RFC3986,um=Array.isArray,mt=(function(){const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),Bs=1024,hm=function(e,t,s,n){if(e.length===0)return e;let i=e;typeof e=="symbol"?i=Symbol.prototype.toString.call(e):typeof e!="string"&&(i=String(e));let o="";for(let a=0;a<i.length;a+=Bs){let c=i.length>=Bs?i.slice(a,a+Bs):i;if(a+Bs<i.length){const l=c.charCodeAt(c.length-1);l>=55296&&l<=56319&&(c=c.slice(0,-1),a-=1)}const u=[];for(let l=0;l<c.length;++l){let h=c.charCodeAt(l);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===cm&&(h===40||h===41)){u[u.length]=c.charAt(l);continue}if(h<128){u[u.length]=mt[h];continue}if(h<2048){u[u.length]=mt[192|h>>6]+mt[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=mt[224|h>>12]+mt[128|h>>6&63]+mt[128|h&63];continue}l+=1,h=65536+((h&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=mt[240|h>>18]+mt[128|h>>12&63]+mt[128|h>>6&63]+mt[128|h&63]}o+=u.join("")}return o},dm=function(e){return!e||typeof e!="object"?!1:!!(e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))},Tl=function(e,t){if(um(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)},fm={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},Tt=Array.isArray,pm=Array.prototype.push,vl=function(r,e){pm.apply(r,Tt(e)?e:[e])},gm=Date.prototype.toISOString,Ol=lm,$s={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:hm,encodeValuesOnly:!1,format:Ol,formatter:am[Ol],indices:!1,serializeDate:function(e){return gm.call(e)},skipNulls:!1,strictNullHandling:!1},mm=function(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"},xi={},Al=function(e,t,s,n,i,o,a,c,u,l,h,d,f,p,g,y,w){let _=e,S=w,m=0,T=!1;for(;(S=S.get(xi))!==void 0&&!T;){const D=S.get(e);if(m+=1,typeof D<"u"){if(D===m)throw new RangeError("Cyclic object value");T=!0}typeof S.get(xi)>"u"&&(m=0)}if(typeof l=="function"?_=l(t,_):_ instanceof Date?_=f(_):s==="comma"&&Tt(_)&&(_=Tl(_,function(D){return D instanceof Date?f(D):D})),_===null){if(o)return u&&!y?u(t,$s.encoder,"key",p):t;_=""}if(mm(_)||dm(_)){if(u){const D=y?t:u(t,$s.encoder,"key",p);return[g(D)+"="+g(u(_,$s.encoder,"value",p))]}return[g(t)+"="+g(String(_))]}const E=[];if(typeof _>"u")return E;let v;if(s==="comma"&&Tt(_))y&&u&&(_=Tl(_,function(D){return D===null||typeof D>"u"?D:u(D)})),v=[{value:_.length>0?_.join(",")||null:void 0}];else if(Tt(l))v=l;else{const D=Object.keys(_);v=h?D.sort(h):D}const I=c?t.replace(/\./g,"%2E"):t,P=n&&Tt(_)&&_.length===1?I+"[]":I;if(i&&Tt(_)&&_.length===0)return P+"[]";for(let D=0;D<v.length;++D){const z=v[D],re=typeof z=="object"&&typeof z.value<"u"?z.value:_[z];if(a&&re===null)continue;const $=d&&c?z.replace(/\./g,"%2E"):z,ee=Tt(_)?typeof s=="function"?s(P,$):P:P+(d?"."+$:"["+$+"]");w.set(e,m);const U=new WeakMap;U.set(xi,w),vl(E,Al(re,ee,s,n,i,o,a,c,s==="comma"&&y&&Tt(_)?null:u,l,h,d,f,p,g,y,U))}return E},ym=function(e){return $s};function _m(r,e){let t=r;const s=ym();let n,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):Tt(s.filter)&&(i=s.filter,n=i);const o=[];if(typeof t!="object"||t===null)return"";const a=fm[s.arrayFormat],c=a==="comma"&&s.commaRoundTrip;n||(n=Object.keys(t)),s.sort&&n.sort(s.sort);const u=new WeakMap;for(let d=0;d<n.length;++d){const f=n[d];s.skipNulls&&t[f]===null||vl(o,Al(t[f],f,a,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,u))}const l=o.join(s.delimiter),h=s.addQueryPrefix===!0?"?":"";return l.length>0?h+l:""}class Il{async prepareItems(e,t){const s=new Map;return t.response.isSuccess?this._prepareItemsSuccess(e,t,s):s}async handleResults(e,t,s){const n=new Oe;if(!s.response.isSuccess){for(const[i,o]of s.response.errors)n.addError(o,i);return n.setData({result:new Map,time:void 0}),n}return this._handleResultsSuccess(e,t,s,n)}_getBatchResultByIndex(e,t){if(e)return e[t]}_createErrorFromAjaxResult(e){return e.hasError("base-error")?e.errors.get("base-error"):new ye({code:"JSSDK_BATCH_SUB_ERROR",description:e.getErrorMessages().join("; "),status:e.getStatus(),requestInfo:{...e.getQuery()},originalError:e.getErrors().next().value})}}class kl extends Il{_buildRow(e){return`${e.method}?${_m(e.query||{})}`}buildCommands(e){if(e.length<1)throw new R({code:"JSSDK_INTERACTION_BATCH_STRATEGY_V2_EMPTY_COMMANDS",description:"commands not set",status:500});const t=e[0];if(typeof t.as=="string"&&t.as.length>0){const n={};for(const i of e)n[i.as]=this._buildRow(i);return n}const s=[];for(const n of e)s.push(this._buildRow(n));return s}async _prepareItemsSuccess(e,t,s){for(const[n,i]of e.entries())await this._processResponseItem(i,i.as??n,t,s);return s}async _processResponseItem(e,t,s,n){const i=s.response.getData().result,o=this._getBatchResultByIndex(i.result,t),a=this._getBatchResultByIndex(i.result_error,t);if(typeof o<"u"||typeof a<"u"){const c=e.method,u=this._getBatchResultByIndex(i.result_time,t),l=new Pr({answer:{error:a?typeof a=="string"?a:a.error:void 0,error_description:a?typeof a=="string"?void 0:a.error_description:void 0,result:o,total:Number.parseInt(this._getBatchResultByIndex(i.result_total,t)||"0"),next:Number.parseInt(this._getBatchResultByIndex(i.result_next,t)||"0"),time:u},query:{method:c,params:e.query||{},requestId:s.requestId},status:s.response.getStatus()});n.set(t,l);return}if(s.parallelDefaultValue)throw new R({code:"JSSDK_INTERACTION_BATCH_STRATEGY_V2_EMPTY_COMMAND_RESPONSE",description:`There were difficulties parsing the response for batch { index: ${t}, method: ${e.method} }`,status:500})}async _handleResultsSuccess(e,t,s,n){const i=new Map;for(const[o,a]of t){if(a.getStatus()!==200||!a.isSuccess){const c=this._createErrorFromAjaxResult(a);this._processResponseError(n,c,`${o}`),i.set(o,a)}i.set(o,a)}return n.setData({result:i,time:s.response.getData().time}),n}}class wm extends kl{prepareCommands(e,t){const s=[];return e.forEach(n=>{const i=Nt.getBatchCommand(n,t);s.push(i)}),s}_processResponseError(e,t,s){e.addError(t,s)}}class bm extends kl{prepareCommands(e,t){const s=[];return Object.entries(e).forEach(([n,i])=>{const o=Nt.getBatchCommand(i,{...t,asDefaultValue:n});s.push(o)}),s}_processResponseError(e,t,s){e.addError(t,s)}}class js extends wl{constructor(e,t,s){super(e,t,s),this._version=K.v2}_prepareRequestConfig(e,t,s){if(s?.idempotencyKey===void 0)return super._prepareRequestConfig(e,t,s);this.getLogger().warning("http.call: `idempotencyKey` is ignored on `restApi:v2` \u2014 the portal honours `Idempotency-Key` only on the v3 endpoint (`/rest/api/`). Use `b24.actions.v3.call.make()` for an idempotent write, or an application-layer dedup guard if the method exists only on v2.",{requestId:e,method:t}).catch(()=>{});const{idempotencyKey:n,...i}=s;return super._prepareRequestConfig(e,t,i)}async batch(e,t){const s={isHaltOnError:!0,...t},n=s.requestId??this._requestIdGenerator.getRequestId();this._logBatchStart(n,e,s);const i=new nm({requestId:n,parallelDefaultValue:!s.isHaltOnError,restrictionManager:this._restrictionManager,logger:this.getLogger()});if(Array.isArray(e)?i.setProcessingStrategy(new wm):i.setProcessingStrategy(new bm),i.addCommands(e),i.size>i.maxSize)throw new ye({code:"JSSDK_BATCH_TOO_LARGE",description:`Batch too large: ${i.size} commands (max: ${i.maxSize})`,status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});if(i.size===0)throw new ye({code:"JSSDK_BATCH_EMPTY",description:"Batch must contain at least one command",status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});const o={halt:s.isHaltOnError?1:0,cmd:i.getCommandsForCall()},a=await this.call("batch",o,n),c=await i.prepareResponse(a);return this._logBatchCompletion(n,c.getData()?.result?.size??0,c.getErrorMessages().length),c}}const Sm=50;class Em extends Sl{get maxSize(){return Sm}async prepareResponse(e){if(!this.processingStrategy)throw new R({code:"JSSDK_INTERACTION_BATCH_EMPTY_PROCESSING_STRATEGY",description:"ProcessingStrategy not set",status:500});const t={requestId:e.getQuery().requestId,parallelDefaultValue:this.parallelDefaultValue,restrictionManager:this.restrictionManager,response:e},s=await this.processingStrategy.prepareItems(this._commands,t);return this.processingStrategy.handleResults(this._commands,s,t)}}class Rl extends Il{buildCommands(e){if(e.length<1)throw new R({code:"JSSDK_INTERACTION_BATCH_BUILD_STRATEGY_V3_EMPTY_COMMANDS",description:"commands not set",status:500});return e}async _prepareItemsSuccess(e,t,s){for(const[n,i]of e.entries())await this._processResponseItem(i,n,t,s);return s}async _processResponseItem(e,t,s,n){const i=s.response.getData().result,o=this._getBatchResultByIndex(i,t);if(typeof o>"u")throw new R({code:"JSSDK_INTERACTION_BATCH_STRATEGY_V3_EMPTY_COMMAND_RESPONSE",description:`There were difficulties parsing the response for batch { index: ${t}, method: ${e.method} }`,status:500});const a=s.response.getData().time,c=new Pr({answer:{result:o,error:void 0,time:a},query:{method:e.method,params:e.query||{},requestId:s.requestId},status:s.response.getStatus()});n.set(t,c)}async _handleResultsSuccess(e,t,s,n){const i=new Map;for(const[o,a]of t){const c=Number.parseInt(`${o}`),u=e[c];if(typeof u>"u")throw new R({code:"JSSDK_INTERACTION_BATCH_BUILD_STRATEGY_V3_EMPTY_COMMAND",description:`command for index ${o} not set`,status:500});const l=u.as??o;if(a.getStatus()!==200||!a.isSuccess){const h=this._createErrorFromAjaxResult(a);this._processResponseError(n,h,`${l}`),i.set(l,a)}i.set(l,a)}return n.setData({result:i,time:s.response.getData().time}),n}}class Tm extends Rl{prepareCommands(e,t){const s=[];return e.forEach(n=>{const i=Nt.getBatchCommand(n,t);s.push(i)}),s}_processResponseError(e,t,s){e.addError(t,s)}}class vm extends Rl{prepareCommands(e,t){const s=[];return Object.entries(e).forEach(([n,i])=>{const o=Nt.getBatchCommand(i,{...t,asDefaultValue:n});s.push(o)}),s}_processResponseError(e,t,s){e.addError(t,s)}}class Us extends wl{constructor(e,t,s){super(e,t,s),this._version=K.v3}async batch(e,t){const s={isHaltOnError:!0,...t},n=s.requestId??this._requestIdGenerator.getRequestId();this._logBatchStart(n,e,s);const i=new Em({requestId:n,parallelDefaultValue:!s.isHaltOnError,restrictionManager:this._restrictionManager,logger:this.getLogger()});if(Array.isArray(e)?i.setProcessingStrategy(new Tm):i.setProcessingStrategy(new vm),i.addCommands(e),i.size>i.maxSize)throw new ye({code:"JSSDK_BATCH_TOO_LARGE",description:`Batch too large: ${i.size} commands (max: ${i.maxSize})`,status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});if(i.size===0)throw new ye({code:"JSSDK_BATCH_EMPTY",description:"Batch must contain at least one command",status:400,requestInfo:{method:"batch",params:{cmd:e},requestId:n},originalError:null});const o=await this.call("batch",i.getCommandsForCall(),n),a=await i.prepareResponse(o);return this._logBatchCompletion(n,a.getData()?.result?.size??0,a.getErrorMessages().length),a}}const Om=()=>({scrollWidth:Math.max(document.documentElement.scrollWidth,document.documentElement.offsetWidth),scrollHeight:Math.max(document.documentElement.scrollHeight,document.documentElement.offsetHeight)});let Am=class xt{static isInternalConstructing=!1;static instance=null;_defLocale=null;constructor(){if(!xt.isInternalConstructing)throw new TypeError("FormatterNumber is not constructable");xt.isInternalConstructing=!1}static getInstance(){return xt.instance||(xt.isInternalConstructing=!0,xt.instance=new xt),xt.instance}setDefLocale(e){this._defLocale=e}format(e,t){let s;(typeof t>"u"||!L.isStringFilled(t))&&(t=L.isStringFilled(this._defLocale)?this._defLocale||"en":typeof navigator>"u"?"en":navigator?.language||"en"),Number.isInteger(e)?s=new Intl.NumberFormat(t,{minimumFractionDigits:0,maximumFractionDigits:0}):s=new Intl.NumberFormat(t,{minimumFractionDigits:2,maximumFractionDigits:2});let n=s.format(e);return t.includes("ru")&&(n=n.replace(",",".")),n}};class O{countryCode;length;structure;example;_cachedRegex=null;constructor(e,t,s,n){this.countryCode=e,this.length=t,this.structure=s,this.example=n}isValid(e){return this.length===e.length&&this.countryCode===e.slice(0,2)&&this._regex().test(e.slice(4))&&this._iso7064Mod9710(this._iso13616Prepare(e))==1}toBBAN(e,t){return(this._regex().exec(e.slice(4)||"")||[]).slice(1).join(t)}fromBBAN(e){if(!this.isValidBBAN(e))throw new Error("Invalid BBAN");const t=("0"+(98-this._iso7064Mod9710(this._iso13616Prepare(this.countryCode+"00"+e)))).slice(-2);return this.countryCode+t+e}isValidBBAN(e){return this.length-4===e.length&&this._regex().test(e)}_regex(){return this._cachedRegex===null&&(this._cachedRegex=this._parseStructure(this.structure)),this._cachedRegex}_parseStructure(e){const t=(e.match(/(.{3})/g)||[]).map(s=>{let n;const i=s.slice(0,1),o=Number.parseInt(s.slice(1),10);switch(i){case"A":n="0-9A-Za-z";break;case"B":n="0-9A-Z";break;case"C":n="A-Za-z";break;case"F":n="0-9";break;case"L":n="a-z";break;case"U":n="A-Z";break;case"W":n="0-9a-z";break}return"(["+n+"]{"+o+"})"});return new RegExp("^"+t.join("")+"$")}_iso13616Prepare(e){return e=e.toUpperCase(),e=e.substring(4)+e.substring(0,4),e.split("").map(t=>{const s=t.charCodeAt(0);return s>=65&&s<=90?(s-65+10).toString():t}).join("")}_iso7064Mod9710(e){let t=e,s;for(;t.length>2;)s=t.slice(0,9),t=Number.parseInt(s,10)%97+t.slice(s.length);return Number.parseInt(t,10)%97}}class vt{static isInternalConstructing=!1;static instance=null;_countries;constructor(){if(!vt.isInternalConstructing)throw new TypeError("FormatterIban is not constructable");vt.isInternalConstructing=!1,this._countries=new Map}static getInstance(){return vt.instance||(vt.isInternalConstructing=!0,vt.instance=new vt),vt.instance}addSpecification(e){this._countries.set(e.countryCode,e)}isValid(e){if(!L.isString(e))return!1;e=this.electronicFormat(e);const t=e.slice(0,2);if(!this._countries.has(t))throw new Error(`No country with code ${t}`);const s=this._countries.get(t);return!!s&&s.isValid(e)}printFormat(e,t){typeof t>"u"&&(t=" ");const s=/(.{4})(?!$)/g;return this.electronicFormat(e).replace(s,"$1"+t)}electronicFormat(e){const t=/[^a-z0-9]/gi;return e.replace(t,"").toUpperCase()}toBBAN(e,t){typeof t>"u"&&(t=" "),e=this.electronicFormat(e);const s=e.slice(0,2);if(!this._countries.has(s))throw new Error(`No country with code ${s}`);const n=this._countries.get(s);if(!n)throw new Error(`No country with code ${s}`);return n.toBBAN(e,t)}fromBBAN(e,t){if(!this._countries.has(e))throw new Error(`No country with code ${e}`);const s=this._countries.get(e);if(!s)throw new Error(`No country with code ${e}`);return s.fromBBAN(this.electronicFormat(t))}isValidBBAN(e,t){if(!L.isString(t))return!1;if(!this._countries.has(e))throw new Error(`No country with code ${e}`);const s=this._countries.get(e);return!!s&&s.isValidBBAN(this.electronicFormat(t))}}const Im=()=>{const r=Am.getInstance(),e=vt.getInstance();return e.addSpecification(new O("AD",24,"F04F04A12","AD1200012030200359100100")),e.addSpecification(new O("AE",23,"F03F16","AE070331234567890123456")),e.addSpecification(new O("AL",28,"F08A16","AL47212110090000000235698741")),e.addSpecification(new O("AT",20,"F05F11","AT611904300234573201")),e.addSpecification(new O("AZ",28,"U04A20","AZ21NABZ00000000137010001944")),e.addSpecification(new O("BA",20,"F03F03F08F02","BA391290079401028494")),e.addSpecification(new O("BE",16,"F03F07F02","BE68539007547034")),e.addSpecification(new O("BG",22,"U04F04F02A08","BG80BNBG96611020345678")),e.addSpecification(new O("BH",22,"U04A14","BH67BMAG00001299123456")),e.addSpecification(new O("BR",29,"F08F05F10U01A01","BR9700360305000010009795493P1")),e.addSpecification(new O("BY",28,"A04F04A16","BY13NBRB3600900000002Z00AB00")),e.addSpecification(new O("CH",21,"F05A12","CH9300762011623852957")),e.addSpecification(new O("CR",22,"F04F14","CR72012300000171549015")),e.addSpecification(new O("CY",28,"F03F05A16","CY17002001280000001200527600")),e.addSpecification(new O("CZ",24,"F04F06F10","CZ6508000000192000145399")),e.addSpecification(new O("DE",22,"F08F10","DE89370400440532013000")),e.addSpecification(new O("DK",18,"F04F09F01","DK5000400440116243")),e.addSpecification(new O("DO",28,"U04F20","DO28BAGR00000001212453611324")),e.addSpecification(new O("EE",20,"F02F02F11F01","EE382200221020145685")),e.addSpecification(new O("EG",29,"F04F04F17","EG800002000156789012345180002")),e.addSpecification(new O("ES",24,"F04F04F01F01F10","ES9121000418450200051332")),e.addSpecification(new O("FI",18,"F06F07F01","FI2112345600000785")),e.addSpecification(new O("FO",18,"F04F09F01","FO6264600001631634")),e.addSpecification(new O("FR",27,"F05F05A11F02","FR1420041010050500013M02606")),e.addSpecification(new O("GB",22,"U04F06F08","GB29NWBK60161331926819")),e.addSpecification(new O("GE",22,"U02F16","GE29NB0000000101904917")),e.addSpecification(new O("GI",23,"U04A15","GI75NWBK000000007099453")),e.addSpecification(new O("GL",18,"F04F09F01","GL8964710001000206")),e.addSpecification(new O("GR",27,"F03F04A16","GR1601101250000000012300695")),e.addSpecification(new O("GT",28,"A04A20","GT82TRAJ01020000001210029690")),e.addSpecification(new O("HR",21,"F07F10","HR1210010051863000160")),e.addSpecification(new O("HU",28,"F03F04F01F15F01","HU42117730161111101800000000")),e.addSpecification(new O("IE",22,"U04F06F08","IE29AIBK93115212345678")),e.addSpecification(new O("IL",23,"F03F03F13","IL620108000000099999999")),e.addSpecification(new O("IS",26,"F04F02F06F10","IS140159260076545510730339")),e.addSpecification(new O("IT",27,"U01F05F05A12","IT60X0542811101000000123456")),e.addSpecification(new O("IQ",23,"U04F03A12","IQ98NBIQ850123456789012")),e.addSpecification(new O("JO",30,"A04F22","JO15AAAA1234567890123456789012")),e.addSpecification(new O("KW",30,"U04A22","KW81CBKU0000000000001234560101")),e.addSpecification(new O("KZ",20,"F03A13","KZ86125KZT5004100100")),e.addSpecification(new O("LB",28,"F04A20","LB62099900000001001901229114")),e.addSpecification(new O("LC",32,"U04F24","LC07HEMM000100010012001200013015")),e.addSpecification(new O("LI",21,"F05A12","LI21088100002324013AA")),e.addSpecification(new O("LT",20,"F05F11","LT121000011101001000")),e.addSpecification(new O("LU",20,"F03A13","LU280019400644750000")),e.addSpecification(new O("LV",21,"U04A13","LV80BANK0000435195001")),e.addSpecification(new O("MC",27,"F05F05A11F02","MC5811222000010123456789030")),e.addSpecification(new O("MD",24,"U02A18","MD24AG000225100013104168")),e.addSpecification(new O("ME",22,"F03F13F02","ME25505000012345678951")),e.addSpecification(new O("MK",19,"F03A10F02","MK07250120000058984")),e.addSpecification(new O("MR",27,"F05F05F11F02","MR1300020001010000123456753")),e.addSpecification(new O("MT",31,"U04F05A18","MT84MALT011000012345MTLCAST001S")),e.addSpecification(new O("MU",30,"U04F02F02F12F03U03","MU17BOMM0101101030300200000MUR")),e.addSpecification(new O("NL",18,"U04F10","NL91ABNA0417164300")),e.addSpecification(new O("NO",15,"F04F06F01","NO9386011117947")),e.addSpecification(new O("PK",24,"U04A16","PK36SCBL0000001123456702")),e.addSpecification(new O("PL",28,"F08F16","PL61109010140000071219812874")),e.addSpecification(new O("PS",29,"U04A21","PS92PALS000000000400123456702")),e.addSpecification(new O("PT",25,"F04F04F11F02","PT50000201231234567890154")),e.addSpecification(new O("QA",29,"U04A21","QA30AAAA123456789012345678901")),e.addSpecification(new O("RO",24,"U04A16","RO49AAAA1B31007593840000")),e.addSpecification(new O("RS",22,"F03F13F02","RS35260005601001611379")),e.addSpecification(new O("SA",24,"F02A18","SA0380000000608010167519")),e.addSpecification(new O("SC",31,"U04F04F16U03","SC18SSCB11010000000000001497USD")),e.addSpecification(new O("SE",24,"F03F16F01","SE4550000000058398257466")),e.addSpecification(new O("SI",19,"F05F08F02","SI56263300012039086")),e.addSpecification(new O("SK",24,"F04F06F10","SK3112000000198742637541")),e.addSpecification(new O("SM",27,"U01F05F05A12","SM86U0322509800000000270100")),e.addSpecification(new O("ST",25,"F08F11F02","ST68000100010051845310112")),e.addSpecification(new O("SV",28,"U04F20","SV62CENR00000000000000700025")),e.addSpecification(new O("TL",23,"F03F14F02","TL380080012345678910157")),e.addSpecification(new O("TN",24,"F02F03F13F02","TN5910006035183598478831")),e.addSpecification(new O("TR",26,"F05F01A16","TR330006100519786457841326")),e.addSpecification(new O("UA",29,"F25","UA511234567890123456789012345")),e.addSpecification(new O("VA",22,"F18","VA59001123000012345678")),e.addSpecification(new O("VG",24,"U04F16","VG96VPVG0000012345678901")),e.addSpecification(new O("XK",20,"F04F10F02","XK051212012345678906")),e.addSpecification(new O("AO",25,"F21","AO69123456789012345678901")),e.addSpecification(new O("BF",27,"F23","BF2312345678901234567890123")),e.addSpecification(new O("BI",16,"F12","BI41123456789012")),e.addSpecification(new O("BJ",28,"F24","BJ39123456789012345678901234")),e.addSpecification(new O("CI",28,"U02F22","CI70CI1234567890123456789012")),e.addSpecification(new O("CM",27,"F23","CM9012345678901234567890123")),e.addSpecification(new O("CV",25,"F21","CV30123456789012345678901")),e.addSpecification(new O("DZ",24,"F20","DZ8612345678901234567890")),e.addSpecification(new O("IR",26,"F22","IR861234568790123456789012")),e.addSpecification(new O("MG",27,"F23","MG1812345678901234567890123")),e.addSpecification(new O("ML",28,"U01F23","ML15A12345678901234567890123")),e.addSpecification(new O("MZ",25,"F21","MZ25123456789012345678901")),e.addSpecification(new O("SN",28,"U01F23","SN52A12345678901234567890123")),e.addSpecification(new O("GF",27,"F05F05A11F02","GF121234512345123456789AB13")),e.addSpecification(new O("GP",27,"F05F05A11F02","GP791234512345123456789AB13")),e.addSpecification(new O("MQ",27,"F05F05A11F02","MQ221234512345123456789AB13")),e.addSpecification(new O("RE",27,"F05F05A11F02","RE131234512345123456789AB13")),e.addSpecification(new O("PF",27,"F05F05A11F02","PF281234512345123456789AB13")),e.addSpecification(new O("TF",27,"F05F05A11F02","TF891234512345123456789AB13")),e.addSpecification(new O("YT",27,"F05F05A11F02","YT021234512345123456789AB13")),e.addSpecification(new O("NC",27,"F05F05A11F02","NC551234512345123456789AB13")),e.addSpecification(new O("BL",27,"F05F05A11F02","BL391234512345123456789AB13")),e.addSpecification(new O("MF",27,"F05F05A11F02","MF551234512345123456789AB13")),e.addSpecification(new O("PM",27,"F05F05A11F02","PM071234512345123456789AB13")),e.addSpecification(new O("WF",27,"F05F05A11F02","WF621234512345123456789AB13")),{formatterNumber:r,formatterIban:e}},Fi=["=","!=",">",">=","<","<=","in","between"];function Mt(r,e,t){if(typeof r!="string"||r.length===0)throw new R({code:"JSSDK_FILTER_V3_INVALID_FIELD",description:`FilterV3: field name must be a non-empty string, got ${JSON.stringify(r)}.`,status:400});if(!Fi.includes(e))throw new R({code:"JSSDK_FILTER_V3_INVALID_OPERATOR",description:`FilterV3: operator "${e}" is not one of ${Fi.join(" ")}.`,status:400});return[r,e,t]}const km=Object.freeze({eq(r,e){return Mt(r,"=",e)},ne(r,e){return Mt(r,"!=",e)},gt(r,e){return Mt(r,">",e)},ge(r,e){return Mt(r,">=",e)},lt(r,e){return Mt(r,"<",e)},le(r,e){return Mt(r,"<=",e)},in(r,e){if(!Array.isArray(e)||e.length===0)throw new R({code:"JSSDK_FILTER_V3_INVALID_IN",description:`FilterV3.in("${r}"): value must be a non-empty array.`,status:400});return Mt(r,"in",e)},between(r,e,t){if(e==null||t===void 0||t===null)throw new R({code:"JSSDK_FILTER_V3_INVALID_BETWEEN",description:`FilterV3.between("${r}"): both range operands must be defined (got [${String(e)}, ${String(t)}]).`,status:400});return Mt(r,"between",[e,t])},and(...r){return{logic:"and",conditions:r}},or(...r){return{logic:"or",conditions:r}},not(r){return Cl(r)?{...r,conditions:[...r.conditions],negative:!0}:{logic:"and",negative:!0,conditions:[r]}},build(...r){const e=r.filter(Boolean);for(const t of e)Rm(t);return e}});function Cl(r){return!Array.isArray(r)&&typeof r=="object"&&r!==null&&"conditions"in r}function Rm(r){if(!Cl(r)&&!(Array.isArray(r)&&typeof r[0]=="string"&&r[0].length>0&&(r.length===2||r.length===3&&Fi.includes(r[1]))))throw new R({code:"JSSDK_FILTER_V3_INVALID_NODE",description:`FilterV3.build: each node must be a [field, operator, value] condition, a [field, value] equality or a group \u2014 got ${JSON.stringify(r)}. Did you forget to spread (build(...nodes)) or build a condition with FilterV3 helpers?`,status:400})}function Nl(r,e){if(typeof r!="string"||r.length===0)throw new R({code:"JSSDK_BATCH_REF_V3_INVALID_PATH",description:`${e}: path must be a non-empty dotted string (e.g. "tasks.id").`,status:400})}const Cm=Object.freeze({ref(r){return Nl(r,"BatchRefV3.ref"),{$ref:r}},refArray(r){if(Nl(r,"BatchRefV3.refArray"),!r.includes("."))throw new R({code:"JSSDK_BATCH_REF_V3_INVALID_REF_ARRAY",description:`BatchRefV3.refArray: path "${r}" must contain a dot ("alias.field") \u2014 the server collects <field> across the alias's items[].`,status:400});return{$refArray:r}}});class Dl{#e;#t;#s;#r;#i;constructor(e){this.#e=Object.freeze(Object.assign({},e)),this.#t=this.#e.b24Url.replaceAll("https://","").replaceAll("http://","").replace(/:(80|443)$/,""),this.#s=`https://${this.#t}/rest`,this.#r=`https://${this.#t}`,this.#i=new Map,this.#i.set(K.v2,`${this.#s}/${this.#e.userId}/${this.#e.secret}`),this.#i.set(K.v3,`${this.#s}/api/${this.#e.userId}/${this.#e.secret}`)}getAuthData(){return{access_token:this.#e.secret,refresh_token:"hook",expires:0,expires_in:0,domain:this.#t,member_id:this.#t}}refreshAuth(){return Promise.resolve(this.getAuthData())}getUniq(e){const t=this.getAuthData();if(t===!1)throw new Error("AuthData not init");return[e,t.member_id].join("_")}getTargetOrigin(){return`${this.#r}`}getTargetOriginWithPath(){return this.#i}get isAdmin(){return!0}}class Bi extends vs{#e;constructor(e,t){super(),this.#e=new Dl(e);const s=`The B24Hook object is intended exclusively for use on the server.
A webhook contains a secret access key, which MUST NOT be used in client-side code (browser, worker, mobile app).`;this._httpOptions=t?.httpOptions??null,this._httpV2=new js(this.#e,this._getHttpOptions(),t?.restrictionParams),this._httpV2.setClientSideWarning(!0,s),this._httpV3=new Us(this.#e,this._getHttpOptions(),t?.restrictionParams),this._httpV3.setClientSideWarning(!0,s),this._isInit=!0}get auth(){return this.#e}offClientSideWarning(){ur.getAllApiVersions().forEach(e=>{this.getHttpClient(e).setClientSideWarning(!1,"")})}getTargetOrigin(){return this._ensureInitialized(),this.#e.getTargetOrigin()}getTargetOriginWithPath(){return this._ensureInitialized(),this.#e.getTargetOriginWithPath()}static fromWebhookUrl(e,t){if(!e.trim())throw new R({code:"JSSDK_HOOK_URL_EMPTY",description:"Webhook URL cannot be empty",status:0});let s;try{s=new URL(e.replace("/rest/api","/rest"))}catch{throw new R({code:"JSSDK_HOOK_URL_INVALID",description:"Invalid webhook URL format",status:0})}if(s.protocol!=="https:")throw new R({code:"JSSDK_HOOK_URL_NOT_HTTPS",description:"Webhook requires HTTPS protocol",status:0});const n=s.pathname.split("/").filter(Boolean);if(!(n.length===3&&n[0]==="rest"||n.length===4&&n[0]==="rest"&&n[1]==="api"))throw new R({code:"JSSDK_HOOK_URL_MALFORMED",description:"Webhook URL must follow format: /rest/<userId>/<secret> or /rest/api/<userId>/<secret>",status:0});const i=n[1]==="api"?2:1,o=n[1]==="api"?3:2,a=n[i],c=n[o];if(!/^\d+$/.test(a))throw new R({code:"JSSDK_HOOK_URL_USER_ID_NOT_NUMERIC",description:"User ID must be numeric in webhook URL",status:0});const u=Number.parseInt(a,10);return new Bi({b24Url:s.origin,userId:u,secret:c},t)}}var ce=(r=>(r.getInitData="getInitData",r.setInstallFinish="setInstallFinish",r.setInstall="setInstall",r.refreshAuth="refreshAuth",r.setAppOption="setAppOption",r.setUserOption="setUserOption",r.resizeWindow="resizeWindow",r.reloadWindow="reloadWindow",r.setTitle="setTitle",r.setScroll="setScroll",r.openApplication="openApplication",r.closeApplication="closeApplication",r.openPath="openPath",r.imCallTo="imCallTo",r.imPhoneTo="imPhoneTo",r.imOpenMessenger="imOpenMessenger",r.imOpenHistory="imOpenHistory",r.selectUser="selectUser",r.selectAccess="selectAccess",r.selectCRM="selectCRM",r.showAppForm="showAppForm",r.getInterface="getInterface",r.placementBindEvent="placementBindEvent",r))(ce||{});const Nm=50,Dm=64;class Ll{#e;#t;#s;#r=new Set;_logger;runCallbackHandler;constructor(e){this._logger=oe.createNullLogger(),this.#e=e,this.#t=new Map,this.#s=new Map,this.runCallbackHandler=this._runCallback.bind(this)}setLogger(e){this._logger=e}getLogger(){return this._logger}subscribe(){window.addEventListener("message",this.runCallbackHandler)}unsubscribe(){window.removeEventListener("message",this.runCallbackHandler);for(const[e,t]of this.#t)t.timeoutId&&clearTimeout(t.timeoutId),this.#t.delete(e),t.reject(new R({code:"JSSDK_FRAME_DISPOSED",description:"The B24Frame was destroyed before the parent window answered this command.",status:0}));this.#s.clear(),this.#r.clear()}async send(e,t=null){return new Promise((s,n)=>{let i;const o={resolve:s,reject:n,timeoutId:null},a=this.#n(o);let c=null;const u=Ki(t||{},["singleOption","callBack","isSafely","safelyTime","requestId"]),{callBack:l,singleOption:h,requestId:d}=t||{};if(l&&this.#s.set(a,l),h?c=h:Object.keys(u).length>0&&(c={...u}),e.toString().includes(":"))i={method:e.toString(),params:c||"",callback:a,appSid:this.#e.getAppSid(),requestId:d};else{i=e.toString(),t?.isRawValue!==!0&&c?c=JSON.stringify(c):t?.isRawValue===!0&&c&&L.isPlainObject(c)&&c.value&&(c=c.value);const f=[c||"",a,this.#e.getAppSid()];i+=":"+f.filter(Boolean).join(":")}if(this.getLogger().debug(`send to ${this.#e.getTargetOrigin()}`,{command:e.toString(),callbackKey:a,origin:this.#e.getTargetOrigin()}).catch(()=>{}),parent.postMessage(i,this.#e.getTargetOrigin()),t?.isSafely){const f=Number.parseInt(String(t?.safelyTime||900));this.#t.get(a).timeoutId=window.setTimeout(()=>{this.#t.has(a)&&(this.getLogger().warning(`action ${e.toString()} stop by timeout`,{command:e.toString(),safelyTime:f}).catch(()=>{}),this.#t.delete(a),s({isSafely:!0}))},f)}})}_runCallback(e){if(e.origin!==this.#e.getTargetOrigin()){!this.#r.has(e.origin)&&this.#r.size<Nm&&(this.#r.add(e.origin),this.getLogger().warning("message rejected: unexpected origin",{origin:e.origin,expected:this.#e.getTargetOrigin()}).catch(()=>{}));return}if(typeof e.data=="string"&&e.data.length>0){const[t="",...s]=e.data.split(":"),n={id:t,args:s.join(":")};if(this.getLogger().debug(`get from ${e.origin}`,{id:n.id,origin:e.origin}).catch(()=>{}),n.args)try{n.args=JSON.parse(n.args)}catch{this.getLogger().warning("message dropped: payload is not valid JSON",{id:n.id,origin:e.origin}).catch(()=>{}),this.#i(n.id,new R({code:"JSSDK_FRAME_BAD_PAYLOAD",description:`The parent window answered command "${n.id.slice(0,Dm)}" with a payload that is not valid JSON.`,status:0}));return}if(this.#t.has(n.id)){const i=this.#t.get(n.id);i.timeoutId&&clearTimeout(i.timeoutId),this.#t.delete(n.id),i.resolve(n.args)}else if(this.#s.has(n.id)){const i=this.#s.get(n.id);i&&i.apply(globalThis,[n.args])}}}#i(e,t){const s=this.#t.get(e);s&&(s.timeoutId&&clearTimeout(s.timeoutId),this.#t.delete(e),s.reject(t))}#n(e){const t=Ia();return this.#t.set(t,e),t}}class Ml{#e="";#t=!0;#s=null;#r=null;#i=null;#n;#o;#a;constructor(e){e.DOMAIN&&(this.#e=e.DOMAIN,this.#e=this.#e.replace(/:(80|443)$/,"")),this.#t=e.PROTOCOL===!0,e.LANG&&(this.#i=e.LANG),e.APP_SID&&(this.#s=e.APP_SID),this.#a=new Map,this.#o=`${this.#t?"https":"http"}://${this.#e}`,this.#n=`${this.#o}/rest`,this.#a.set(K.v2,`${this.#n}`),this.#a.set(K.v3,`${this.#n}/api`)}initData(e){return this.#e||(this.#e=e.DOMAIN),this.#r||(this.#r=e.PATH),this.#i||(this.#i=e.LANG),this.#t=Number.parseInt(e.PROTOCOL)===1,this.#e=this.#e.replace(/:(80|443)$/,""),this.#o=`${this.#t?"https":"http"}://${this.#e}`,this.#n=`${this.#o}/rest`,this.#a.set(K.v2,`${this.#n}`),this.#a.set(K.v3,`${this.#n}/api`),this}getAppSid(){if(this.#s===null)throw new R({code:"JSSDK_FRAME_APP_SID_NOT_INIT",description:"Not init appSid",status:0});return this.#s}getTargetOrigin(){return this.#o}getTargetOriginWithPath(){return this.#a}getLang(){return this.#i||Ln.en}}const Pl=1e4;class xl{#e=null;#t=null;#s=0;#r=0;#i=null;#n=!1;#o=null;#a;#h;constructor(e,t){this.#a=e,this.#h=t}initData(e){return e.AUTH_ID&&(this.#e=e.AUTH_ID,this.#t=e.REFRESH_ID,this.#r=Number.parseInt(e.AUTH_EXPIRES),this.#s=Date.now()+this.#r*1e3,this.#n=e.IS_ADMIN,this.#i=e.MEMBER_ID||""),this}getAuthData(){return this.#s>Date.now()?{access_token:this.#e,refresh_token:this.#t,expires:this.#s/1e3,expires_in:this.#r,domain:this.#a.getTargetOrigin(),member_id:this.#i}:!1}refreshAuth(){if(this.#o!==null)return this.#o;const e=(async()=>{try{return await this.#d()}finally{this.#o=null}})();return this.#o=e,e}async#d(){let e;const t=new Promise((s,n)=>{e=setTimeout(()=>n(new R({code:"JSSDK_FRAME_REFRESH_AUTH_TIMEOUT",status:408,description:`refreshAuth: the parent window did not answer within ${Pl}ms`})),Pl)});try{const s=await Promise.race([this.#h.send(ce.refreshAuth,{}),t]),n=Number.parseInt(s?.AUTH_EXPIRES);if(!Number.isFinite(n)||n<=0)throw new R({code:"JSSDK_FRAME_REFRESH_AUTH_BAD_RESPONSE",status:500,description:"refreshAuth: the parent window answered without a usable AUTH_EXPIRES"});return this.#e=s.AUTH_ID,this.#t=s.REFRESH_ID,this.#r=n,this.#s=Date.now()+n*1e3,this.getAuthData()}finally{e&&clearTimeout(e)}}getUniq(e){return[e,this.#i||""].join("_")}get isAdmin(){return this.#n}getTargetOrigin(){return this.#a.getTargetOrigin()}getTargetOriginWithPath(){return this.#a.getTargetOriginWithPath()}}class Fl{#e;constructor(e){this.#e=e}get message(){return this.#e}async closeApplication(){return this.#e.send(ce.closeApplication,{isSafely:!1})}async fitWindow(){const e="100%",t=this.getScrollSize().scrollHeight;return this.#e.send(ce.resizeWindow,{width:e,height:t,isSafely:!0})}async resizeWindow(e,t){return e>0&&t>0?this.#e.send(ce.resizeWindow,{width:e,height:t,isSafely:!0}):Promise.reject(new Error(`Wrong width:number = ${e} or height:number = ${t}`))}async resizeWindowAuto(e=null,t=0,s=0){const n=document.body;let i=Math.max(n.scrollWidth,n.offsetWidth);s>0&&(i=Math.max(s,i));let o=Math.max(n.scrollHeight,n.offsetHeight);return e&&(o=Math.max(e.scrollHeight,e.offsetHeight)),t>0&&(o=Math.max(t,o)),this.resizeWindow(i,o)}getScrollSize(){return Om()}async scrollParentWindow(e){return Number.isInteger(e)?(e<0&&(e=0),this.#e.send(ce.setScroll,{scroll:e,isSafely:!0})):Promise.reject(new Error("Wrong scroll number"))}async reloadWindow(){return this.#e.send(ce.reloadWindow,{isSafely:!0})}async setTitle(e){return this.#e.send(ce.setTitle,{title:e.toString(),isSafely:!0})}async imCallTo(e,t=!0){return this.#e.send(ce.imCallTo,{userId:e,video:t,isSafely:!0})}async imPhoneTo(e,t){return this.#e.send(ce.imPhoneTo,{phone:e,...t===void 0?{}:{params:t},isSafely:!0})}async imOpenMessenger(e,t){return this.#e.send(ce.imOpenMessenger,{dialogId:e,...t===void 0?{}:{messageId:t},isSafely:!0})}async imOpenHistory(e){return this.#e.send(ce.imOpenHistory,{dialogId:e,isSafely:!0})}}let Bl=class{#e;#t=null;#s=null;constructor(e){this.#e=e}initData(e){return e.APP_OPTIONS&&(this.#t=e.APP_OPTIONS),e.USER_OPTIONS&&(this.#s=e.USER_OPTIONS),this}appGet(e){if(this.#t&&this.#t[e])return this.#t[e];throw new Error(`app.option.${e} not set`)}async appSet(e,t){return this.#t||(this.#t=[]),this.#t[e]=t,this.#r(ce.setAppOption,e,this.#t[e])}userGet(e){if(this.#s&&this.#s[e])return this.#s[e];throw new Error(`user.option.${e} not set`)}async userSet(e,t){return this.#t||(this.#t=[]),this.#t[e]||(this.#t[e]=null),this.#s[e]=t,this.#r(ce.setUserOption,e,this.#s[e])}async#r(e,t,s){return this.#e.send(e,{name:t,value:s,isSafely:!0}).then(()=>Promise.resolve())}};class $l{#e;constructor(e){this.#e=e}async selectUser(){return this.#e.send(ce.selectUser,{mult:!1})}async selectUsers(){return this.#e.send(ce.selectUser,{mult:!0})}async selectAccess(e=[]){return this.#e.send(ce.selectAccess,{value:e})}async selectCRM(e){const t=await this.#e.send(ce.selectCRM,{entityType:e?.entityType,multiple:e?.multiple,value:e?.value}),s={};if(!t)return s;const n=l=>{if(l!=null)return Array.isArray(l)?l:Object.values(l)},i=n(t.lead);i&&(s.lead=i);const o=n(t.contact);o&&(s.contact=o);const a=n(t.company);a&&(s.company=a);const c=n(t.deal);c&&(s.deal=c);const u=n(t.quote);return u&&(s.quote=u),s}}class jl{#e;#t;constructor(e,t){this.#e=e,this.#t=t}getUrl(e="/"){return new URL(e,this.#e.getTargetOrigin())}getTargetOrigin(){return this.#e.getTargetOrigin()}async openSliderAppPage(e={}){return this.#t.send(ce.openApplication,e)}async closeSliderAppPage(){return this.#t.send(ce.closeApplication,{isSafely:!1})}#s(e=1640){return e>0?e>1200&&e<=1640?"/crm/type/0/details/0/../../../../..":e>950&&e<=1200?"/company/personal/user/0/groups/create/../../../../../..":e>900&&e<=950?"/crm/company/requisite/0/../../../..":e<=900?"/workgroups/group/0/card/../../../..":"/crm/deal/../..":"/crm/deal/../.."}async openPath(e,t=1640){const s=new URL(e);return s.searchParams.set("IFRAME","Y"),s.searchParams.set("IFRAME_TYPE","SIDE_SLIDER"),this.#t.send(ce.openPath,{path:[this.#s(t),s.pathname,s.search].join("")}).then(n=>n?.result==="error"?n?.errorCode==="METHOD_NOT_SUPPORTED_ON_DEVICE"?new Promise((i,o)=>{const a=window.open(e,"_blank");if(!a){o(new Error("Error open window"));return}let c=0;const u=1e3*60*5,l=window.setInterval(()=>{c=c+1,a.closed?(clearInterval(l),i({isOpenAtNewWindow:!0,isClose:!0})):c>u&&(clearInterval(l),i({isOpenAtNewWindow:!0,isClose:!1}))},1e3)}):Promise.reject(new Error(n?.errorCode)):n?.result==="close"?Promise.resolve({isOpenAtNewWindow:!1,isClose:!0}):Promise.resolve({isOpenAtNewWindow:!1,isClose:!1}))}}const $i=Object.freeze({});function Ul(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Lm(r){try{if(Ul(r))return Object.freeze({...r});if(typeof r=="string"&&r.length>0){const e=JSON.parse(r);return Ul(e)?Object.freeze({...e}):$i}}catch{return $i}return $i}class Vl{#e;#t="";#s=Object.freeze({});constructor(e){this.#e=e}initData(e){return this.#t=e.PLACEMENT||"DEFAULT",this.#s=Lm(e.PLACEMENT_OPTIONS),this}get title(){return this.#t}get placement(){return this.#t}get isDefault(){return this.placement==="DEFAULT"}get options(){return this.#s}get isSliderMode(){return this.#s.IFRAME==="Y"}async getInterface(){return this.#e.send(ce.getInterface,{isSafely:!0})}async bindEvent(e,t){return this.#e.send(ce.placementBindEvent,{event:e,callBack:t,isSafely:!0})}async call(e,t={}){if(e==="setValue"&&!L.isString(t?.value))throw new TypeError("placement.call('setValue', { value }) expects `value` to be a JSON-serialized string. Use placement.setValue(value) to serialize automatically, or call JSON.stringify yourself.");return this.#e.send(e,{...t,isSafely:!0,isRawValue:["setValue"].includes(e)})}async setValue(e){return this.#e.send("setValue",{value:JSON.stringify(e),isSafely:!0,isRawValue:!0})}async callCustomBind(e,t=null,s){let n={};return L.isString(t)?n.singleOption=t:L.isObjectLike(t)&&(n={...t}),this.#e.send(e,{...n,callBack:s,isSafely:!0})}}function ji(r){const e=(i,o)=>Number.isFinite(i)&&i>0?i:o,t=e(r?.marginMs,3e5),s=Math.max(3e4,e(r?.minDelayMs,3e4)),n=e(r?.maxDelayMs,6e5);return{marginMs:t,minDelayMs:s,maxDelayMs:Math.max(s,n)}}function ql(r,e,t){if(!Number.isFinite(r)||r<=0)return!0;const{marginMs:s}=ji(t);return r*1e3-e<=s}function Hl(r,e,t){const{marginMs:s,minDelayMs:n,maxDelayMs:i}=ji(t);if(!Number.isFinite(r)||r<=0)return n;const o=r*1e3-e-s;return Math.min(i,Math.max(n,o))}class Mm{#e;#t;#s;#r=null;#i=!1;#n=null;#o=null;#a=0;#h=0;#d=0;constructor(e,t,s){this.#e=e,this.#s=t,this.#t=ji(s)}start(){if(this.#i||typeof window>"u")return;this.#i=!0,this.#h=0;const e=this.#a;if(typeof document<"u"&&(this.#o=()=>{if(document.visibilityState!=="visible")return;const t=this.#a,s=this.#d-Date.now();if(s>0){this.#u(s,t);return}this.#c(t)},document.addEventListener("visibilitychange",this.#o)),this.#n!==null){this.#u(this.#t.minDelayMs,e);return}this.#c(e)}stop(){this.#i=!1,this.#a+=1,this.#f(),this.#o!==null&&typeof document<"u"&&document.removeEventListener("visibilitychange",this.#o),this.#o=null}get isRunning(){return this.#i}async#c(e){if(!this.#i||this.#n===e)return;this.#n=e;let t=this.#t.minDelayMs;try{const s=this.#e.getAuthData(),n=s===!1?void 0:s.expires;if(!ql(n,Date.now(),this.#t))this.#h=0,t=Hl(n,Date.now(),this.#t);else{const i=await this.#e.refreshAuth(),o=i?i.expires:void 0;ql(o,Date.now(),this.#t)?(this.#h+=1,t=this.#l()):(this.#h=0,t=Hl(o,Date.now(),this.#t))}}catch(s){this.#h+=1,t=this.#l();try{this.#s().warning("keepAuthFresh: refresh failed, will retry",{error:s instanceof Error?s.message:String(s),failures:this.#h,retryInMs:t}).catch(()=>{})}catch{}}finally{this.#n===e&&(this.#n=null),this.#u(t,e)}}#l(){const e=Math.min(Math.max(this.#h-1,0),10);return Math.min(this.#t.maxDelayMs,this.#t.minDelayMs*2**e)}#u(e,t){if(!this.#i||this.#a!==t)return;this.#f(),this.#d=Date.now()+e,this.#r=setTimeout(()=>{this.#r=null,this.#c(t)},e);const s=this.#r;typeof s?.unref=="function"&&s.unref()}#f(){this.#r!==null&&(clearTimeout(this.#r),this.#r=null)}}class Wl extends vs{#e=!1;#t=!1;#s;#r;#i;#n;#o;#a;#h;#d;#c;#l;#u=null;constructor(e,t){super(),this.#c=t?.restrictionParams,this.#l=t?.keepAuthFresh,this._httpOptions=t?.httpOptions??null,this.#s=new Ml(e),this.#r=new Ll(this.#s),this.#r.subscribe(),this.#i=new xl(this.#s,this.#r),this.#n=new Fl(this.#r),this.#o=new Bl(this.#r),this.#a=new $l(this.#r),this.#h=new jl(this.#s,this.#r),this.#d=new Vl(this.#r),this._isInit=!1}setLogger(e){super.setLogger(e),this.#r.setLogger(this.getLogger())}get isFirstRun(){return this._ensureInitialized(),this.#t}get isInstallMode(){return this._ensureInitialized(),this.#e}get parent(){return this._ensureInitialized(),this.#n}get auth(){return this._ensureInitialized(),this.#i}get slider(){return this._ensureInitialized(),this.#h}get placement(){return this._ensureInitialized(),this.#d}get options(){return this._ensureInitialized(),this.#o}get dialog(){return this._ensureInitialized(),this.#a}async init(){const e=await this.#r.send(ce.getInitData,{});return this.getLogger().debug("init data",{PLACEMENT:e.PLACEMENT,LANG:e.LANG,INSTALL:e.INSTALL,IS_ADMIN:e.IS_ADMIN,FIRST_RUN:e.FIRST_RUN}).catch(()=>{}),this.#s.initData(e),this.#i.initData(e),this.#d.initData(e),this.#o.initData(e),this.#e=e.INSTALL,this.#t=e.FIRST_RUN,this._httpV2=new js(this.#i,this._getHttpOptions(),this.#c),this._httpV3=new Us(this.#i,this._getHttpOptions(),this.#c),this._isInit=!0,this.#f(),this.#t?this.#r.send(ce.setInstall,{install:!0}):Promise.resolve()}destroy(){this.#u?.stop(),this.#u=null,this.#r.unsubscribe(),super.destroy()}#f(){!this.#l||this.#u!==null||(this.#u=new Mm(this.#i,()=>this.getLogger(),this.#l===!0?void 0:this.#l),this.#u.start())}async installFinish(){return this.isInstallMode?this.#r.send(ce.setInstallFinish,{}):Promise.reject(new R({code:"JSSDK_FRAME_INSTALL_ALREADY_FINISHED",description:"Application was previously installed. You cannot call installFinish",status:0}))}getTargetOrigin(){return this._ensureInitialized(),this.#i.getTargetOrigin()}getTargetOriginWithPath(){return this._ensureInitialized(),this.#i.getTargetOriginWithPath()}getAppSid(){return this._ensureInitialized(),this.#s.getAppSid()}getLang(){return this._ensureInitialized(),this.#s.getLang()}}class zl extends R{}function Jl(r){let e=r.length;for(;e>0&&r[e-1]==="/";)e--;return r.slice(0,e)}class Kl{#e;#t=null;#s=null;#r;#i;#n=0;#o=0;#a;#h;#d;#c;#l;#u=null;constructor(e,t){this.#r=Object.assign({},e),this.#i=Object.freeze(Object.assign({},t)),this.#a=this.#r.domain.replaceAll("https://","").replaceAll("http://","").replace(/:(80|443)$/,""),this.#h=Jl(this.#r.clientEndpoint),this.#d=this.#h.replace(/\/rest$/,""),this.#l=Jl(this.#r.serverEndpoint).replace(/\/rest$/,""),this.#n=this.#r.expires*1e3,this.#o=this.#r.expiresIn,this.#e=_e.create({baseURL:this.#l}),this.#c=new Map,this.#c.set(K.v2,`${this.#h}`),this.#c.set(K.v3,`${this.#h}/api`)}getAuthData(){return this.#n>Date.now()?{access_token:this.#r.accessToken,refresh_token:this.#r.refreshToken,expires:this.#n/1e3,expires_in:this.#o,domain:this.#a,member_id:this.#r.memberId}:!1}async refreshAuth(){try{let e;if(this.#s)e=await this.#s();else{const s=new URLSearchParams({grant_type:"refresh_token",client_id:this.#i.clientId,client_secret:this.#i.clientSecret,refresh_token:this.#r.refreshToken}),n=await this.#e.post("/oauth/token/",s,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(n.data.error)throw new R({code:"JSSDK_OAUTH_TOKEN_REFRESH_FAILED",description:`Token update error: ${n.data.error}`,status:0});if(n.status!==200)throw new R({code:"JSSDK_OAUTH_TOKEN_REFRESH_BAD_STATUS",description:`Token update error status code: ${n.status}`,status:n.status});e=n.data}if(!e)throw new R({code:"JSSDK_OAUTH_TOKEN_REFRESH_NO_DATA",description:"Unable to obtain authorization update data",status:0});this.#r.accessToken=e.access_token,this.#r.refreshToken=e.refresh_token,this.#r.expires=Number.parseInt(e.expires||"0"),this.#r.expiresIn=Number.parseInt(e.expires_in||"3600"),this.#r.clientEndpoint=e.client_endpoint,this.#r.serverEndpoint=e.server_endpoint,this.#r.scope=e.scope,this.#r.status=Object.values(wt).find(s=>s===e.status)||wt.Free,this.#n=this.#r.expires*1e3;const t=this.getAuthData();return this.#t&&await this.#t({authData:t,b24OAuthParams:this.#r}),t}catch(e){if(e instanceof Li){const t={code:e?.code||0,description:e?.message||""};if(e.response&&e.response.data&&!L.isUndefined(e.response.data.error)){const s=e.response.data;s.error&&typeof s.error=="object"&&"code"in s.error?(t.code=s.error.code,t.description=s.error.message,s.error.validation&&s.error.validation.forEach(n=>{t.description+=`${n?.message||JSON.stringify(n)}`})):s.error&&typeof s.error=="string"&&(t.code=s.error,t.description=s?.error_description??t.description)}throw new zl({code:String(t.code),description:t.description,status:e.response?.status||0})}else if(e instanceof Error)throw e;throw new Error(`Strange error: ${String(e)}`,{cause:e})}}setCallbackRefreshAuth(e){this.#t=e}removeCallbackRefreshAuth(){this.#t=null}setCustomRefreshAuth(e){this.#s=e}removeCustomRefreshAuth(){this.#s=null}getUniq(e){return[e,this.#r.memberId||""].join("_")}getTargetOrigin(){return`${this.#d}`}getTargetOriginWithPath(){return this.#c}get isAdmin(){if(this.#u===null)throw new R({code:"JSSDK_OAUTH_IS_ADMIN_NOT_INIT",description:"isAdmin not init. You need call B24OAuth::initIsAdmin().",status:0});return this.#u}async initIsAdmin(e,t){if(this.#u=!1,e.apiVersion===K.v3){const n=await e.call("profile",{},t);if(!n.isSuccess)throw new R({code:"JSSDK_OAUTH_PROFILE_FAILED",description:n.getErrorMessages().join(";"),status:0});n.getData().result.profile?.admin&&(this.#u=!0);return}const s=await e.call("profile",{},t);if(!s.isSuccess)throw new R({code:"JSSDK_OAUTH_PROFILE_FAILED",description:s.getErrorMessages().join(";"),status:0});s.getData().result?.ADMIN&&(this.#u=!0)}}class Pm extends vs{#e;constructor(e,t,s){super(),this.#e=new Kl(e,t);const n=`The B24OAuth object is intended exclusively for use on the server.
A webhook contains a secret access key, which MUST NOT be used in client-side code (browser, worker, mobile app).`;this._httpOptions=s?.httpOptions??null,this._httpV2=new js(this.#e,this._getHttpOptions(),s?.restrictionParams),this._httpV2.setClientSideWarning(!0,n),this._httpV3=new Us(this.#e,this._getHttpOptions(),s?.restrictionParams),this._httpV3.setClientSideWarning(!0,n),this._isInit=!0}async initIsAdmin(e){const t="profile";this._ensureInitialized();try{const s=ur.automaticallyObtainApiVersion(t),n=this.getHttpClient(s);return this.#e.initIsAdmin(n,e)}catch(s){this.getLogger().error("initIsAdmin: setup failed before the profile call; treating the user as non-admin",{code:s instanceof R?s.code:"JSSDK_OAUTH_IS_ADMIN_LOOKUP_FAILED"}).catch(()=>{});return}}setCallbackRefreshAuth(e){this._ensureInitialized(),this.#e.setCallbackRefreshAuth(e)}removeCallbackRefreshAuth(){this._ensureInitialized(),this.#e.removeCallbackRefreshAuth()}setCustomRefreshAuth(e){this._ensureInitialized(),this.#e.setCustomRefreshAuth(e)}removeCustomRefreshAuth(){this._ensureInitialized(),this.#e.removeCustomRefreshAuth()}offClientSideWarning(){ur.getAllApiVersions().forEach(e=>{this.getHttpClient(e).setClientSideWarning(!1,"")})}get auth(){return this.#e}getTargetOrigin(){return this._ensureInitialized(),this.#e.getTargetOrigin()}getTargetOriginWithPath(){return this._ensureInitialized(),this.#e.getTargetOriginWithPath()}}class Ui extends Error{constructor(e,...t){super(...t),this.name="UnhandledMatchError",this.message=`Unhandled match value of type ${e}`,this.stack=`${new Error("for stack").stack}`}}class gr{_b24;_data=null;_logger;constructor(e){this._b24=e,this._logger=oe.createNullLogger()}setLogger(e){this._logger=e}getLogger(){return this._logger}async initData(e){return Promise.reject(new Error("Rewrite this function"))}}class xm extends gr{_data=null;async initData(e){this._data=e}get data(){if(this._data===null)throw new Error("ProfileManager.data not initialized");return this._data}}class Fm extends gr{_data=null;async initData(e){this._data=e}get data(){if(this._data===null)throw new Error("AppManager.data not initialized");return this._data}get statusCode(){return Ba[this.data.status]||"Unknown status"}}class Bm extends gr{_data=null;async initData(e){this._data=e}get data(){if(this._data===null)throw new Error("PaymentManager.data not initialized");return this._data}}class $m extends gr{_data=null;async initData(e){this._data=e,await this.makeRestrictionManagerParams()}get data(){if(this._data===null)throw new Error("LicenseManager.data not initialized");return this._data}async makeRestrictionManagerParams(){if(!this.data?.license)return;const e=xr.fromTariffPlan(this.data.license);this.getLogger().debug("set restriction manager params",{license:this.data.license,restrictionParams:e}).catch(()=>{}),await this._b24.setRestrictionManagerParams(e)}}class jm extends gr{async initData(e){this._data={currencyBase:"?",currencyList:new Map},this.setBaseCurrency(e.currencyBase),this.setCurrencyList(e.currencyList);try{await this.loadData()}catch(t){throw t instanceof Error?t:(this.getLogger().error("Failed to load data",{error:t}).catch(()=>{}),new Error("Failed to load data",{cause:t}))}}async loadData(){const e=this.currencyList.map(t=>({method:"crm.currency.get",params:{id:t}}));if(e.length===0)return Promise.resolve();try{const t=(await this._b24.actions.v2.batchByChunk.make({calls:e,options:{isHaltOnError:!0}})).getData();if(!Array.isArray(t))return Promise.resolve();t.forEach(s=>{if(typeof s.LANG>"u")return;const n=s.CURRENCY,i=this.data.currencyList.get(n);if(!(typeof i>"u"))for(const[o,a]of Object.entries(s.LANG))switch(i.lang[o]={decimals:Number.parseInt(a.DECIMALS),decPoint:a.DEC_POINT,formatString:a.FORMAT_STRING,fullName:a.FULL_NAME,isHideZero:a.HIDE_ZERO==="Y",thousandsSep:a.THOUSANDS_SEP,thousandsVariant:a.THOUSANDS_VARIANT},i.lang[o].thousandsVariant){case"N":i.lang[o].thousandsSep="";break;case"D":i.lang[o].thousandsSep=".";break;case"C":i.lang[o].thousandsSep=",";break;case"S":i.lang[o].thousandsSep=" ";break;case"B":i.lang[o].thousandsSep=" ";break;default:L.isStringFilled(i.lang[o].thousandsSep)||(i.lang[o].thousandsSep=" ");break}})}catch(t){this.getLogger().error("Failed to load data",{error:t}).catch(()=>{})}}get data(){if(this._data===null)throw new Error("CurrencyManager.data not initialized");return this._data}setBaseCurrency(e){this._data.currencyBase=e}get baseCurrency(){return this.data.currencyBase}setCurrencyList(e=[]){this.data.currencyList.clear();for(const t of e)this.data.currencyList.set(t.CURRENCY,{amount:Number.parseFloat(t.CURRENCY),amountCnt:Number.parseInt(t.AMOUNT_CNT),isBase:t.BASE==="Y",currencyCode:t.CURRENCY,dateUpdate:bs.toDateTime(t.DATE_UPDATE),decimals:Number.parseInt(t.DECIMALS),decPoint:t.DEC_POINT,formatString:t.FORMAT_STRING,fullName:t.FULL_NAME,lid:t.LID,sort:Number.parseInt(t.SORT),thousandsSep:t?.THOUSANDS_SEP||null,lang:{}})}getCurrencyFullName(e,t){const s=this.data.currencyList.get(e);if(typeof s>"u")throw new Ui(e);let n=s.fullName;if(!(typeof t>"u")){const i=s.lang[t];L.isUndefined(i)||(n=i.fullName)}return n}getCurrencyLiteral(e,t){const s=this.data.currencyList.get(e);if(typeof s>"u")throw new Ui(e);let n=s.formatString;if(!(typeof t>"u")){const i=s.lang[t];L.isUndefined(i)||(n=i.formatString)}return n.replaceAll("&#","&%").replaceAll("#","").replaceAll("&%","&#").trim()||""}get currencyList(){return[...this.data.currencyList.keys()]}format(e,t,s){const n=this.data.currencyList.get(t);if(typeof n>"u")throw new Ui(t);const i={formatString:n.formatString,decimals:n.decimals,decPoint:n.decPoint,thousandsSep:n.thousandsSep};L.isStringFilled(i.thousandsSep)||(i.thousandsSep="");const o=n.lang[s];return L.isUndefined(o)||(i.formatString=o.formatString,i.decimals=o.decimals,i.decPoint=o.decPoint,i.thousandsSep=o.thousandsSep),i.formatString.replaceAll("&#","&%").replace("#",bs.numberFormat(e,i.decimals,i.decPoint,i.thousandsSep)).replaceAll("&%","&#")||""}}class Vi extends gr{_data;_type;static getSupportTypes(){return[bt.NotSet,bt.JsonArray,bt.JsonObject,bt.FloatVal,bt.IntegerVal,bt.BoolYN,bt.StringVal]}static prepareArrayList(e){return L.isArray(e)?e:L.isObject(e)?Object.values(e):[]}constructor(e,t){super(e),this._type=t,this._data=new Map}get data(){return this._data}reset(){this.data.clear()}async initData(e){if(this.reset(),L.isObject(e))for(const[t,s]of Object.entries(e))this.data.set(t,s)}getJsonArray(e,t=[]){if(!this.data.has(e))return t;let s=this.data.get(e);try{s=JSON.parse(s),!L.isArray(s)&&!L.isObject(s)&&(s=t)}catch(n){this.getLogger().error("Failed JSON parse",{error:n}).catch(()=>{}),s=t}return Vi.prepareArrayList(s)}getJsonObject(e,t={}){if(!this.data.has(e))return t;let s=this.data.get(e);try{s=JSON.parse(s)}catch(n){this.getLogger().error("Failed JSON parse",{error:n}).catch(()=>{}),s=t}return L.isObject(s)||(s=t),s}getFloat(e,t=0){return this.data.has(e)?In(this.data.get(e)):t}getInteger(e,t=0){return this.data.has(e)?pt(this.data.get(e)):t}getBoolYN(e,t=!0){return this.data.has(e)?ws(this.data.get(e)):t}getBoolNY(e,t=!1){return this.data.has(e)?ws(this.data.get(e)):t}getString(e,t=""){return this.data.has(e)?this.data.get(e).toString():t}getDate(e,t=null){if(!this.data.has(e))return t;try{const s=bs.toDateTime(this.data.get(e).toString());return s.isValid?s:t}catch{return t}}encode(e){return JSON.stringify(e)}decode(e,t){try{return e.length>0?JSON.parse(e):t}catch(s){this.getLogger().error("Failed JSON parse",{error:s}).catch(()=>{})}return t}getMethodSave(){switch(this._type){case"app":return"app.option.set";case"user":return"user.option.set"}}async save(e,t,s){const n=[];return n.push({method:this.getMethodSave(),params:{options:e}}),L.isObject(t)&&n.push({method:"pull.application.event.add",params:{COMMAND:t?.command,PARAMS:t?.params,MODULE_ID:t?.moduleId}}),this._b24.actions.v2.batch.make({calls:n,options:{isHaltOnError:!0,returnAjaxResult:!1,requestId:s}})}}class Gl{_logger;userId;siteId;constructor(e={}){this._logger=oe.createNullLogger(),this.userId=e.userId?pt(e.userId):0,this.siteId=e.siteId??"none"}setLogger(e){this._logger=e}getLogger(){return this._logger}set(e,t){if(typeof window>"u"||typeof window.localStorage>"u"){this.getLogger().error("localStorage undefined",{error:new Error("undefined window.localStorage")}).catch(()=>{});return}typeof t!="string"&&t&&(t=JSON.stringify(t)),window.localStorage.setItem(this._getKey(e),t)}get(e,t){if(typeof window>"u"||typeof window.localStorage>"u")return t||null;const s=window.localStorage.getItem(this._getKey(e));return s===null?t||null:JSON.parse(s)}remove(e){if(typeof window>"u"||typeof window.localStorage>"u"){this.getLogger().error("localStorage undefined",{error:new Error("undefined window.localStorage")}).catch(()=>{});return}return window.localStorage.removeItem(this._getKey(e))}_getKey(e){return`@bxshefby/b24jssdk-pull-${this.userId}-${this.siteId}-${e}`}compareKey(e,t){return e===this._getKey(t)}}class Um extends Error{constructor(e){super(e),this.name="ErrorNotConnected"}}class Vm extends Error{constructor(e){super(e),this.name="ErrorTimeout"}}const Vs="2.0";class qm{_logger;_connector;_idCounter=0;_handlers={};_rpcResponseAwaiters=new Map;constructor(e){if(this._logger=oe.createNullLogger(),this._connector=e.connector,L.isPlainObject(e.handlers))for(const t in e.handlers)this.handle(t,e.handlers[t])}setLogger(e){this._logger=e}getLogger(){return this._logger}handle(e,t){this._handlers[e]=t}async executeOutgoingRpcCommand(e,t,s=5){return new Promise((n,i)=>{const o=this.createRequest(e,t);if(!this._connector.send(JSON.stringify(o))){i(new Um("websocket is not connected"));return}if(!(s>0)){n(void 0);return}const a=setTimeout(()=>{this._rpcResponseAwaiters.delete(o.id),i(new Vm("no response"))},s*1e3);this._rpcResponseAwaiters.set(o.id,{resolve:n,reject:i,timeout:a})})}executeOutgoingRpcBatch(e){const t=[],s=[];return e.forEach(({method:n,params:i,id:o})=>{const a=this.createRequest(n,i,o);t.push(a),s.push(new Promise((c,u)=>this._rpcResponseAwaiters.set(a.id,{resolve:c,reject:u})))}),this._connector.send(JSON.stringify(t)),s}processRpcResponse(e){if("id"in e&&this._rpcResponseAwaiters.has(Number(e.id))){const t=this._rpcResponseAwaiters.get(Number(e.id));t&&("result"in e?t.resolve(e.result):"error"in e?t.reject(e?.error||"error"):t.reject("wrong response structure"),clearTimeout(t.timeout),this._rpcResponseAwaiters.delete(Number(e.id)));return}this.getLogger().error(`${ie()}: Pull: Received rpc response with unknown id`,qe({response:e})).catch(()=>{})}parseJsonRpcMessage(e){let t;try{t=JSON.parse(e)}catch(s){return this.getLogger().error(`${ie()}: Pull: Could not decode json rpc message`,{error:s}).catch(()=>{}),[]}return L.isArray(t)?this.executeIncomingRpcBatch(t):L.isJsonRpcRequest(t)?this.executeIncomingRpcCommand(t):L.isJsonRpcResponse(t)?(this.processRpcResponse(t),[]):(this.getLogger().error(`${ie()}: Pull: unknown rpc packet`,qe({decoded:t})).catch(()=>{}),[])}executeIncomingRpcCommand({method:e,params:t}){return e in this._handlers?this._handlers[e].call(this,t||{}):{jsonrpc:Vs,error:Dn.MethodNotFound}}executeIncomingRpcBatch(e){const t=[];for(const s of e)if("jsonrpc"in s)if("method"in s){const n=this.executeIncomingRpcCommand(s);n&&(n.jsonrpc=Vs,n.id=s.id,t.push(n))}else this.processRpcResponse(s);else this.getLogger().error(`${ie()}: Pull: unknown rpc command in batch`,qe({command:s})).catch(()=>{}),t.push({jsonrpc:Vs,error:Dn.InvalidRequest});return t}nextId(){return++this._idCounter}createPublishRequest(e){return e.map(t=>this.createRequest("publish",t))}createRequest(e,t,s){return s||(s=this.nextId()),{jsonrpc:Vs,method:e,params:t,id:s}}}class Hm{_logger;_storage;_ttl=1440*60;_callbacks;constructor(e={}){this._logger=oe.createNullLogger(),e=e||{},this._storage=e.storage||new Gl,this._callbacks={onWebSocketBlockChanged:L.isFunction(e.onWebSocketBlockChanged)?e.onWebSocketBlockChanged:()=>{}},this._storage&&typeof window<"u"&&window.addEventListener("storage",this.onLocalStorageSet.bind(this))}setLogger(e){this._logger=e}getLogger(){return this._logger}onLocalStorageSet(e){this._storage.compareKey(e.key||"",Ve.WebsocketBlocked)&&e.newValue!==e.oldValue&&this._callbacks.onWebSocketBlockChanged({isWebSocketBlocked:this.isWebSocketBlocked()})}isWebSocketBlocked(){return this._storage?this._storage.get(Ve.WebsocketBlocked,0)>Date.now():!1}setWebSocketBlocked(e){if(!this._storage)return!1;try{this._storage.set(Ve.WebsocketBlocked,e?Date.now()+this._ttl:0)}catch(t){return this.getLogger().error(`${ie()}: Pull: Could not save WS_blocked flag in local storage`,{error:t}).catch(()=>{}),!1}return!0}isLongPollingBlocked(){return this._storage?this._storage.get(Ve.LongPollingBlocked,0)>Date.now():!1}setLongPollingBlocked(e){if(!this._storage)return!1;try{this._storage.set(Ve.LongPollingBlocked,e?Date.now()+this._ttl:0)}catch(t){return this.getLogger().error(`${ie()}: Pull: Could not save LP_blocked flag in local storage.`,{error:t}).catch(()=>{}),!1}return!0}isLoggingEnabled(){return this._storage?this._storage.get(Ve.LoggingEnabled,0)>this.getTimestamp():!1}setLoggingEnabled(e){if(!this._storage)return!1;try{this._storage.set(Ve.LoggingEnabled,e?this.getTimestamp()+this._ttl:0)}catch(t){return this.getLogger().error(`${ie()}: LocalStorage error.`,{error:t}).catch(()=>{}),!1}return!0}getTimestamp(){return Date.now()}}const Yl="JSSDK_PULL_PUBLIC_IDS_UNAVAILABLE";class Wm{_logger;_publicIds;_restClient;_getPublicListMethod;constructor(e){this._logger=oe.createNullLogger(),this._publicIds=new Map,this._restClient=e.b24,this._getPublicListMethod=e.getPublicListMethod||"pull.channel.public.list"}setLogger(e){this._logger=e}getLogger(){return this._logger}async getPublicIds(e){const t=new Date,s={},n=[];for(const i of e){const o=this._publicIds.get(i);o&&o.end>t?s[o.userId]=o:n.push(i)}return n.length===0?Promise.resolve(s):new Promise((i,o)=>{this._restClient.actions.v2.call.make({method:this._getPublicListMethod,params:{users:n}}).then(a=>{if(!a.isSuccess)return o(this.publicIdsUnavailable(new Error(a.getErrorMessages().join("; "))));const c=a.getData();c?.result&&this.setPublicIds(Object.values(c.result));for(const u of n){const l=this._publicIds.get(u);l&&(s[l.userId]=l)}if(Object.keys(s).length===0)return o(this.publicIdsUnavailable(new Error(`\`${this._getPublicListMethod}\` answered without a channel for any requested user`)));i(s)}).catch(a=>a instanceof R&&a.code===Yl?o(a):o(this.publicIdsUnavailable(a)))})}publicIdsUnavailable(e){return this.getLogger().error("some error in getPublicIds",{error:e}).catch(()=>{}),new R({code:Yl,description:`Pull: could not resolve channel ids through \`${this._getPublicListMethod}\`, so there is nobody to send to. Publishing from the client needs that method; that method is not part of the application REST surface \u2014 put messages into the channel with \`pull.application.event.add\` from your back end instead.`,status:0,...e instanceof Error?{originalError:e}:{}})}setPublicIds(e){e.forEach(t=>{const s=Number(t.user_id);this._publicIds.set(s,{userId:s,publicId:t.public_id,signature:t.signature,start:new Date(t.start),end:new Date(t.end)})})}}var Jr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zm(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var qi={exports:{}};/*!
* protobuf.js v6.8.6 (c) 2016, daniel wirtz
* compiled mon, 26 feb 2018 11:35:34 utc
* licensed under the bsd-3-clause license
* see: https://github.com/dcodeio/protobuf.js for details
*
* Modify a list for integration with Bitrix Framework:
* - removed integration with RequireJS and AMD package builders;
*/var Zl;function Jm(){return Zl||(Zl=1,(function(r){(function(e){(function(t,s,n){function i(a){var c=s[a];return c||t[a][0].call(c=s[a]={exports:{}},i,c,c.exports),c.exports}var o=i(n[0]);r&&r.exports&&(r.exports=o)})({1:[function(t,s,n){s.exports=i;function i(o,a){for(var c=new Array(arguments.length-1),u=0,l=2,h=!0;l<arguments.length;)c[u++]=arguments[l++];return new Promise(function(d,f){c[u]=function(p){if(h)if(h=!1,p)f(p);else{for(var g=new Array(arguments.length-1),y=0;y<g.length;)g[y++]=arguments[y];d.apply(null,g)}};try{o.apply(a||null,c)}catch(p){h&&(h=!1,f(p))}})}},{}],2:[function(t,s,n){var i=n;i.length=function(l){var h=l.length;if(!h)return 0;for(var d=0;--h%4>1&&l.charAt(h)==="=";)++d;return Math.ceil(l.length*3)/4-d};for(var o=new Array(64),a=new Array(123),c=0;c<64;)a[o[c]=c<26?c+65:c<52?c+71:c<62?c-4:c-59|43]=c++;i.encode=function(l,h,d){for(var f=null,p=[],g=0,y=0,w;h<d;){var _=l[h++];switch(y){case 0:p[g++]=o[_>>2],w=(_&3)<<4,y=1;break;case 1:p[g++]=o[w|_>>4],w=(_&15)<<2,y=2;break;case 2:p[g++]=o[w|_>>6],p[g++]=o[_&63],y=0;break}g>8191&&((f||(f=[])).push(String.fromCharCode.apply(String,p)),g=0)}return y&&(p[g++]=o[w],p[g++]=61,y===1&&(p[g++]=61)),f?(g&&f.push(String.fromCharCode.apply(String,p.slice(0,g))),f.join("")):String.fromCharCode.apply(String,p.slice(0,g))};var u="invalid encoding";i.decode=function(l,h,d){for(var f=d,p=0,g,y=0;y<l.length;){var w=l.charCodeAt(y++);if(w===61&&p>1)break;if((w=a[w])===e)throw Error(u);switch(p){case 0:g=w,p=1;break;case 1:h[d++]=g<<2|(w&48)>>4,g=w,p=2;break;case 2:h[d++]=(g&15)<<4|(w&60)>>2,g=w,p=3;break;case 3:h[d++]=(g&3)<<6|w,p=0;break}}if(p===1)throw Error(u);return d-f},i.test=function(l){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(l)}},{}],3:[function(t,s,n){s.exports=i;function i(o,a){typeof o=="string"&&(a=o,o=e);var c=[];function u(h){if(typeof h!="string"){var d=l();if(i.verbose&&console.log("codegen: "+d),d="return "+d,h){for(var f=Object.keys(h),p=new Array(f.length+1),g=new Array(f.length),y=0;y<f.length;)p[y]=f[y],g[y]=h[f[y++]];return p[y]=d,Function.apply(null,p).apply(null,g)}return Function(d)()}for(var w=new Array(arguments.length-1),_=0;_<w.length;)w[_]=arguments[++_];if(_=0,h=h.replace(/%([%dfijs])/g,function(S,m){var T=w[_++];switch(m){case"d":case"f":return String(Number(T));case"i":return String(Math.floor(T));case"j":return JSON.stringify(T);case"s":return String(T)}return"%"}),_!==w.length)throw Error("parameter count mismatch");return c.push(h),u}function l(h){return"function "+(h||a||"")+"("+(o&&o.join(",")||"")+`){
`+c.join(`
`)+`
}`}return u.toString=l,u}i.verbose=!1},{}],4:[function(t,s,n){s.exports=i;function i(){this._listeners={}}i.prototype.on=function(o,a,c){return(this._listeners[o]||(this._listeners[o]=[])).push({fn:a,ctx:c||this}),this},i.prototype.off=function(o,a){if(o===e)this._listeners={};else if(a===e)this._listeners[o]=[];else for(var c=this._listeners[o],u=0;u<c.length;)c[u].fn===a?c.splice(u,1):++u;return this},i.prototype.emit=function(o){var a=this._listeners[o];if(a){for(var c=[],u=1;u<arguments.length;)c.push(arguments[u++]);for(u=0;u<a.length;)a[u].fn.apply(a[u++].ctx,c)}return this}},{}],5:[function(t,s,n){s.exports=c;var i=t(1),o=t(7),a=o("fs");function c(u,l,h){return typeof l=="function"?(h=l,l={}):l||(l={}),h?!l.xhr&&a&&a.readFile?a.readFile(u,function(d,f){return d&&typeof XMLHttpRequest<"u"?c.xhr(u,l,h):d?h(d):h(null,l.binary?f:f.toString("utf8"))}):c.xhr(u,l,h):i(c,this,u,l)}c.xhr=function(u,l,h){var d=new XMLHttpRequest;d.onreadystatechange=function(){if(d.readyState!==4)return e;if(d.status!==0&&d.status!==200)return h(Error("status "+d.status));if(l.binary){var f=d.response;if(!f){f=[];for(var p=0;p<d.responseText.length;++p)f.push(d.responseText.charCodeAt(p)&255)}return h(null,typeof Uint8Array<"u"?new Uint8Array(f):f)}return h(null,d.responseText)},l.binary&&("overrideMimeType"in d&&d.overrideMimeType("text/plain; charset=x-user-defined"),d.responseType="arraybuffer"),d.open("GET",u),d.send()}},{1:1,7:7}],6:[function(t,s,n){s.exports=i(i);function i(l){return typeof Float32Array<"u"?(function(){var h=new Float32Array([-0]),d=new Uint8Array(h.buffer),f=d[3]===128;function p(_,S,m){h[0]=_,S[m]=d[0],S[m+1]=d[1],S[m+2]=d[2],S[m+3]=d[3]}function g(_,S,m){h[0]=_,S[m]=d[3],S[m+1]=d[2],S[m+2]=d[1],S[m+3]=d[0]}l.writeFloatLE=f?p:g,l.writeFloatBE=f?g:p;function y(_,S){return d[0]=_[S],d[1]=_[S+1],d[2]=_[S+2],d[3]=_[S+3],h[0]}function w(_,S){return d[3]=_[S],d[2]=_[S+1],d[1]=_[S+2],d[0]=_[S+3],h[0]}l.readFloatLE=f?y:w,l.readFloatBE=f?w:y})():(function(){function h(f,p,g,y){var w=p<0?1:0;if(w&&(p=-p),p===0)f(1/p>0?0:2147483648,g,y);else if(isNaN(p))f(2143289344,g,y);else if(p>34028234663852886e22)f((w<<31|2139095040)>>>0,g,y);else if(p<11754943508222875e-54)f((w<<31|Math.round(p/1401298464324817e-60))>>>0,g,y);else{var _=Math.floor(Math.log(p)/Math.LN2),S=Math.round(p*Math.pow(2,-_)*8388608)&8388607;f((w<<31|_+127<<23|S)>>>0,g,y)}}l.writeFloatLE=h.bind(null,o),l.writeFloatBE=h.bind(null,a);function d(f,p,g){var y=f(p,g),w=(y>>31)*2+1,_=y>>>23&255,S=y&8388607;return _===255?S?NaN:w*(1/0):_===0?w*1401298464324817e-60*S:w*Math.pow(2,_-150)*(S+8388608)}l.readFloatLE=d.bind(null,c),l.readFloatBE=d.bind(null,u)})(),typeof Float64Array<"u"?(function(){var h=new Float64Array([-0]),d=new Uint8Array(h.buffer),f=d[7]===128;function p(_,S,m){h[0]=_,S[m]=d[0],S[m+1]=d[1],S[m+2]=d[2],S[m+3]=d[3],S[m+4]=d[4],S[m+5]=d[5],S[m+6]=d[6],S[m+7]=d[7]}function g(_,S,m){h[0]=_,S[m]=d[7],S[m+1]=d[6],S[m+2]=d[5],S[m+3]=d[4],S[m+4]=d[3],S[m+5]=d[2],S[m+6]=d[1],S[m+7]=d[0]}l.writeDoubleLE=f?p:g,l.writeDoubleBE=f?g:p;function y(_,S){return d[0]=_[S],d[1]=_[S+1],d[2]=_[S+2],d[3]=_[S+3],d[4]=_[S+4],d[5]=_[S+5],d[6]=_[S+6],d[7]=_[S+7],h[0]}function w(_,S){return d[7]=_[S],d[6]=_[S+1],d[5]=_[S+2],d[4]=_[S+3],d[3]=_[S+4],d[2]=_[S+5],d[1]=_[S+6],d[0]=_[S+7],h[0]}l.readDoubleLE=f?y:w,l.readDoubleBE=f?w:y})():(function(){function h(f,p,g,y,w,_){var S=y<0?1:0;if(S&&(y=-y),y===0)f(0,w,_+p),f(1/y>0?0:2147483648,w,_+g);else if(isNaN(y))f(0,w,_+p),f(2146959360,w,_+g);else if(y>17976931348623157e292)f(0,w,_+p),f((S<<31|2146435072)>>>0,w,_+g);else{var m;if(y<22250738585072014e-324)m=y/5e-324,f(m>>>0,w,_+p),f((S<<31|m/4294967296)>>>0,w,_+g);else{var T=Math.floor(Math.log(y)/Math.LN2);T===1024&&(T=1023),m=y*Math.pow(2,-T),f(m*4503599627370496>>>0,w,_+p),f((S<<31|T+1023<<20|m*1048576&1048575)>>>0,w,_+g)}}}l.writeDoubleLE=h.bind(null,o,0,4),l.writeDoubleBE=h.bind(null,a,4,0);function d(f,p,g,y,w){var _=f(y,w+p),S=f(y,w+g),m=(S>>31)*2+1,T=S>>>20&2047,E=4294967296*(S&1048575)+_;return T===2047?E?NaN:m*(1/0):T===0?m*5e-324*E:m*Math.pow(2,T-1075)*(E+4503599627370496)}l.readDoubleLE=d.bind(null,c,0,4),l.readDoubleBE=d.bind(null,u,4,0)})(),l}function o(l,h,d){h[d]=l&255,h[d+1]=l>>>8&255,h[d+2]=l>>>16&255,h[d+3]=l>>>24}function a(l,h,d){h[d]=l>>>24,h[d+1]=l>>>16&255,h[d+2]=l>>>8&255,h[d+3]=l&255}function c(l,h){return(l[h]|l[h+1]<<8|l[h+2]<<16|l[h+3]<<24)>>>0}function u(l,h){return(l[h]<<24|l[h+1]<<16|l[h+2]<<8|l[h+3])>>>0}},{}],7:[function(t,s,n){s.exports=i;function i(o){try{var a=t(o);if(a&&(a.length||Object.keys(a).length))return a}catch{}return null}},{}],8:[function(t,s,n){var i=n,o=i.isAbsolute=function(c){return/^(?:\/|\w+:)/.test(c)},a=i.normalize=function(c){c=c.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var u=c.split("/"),l=o(c),h="";l&&(h=u.shift()+"/");for(var d=0;d<u.length;)u[d]===".."?d>0&&u[d-1]!==".."?u.splice(--d,2):l?u.splice(d,1):++d:u[d]==="."?u.splice(d,1):++d;return h+u.join("/")};i.resolve=function(c,u,l){return l||(u=a(u)),o(u)?u:(l||(c=a(c)),(c=c.replace(/(?:\/|^)[^/]+$/,"")).length?a(c+"/"+u):u)}},{}],9:[function(t,s,n){s.exports=i;function i(o,a,c){var u=c||8192,l=u>>>1,h=null,d=u;return function(f){if(f<1||f>l)return o(f);d+f>u&&(h=o(u),d=0);var p=a.call(h,d,d+=f);return d&7&&(d=(d|7)+1),p}}},{}],10:[function(t,s,n){var i=n;i.length=function(o){for(var a=0,c=0,u=0;u<o.length;++u)c=o.charCodeAt(u),c<128?a+=1:c<2048?a+=2:(c&64512)===55296&&(o.charCodeAt(u+1)&64512)===56320?(++u,a+=4):a+=3;return a},i.read=function(o,a,c){var u=c-a;if(u<1)return"";for(var l=null,h=[],d=0,f;a<c;)f=o[a++],f<128?h[d++]=f:f>191&&f<224?h[d++]=(f&31)<<6|o[a++]&63:f>239&&f<365?(f=((f&7)<<18|(o[a++]&63)<<12|(o[a++]&63)<<6|o[a++]&63)-65536,h[d++]=55296+(f>>10),h[d++]=56320+(f&1023)):h[d++]=(f&15)<<12|(o[a++]&63)<<6|o[a++]&63,d>8191&&((l||(l=[])).push(String.fromCharCode.apply(String,h)),d=0);return l?(d&&l.push(String.fromCharCode.apply(String,h.slice(0,d))),l.join("")):String.fromCharCode.apply(String,h.slice(0,d))},i.write=function(o,a,c){for(var u=c,l,h,d=0;d<o.length;++d)l=o.charCodeAt(d),l<128?a[c++]=l:l<2048?(a[c++]=l>>6|192,a[c++]=l&63|128):(l&64512)===55296&&((h=o.charCodeAt(d+1))&64512)===56320?(l=65536+((l&1023)<<10)+(h&1023),++d,a[c++]=l>>18|240,a[c++]=l>>12&63|128,a[c++]=l>>6&63|128,a[c++]=l&63|128):(a[c++]=l>>12|224,a[c++]=l>>6&63|128,a[c++]=l&63|128);return c-u}},{}],11:[function(t,s,n){s.exports=o;var i=/\/|\./;function o(c,u){i.test(c)||(c="google/protobuf/"+c+".proto",u={nested:{google:{nested:{protobuf:{nested:u}}}}}),o[c]=u}o("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var a;o("duration",{Duration:a={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),o("timestamp",{Timestamp:a}),o("empty",{Empty:{fields:{}}}),o("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),o("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),o("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),o.get=function(c){return o[c]||null}},{}],12:[function(t,s,n){var i=n,o=t(15),a=t(37);function c(l,h,d,f){if(h.resolvedType)if(h.resolvedType instanceof o){l("switch(d%s){",f);for(var p=h.resolvedType.values,g=Object.keys(p),y=0;y<g.length;++y)h.repeated&&p[g[y]]===h.typeDefault&&l("default:"),l("case%j:",g[y])("case %i:",p[g[y]])("m%s=%j",f,p[g[y]])("break");l("}")}else l('if(typeof d%s!=="object")',f)("throw TypeError(%j)",h.fullName+": object expected")("m%s=types[%i].fromObject(d%s)",f,d,f);else{var w=!1;switch(h.type){case"double":case"float":l("m%s=Number(d%s)",f,f);break;case"uint32":case"fixed32":l("m%s=d%s>>>0",f,f);break;case"int32":case"sint32":case"sfixed32":l("m%s=d%s|0",f,f);break;case"uint64":w=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":l("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",f,f,w)('else if(typeof d%s==="string")',f)("m%s=parseInt(d%s,10)",f,f)('else if(typeof d%s==="number")',f)("m%s=d%s",f,f)('else if(typeof d%s==="object")',f)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",f,f,f,w?"true":"");break;case"bytes":l('if(typeof d%s==="string")',f)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",f,f,f)("else if(d%s.length)",f)("m%s=d%s",f,f);break;case"string":l("m%s=String(d%s)",f,f);break;case"bool":l("m%s=Boolean(d%s)",f,f);break}}return l}i.fromObject=function(l){var h=l.fieldsArray,d=a.codegen(["d"],l.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!h.length)return d("return new this.ctor");d("var m=new this.ctor");for(var f=0;f<h.length;++f){var p=h[f].resolve(),g=a.safeProp(p.name);p.map?(d("if(d%s){",g)('if(typeof d%s!=="object")',g)("throw TypeError(%j)",p.fullName+": object expected")("m%s={}",g)("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){",g),c(d,p,f,g+"[ks[i]]")("}")("}")):p.repeated?(d("if(d%s){",g)("if(!Array.isArray(d%s))",g)("throw TypeError(%j)",p.fullName+": array expected")("m%s=[]",g)("for(var i=0;i<d%s.length;++i){",g),c(d,p,f,g+"[i]")("}")("}")):(p.resolvedType instanceof o||d("if(d%s!=null){",g),c(d,p,f,g),p.resolvedType instanceof o||d("}"))}return d("return m")};function u(l,h,d,f){if(h.resolvedType)h.resolvedType instanceof o?l("d%s=o.enums===String?types[%i].values[m%s]:m%s",f,d,f,f):l("d%s=types[%i].toObject(m%s,o)",f,d,f);else{var p=!1;switch(h.type){case"double":case"float":l("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",f,f,f,f);break;case"uint64":p=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":l('if(typeof m%s==="number")',f)("d%s=o.longs===String?String(m%s):m%s",f,f,f)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",f,f,f,f,p?"true":"",f);break;case"bytes":l("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",f,f,f,f,f);break;default:l("d%s=m%s",f,f);break}}return l}i.toObject=function(l){var h=l.fieldsArray.slice().sort(a.compareFieldsById);if(!h.length)return a.codegen()("return {}");for(var d=a.codegen(["m","o"],l.name+"$toObject")("if(!o)")("o={}")("var d={}"),f=[],p=[],g=[],y=0;y<h.length;++y)h[y].partOf||(h[y].resolve().repeated?f:h[y].map?p:g).push(h[y]);if(f.length){for(d("if(o.arrays||o.defaults){"),y=0;y<f.length;++y)d("d%s=[]",a.safeProp(f[y].name));d("}")}if(p.length){for(d("if(o.objects||o.defaults){"),y=0;y<p.length;++y)d("d%s={}",a.safeProp(p[y].name));d("}")}if(g.length){for(d("if(o.defaults){"),y=0;y<g.length;++y){var w=g[y],_=a.safeProp(w.name);w.resolvedType instanceof o?d("d%s=o.enums===String?%j:%j",_,w.resolvedType.valuesById[w.typeDefault],w.typeDefault):w.long?d("if(util.Long){")("var n=new util.Long(%i,%i,%j)",w.typeDefault.low,w.typeDefault.high,w.typeDefault.unsigned)("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n",_)("}else")("d%s=o.longs===String?%j:%i",_,w.typeDefault.toString(),w.typeDefault.toNumber()):w.bytes?d("d%s=o.bytes===String?%j:%s",_,String.fromCharCode.apply(String,w.typeDefault),"["+Array.prototype.slice.call(w.typeDefault).join(",")+"]"):d("d%s=%j",_,w.typeDefault)}d("}")}var S=!1;for(y=0;y<h.length;++y){var w=h[y],m=l._fieldsArray.indexOf(w),_=a.safeProp(w.name);w.map?(S||(S=!0,d("var ks2")),d("if(m%s&&(ks2=Object.keys(m%s)).length){",_,_)("d%s={}",_)("for(var j=0;j<ks2.length;++j){"),u(d,w,m,_+"[ks2[j]]")("}")):w.repeated?(d("if(m%s&&m%s.length){",_,_)("d%s=[]",_)("for(var j=0;j<m%s.length;++j){",_),u(d,w,m,_+"[j]")("}")):(d("if(m%s!=null&&m.hasOwnProperty(%j)){",_,w.name),u(d,w,m,_),w.partOf&&d("if(o.oneofs)")("d%s=%j",a.safeProp(w.partOf.name),w.name)),d("}")}return d("return d")}},{15:15,37:37}],13:[function(t,s,n){s.exports=u;var i=t(15),o=t(36),a=t(37);function c(l){return"missing required '"+l.name+"'"}function u(l){var h=a.codegen(["r","l"],l.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(l.fieldsArray.filter(function(w){return w.map}).length?",k":""))("while(r.pos<c){")("var t=r.uint32()");l.group&&h("if((t&7)===4)")("break"),h("switch(t>>>3){");for(var d=0;d<l.fieldsArray.length;++d){var f=l._fieldsArray[d].resolve(),p=f.resolvedType instanceof i?"int32":f.type,g="m"+a.safeProp(f.name);h("case %i:",f.id),f.map?(h("r.skip().pos++")("if(%s===util.emptyObject)",g)("%s={}",g)("k=r.%s()",f.keyType)("r.pos++"),o.long[f.keyType]!==e?o.basic[p]===e?h('%s[typeof k==="object"?util.longToHash(k):k]=types[%i].decode(r,r.uint32())',g,d):h('%s[typeof k==="object"?util.longToHash(k):k]=r.%s()',g,p):o.basic[p]===e?h("%s[k]=types[%i].decode(r,r.uint32())",g,d):h("%s[k]=r.%s()",g,p)):f.repeated?(h("if(!(%s&&%s.length))",g,g)("%s=[]",g),o.packed[p]!==e&&h("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos<c2)")("%s.push(r.%s())",g,p)("}else"),o.basic[p]===e?h(f.resolvedType.group?"%s.push(types[%i].decode(r))":"%s.push(types[%i].decode(r,r.uint32()))",g,d):h("%s.push(r.%s())",g,p)):o.basic[p]===e?h(f.resolvedType.group?"%s=types[%i].decode(r)":"%s=types[%i].decode(r,r.uint32())",g,d):h("%s=r.%s()",g,p),h("break")}for(h("default:")("r.skipType(t&7)")("break")("}")("}"),d=0;d<l._fieldsArray.length;++d){var y=l._fieldsArray[d];y.required&&h("if(!m.hasOwnProperty(%j))",y.name)("throw util.ProtocolError(%j,{instance:m})",c(y))}return h("return m")}},{15:15,36:36,37:37}],14:[function(t,s,n){s.exports=u;var i=t(15),o=t(36),a=t(37);function c(l,h,d,f){return h.resolvedType.group?l("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",d,f,(h.id<<3|3)>>>0,(h.id<<3|4)>>>0):l("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",d,f,(h.id<<3|2)>>>0)}function u(l){for(var h=a.codegen(["m","w"],l.name+"$encode")("if(!w)")("w=Writer.create()"),p,d,f=l.fieldsArray.slice().sort(a.compareFieldsById),p=0;p<f.length;++p){var g=f[p].resolve(),y=l._fieldsArray.indexOf(g),w=g.resolvedType instanceof i?"int32":g.type,_=o.basic[w];d="m"+a.safeProp(g.name),g.map?(h("if(%s!=null&&m.hasOwnProperty(%j)){",d,g.name)("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){",d)("w.uint32(%i).fork().uint32(%i).%s(ks[i])",(g.id<<3|2)>>>0,8|o.mapKey[g.keyType],g.keyType),_===e?h("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",y,d):h(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|_,w,d),h("}")("}")):g.repeated?(h("if(%s!=null&&%s.length){",d,d),g.packed&&o.packed[w]!==e?h("w.uint32(%i).fork()",(g.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",d)("w.%s(%s[i])",w,d)("w.ldelim()"):(h("for(var i=0;i<%s.length;++i)",d),_===e?c(h,g,y,d+"[i]"):h("w.uint32(%i).%s(%s[i])",(g.id<<3|_)>>>0,w,d)),h("}")):(g.optional&&h("if(%s!=null&&m.hasOwnProperty(%j))",d,g.name),_===e?c(h,g,y,d):h("w.uint32(%i).%s(%s)",(g.id<<3|_)>>>0,w,d))}return h("return w")}},{15:15,36:36,37:37}],15:[function(t,s,n){s.exports=c;var i=t(24);((c.prototype=Object.create(i.prototype)).constructor=c).className="Enum";var o=t(23),a=t(37);function c(u,l,h,d,f){if(i.call(this,u,h),l&&typeof l!="object")throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=d,this.comments=f||{},this.reserved=e,l)for(var p=Object.keys(l),g=0;g<p.length;++g)typeof l[p[g]]=="number"&&(this.valuesById[this.values[p[g]]=l[p[g]]]=p[g])}c.fromJSON=function(u,l){var h=new c(u,l.values,l.options,l.comment,l.comments);return h.reserved=l.reserved,h},c.prototype.toJSON=function(u){var l=u?!!u.keepComments:!1;return a.toObject(["options",this.options,"values",this.values,"reserved",this.reserved&&this.reserved.length?this.reserved:e,"comment",l?this.comment:e,"comments",l?this.comments:e])},c.prototype.add=function(u,l,h){if(!a.isString(u))throw TypeError("name must be a string");if(!a.isInteger(l))throw TypeError("id must be an integer");if(this.values[u]!==e)throw Error("duplicate name '"+u+"' in "+this);if(this.isReservedId(l))throw Error("id "+l+" is reserved in "+this);if(this.isReservedName(u))throw Error("name '"+u+"' is reserved in "+this);if(this.valuesById[l]!==e){if(!(this.options&&this.options.allow_alias))throw Error("duplicate id "+l+" in "+this);this.values[u]=l}else this.valuesById[this.values[u]=l]=u;return this.comments[u]=h||null,this},c.prototype.remove=function(u){if(!a.isString(u))throw TypeError("name must be a string");var l=this.values[u];if(l==null)throw Error("name '"+u+"' does not exist in "+this);return delete this.valuesById[l],delete this.values[u],delete this.comments[u],this},c.prototype.isReservedId=function(u){return o.isReservedId(this.reserved,u)},c.prototype.isReservedName=function(u){return o.isReservedName(this.reserved,u)}},{23:23,24:24,37:37}],16:[function(t,s,n){s.exports=h;var i=t(24);((h.prototype=Object.create(i.prototype)).constructor=h).className="Field";var o=t(15),a=t(36),c=t(37),u,l=/^required|optional|repeated$/;h.fromJSON=function(d,f){return new h(d,f.id,f.type,f.rule,f.extend,f.options,f.comment)};function h(d,f,p,g,y,w,_){if(c.isObject(g)?(_=y,w=g,g=y=e):c.isObject(y)&&(_=w,w=y,y=e),i.call(this,d,w),!c.isInteger(f)||f<0)throw TypeError("id must be a non-negative integer");if(!c.isString(p))throw TypeError("type must be a string");if(g!==e&&!l.test(g=g.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(y!==e&&!c.isString(y))throw TypeError("extend must be a string");this.rule=g&&g!=="optional"?g:e,this.type=p,this.id=f,this.extend=y||e,this.required=g==="required",this.optional=!this.required,this.repeated=g==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=c.Long?a.long[p]!==e:!1,this.bytes=p==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=_}Object.defineProperty(h.prototype,"packed",{get:function(){return this._packed===null&&(this._packed=this.getOption("packed")!==!1),this._packed}}),h.prototype.setOption=function(d,f,p){return d==="packed"&&(this._packed=null),i.prototype.setOption.call(this,d,f,p)},h.prototype.toJSON=function(d){var f=d?!!d.keepComments:!1;return c.toObject(["rule",this.rule!=="optional"&&this.rule||e,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",f?this.comment:e])},h.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=a.defaults[this.type])===e&&(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof u?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]),this.options&&this.options.default!=null&&(this.typeDefault=this.options.default,this.resolvedType instanceof o&&typeof this.typeDefault=="string"&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&((this.options.packed===!0||this.options.packed!==e&&this.resolvedType&&!(this.resolvedType instanceof o))&&delete this.options.packed,Object.keys(this.options).length||(this.options=e)),this.long)this.typeDefault=c.Long.fromNumber(this.typeDefault,this.type.charAt(0)==="u"),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&typeof this.typeDefault=="string"){var d;c.base64.test(this.typeDefault)?c.base64.decode(this.typeDefault,d=c.newBuffer(c.base64.length(this.typeDefault)),0):c.utf8.write(this.typeDefault,d=c.newBuffer(c.utf8.length(this.typeDefault)),0),this.typeDefault=d}return this.map?this.defaultValue=c.emptyObject:this.repeated?this.defaultValue=c.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof u&&(this.parent.ctor.prototype[this.name]=this.defaultValue),i.prototype.resolve.call(this)},h.d=function(d,f,p,g){return typeof f=="function"?f=c.decorateType(f).name:f&&typeof f=="object"&&(f=c.decorateEnum(f).name),function(y,w){c.decorateType(y.constructor).add(new h(w,d,f,p,{default:g}))}},h._configure=function(d){u=d}},{15:15,24:24,36:36,37:37}],17:[function(t,s,n){var i=s.exports=t(18);i.build="light";function o(c,u,l){return typeof u=="function"?(l=u,u=new i.Root):u||(u=new i.Root),u.load(c,l)}i.load=o;function a(c,u){return u||(u=new i.Root),u.loadSync(c)}i.loadSync=a,i.encoder=t(14),i.decoder=t(13),i.verifier=t(40),i.converter=t(12),i.ReflectionObject=t(24),i.Namespace=t(23),i.Root=t(29),i.Enum=t(15),i.Type=t(35),i.Field=t(16),i.OneOf=t(25),i.MapField=t(20),i.Service=t(33),i.Method=t(22),i.Message=t(21),i.wrappers=t(41),i.types=t(36),i.util=t(37),i.ReflectionObject._configure(i.Root),i.Namespace._configure(i.Type,i.Service),i.Root._configure(i.Type),i.Field._configure(i.Type)},{12:12,13:13,14:14,15:15,16:16,18:18,20:20,21:21,22:22,23:23,24:24,25:25,29:29,33:33,35:35,36:36,37:37,40:40,41:41}],18:[function(t,s,n){var i=n;i.build="minimal",i.Writer=t(42),i.BufferWriter=t(43),i.Reader=t(27),i.BufferReader=t(28),i.util=t(39),i.rpc=t(31),i.roots=t(30),i.configure=o;function o(){i.Reader._configure(i.BufferReader),i.util._configure()}i.Writer._configure(i.BufferWriter),o()},{27:27,28:28,30:30,31:31,39:39,42:42,43:43}],19:[function(t,s,n){var i=s.exports=t(17);i.build="full",i.tokenize=t(34),i.parse=t(26),i.common=t(11),i.Root._configure(i.Type,i.parse,i.common)},{11:11,17:17,26:26,34:34}],20:[function(t,s,n){s.exports=c;var i=t(16);((c.prototype=Object.create(i.prototype)).constructor=c).className="MapField";var o=t(36),a=t(37);function c(u,l,h,d,f,p){if(i.call(this,u,l,d,e,e,f,p),!a.isString(h))throw TypeError("keyType must be a string");this.keyType=h,this.resolvedKeyType=null,this.map=!0}c.fromJSON=function(u,l){return new c(u,l.id,l.keyType,l.type,l.options,l.comment)},c.prototype.toJSON=function(u){var l=u?!!u.keepComments:!1;return a.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",l?this.comment:e])},c.prototype.resolve=function(){if(this.resolved)return this;if(o.mapKey[this.keyType]===e)throw Error("invalid key type: "+this.keyType);return i.prototype.resolve.call(this)},c.d=function(u,l,h){return typeof h=="function"?h=a.decorateType(h).name:h&&typeof h=="object"&&(h=a.decorateEnum(h).name),function(d,f){a.decorateType(d.constructor).add(new c(f,u,l,h))}}},{16:16,36:36,37:37}],21:[function(t,s,n){s.exports=o;var i=t(39);function o(a){if(a)for(var c=Object.keys(a),u=0;u<c.length;++u)this[c[u]]=a[c[u]]}o.create=function(a){return this.$type.create(a)},o.encode=function(a,c){return this.$type.encode(a,c)},o.encodeDelimited=function(a,c){return this.$type.encodeDelimited(a,c)},o.decode=function(a){return this.$type.decode(a)},o.decodeDelimited=function(a){return this.$type.decodeDelimited(a)},o.verify=function(a){return this.$type.verify(a)},o.fromObject=function(a){return this.$type.fromObject(a)},o.toObject=function(a,c){return this.$type.toObject(a,c)},o.prototype.toJSON=function(){return this.$type.toObject(this,i.toJSONOptions)}},{39:39}],22:[function(t,s,n){s.exports=a;var i=t(24);((a.prototype=Object.create(i.prototype)).constructor=a).className="Method";var o=t(37);function a(c,u,l,h,d,f,p,g){if(o.isObject(d)?(p=d,d=f=e):o.isObject(f)&&(p=f,f=e),!(u===e||o.isString(u)))throw TypeError("type must be a string");if(!o.isString(l))throw TypeError("requestType must be a string");if(!o.isString(h))throw TypeError("responseType must be a string");i.call(this,c,p),this.type=u||"rpc",this.requestType=l,this.requestStream=d?!0:e,this.responseType=h,this.responseStream=f?!0:e,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=g}a.fromJSON=function(c,u){return new a(c,u.type,u.requestType,u.responseType,u.requestStream,u.responseStream,u.options,u.comment)},a.prototype.toJSON=function(c){var u=c?!!c.keepComments:!1;return o.toObject(["type",this.type!=="rpc"&&this.type||e,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",u?this.comment:e])},a.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),i.prototype.resolve.call(this))}},{24:24,37:37}],23:[function(t,s,n){s.exports=d;var i=t(24);((d.prototype=Object.create(i.prototype)).constructor=d).className="Namespace";var o=t(15),a=t(16),c=t(37),u,l;d.fromJSON=function(p,g){return new d(p,g.options).addJSON(g.nested)};function h(p,g){if(!(p&&p.length))return e;for(var y={},w=0;w<p.length;++w)y[p[w].name]=p[w].toJSON(g);return y}d.arrayToJSON=h,d.isReservedId=function(p,g){if(p){for(var y=0;y<p.length;++y)if(typeof p[y]!="string"&&p[y][0]<=g&&p[y][1]>=g)return!0}return!1},d.isReservedName=function(p,g){if(p){for(var y=0;y<p.length;++y)if(p[y]===g)return!0}return!1};function d(p,g){i.call(this,p,g),this.nested=e,this._nestedArray=null}function f(p){return p._nestedArray=null,p}Object.defineProperty(d.prototype,"nestedArray",{get:function(){return this._nestedArray||(this._nestedArray=c.toArray(this.nested))}}),d.prototype.toJSON=function(p){return c.toObject(["options",this.options,"nested",h(this.nestedArray,p)])},d.prototype.addJSON=function(p){var g=this;if(p)for(var y=Object.keys(p),w=0,_;w<y.length;++w)_=p[y[w]],g.add((_.fields!==e?u.fromJSON:_.values!==e?o.fromJSON:_.methods!==e?l.fromJSON:_.id!==e?a.fromJSON:d.fromJSON)(y[w],_));return this},d.prototype.get=function(p){return this.nested&&this.nested[p]||null},d.prototype.getEnum=function(p){if(this.nested&&this.nested[p]instanceof o)return this.nested[p].values;throw Error("no such enum: "+p)},d.prototype.add=function(p){if(!(p instanceof a&&p.extend!==e||p instanceof u||p instanceof o||p instanceof l||p instanceof d))throw TypeError("object must be a valid nested object");if(!this.nested)this.nested={};else{var g=this.get(p.name);if(g)if(g instanceof d&&p instanceof d&&!(g instanceof u||g instanceof l)){for(var y=g.nestedArray,w=0;w<y.length;++w)p.add(y[w]);this.remove(g),this.nested||(this.nested={}),p.setOptions(g.options,!0)}else throw Error("duplicate name '"+p.name+"' in "+this)}return this.nested[p.name]=p,p.onAdd(this),f(this)},d.prototype.remove=function(p){if(!(p instanceof i))throw TypeError("object must be a ReflectionObject");if(p.parent!==this)throw Error(p+" is not a member of "+this);return delete this.nested[p.name],Object.keys(this.nested).length||(this.nested=e),p.onRemove(this),f(this)},d.prototype.define=function(p,g){if(c.isString(p))p=p.split(".");else if(!Array.isArray(p))throw TypeError("illegal path");if(p&&p.length&&p[0]==="")throw Error("path must be relative");for(var y=this;p.length>0;){var w=p.shift();if(y.nested&&y.nested[w]){if(y=y.nested[w],!(y instanceof d))throw Error("path conflicts with non-namespace objects")}else y.add(y=new d(w))}return g&&y.addJSON(g),y},d.prototype.resolveAll=function(){for(var p=this.nestedArray,g=0;g<p.length;)p[g]instanceof d?p[g++].resolveAll():p[g++].resolve();return this.resolve()},d.prototype.lookup=function(p,g,y){if(typeof g=="boolean"?(y=g,g=e):g&&!Array.isArray(g)&&(g=[g]),c.isString(p)&&p.length){if(p===".")return this.root;p=p.split(".")}else if(!p.length)return this;if(p[0]==="")return this.root.lookup(p.slice(1),g);var w=this.get(p[0]);if(w){if(p.length===1){if(!g||g.indexOf(w.constructor)>-1)return w}else if(w instanceof d&&(w=w.lookup(p.slice(1),g,!0)))return w}else for(var _=0;_<this.nestedArray.length;++_)if(this._nestedArray[_]instanceof d&&(w=this._nestedArray[_].lookup(p,g,!0)))return w;return this.parent===null||y?null:this.parent.lookup(p,g)},d.prototype.lookupType=function(p){var g=this.lookup(p,[u]);if(!g)throw Error("no such type: "+p);return g},d.prototype.lookupEnum=function(p){var g=this.lookup(p,[o]);if(!g)throw Error("no such Enum '"+p+"' in "+this);return g},d.prototype.lookupTypeOrEnum=function(p){var g=this.lookup(p,[u,o]);if(!g)throw Error("no such Type or Enum '"+p+"' in "+this);return g},d.prototype.lookupService=function(p){var g=this.lookup(p,[l]);if(!g)throw Error("no such Service '"+p+"' in "+this);return g},d._configure=function(p,g){u=p,l=g}},{15:15,16:16,24:24,37:37}],24:[function(t,s,n){s.exports=a,a.className="ReflectionObject";var i=t(37),o;function a(c,u){if(!i.isString(c))throw TypeError("name must be a string");if(u&&!i.isObject(u))throw TypeError("options must be an object");this.options=u,this.name=c,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(a.prototype,{root:{get:function(){for(var c=this;c.parent!==null;)c=c.parent;return c}},fullName:{get:function(){for(var c=[this.name],u=this.parent;u;)c.unshift(u.name),u=u.parent;return c.join(".")}}}),a.prototype.toJSON=function(){throw Error()},a.prototype.onAdd=function(c){this.parent&&this.parent!==c&&this.parent.remove(this),this.parent=c,this.resolved=!1;var u=c.root;u instanceof o&&u._handleAdd(this)},a.prototype.onRemove=function(c){var u=c.root;u instanceof o&&u._handleRemove(this),this.parent=null,this.resolved=!1},a.prototype.resolve=function(){return this.resolved?this:(this.root instanceof o&&(this.resolved=!0),this)},a.prototype.getOption=function(c){return this.options?this.options[c]:e},a.prototype.setOption=function(c,u,l){return(!l||!this.options||this.options[c]===e)&&((this.options||(this.options={}))[c]=u),this},a.prototype.setOptions=function(c,u){if(c)for(var l=Object.keys(c),h=0;h<l.length;++h)this.setOption(l[h],c[l[h]],u);return this},a.prototype.toString=function(){var c=this.constructor.className,u=this.fullName;return u.length?c+" "+u:c},a._configure=function(c){o=c}},{37:37}],25:[function(t,s,n){s.exports=c;var i=t(24);((c.prototype=Object.create(i.prototype)).constructor=c).className="OneOf";var o=t(16),a=t(37);function c(l,h,d,f){if(Array.isArray(h)||(d=h,h=e),i.call(this,l,d),!(h===e||Array.isArray(h)))throw TypeError("fieldNames must be an Array");this.oneof=h||[],this.fieldsArray=[],this.comment=f}c.fromJSON=function(l,h){return new c(l,h.oneof,h.options,h.comment)},c.prototype.toJSON=function(l){var h=l?!!l.keepComments:!1;return a.toObject(["options",this.options,"oneof",this.oneof,"comment",h?this.comment:e])};function u(l){if(l.parent)for(var h=0;h<l.fieldsArray.length;++h)l.fieldsArray[h].parent||l.parent.add(l.fieldsArray[h])}c.prototype.add=function(l){if(!(l instanceof o))throw TypeError("field must be a Field");return l.parent&&l.parent!==this.parent&&l.parent.remove(l),this.oneof.push(l.name),this.fieldsArray.push(l),l.partOf=this,u(this),this},c.prototype.remove=function(l){if(!(l instanceof o))throw TypeError("field must be a Field");var h=this.fieldsArray.indexOf(l);if(h<0)throw Error(l+" is not a member of "+this);return this.fieldsArray.splice(h,1),h=this.oneof.indexOf(l.name),h>-1&&this.oneof.splice(h,1),l.partOf=null,this},c.prototype.onAdd=function(l){i.prototype.onAdd.call(this,l);for(var h=this,d=0;d<this.oneof.length;++d){var f=l.get(this.oneof[d]);f&&!f.partOf&&(f.partOf=h,h.fieldsArray.push(f))}u(this)},c.prototype.onRemove=function(l){for(var h=0,d;h<this.fieldsArray.length;++h)(d=this.fieldsArray[h]).parent&&d.parent.remove(d);i.prototype.onRemove.call(this,l)},c.d=function(){for(var l=new Array(arguments.length),h=0;h<arguments.length;)l[h]=arguments[h++];return function(d,f){a.decorateType(d.constructor).add(new c(f,l)),Object.defineProperty(d,f,{get:a.oneOfGetter(l),set:a.oneOfSetter(l)})}}},{16:16,24:24,37:37}],26:[function(t,s,n){s.exports=D,D.filename=null,D.defaults={keepCase:!1};var i=t(34),o=t(29),a=t(35),c=t(16),u=t(20),l=t(25),h=t(15),d=t(33),f=t(22),p=t(36),g=t(37),y=/^[1-9][0-9]*$/,w=/^-?[1-9][0-9]*$/,_=/^0[x][0-9a-fA-F]+$/,S=/^-?0[x][0-9a-fA-F]+$/,m=/^0[0-7]+$/,T=/^-?0[0-7]+$/,E=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,v=/^[a-zA-Z_][a-zA-Z_0-9]*$/,I=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,P=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function D(z,re,$){re instanceof o||($=re,re=new o),$||($=D.defaults);var ee=i(z,$.alternateCommentMode||!1),U=ee.next,le=ee.push,ue=ee.peek,j=ee.skip,We=ee.cmnt,Ze=!0,lt,J,X,G,ae=!1,pe=re,ve=$.keepCase?function(N){return N}:g.camelCase;function q(N,k,x){var B=D.filename;return x||(D.filename=null),Error("illegal "+(k||"token")+" '"+N+"' ("+(B?B+", ":"")+"line "+ee.line+")")}function Xe(){var N=[],k;do{if((k=U())!=='"'&&k!=="'")throw q(k);N.push(U()),j(k),k=ue()}while(k==='"'||k==="'");return N.join("")}function se(N){var k=U();switch(k){case"'":case'"':return le(k),Xe();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return Ue(k,!0)}catch{if(I.test(k))return k;throw q(k,"value")}}function Be(N,k){var x,B;do k&&((x=ue())==='"'||x==="'")?N.push(Xe()):N.push([B=ut(U()),j("to",!0)?ut(U()):B]);while(j(",",!0));j(";")}function Ue(N,k){var x=1;switch(N.charAt(0)==="-"&&(x=-1,N=N.substring(1)),N){case"inf":case"INF":case"Inf":return x*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(y.test(N))return x*parseInt(N,10);if(_.test(N))return x*parseInt(N,16);if(m.test(N))return x*parseInt(N,8);if(E.test(N))return x*parseFloat(N);throw q(N,"number",k)}function ut(N,k){switch(N){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!k&&N.charAt(0)==="-")throw q(N,"id");if(w.test(N))return parseInt(N,10);if(S.test(N))return parseInt(N,16);if(T.test(N))return parseInt(N,8);throw q(N,"id")}function _r(){if(lt!==e)throw q("package");if(lt=U(),!I.test(lt))throw q(lt,"name");pe=pe.define(lt),j(";")}function wr(){var N=ue(),k;switch(N){case"weak":k=X||(X=[]),U();break;case"public":U();default:k=J||(J=[]);break}N=Xe(),j(";"),k.push(N)}function qs(){if(j("="),G=Xe(),ae=G==="proto3",!ae&&G!=="proto2")throw q(G,"syntax");j(";")}function Zr(N,k){switch(k){case"option":return Le(N,k),j(";"),!0;case"message":return ht(N,k),!0;case"enum":return Y(N,k),!0;case"service":return Kt(N,k),!0;case"extend":return Ty(N,k),!0}return!1}function we(N,k,x){var B=ee.line;if(N&&(N.comment=We(),N.filename=D.filename),j("{",!0)){for(var be;(be=U())!=="}";)k(be);j(";",!0)}else x&&x(),j(";"),N&&typeof N.comment!="string"&&(N.comment=We(B))}function ht(N,k){if(!v.test(k=U()))throw q(k,"type name");var x=new a(k);we(x,function(B){if(!Zr(x,B))switch(B){case"map":Xr(x);break;case"required":case"optional":case"repeated":$e(x,B);break;case"oneof":dt(x,B);break;case"extensions":Be(x.extensions||(x.extensions=[]));break;case"reserved":Be(x.reserved||(x.reserved=[]),!0);break;default:if(!ae||!I.test(B))throw q(B);le(B),$e(x,"optional");break}}),N.add(x)}function $e(N,k,x){var B=U();if(B==="group"){Hs(N,k);return}if(!I.test(B))throw q(B,"type");var be=U();if(!v.test(be))throw q(be,"name");be=ve(be),j("=");var Ie=new c(be,ut(U()),B,k,x);we(Ie,function(At){if(At==="option")Le(Ie,At),j(";");else throw q(At)},function(){es(Ie)}),N.add(Ie),!ae&&Ie.repeated&&(p.packed[B]!==e||p.basic[B]===e)&&Ie.setOption("packed",!1,!0)}function Hs(N,k){var x=U();if(!v.test(x))throw q(x,"name");var B=g.lcFirst(x);x===B&&(x=g.ucFirst(x)),j("=");var be=ut(U()),Ie=new a(x);Ie.group=!0;var At=new c(B,be,x,k);At.filename=D.filename,we(Ie,function(Gt){switch(Gt){case"option":Le(Ie,Gt),j(";");break;case"required":case"optional":case"repeated":$e(Ie,Gt);break;default:throw q(Gt)}}),N.add(Ie).add(At)}function Xr(N){j("<");var k=U();if(p.mapKey[k]===e)throw q(k,"type");j(",");var x=U();if(!I.test(x))throw q(x,"type");j(">");var B=U();if(!v.test(B))throw q(B,"name");j("=");var be=new u(ve(B),ut(U()),k,x);we(be,function(Ie){if(Ie==="option")Le(be,Ie),j(";");else throw q(Ie)},function(){es(be)}),N.add(be)}function dt(N,k){if(!v.test(k=U()))throw q(k,"name");var x=new l(ve(k));we(x,function(B){B==="option"?(Le(x,B),j(";")):(le(B),$e(x,"optional"))}),N.add(x)}function Y(N,k){if(!v.test(k=U()))throw q(k,"name");var x=new h(k);we(x,function(B){switch(B){case"option":Le(x,B),j(";");break;case"reserved":Be(x.reserved||(x.reserved=[]),!0);break;default:Ne(x,B)}}),N.add(x)}function Ne(N,k){if(!v.test(k))throw q(k,"name");j("=");var x=ut(U(),!0),B={};we(B,function(be){if(be==="option")Le(B,be),j(";");else throw q(be)},function(){es(B)}),N.add(k,x,B.comment)}function Le(N,k){var x=j("(",!0);if(!I.test(k=U()))throw q(k,"name");var B=k;x&&(j(")"),B="("+B+")",k=ue(),P.test(k)&&(B+=k,U())),j("="),ft(N,B)}function ft(N,k){if(j("{",!0))do{if(!v.test(ze=U()))throw q(ze,"name");ue()==="{"?ft(N,k+"."+ze):(j(":"),ue()==="{"?ft(N,k+"."+ze):Qr(N,k+"."+ze,se()))}while(!j("}",!0));else Qr(N,k,se())}function Qr(N,k,x){N.setOption&&N.setOption(k,x)}function es(N){if(j("[",!0)){do Le(N,"option");while(j(",",!0));j("]")}return N}function Kt(N,k){if(!v.test(k=U()))throw q(k,"service name");var x=new d(k);we(x,function(B){if(!Zr(x,B))if(B==="rpc")Ey(x,B);else throw q(B)}),N.add(x)}function Ey(N,k){var x=k;if(!v.test(k=U()))throw q(k,"name");var B=k,be,Ie,At,Gt;if(j("("),j("stream",!0)&&(Ie=!0),!I.test(k=U())||(be=k,j(")"),j("returns"),j("("),j("stream",!0)&&(Gt=!0),!I.test(k=U())))throw q(k);At=k,j(")");var Hi=new f(B,x,be,At,Ie,Gt);we(Hi,function(Wi){if(Wi==="option")Le(Hi,Wi),j(";");else throw q(Wi)}),N.add(Hi)}function Ty(N,k){if(!I.test(k=U()))throw q(k,"reference");var x=k;we(null,function(B){switch(B){case"required":case"repeated":case"optional":$e(N,B,x);break;default:if(!ae||!I.test(B))throw q(B);le(B),$e(N,"optional",x);break}})}for(var ze;(ze=U())!==null;)switch(ze){case"package":if(!Ze)throw q(ze);_r();break;case"import":if(!Ze)throw q(ze);wr();break;case"syntax":if(!Ze)throw q(ze);qs();break;case"option":if(!Ze)throw q(ze);Le(pe,ze),j(";");break;default:if(Zr(pe,ze)){Ze=!1;continue}throw q(ze)}return D.filename=null,{package:lt,imports:J,weakImports:X,syntax:G,root:re}}},{15:15,16:16,20:20,22:22,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,s,n){s.exports=l;var i=t(39),o,a=i.LongBits,c=i.utf8;function u(g,y){return RangeError("index out of range: "+g.pos+" + "+(y||1)+" > "+g.len)}function l(g){this.buf=g,this.pos=0,this.len=g.length}var h=typeof Uint8Array<"u"?function(g){if(g instanceof Uint8Array||Array.isArray(g))return new l(g);throw Error("illegal buffer")}:function(g){if(Array.isArray(g))return new l(g);throw Error("illegal buffer")};l.create=i.Buffer?function(g){return(l.create=function(y){return i.Buffer.isBuffer(y)?new o(y):h(y)})(g)}:h,l.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,l.prototype.uint32=(function(){var g=4294967295;return function(){if(g=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(g=(g|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(g=(g|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(g=(g|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(g=(g|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return g;if((this.pos+=5)>this.len)throw this.pos=this.len,u(this,10);return g}})(),l.prototype.int32=function(){return this.uint32()|0},l.prototype.sint32=function(){var g=this.uint32();return g>>>1^-(g&1)|0};function d(){var g=new a(0,0),y=0;if(this.len-this.pos>4){for(;y<4;++y)if(g.lo=(g.lo|(this.buf[this.pos]&127)<<y*7)>>>0,this.buf[this.pos++]<128)return g;if(g.lo=(g.lo|(this.buf[this.pos]&127)<<28)>>>0,g.hi=(g.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return g;y=0}else{for(;y<3;++y){if(this.pos>=this.len)throw u(this);if(g.lo=(g.lo|(this.buf[this.pos]&127)<<y*7)>>>0,this.buf[this.pos++]<128)return g}return g.lo=(g.lo|(this.buf[this.pos++]&127)<<y*7)>>>0,g}if(this.len-this.pos>4){for(;y<5;++y)if(g.hi=(g.hi|(this.buf[this.pos]&127)<<y*7+3)>>>0,this.buf[this.pos++]<128)return g}else for(;y<5;++y){if(this.pos>=this.len)throw u(this);if(g.hi=(g.hi|(this.buf[this.pos]&127)<<y*7+3)>>>0,this.buf[this.pos++]<128)return g}throw Error("invalid varint encoding")}l.prototype.bool=function(){return this.uint32()!==0};function f(g,y){return(g[y-4]|g[y-3]<<8|g[y-2]<<16|g[y-1]<<24)>>>0}l.prototype.fixed32=function(){if(this.pos+4>this.len)throw u(this,4);return f(this.buf,this.pos+=4)},l.prototype.sfixed32=function(){if(this.pos+4>this.len)throw u(this,4);return f(this.buf,this.pos+=4)|0};function p(){if(this.pos+8>this.len)throw u(this,8);return new a(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}l.prototype.float=function(){if(this.pos+4>this.len)throw u(this,4);var g=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,g},l.prototype.double=function(){if(this.pos+8>this.len)throw u(this,4);var g=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,g},l.prototype.bytes=function(){var g=this.uint32(),y=this.pos,w=this.pos+g;if(w>this.len)throw u(this,g);return this.pos+=g,Array.isArray(this.buf)?this.buf.slice(y,w):y===w?new this.buf.constructor(0):this._slice.call(this.buf,y,w)},l.prototype.string=function(){var g=this.bytes();return c.read(g,0,g.length)},l.prototype.skip=function(g){if(typeof g=="number"){if(this.pos+g>this.len)throw u(this,g);this.pos+=g}else do if(this.pos>=this.len)throw u(this);while(this.buf[this.pos++]&128);return this},l.prototype.skipType=function(g){switch(g){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:do{if((g=this.uint32()&7)===4)break;this.skipType(g)}while(!0);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+g+" at offset "+this.pos)}return this},l._configure=function(g){o=g;var y=i.Long?"toLong":"toNumber";i.merge(l.prototype,{int64:function(){return d.call(this)[y](!1)},uint64:function(){return d.call(this)[y](!0)},sint64:function(){return d.call(this).zzDecode()[y](!1)},fixed64:function(){return p.call(this)[y](!0)},sfixed64:function(){return p.call(this)[y](!1)}})}},{39:39}],28:[function(t,s,n){s.exports=a;var i=t(27);(a.prototype=Object.create(i.prototype)).constructor=a;var o=t(39);function a(c){i.call(this,c)}o.Buffer&&(a.prototype._slice=o.Buffer.prototype.slice),a.prototype.string=function(){var c=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+c,this.len))}},{27:27,39:39}],29:[function(t,s,n){s.exports=f;var i=t(23);((f.prototype=Object.create(i.prototype)).constructor=f).className="Root";var o=t(16),a=t(15),c=t(25),u=t(37),l,h,d;function f(w){i.call(this,"",w),this.deferred=[],this.files=[]}f.fromJSON=function(w,_){return _||(_=new f),w.options&&_.setOptions(w.options),_.addJSON(w.nested)},f.prototype.resolvePath=u.path.resolve;function p(){}f.prototype.load=function w(_,S,m){typeof S=="function"&&(m=S,S=e);var T=this;if(!m)return u.asPromise(w,T,_,S);var E=m===p;function v($,ee){if(m){var U=m;if(m=null,E)throw $;U($,ee)}}function I($,ee){try{if(u.isString(ee)&&ee.charAt(0)==="{"&&(ee=JSON.parse(ee)),!u.isString(ee))T.setOptions(ee.options).addJSON(ee.nested);else{h.filename=$;var U=h(ee,T,S),le,ue=0;if(U.imports)for(;ue<U.imports.length;++ue)(le=T.resolvePath($,U.imports[ue]))&&P(le);if(U.weakImports)for(ue=0;ue<U.weakImports.length;++ue)(le=T.resolvePath($,U.weakImports[ue]))&&P(le,!0)}}catch(j){v(j)}!E&&!D&&v(null,T)}function P($,ee){var U=$.lastIndexOf("google/protobuf/");if(U>-1){var le=$.substring(U);le in d&&($=le)}if(!(T.files.indexOf($)>-1)){if(T.files.push($),$ in d){E?I($,d[$]):(++D,setTimeout(function(){--D,I($,d[$])}));return}if(E){var ue;try{ue=u.fs.readFileSync($).toString("utf8")}catch(j){ee||v(j);return}I($,ue)}else++D,u.fetch($,function(j,We){if(--D,!!m){if(j){ee?D||v(null,T):v(j);return}I($,We)}})}}var D=0;u.isString(_)&&(_=[_]);for(var z=0,re;z<_.length;++z)(re=T.resolvePath("",_[z]))&&P(re);return E?T:(D||v(null,T),e)},f.prototype.loadSync=function(w,_){if(!u.isNode)throw Error("not supported");return this.load(w,_,p)},f.prototype.resolveAll=function(){if(this.deferred.length)throw Error("unresolvable extensions: "+this.deferred.map(function(w){return"'extend "+w.extend+"' in "+w.parent.fullName}).join(", "));return i.prototype.resolveAll.call(this)};var g=/^[A-Z]/;function y(w,_){var S=_.parent.lookup(_.extend);if(S){var m=new o(_.fullName,_.id,_.type,_.rule,e,_.options);return m.declaringField=_,_.extensionField=m,S.add(m),!0}return!1}f.prototype._handleAdd=function(w){if(w instanceof o)w.extend!==e&&!w.extensionField&&(y(this,w)||this.deferred.push(w));else if(w instanceof a)g.test(w.name)&&(w.parent[w.name]=w.values);else if(!(w instanceof c)){if(w instanceof l)for(var _=0;_<this.deferred.length;)y(this,this.deferred[_])?this.deferred.splice(_,1):++_;for(var S=0;S<w.nestedArray.length;++S)this._handleAdd(w._nestedArray[S]);g.test(w.name)&&(w.parent[w.name]=w)}},f.prototype._handleRemove=function(w){if(w instanceof o){if(w.extend!==e)if(w.extensionField)w.extensionField.parent.remove(w.extensionField),w.extensionField=null;else{var _=this.deferred.indexOf(w);_>-1&&this.deferred.splice(_,1)}}else if(w instanceof a)g.test(w.name)&&delete w.parent[w.name];else if(w instanceof i){for(var S=0;S<w.nestedArray.length;++S)this._handleRemove(w._nestedArray[S]);g.test(w.name)&&delete w.parent[w.name]}},f._configure=function(w,_,S){l=w,h=_,d=S}},{15:15,16:16,23:23,25:25,37:37}],30:[function(t,s,n){s.exports={}},{}],31:[function(t,s,n){var i=n;i.Service=t(32)},{32:32}],32:[function(t,s,n){s.exports=o;var i=t(39);(o.prototype=Object.create(i.EventEmitter.prototype)).constructor=o;function o(a,c,u){if(typeof a!="function")throw TypeError("rpcImpl must be a function");i.EventEmitter.call(this),this.rpcImpl=a,this.requestDelimited=!!c,this.responseDelimited=!!u}o.prototype.rpcCall=function a(c,u,l,h,d){if(!h)throw TypeError("request must be specified");var f=this;if(!d)return i.asPromise(a,f,c,u,l,h);if(!f.rpcImpl)return setTimeout(function(){d(Error("already ended"))},0),e;try{return f.rpcImpl(c,u[f.requestDelimited?"encodeDelimited":"encode"](h).finish(),function(p,g){if(p)return f.emit("error",p,c),d(p);if(g===null)return f.end(!0),e;if(!(g instanceof l))try{g=l[f.responseDelimited?"decodeDelimited":"decode"](g)}catch(y){return f.emit("error",y,c),d(y)}return f.emit("data",g,c),d(null,g)})}catch(p){return f.emit("error",p,c),setTimeout(function(){d(p)},0),e}},o.prototype.end=function(a){return this.rpcImpl&&(a||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{39:39}],33:[function(t,s,n){s.exports=u;var i=t(23);((u.prototype=Object.create(i.prototype)).constructor=u).className="Service";var o=t(22),a=t(37),c=t(31);function u(h,d){i.call(this,h,d),this.methods={},this._methodsArray=null}u.fromJSON=function(h,d){var f=new u(h,d.options);if(d.methods)for(var p=Object.keys(d.methods),g=0;g<p.length;++g)f.add(o.fromJSON(p[g],d.methods[p[g]]));return d.nested&&f.addJSON(d.nested),f.comment=d.comment,f},u.prototype.toJSON=function(h){var d=i.prototype.toJSON.call(this,h),f=h?!!h.keepComments:!1;return a.toObject(["options",d&&d.options||e,"methods",i.arrayToJSON(this.methodsArray,h)||{},"nested",d&&d.nested||e,"comment",f?this.comment:e])},Object.defineProperty(u.prototype,"methodsArray",{get:function(){return this._methodsArray||(this._methodsArray=a.toArray(this.methods))}});function l(h){return h._methodsArray=null,h}u.prototype.get=function(h){return this.methods[h]||i.prototype.get.call(this,h)},u.prototype.resolveAll=function(){for(var h=this.methodsArray,d=0;d<h.length;++d)h[d].resolve();return i.prototype.resolve.call(this)},u.prototype.add=function(h){if(this.get(h.name))throw Error("duplicate name '"+h.name+"' in "+this);return h instanceof o?(this.methods[h.name]=h,h.parent=this,l(this)):i.prototype.add.call(this,h)},u.prototype.remove=function(h){if(h instanceof o){if(this.methods[h.name]!==h)throw Error(h+" is not a member of "+this);return delete this.methods[h.name],h.parent=null,l(this)}return i.prototype.remove.call(this,h)},u.prototype.create=function(h,d,f){for(var p=new c.Service(h,d,f),g=0,y;g<this.methodsArray.length;++g){var w=a.lcFirst((y=this._methodsArray[g]).resolve().name).replace(/[^$\w_]/g,"");p[w]=a.codegen(["r","c"],a.isReserved(w)?w+"_":w)("return this.rpcCall(m,q,s,r,c)")({m:y,q:y.resolvedRequestType.ctor,s:y.resolvedResponseType.ctor})}return p}},{22:22,23:23,31:31,37:37}],34:[function(t,s,n){s.exports=g;var i=/[\s{}=;:[\],'"()<>]/g,o=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,a=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,c=/^ *[*/]+ */,u=/^\s*\*?\/*/,l=/\n/g,h=/\s/,d=/\\(.?)/g,f={0:"\0",r:"\r",n:`
`,t:" "};function p(y){return y.replace(d,function(w,_){switch(_){case"\\":case"":return _;default:return f[_]||""}})}g.unescape=p;function g(y,w){y=y.toString();var _=0,S=y.length,m=1,T=null,E=null,v=0,I=!1,P=[],D=null;function z(J){return Error("illegal "+J+" (line "+m+")")}function re(){var J=D==="'"?a:o;J.lastIndex=_-1;var X=J.exec(y);if(!X)throw z("string");return _=J.lastIndex,j(D),D=null,p(X[1])}function $(J){return y.charAt(J)}function ee(J,X){T=y.charAt(J++),v=m,I=!1;var G;w?G=2:G=3;var ae=J-G,pe;do if(--ae<0||(pe=y.charAt(ae))===`
`){I=!0;break}while(pe===" "||pe===" ");for(var ve=y.substring(J,X).split(l),q=0;q<ve.length;++q)ve[q]=ve[q].replace(w?u:c,"").trim();E=ve.join(`
`).trim()}function U(J){var X=le(J),G=y.substring(J,X),ae=/^\s*\/{1,2}/.test(G);return ae}function le(J){for(var X=J;X<S&&$(X)!==`
`;)X++;return X}function ue(){if(P.length>0)return P.shift();if(D)return re();var J,X,G,ae,pe;do{if(_===S)return null;for(J=!1;h.test(G=$(_));)if(G===`
`&&++m,++_===S)return null;if($(_)==="/"){if(++_===S)throw z("comment");if($(_)==="/")if(w){if(ae=_,pe=!1,U(_)){pe=!0;do{if(_=le(_),_===S)break;_++}while(U(_))}else _=Math.min(S,le(_)+1);pe&&ee(ae,_),m++,J=!0}else{for(pe=$(ae=_+1)==="/";$(++_)!==`
`;)if(_===S)return null;++_,pe&&ee(ae,_-1),++m,J=!0}else if((G=$(_))==="*"){ae=_+1,pe=w||$(ae)==="*";do{if(G===`
`&&++m,++_===S)throw z("comment");X=G,G=$(_)}while(X!=="*"||G!=="/");++_,pe&&ee(ae,_-2),J=!0}else return"/"}}while(J);var ve=_;i.lastIndex=0;var q=i.test($(ve++));if(!q)for(;ve<S&&!i.test($(ve));)++ve;var Xe=y.substring(_,_=ve);return(Xe==='"'||Xe==="'")&&(D=Xe),Xe}function j(J){P.push(J)}function We(){if(!P.length){var J=ue();if(J===null)return null;j(J)}return P[0]}function Ze(J,X){var G=We(),ae=G===J;if(ae)return ue(),!0;if(!X)throw z("token '"+G+"', '"+J+"' expected");return!1}function lt(J){var X=null;return J===e?v===m-1&&(w||T==="*"||I)&&(X=E):(v<J&&We(),v===J&&!I&&(w||T==="/")&&(X=E)),X}return Object.defineProperty({next:ue,peek:We,push:j,skip:Ze,cmnt:lt},"line",{get:function(){return m}})}},{}],35:[function(t,s,n){s.exports=m;var i=t(23);((m.prototype=Object.create(i.prototype)).constructor=m).className="Type";var o=t(15),a=t(25),c=t(16),u=t(20),l=t(33),h=t(21),d=t(27),f=t(42),p=t(37),g=t(14),y=t(13),w=t(40),_=t(12),S=t(41);function m(E,v){i.call(this,E,v),this.fields={},this.oneofs=e,this.extensions=e,this.reserved=e,this.group=e,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}Object.defineProperties(m.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var E=Object.keys(this.fields),v=0;v<E.length;++v){var I=this.fields[E[v]],P=I.id;if(this._fieldsById[P])throw Error("duplicate id "+P+" in "+this);this._fieldsById[P]=I}return this._fieldsById}},fieldsArray:{get:function(){return this._fieldsArray||(this._fieldsArray=p.toArray(this.fields))}},oneofsArray:{get:function(){return this._oneofsArray||(this._oneofsArray=p.toArray(this.oneofs))}},ctor:{get:function(){return this._ctor||(this.ctor=m.generateConstructor(this)())},set:function(E){var v=E.prototype;v instanceof h||((E.prototype=new h).constructor=E,p.merge(E.prototype,v)),E.$type=E.prototype.$type=this,p.merge(E,h,!0),this._ctor=E;for(var I=0;I<this.fieldsArray.length;++I)this._fieldsArray[I].resolve();var P={};for(I=0;I<this.oneofsArray.length;++I)P[this._oneofsArray[I].resolve().name]={get:p.oneOfGetter(this._oneofsArray[I].oneof),set:p.oneOfSetter(this._oneofsArray[I].oneof)};I&&Object.defineProperties(E.prototype,P)}}}),m.generateConstructor=function(E){for(var v=p.codegen(["p"],E.name),I=0,P;I<E.fieldsArray.length;++I)(P=E._fieldsArray[I]).map?v("this%s={}",p.safeProp(P.name)):P.repeated&&v("this%s=[]",p.safeProp(P.name));return v("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)")("this[ks[i]]=p[ks[i]]")};function T(E){return E._fieldsById=E._fieldsArray=E._oneofsArray=null,delete E.encode,delete E.decode,delete E.verify,E}m.fromJSON=function(E,v){var I=new m(E,v.options);I.extensions=v.extensions,I.reserved=v.reserved;for(var P=Object.keys(v.fields),D=0;D<P.length;++D)I.add((typeof v.fields[P[D]].keyType<"u"?u.fromJSON:c.fromJSON)(P[D],v.fields[P[D]]));if(v.oneofs)for(P=Object.keys(v.oneofs),D=0;D<P.length;++D)I.add(a.fromJSON(P[D],v.oneofs[P[D]]));if(v.nested)for(P=Object.keys(v.nested),D=0;D<P.length;++D){var z=v.nested[P[D]];I.add((z.id!==e?c.fromJSON:z.fields!==e?m.fromJSON:z.values!==e?o.fromJSON:z.methods!==e?l.fromJSON:i.fromJSON)(P[D],z))}return v.extensions&&v.extensions.length&&(I.extensions=v.extensions),v.reserved&&v.reserved.length&&(I.reserved=v.reserved),v.group&&(I.group=!0),v.comment&&(I.comment=v.comment),I},m.prototype.toJSON=function(E){var v=i.prototype.toJSON.call(this,E),I=E?!!E.keepComments:!1;return p.toObject(["options",v&&v.options||e,"oneofs",i.arrayToJSON(this.oneofsArray,E),"fields",i.arrayToJSON(this.fieldsArray.filter(function(P){return!P.declaringField}),E)||{},"extensions",this.extensions&&this.extensions.length?this.extensions:e,"reserved",this.reserved&&this.reserved.length?this.reserved:e,"group",this.group||e,"nested",v&&v.nested||e,"comment",I?this.comment:e])},m.prototype.resolveAll=function(){for(var E=this.fieldsArray,v=0;v<E.length;)E[v++].resolve();var I=this.oneofsArray;for(v=0;v<I.length;)I[v++].resolve();return i.prototype.resolveAll.call(this)},m.prototype.get=function(E){return this.fields[E]||this.oneofs&&this.oneofs[E]||this.nested&&this.nested[E]||null},m.prototype.add=function(E){if(this.get(E.name))throw Error("duplicate name '"+E.name+"' in "+this);if(E instanceof c&&E.extend===e){if(this._fieldsById?this._fieldsById[E.id]:this.fieldsById[E.id])throw Error("duplicate id "+E.id+" in "+this);if(this.isReservedId(E.id))throw Error("id "+E.id+" is reserved in "+this);if(this.isReservedName(E.name))throw Error("name '"+E.name+"' is reserved in "+this);return E.parent&&E.parent.remove(E),this.fields[E.name]=E,E.message=this,E.onAdd(this),T(this)}return E instanceof a?(this.oneofs||(this.oneofs={}),this.oneofs[E.name]=E,E.onAdd(this),T(this)):i.prototype.add.call(this,E)},m.prototype.remove=function(E){if(E instanceof c&&E.extend===e){if(!this.fields||this.fields[E.name]!==E)throw Error(E+" is not a member of "+this);return delete this.fields[E.name],E.parent=null,E.onRemove(this),T(this)}if(E instanceof a){if(!this.oneofs||this.oneofs[E.name]!==E)throw Error(E+" is not a member of "+this);return delete this.oneofs[E.name],E.parent=null,E.onRemove(this),T(this)}return i.prototype.remove.call(this,E)},m.prototype.isReservedId=function(E){return i.isReservedId(this.reserved,E)},m.prototype.isReservedName=function(E){return i.isReservedName(this.reserved,E)},m.prototype.create=function(E){return new this.ctor(E)},m.prototype.setup=function(){for(var E=this.fullName,v=[],I=0;I<this.fieldsArray.length;++I)v.push(this._fieldsArray[I].resolve().resolvedType);this.encode=g(this)({Writer:f,types:v,util:p}),this.decode=y(this)({Reader:d,types:v,util:p}),this.verify=w(this)({types:v,util:p}),this.fromObject=_.fromObject(this)({types:v,util:p}),this.toObject=_.toObject(this)({types:v,util:p});var P=S[E];if(P){var D=Object.create(this);D.fromObject=this.fromObject,this.fromObject=P.fromObject.bind(D),D.toObject=this.toObject,this.toObject=P.toObject.bind(D)}return this},m.prototype.encode=function(E,v){return this.setup().encode(E,v)},m.prototype.encodeDelimited=function(E,v){return this.encode(E,v&&v.len?v.fork():v).ldelim()},m.prototype.decode=function(E,v){return this.setup().decode(E,v)},m.prototype.decodeDelimited=function(E){return E instanceof d||(E=d.create(E)),this.decode(E,E.uint32())},m.prototype.verify=function(E){return this.setup().verify(E)},m.prototype.fromObject=function(E){return this.setup().fromObject(E)},m.prototype.toObject=function(E,v){return this.setup().toObject(E,v)},m.d=function(E){return function(v){p.decorateType(v,E)}}},{12:12,13:13,14:14,15:15,16:16,20:20,21:21,23:23,25:25,27:27,33:33,37:37,40:40,41:41,42:42}],36:[function(t,s,n){var i=n,o=t(37),a=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function c(u,l){var h=0,d={};for(l|=0;h<u.length;)d[a[h+l]]=u[h++];return d}i.basic=c([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]),i.defaults=c([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",o.emptyArray,null]),i.long=c([0,0,0,1,1],7),i.mapKey=c([0,0,0,5,5,0,0,0,1,1,0,2],2),i.packed=c([1,5,0,0,0,5,5,0,0,0,1,1,0])},{37:37}],37:[function(t,s,n){var i=s.exports=t(39),o=t(30),a,c;i.codegen=t(3),i.fetch=t(5),i.path=t(8),i.fs=i.inquire("fs"),i.toArray=function(f){if(f){for(var p=Object.keys(f),g=new Array(p.length),y=0;y<p.length;)g[y]=f[p[y++]];return g}return[]},i.toObject=function(f){for(var p={},g=0;g<f.length;){var y=f[g++],w=f[g++];w!==e&&(p[y]=w)}return p};var u=/\\/g,l=/"/g;i.isReserved=function(f){return/^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(f)},i.safeProp=function(f){return!/^[$\w_]+$/.test(f)||i.isReserved(f)?'["'+f.replace(u,"\\\\").replace(l,'\\"')+'"]':"."+f},i.ucFirst=function(f){return f.charAt(0).toUpperCase()+f.substring(1)};var h=/_([a-z])/g;i.camelCase=function(f){return f.substring(0,1)+f.substring(1).replace(h,function(p,g){return g.toUpperCase()})},i.compareFieldsById=function(f,p){return f.id-p.id},i.decorateType=function(f,p){if(f.$type)return p&&f.$type.name!==p&&(i.decorateRoot.remove(f.$type),f.$type.name=p,i.decorateRoot.add(f.$type)),f.$type;a||(a=t(35));var g=new a(p||f.name);return i.decorateRoot.add(g),g.ctor=f,Object.defineProperty(f,"$type",{value:g,enumerable:!1}),Object.defineProperty(f.prototype,"$type",{value:g,enumerable:!1}),g};var d=0;i.decorateEnum=function(f){if(f.$type)return f.$type;c||(c=t(15));var p=new c("Enum"+d++,f);return i.decorateRoot.add(p),Object.defineProperty(f,"$type",{value:p,enumerable:!1}),p},Object.defineProperty(i,"decorateRoot",{get:function(){return o.decorated||(o.decorated=new(t(29)))}})},{15:15,29:29,3:3,30:30,35:35,39:39,5:5,8:8}],38:[function(t,s,n){s.exports=o;var i=t(39);function o(l,h){this.lo=l>>>0,this.hi=h>>>0}var a=o.zero=new o(0,0);a.toNumber=function(){return 0},a.zzEncode=a.zzDecode=function(){return this},a.length=function(){return 1};var c=o.zeroHash="\0\0\0\0\0\0\0\0";o.fromNumber=function(l){if(l===0)return a;var h=l<0;h&&(l=-l);var d=l>>>0,f=(l-d)/4294967296>>>0;return h&&(f=~f>>>0,d=~d>>>0,++d>4294967295&&(d=0,++f>4294967295&&(f=0))),new o(d,f)},o.from=function(l){if(typeof l=="number")return o.fromNumber(l);if(i.isString(l))if(i.Long)l=i.Long.fromString(l);else return o.fromNumber(parseInt(l,10));return l.low||l.high?new o(l.low>>>0,l.high>>>0):a},o.prototype.toNumber=function(l){if(!l&&this.hi>>>31){var h=~this.lo+1>>>0,d=~this.hi>>>0;return h||(d=d+1>>>0),-(h+d*4294967296)}return this.lo+this.hi*4294967296},o.prototype.toLong=function(l){return i.Long?new i.Long(this.lo|0,this.hi|0,!!l):{low:this.lo|0,high:this.hi|0,unsigned:!!l}};var u=String.prototype.charCodeAt;o.fromHash=function(l){return l===c?a:new o((u.call(l,0)|u.call(l,1)<<8|u.call(l,2)<<16|u.call(l,3)<<24)>>>0,(u.call(l,4)|u.call(l,5)<<8|u.call(l,6)<<16|u.call(l,7)<<24)>>>0)},o.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},o.prototype.zzEncode=function(){var l=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^l)>>>0,this.lo=(this.lo<<1^l)>>>0,this},o.prototype.zzDecode=function(){var l=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^l)>>>0,this.hi=(this.hi>>>1^l)>>>0,this},o.prototype.length=function(){var l=this.lo,h=(this.lo>>>28|this.hi<<4)>>>0,d=this.hi>>>24;return d===0?h===0?l<16384?l<128?1:2:l<2097152?3:4:h<16384?h<128?5:6:h<2097152?7:8:d<128?9:10}},{39:39}],39:[function(t,s,n){var i=n;i.asPromise=t(1),i.base64=t(2),i.EventEmitter=t(4),i.float=t(6),i.inquire=t(7),i.utf8=t(10),i.pool=t(9),i.LongBits=t(38),i.emptyArray=Object.freeze?Object.freeze([]):[],i.emptyObject=Object.freeze?Object.freeze({}):{},i.isNode=!!(Jr.process&&Jr.process.versions&&Jr.process.versions.node),i.isInteger=Number.isInteger||function(c){return typeof c=="number"&&isFinite(c)&&Math.floor(c)===c},i.isString=function(c){return typeof c=="string"||c instanceof String},i.isObject=function(c){return c&&typeof c=="object"},i.isset=i.isSet=function(c,u){var l=c[u];return l!=null&&c.hasOwnProperty(u)?typeof l!="object"||(Array.isArray(l)?l.length:Object.keys(l).length)>0:!1},i.Buffer=(function(){try{var c=i.inquire("buffer").Buffer;return c.prototype.utf8Write?c:null}catch{return null}})(),i._Buffer_from=null,i._Buffer_allocUnsafe=null,i.newBuffer=function(c){return typeof c=="number"?i.Buffer?i._Buffer_allocUnsafe(c):new i.Array(c):i.Buffer?i._Buffer_from(c):typeof Uint8Array>"u"?c:new Uint8Array(c)},i.Array=typeof Uint8Array<"u"?Uint8Array:Array,i.Long=Jr.dcodeIO&&Jr.dcodeIO.Long||i.inquire("long"),i.key2Re=/^true|false|0|1$/,i.key32Re=/^-?(?:0|[1-9][0-9]*)$/,i.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,i.longToHash=function(c){return c?i.LongBits.from(c).toHash():i.LongBits.zeroHash},i.longFromHash=function(c,u){var l=i.LongBits.fromHash(c);return i.Long?i.Long.fromBits(l.lo,l.hi,u):l.toNumber(!!u)};function o(c,u,l){for(var h=Object.keys(u),d=0;d<h.length;++d)(c[h[d]]===e||!l)&&(c[h[d]]=u[h[d]]);return c}i.merge=o,i.lcFirst=function(c){return c.charAt(0).toLowerCase()+c.substring(1)};function a(c){function u(l,h){if(!(this instanceof u))return new u(l,h);Object.defineProperty(this,"message",{get:function(){return l}}),Error.captureStackTrace?Error.captureStackTrace(this,u):Object.defineProperty(this,"stack",{value:new Error().stack||""}),h&&o(this,h)}return(u.prototype=Object.create(Error.prototype)).constructor=u,Object.defineProperty(u.prototype,"name",{get:function(){return c}}),u.prototype.toString=function(){return this.name+": "+this.message},u}i.newError=a,i.ProtocolError=a("ProtocolError"),i.oneOfGetter=function(c){for(var u={},l=0;l<c.length;++l)u[c[l]]=1;return function(){for(var h=Object.keys(this),d=h.length-1;d>-1;--d)if(u[h[d]]===1&&this[h[d]]!==e&&this[h[d]]!==null)return h[d]}},i.oneOfSetter=function(c){return function(u){for(var l=0;l<c.length;++l)c[l]!==u&&delete this[c[l]]}},i.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},i._configure=function(){var c=i.Buffer;if(!c){i._Buffer_from=i._Buffer_allocUnsafe=null;return}i._Buffer_from=c.from!==Uint8Array.from&&c.from||function(u,l){return new c(u,l)},i._Buffer_allocUnsafe=c.allocUnsafe||function(u){return new c(u)}}},{1:1,10:10,2:2,38:38,4:4,6:6,7:7,9:9}],40:[function(t,s,n){s.exports=l;var i=t(15),o=t(37);function a(h,d){return h.name+": "+d+(h.repeated&&d!=="array"?"[]":h.map&&d!=="object"?"{k:"+h.keyType+"}":"")+" expected"}function c(h,d,f,p){if(d.resolvedType)if(d.resolvedType instanceof i){h("switch(%s){",p)("default:")("return%j",a(d,"enum value"));for(var g=Object.keys(d.resolvedType.values),y=0;y<g.length;++y)h("case %i:",d.resolvedType.values[g[y]]);h("break")("}")}else h("{")("var e=types[%i].verify(%s);",f,p)("if(e)")("return%j+e",d.name+".")("}");else switch(d.type){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":h("if(!util.isInteger(%s))",p)("return%j",a(d,"integer"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":h("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))",p,p,p,p)("return%j",a(d,"integer|Long"));break;case"float":case"double":h('if(typeof %s!=="number")',p)("return%j",a(d,"number"));break;case"bool":h('if(typeof %s!=="boolean")',p)("return%j",a(d,"boolean"));break;case"string":h("if(!util.isString(%s))",p)("return%j",a(d,"string"));break;case"bytes":h('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))',p,p,p)("return%j",a(d,"buffer"));break}return h}function u(h,d,f){switch(d.keyType){case"int32":case"uint32":case"sint32":case"fixed32":case"sfixed32":h("if(!util.key32Re.test(%s))",f)("return%j",a(d,"integer key"));break;case"int64":case"uint64":case"sint64":case"fixed64":case"sfixed64":h("if(!util.key64Re.test(%s))",f)("return%j",a(d,"integer|Long key"));break;case"bool":h("if(!util.key2Re.test(%s))",f)("return%j",a(d,"boolean key"));break}return h}function l(h){var d=o.codegen(["m"],h.name+"$verify")('if(typeof m!=="object"||m===null)')("return%j","object expected"),f=h.oneofsArray,p={};f.length&&d("var p={}");for(var g=0;g<h.fieldsArray.length;++g){var y=h._fieldsArray[g].resolve(),w="m"+o.safeProp(y.name);if(y.optional&&d("if(%s!=null&&m.hasOwnProperty(%j)){",w,y.name),y.map)d("if(!util.isObject(%s))",w)("return%j",a(y,"object"))("var k=Object.keys(%s)",w)("for(var i=0;i<k.length;++i){"),u(d,y,"k[i]"),c(d,y,g,w+"[k[i]]")("}");else if(y.repeated)d("if(!Array.isArray(%s))",w)("return%j",a(y,"array"))("for(var i=0;i<%s.length;++i){",w),c(d,y,g,w+"[i]")("}");else{if(y.partOf){var _=o.safeProp(y.partOf.name);p[y.partOf.name]===1&&d("if(p%s===1)",_)("return%j",y.partOf.name+": multiple values"),p[y.partOf.name]=1,d("p%s=1",_)}c(d,y,g,w)}y.optional&&d("}")}return d("return null")}},{15:15,37:37}],41:[function(t,s,n){var i=n,o=t(21);i[".google.protobuf.Any"]={fromObject:function(a){if(a&&a["@type"]){var c=this.lookup(a["@type"]);if(c){var u=a["@type"].charAt(0)==="."?a["@type"].substr(1):a["@type"];return this.create({type_url:"/"+u,value:c.encode(c.fromObject(a)).finish()})}}return this.fromObject(a)},toObject:function(a,c){if(c&&c.json&&a.type_url&&a.value){var u=a.type_url.substring(a.type_url.lastIndexOf("/")+1),l=this.lookup(u);l&&(a=l.decode(a.value))}if(!(a instanceof this.ctor)&&a instanceof o){var h=a.$type.toObject(a,c);return h["@type"]=a.$type.fullName,h}return this.toObject(a,c)}}},{21:21}],42:[function(t,s,n){s.exports=f;var i=t(39),o,a=i.LongBits,c=i.base64,u=i.utf8;function l(m,T,E){this.fn=m,this.len=T,this.next=e,this.val=E}function h(){}function d(m){this.head=m.head,this.tail=m.tail,this.len=m.len,this.next=m.states}function f(){this.len=0,this.head=new l(h,0,0),this.tail=this.head,this.states=null}f.create=i.Buffer?function(){return(f.create=function(){return new o})()}:function(){return new f},f.alloc=function(m){return new i.Array(m)},i.Array!==Array&&(f.alloc=i.pool(f.alloc,i.Array.prototype.subarray)),f.prototype._push=function(m,T,E){return this.tail=this.tail.next=new l(m,T,E),this.len+=T,this};function p(m,T,E){T[E]=m&255}function g(m,T,E){for(;m>127;)T[E++]=m&127|128,m>>>=7;T[E]=m}function y(m,T){this.len=m,this.next=e,this.val=T}y.prototype=Object.create(l.prototype),y.prototype.fn=g,f.prototype.uint32=function(m){return this.len+=(this.tail=this.tail.next=new y((m=m>>>0)<128?1:m<16384?2:m<2097152?3:m<268435456?4:5,m)).len,this},f.prototype.int32=function(m){return m<0?this._push(w,10,a.fromNumber(m)):this.uint32(m)},f.prototype.sint32=function(m){return this.uint32((m<<1^m>>31)>>>0)};function w(m,T,E){for(;m.hi;)T[E++]=m.lo&127|128,m.lo=(m.lo>>>7|m.hi<<25)>>>0,m.hi>>>=7;for(;m.lo>127;)T[E++]=m.lo&127|128,m.lo=m.lo>>>7;T[E++]=m.lo}f.prototype.uint64=function(m){var T=a.from(m);return this._push(w,T.length(),T)},f.prototype.int64=f.prototype.uint64,f.prototype.sint64=function(m){var T=a.from(m).zzEncode();return this._push(w,T.length(),T)},f.prototype.bool=function(m){return this._push(p,1,m?1:0)};function _(m,T,E){T[E]=m&255,T[E+1]=m>>>8&255,T[E+2]=m>>>16&255,T[E+3]=m>>>24}f.prototype.fixed32=function(m){return this._push(_,4,m>>>0)},f.prototype.sfixed32=f.prototype.fixed32,f.prototype.fixed64=function(m){var T=a.from(m);return this._push(_,4,T.lo)._push(_,4,T.hi)},f.prototype.sfixed64=f.prototype.fixed64,f.prototype.float=function(m){return this._push(i.float.writeFloatLE,4,m)},f.prototype.double=function(m){return this._push(i.float.writeDoubleLE,8,m)};var S=i.Array.prototype.set?function(m,T,E){T.set(m,E)}:function(m,T,E){for(var v=0;v<m.length;++v)T[E+v]=m[v]};f.prototype.bytes=function(m){var T=m.length>>>0;if(!T)return this._push(p,1,0);if(i.isString(m)){var E=f.alloc(T=c.length(m));c.decode(m,E,0),m=E}return this.uint32(T)._push(S,T,m)},f.prototype.string=function(m){var T=u.length(m);return T?this.uint32(T)._push(u.write,T,m):this._push(p,1,0)},f.prototype.fork=function(){return this.states=new d(this),this.head=this.tail=new l(h,0,0),this.len=0,this},f.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new l(h,0,0),this.len=0),this},f.prototype.ldelim=function(){var m=this.head,T=this.tail,E=this.len;return this.reset().uint32(E),E&&(this.tail.next=m.next,this.tail=T,this.len+=E),this},f.prototype.finish=function(){for(var m=this.head.next,T=this.constructor.alloc(this.len),E=0;m;)m.fn(m.val,T,E),E+=m.len,m=m.next;return T},f._configure=function(m){o=m}},{39:39}],43:[function(t,s,n){s.exports=c;var i=t(42);(c.prototype=Object.create(i.prototype)).constructor=c;var o=t(39),a=o.Buffer;function c(){i.call(this)}c.alloc=function(h){return(c.alloc=o._Buffer_allocUnsafe)(h)};var u=a&&a.prototype instanceof Uint8Array&&a.prototype.set.name==="set"?function(h,d,f){d.set(h,f)}:function(h,d,f){if(h.copy)h.copy(d,f,0,h.length);else for(var p=0;p<h.length;)d[f++]=h[p++]};c.prototype.bytes=function(h){o.isString(h)&&(h=o._Buffer_from(h,"base64"));var d=h.length>>>0;return this.uint32(d),d&&this._push(u,d,h),this};function l(h,d,f){h.length<40?o.utf8.write(h,d,f):d.utf8Write(h,f)}c.prototype.string=function(h){var d=a.byteLength(h);return this.uint32(d),d&&this._push(l,d,h),this}},{39:39,42:42}]},{},[19])})()})(qi)),qi.exports}var Km=Jm();const Kr=zm(Km);let Q=Kr.Reader,Fe=Kr.Writer,Ce=Kr.util;const F=Kr.roots["push-server"]||(Kr.roots["push-server"]={});F.RequestBatch=(function(){function r(e){if(this.requests=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.requests=Ce.emptyArray,r.create=function(e){return new r(e)},r.encode=function(e,t){if(t||(t=Fe.create()),e.requests!=null&&e.requests.length)for(var s=0;s<e.requests.length;++s)F.Request.encode(e.requests[s],t.uint32(10).fork()).ldelim();return t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.RequestBatch;e.pos<s;){var i=e.uint32();i>>>3===1?(n.requests&&n.requests.length||(n.requests=[]),n.requests.push(F.Request.decode(e,e.uint32()))):e.skipType(i&7)}return n},r})(),F.Request=(function(){function r(t){if(t)for(var s=Object.keys(t),n=0;n<s.length;++n)t[s[n]]!=null&&(this[s[n]]=t[s[n]])}r.prototype.incomingMessages=null,r.prototype.channelStats=null,r.prototype.serverStats=null;var e;return Object.defineProperty(r.prototype,"command",{get:Ce.oneOfGetter(e=["incomingMessages","channelStats","serverStats"]),set:Ce.oneOfSetter(e)}),r.create=function(t){return new r(t)},r.encode=function(t,s){return s||(s=Fe.create()),t.incomingMessages!=null&&t.hasOwnProperty("incomingMessages")&&F.IncomingMessagesRequest.encode(t.incomingMessages,s.uint32(10).fork()).ldelim(),t.channelStats!=null&&t.hasOwnProperty("channelStats")&&F.ChannelStatsRequest.encode(t.channelStats,s.uint32(18).fork()).ldelim(),t.serverStats!=null&&t.hasOwnProperty("serverStats")&&F.ServerStatsRequest.encode(t.serverStats,s.uint32(26).fork()).ldelim(),s},r.decode=function(t,s){t instanceof Q||(t=Q.create(t));for(var n=s===void 0?t.len:t.pos+s,i=new F.Request;t.pos<n;){var o=t.uint32();switch(o>>>3){case 1:i.incomingMessages=F.IncomingMessagesRequest.decode(t,t.uint32());break;case 2:i.channelStats=F.ChannelStatsRequest.decode(t,t.uint32());break;case 3:i.serverStats=F.ServerStatsRequest.decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i},r})(),F.IncomingMessagesRequest=(function(){function r(e){if(this.messages=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.messages=Ce.emptyArray,r.create=function(e){return new r(e)},r.encode=function(e,t){if(t||(t=Fe.create()),e.messages!=null&&e.messages.length)for(var s=0;s<e.messages.length;++s)F.IncomingMessage.encode(e.messages[s],t.uint32(10).fork()).ldelim();return t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.IncomingMessagesRequest;e.pos<s;){var i=e.uint32();i>>>3===1?(n.messages&&n.messages.length||(n.messages=[]),n.messages.push(F.IncomingMessage.decode(e,e.uint32()))):e.skipType(i&7)}return n},r})(),F.IncomingMessage=(function(){function r(e){if(this.receivers=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.receivers=Ce.emptyArray,r.prototype.sender=null,r.prototype.body="",r.prototype.expiry=0,r.prototype.type="",r.create=function(e){return new r(e)},r.encode=function(e,t){if(t||(t=Fe.create()),e.receivers!=null&&e.receivers.length)for(var s=0;s<e.receivers.length;++s)F.Receiver.encode(e.receivers[s],t.uint32(10).fork()).ldelim();return e.sender!=null&&e.hasOwnProperty("sender")&&F.Sender.encode(e.sender,t.uint32(18).fork()).ldelim(),e.body!=null&&e.hasOwnProperty("body")&&t.uint32(26).string(e.body),e.expiry!=null&&e.hasOwnProperty("expiry")&&t.uint32(32).uint32(e.expiry),e.type!=null&&e.hasOwnProperty("type")&&t.uint32(42).string(e.type),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.IncomingMessage;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.receivers&&n.receivers.length||(n.receivers=[]),n.receivers.push(F.Receiver.decode(e,e.uint32()));break;case 2:n.sender=F.Sender.decode(e,e.uint32());break;case 3:n.body=e.string();break;case 4:n.expiry=e.uint32();break;case 5:n.type=e.string();break;default:e.skipType(i&7);break}}return n},r})(),F.ChannelStatsRequest=(function(){function r(e){if(this.channels=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.channels=Ce.emptyArray,r.create=function(e){return new r(e)},r.encode=function(e,t){if(t||(t=Fe.create()),e.channels!=null&&e.channels.length)for(var s=0;s<e.channels.length;++s)F.ChannelId.encode(e.channels[s],t.uint32(10).fork()).ldelim();return t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.ChannelStatsRequest;e.pos<s;){var i=e.uint32();i>>>3===1?(n.channels&&n.channels.length||(n.channels=[]),n.channels.push(F.ChannelId.decode(e,e.uint32()))):e.skipType(i&7)}return n},r})(),F.ChannelId=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.id=Ce.newBuffer([]),r.prototype.isPrivate=!1,r.prototype.signature=Ce.newBuffer([]),r.create=function(e){return new r(e)},r.encode=function(e,t){return t||(t=Fe.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.isPrivate!=null&&e.hasOwnProperty("isPrivate")&&t.uint32(16).bool(e.isPrivate),e.signature!=null&&e.hasOwnProperty("signature")&&t.uint32(26).bytes(e.signature),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.ChannelId;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.isPrivate=e.bool();break;case 3:n.signature=e.bytes();break;default:e.skipType(i&7);break}}return n},r})(),F.ServerStatsRequest=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.create=function(e){return new r(e)},r.encode=function(e,t){return t||(t=Fe.create()),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.ServerStatsRequest;e.pos<s;){var i=e.uint32();switch(i>>>3){default:e.skipType(i&7);break}}return n},r})(),F.Sender=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.type=0,r.prototype.id=Ce.newBuffer([]),r.create=function(e){return new r(e)},r.encode=function(e,t){return t||(t=Fe.create()),e.type!=null&&e.hasOwnProperty("type")&&t.uint32(8).int32(e.type),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(18).bytes(e.id),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.Sender;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.type=e.int32();break;case 2:n.id=e.bytes();break;default:e.skipType(i&7);break}}return n},r})(),F.SenderType=(function(){var r={},e=Object.create(r);return e[r[0]="UNKNOWN"]=0,e[r[1]="CLIENT"]=1,e[r[2]="BACKEND"]=2,e})(),F.Receiver=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.id=Ce.newBuffer([]),r.prototype.isPrivate=!1,r.prototype.signature=Ce.newBuffer([]),r.create=function(e){return new r(e)},r.encode=function(e,t){return t||(t=Fe.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.isPrivate!=null&&e.hasOwnProperty("isPrivate")&&t.uint32(16).bool(e.isPrivate),e.signature!=null&&e.hasOwnProperty("signature")&&t.uint32(26).bytes(e.signature),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.Receiver;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.isPrivate=e.bool();break;case 3:n.signature=e.bytes();break;default:e.skipType(i&7);break}}return n},r})(),F.ResponseBatch=(function(){function r(e){if(this.responses=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.responses=Ce.emptyArray,r.create=function(e){return new r(e)},r.encode=function(e,t){if(t||(t=Fe.create()),e.responses!=null&&e.responses.length)for(var s=0;s<e.responses.length;++s)F.Response.encode(e.responses[s],t.uint32(10).fork()).ldelim();return t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.ResponseBatch;e.pos<s;){var i=e.uint32();i>>>3===1?(n.responses&&n.responses.length||(n.responses=[]),n.responses.push(F.Response.decode(e,e.uint32()))):e.skipType(i&7)}return n},r})(),F.Response=(function(){function r(t){if(t)for(var s=Object.keys(t),n=0;n<s.length;++n)t[s[n]]!=null&&(this[s[n]]=t[s[n]])}r.prototype.outgoingMessages=null,r.prototype.channelStats=null,r.prototype.serverStats=null;var e;return Object.defineProperty(r.prototype,"command",{get:Ce.oneOfGetter(e=["outgoingMessages","channelStats","serverStats"]),set:Ce.oneOfSetter(e)}),r.create=function(t){return new r(t)},r.encode=function(t,s){return s||(s=Fe.create()),t.outgoingMessages!=null&&t.hasOwnProperty("outgoingMessages")&&F.OutgoingMessagesResponse.encode(t.outgoingMessages,s.uint32(10).fork()).ldelim(),t.channelStats!=null&&t.hasOwnProperty("channelStats")&&F.ChannelStatsResponse.encode(t.channelStats,s.uint32(18).fork()).ldelim(),t.serverStats!=null&&t.hasOwnProperty("serverStats")&&F.JsonResponse.encode(t.serverStats,s.uint32(26).fork()).ldelim(),s},r.decode=function(t,s){t instanceof Q||(t=Q.create(t));for(var n=s===void 0?t.len:t.pos+s,i=new F.Response;t.pos<n;){var o=t.uint32();switch(o>>>3){case 1:i.outgoingMessages=F.OutgoingMessagesResponse.decode(t,t.uint32());break;case 2:i.channelStats=F.ChannelStatsResponse.decode(t,t.uint32());break;case 3:i.serverStats=F.JsonResponse.decode(t,t.uint32());break;default:t.skipType(o&7);break}}return i},r})(),F.OutgoingMessagesResponse=(function(){function r(e){if(this.messages=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.messages=Ce.emptyArray,r.create=function(e){return new r(e)},r.encode=function(e,t){if(t||(t=Fe.create()),e.messages!=null&&e.messages.length)for(var s=0;s<e.messages.length;++s)F.OutgoingMessage.encode(e.messages[s],t.uint32(10).fork()).ldelim();return t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.OutgoingMessagesResponse;e.pos<s;){var i=e.uint32();i>>>3===1?(n.messages&&n.messages.length||(n.messages=[]),n.messages.push(F.OutgoingMessage.decode(e,e.uint32()))):e.skipType(i&7)}return n},r})(),F.OutgoingMessage=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.id=Ce.newBuffer([]),r.prototype.body="",r.prototype.expiry=0,r.prototype.created=0,r.prototype.sender=null,r.create=function(e){return new r(e)},r.encode=function(e,t){return t||(t=Fe.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.body!=null&&e.hasOwnProperty("body")&&t.uint32(18).string(e.body),e.expiry!=null&&e.hasOwnProperty("expiry")&&t.uint32(24).uint32(e.expiry),e.created!=null&&e.hasOwnProperty("created")&&t.uint32(37).fixed32(e.created),e.sender!=null&&e.hasOwnProperty("sender")&&F.Sender.encode(e.sender,t.uint32(42).fork()).ldelim(),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.OutgoingMessage;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.body=e.string();break;case 3:n.expiry=e.uint32();break;case 4:n.created=e.fixed32();break;case 5:n.sender=F.Sender.decode(e,e.uint32());break;default:e.skipType(i&7);break}}return n},r})(),F.ChannelStatsResponse=(function(){function r(e){if(this.channels=[],e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.channels=Ce.emptyArray,r.create=function(e){return new r(e)},r.encode=function(e,t){if(t||(t=Fe.create()),e.channels!=null&&e.channels.length)for(var s=0;s<e.channels.length;++s)F.ChannelStats.encode(e.channels[s],t.uint32(10).fork()).ldelim();return t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.ChannelStatsResponse;e.pos<s;){var i=e.uint32();i>>>3===1?(n.channels&&n.channels.length||(n.channels=[]),n.channels.push(F.ChannelStats.decode(e,e.uint32()))):e.skipType(i&7)}return n},r})(),F.ChannelStats=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.id=Ce.newBuffer([]),r.prototype.isPrivate=!1,r.prototype.isOnline=!1,r.create=function(e){return new r(e)},r.encode=function(e,t){return t||(t=Fe.create()),e.id!=null&&e.hasOwnProperty("id")&&t.uint32(10).bytes(e.id),e.isPrivate!=null&&e.hasOwnProperty("isPrivate")&&t.uint32(16).bool(e.isPrivate),e.isOnline!=null&&e.hasOwnProperty("isOnline")&&t.uint32(24).bool(e.isOnline),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.ChannelStats;e.pos<s;){var i=e.uint32();switch(i>>>3){case 1:n.id=e.bytes();break;case 2:n.isPrivate=e.bool();break;case 3:n.isOnline=e.bool();break;default:e.skipType(i&7);break}}return n},r})(),F.JsonResponse=(function(){function r(e){if(e)for(var t=Object.keys(e),s=0;s<t.length;++s)e[t[s]]!=null&&(this[t[s]]=e[t[s]])}return r.prototype.json="",r.create=function(e){return new r(e)},r.encode=function(e,t){return t||(t=Fe.create()),e.json!=null&&e.hasOwnProperty("json")&&t.uint32(10).string(e.json),t},r.decode=function(e,t){e instanceof Q||(e=Q.create(e));for(var s=t===void 0?e.len:e.pos+t,n=new F.JsonResponse;e.pos<s;){var i=e.uint32();i>>>3===1?n.json=e.string():e.skipType(i&7)}return n},r})();const Gm=F.ResponseBatch,Xl=F.RequestBatch;F.IncomingMessage,F.Receiver;class Pt extends Error{name="WireError"}const mr=0,Te=2,Ql=5,Ym=3,Zm=4,Xm=64;function Ye(r,e){return r<<3|e}class yr{#e=new Uint8Array(64);#t=0;get length(){return this.#t}#s(e){const t=this.#t+e;if(t<=this.#e.length)return;let s=this.#e.length*2;for(;s<t;)s*=2;const n=new Uint8Array(s);n.set(this.#e.subarray(0,this.#t)),this.#e=n}#r(e){this.#s(1),this.#e[this.#t++]=e}varint(e){let t=e>>>0;for(;t>127;)this.#r(t&127|128),t>>>=7;return this.#r(t),this}fixed32(e){const t=e>>>0;return this.#s(4),this.#e[this.#t++]=t&255,this.#e[this.#t++]=t>>>8&255,this.#e[this.#t++]=t>>>16&255,this.#e[this.#t++]=t>>>24&255,this}bytes(e){return this.varint(e.length),this.#s(e.length),this.#e.set(e,this.#t),this.#t+=e.length,this}string(e){return this.bytes(new TextEncoder().encode(e))}finish(){return this.#e.slice(0,this.#t)}}class Qm{#e;#t=0;constructor(e){this.#e=e}get done(){return this.#t>=this.#e.length}varint(){let e=0,t=0;for(;;){if(this.done)throw new Pt("pull protobuf: truncated varint");const s=this.#e[this.#t++];if(e+=(s&127)*2**t,(s&128)===0)return e;if(t+=7,t>=70)throw new Pt("pull protobuf: varint longer than ten bytes")}}uint32(){return this.varint()>>>0}fixed32(){if(this.#t+4>this.#e.length)throw new Pt("pull protobuf: truncated fixed32");const e=this.#e[this.#t]|this.#e[this.#t+1]<<8|this.#e[this.#t+2]<<16|this.#e[this.#t+3]<<24;return this.#t+=4,e>>>0}bytes(){const e=this.varint();if(this.#t+e>this.#e.length)throw new Pt("pull protobuf: length-delimited field runs past the end");const t=this.#e.subarray(this.#t,this.#t+e);return this.#t+=e,t}string(){return new TextDecoder().decode(this.bytes())}skip(e,t=0){switch(e){case mr:{this.varint();break}case Te:{this.bytes();break}case Ql:{this.fixed32();break}case 1:{if(this.#t+8>this.#e.length)throw new Pt("pull protobuf: truncated 64-bit field");this.#t+=8;break}case Ym:{this.#s(t);break}default:throw new Pt(`pull protobuf: unsupported wire type ${e}`)}}#s(e){if(e>=Xm)throw new Pt("pull protobuf: groups nested too deeply");for(;;){const t=this.varint()&7;if(t===Zm)return;this.skip(t,e+1)}}}function Ot(r,e){return Object.hasOwn(r,e)&&r[e]!==null&&r[e]!==void 0}function ey(r){const e=new yr;return Ot(r,"id")&&e.varint(Ye(1,Te)).bytes(r.id),Ot(r,"isPrivate")&&e.varint(Ye(2,mr)).varint(r.isPrivate?1:0),Ot(r,"signature")&&e.varint(Ye(3,Te)).bytes(r.signature),e.finish()}function ty(r){const e=new yr;return Ot(r,"type")&&e.varint(Ye(1,mr)).varint(r.type),Ot(r,"id")&&e.varint(Ye(2,Te)).bytes(r.id),e.finish()}function ry(r){const e=new yr;for(const t of r.receivers??[])e.varint(Ye(1,Te)).bytes(ey(t));return Ot(r,"sender")&&e.varint(Ye(2,Te)).bytes(ty(r.sender)),Ot(r,"body")&&e.varint(Ye(3,Te)).string(r.body),Ot(r,"expiry")&&e.varint(Ye(4,mr)).varint(r.expiry),Ot(r,"type")&&e.varint(Ye(5,Te)).string(r.type),e.finish()}function sy(r){const e=new yr;for(const n of r)e.varint(Ye(1,Te)).bytes(ry(n));const t=new yr;t.varint(Ye(1,Te)).bytes(e.finish());const s=new yr;return s.varint(Ye(1,Te)).bytes(t.finish()),s.finish()}function Gr(r,e,t){const s=new Qm(r);for(;!s.done;)try{const n=s.varint();t(n>>>3,n&7,s)}catch(n){if(!(n instanceof Pt))throw n;e.damaged=!0;return}}function ny(r,e){const t={type:0,id:new Uint8Array(0)};return Gr(r,e,(s,n,i)=>{s===1&&n===mr?t.type=i.uint32():s===2&&n===Te?t.id=i.bytes():i.skip(n)}),t}function iy(r,e){const t={id:new Uint8Array(0),body:"",expiry:0,created:0};return Gr(r,e,(s,n,i)=>{s===1&&n===Te?t.id=i.bytes():s===2&&n===Te?t.body=i.string():s===3&&n===mr?t.expiry=i.uint32():s===4&&n===Ql?t.created=i.fixed32():s===5&&n===Te?t.sender=ny(i.bytes(),e):i.skip(n)}),t}function oy(r,e){const t=[];return Gr(r,e,(s,n,i)=>{s===1&&n===Te?t.push(iy(i.bytes(),e)):i.skip(n)}),{messages:t}}function ay(r,e){const t={};return Gr(r,e,(s,n,i)=>{s===1&&n===Te?(t.outgoingMessages=oy(i.bytes(),e),t.command="outgoingMessages"):s===2&&n===Te?(i.bytes(),t.command="channelStats"):s===3&&n===Te?(i.bytes(),t.command="serverStats"):i.skip(n)}),t}function cy(r){const e={damaged:!1},t=[];return Gr(r,e,(s,n,i)=>{s===1&&n===Te?t.push(ay(i.bytes(),e)):i.skip(n)}),{responses:t,damaged:e.damaged}}class eu{_logger;_connected=!1;_connectionType;_disconnectCode=0;_disconnectReason="";_parent;_callbacks;constructor(e){this._logger=oe.createNullLogger(),this._parent=e.parent,this._connectionType=he.Undefined,this._callbacks={onOpen:L.isFunction(e.onOpen)?e.onOpen:()=>{},onDisconnect:L.isFunction(e.onDisconnect)?e.onDisconnect:()=>{},onError:L.isFunction(e.onError)?e.onError:()=>{},onMessage:L.isFunction(e.onMessage)?e.onMessage:()=>{}}}setLogger(e){this._logger=e}getLogger(){return this._logger}destroy(){}get connected(){return this._connected}set connected(e){e!=this._connected&&(this._connected=e,this._connected?this._callbacks.onOpen():this._callbacks.onDisconnect({code:this.disconnectCode,reason:this.disconnectReason}))}get disconnectCode(){return this._disconnectCode}get disconnectReason(){return this._disconnectReason}get connectionPath(){return this._parent.getConnectionPath(this._connectionType)}}const ly=3e4;class uy extends eu{_socket;_socketCreatedAt=0;_onSocketOpenHandler;_onSocketCloseHandler;_onSocketErrorHandler;_onSocketMessageHandler;constructor(e){super(e),this._connectionType=he.WebSocket,this._socket=null,this._onSocketOpenHandler=this._onSocketOpen.bind(this),this._onSocketCloseHandler=this._onSocketClose.bind(this),this._onSocketErrorHandler=this._onSocketError.bind(this),this._onSocketMessageHandler=this._onSocketMessage.bind(this)}destroy(){super.destroy(),this._socket&&(this._socket.close(),this._socket=null)}connect(){if(this._socket){const e=this._socket.readyState===0&&Date.now()-this._socketCreatedAt<ly;if(this._socket.readyState===1||e)return;this.clearEventListener(),this._socket.close(),this._socket=null}this._createSocket()}get socket(){return this._socket}disconnect(e,t){this._socket!==null&&(this.clearEventListener(),this._socket.close(e,t)),this._socket=null,this._disconnectCode=e,this._disconnectReason=t,this.connected=!1}send(e){return!this._socket||this._socket.readyState!==1?(this.getLogger().error(`${ie()}: Pull: WebSocket is not connected`).catch(()=>{}),!1):(this._socket.send(e),!0)}_onSocketOpen(){this.connected=!0}_onSocketClose(e){this._socket=null,this._disconnectCode=Number(e.code),this._disconnectReason=e.reason,this.connected=!1}_onSocketError(e){this._callbacks.onError(new Error(`Socket error: ${e}`))}_onSocketMessage(e){this._callbacks.onMessage(e.data)}clearEventListener(){this._socket&&(this._socket.removeEventListener("open",this._onSocketOpenHandler),this._socket.removeEventListener("close",this._onSocketCloseHandler),this._socket.removeEventListener("error",this._onSocketErrorHandler),this._socket.removeEventListener("message",this._onSocketMessageHandler))}_createSocket(){if(this._socket)throw new Error("Socket already exists");if(!this.connectionPath)throw new Error("Websocket connection path is not defined");this._socket=new WebSocket(this.connectionPath),this._socketCreatedAt=Date.now(),this._socket.binaryType="arraybuffer",this._socket.addEventListener("open",this._onSocketOpenHandler),this._socket.addEventListener("close",this._onSocketCloseHandler),this._socket.addEventListener("error",this._onSocketErrorHandler),this._socket.addEventListener("message",this._onSocketMessageHandler)}}const hy=60;class dy extends eu{_active;_requestTimeout;_failureTimeout;_xhr;_requestAborted;constructor(e){super(e),this._active=!1,this._connectionType=he.LongPolling,this._requestTimeout=null,this._failureTimeout=null,this._xhr=null,this._requestAborted=!1}connect(){if(!this._xhr){if(typeof XMLHttpRequest>"u"){this._callbacks.onError(new Error("LongPollingConnector: XMLHttpRequest is not available in this environment (SSR/Node); a long-polling connection requires a browser"));return}this._xhr=this.createXhr()}this._active=!0,this.performRequest()}disconnect(e,t){this._active=!1,this.clearTimeOut(),this._xhr&&(this._requestAborted=!0,this._xhr.abort()),this._disconnectCode=e,this._disconnectReason=t,this.connected=!1}performRequest(){if(!this._active)return;if(!this.connectionPath)throw new Error("Long polling connection path is not defined");const e=this._xhr;e&&(e.readyState!==0&&e.readyState!==4||(this.clearTimeOut(),this._failureTimeout=setTimeout(()=>{this.connected=!0},5e3),this._requestTimeout=setTimeout(this.onRequestTimeout.bind(this),hy*1e3),e.open("GET",this.connectionPath),e.send()))}onRequestTimeout(){this._requestAborted=!0,this._xhr?.abort(),this.performRequest()}onXhrReadyStateChange(){const e=this._xhr;e&&e.readyState===4&&((!this._requestAborted||e.status==200)&&this.onResponse(e.response),this._requestAborted=!1)}send(e){const t=this._parent.getPublicationPath();if(!t)return this.getLogger().error(`${ie()}: Pull: publication path is empty`).catch(()=>{}),!1;if(typeof XMLHttpRequest>"u")return this.getLogger().error(`${ie()}: Pull: XMLHttpRequest is not available; cannot publish`).catch(()=>{}),!1;const s=new XMLHttpRequest;return s.open("POST",t),s.send(e),!0}onResponse(e){this.clearTimeOut();const t=this._xhr;if(t)if(t.status===200)this.connected=!0,L.isStringFilled(e)||e instanceof ArrayBuffer?this._callbacks.onMessage(e):this._parent.session.mid=null,this.performRequest();else if(t.status===304){if(this.connected=!0,t.getResponseHeader("Expires")==="Thu, 01 Jan 1973 11:11:01 GMT"){const s=t.getResponseHeader("Last-Message-Id");L.isStringFilled(s)&&this._parent.setLastMessageId(s||"")}this.performRequest()}else this._callbacks.onError(new Error("Could not connect to the server")),this.connected=!1}clearTimeOut(){this._failureTimeout&&(clearTimeout(this._failureTimeout),this._failureTimeout=null),this._requestTimeout&&(clearTimeout(this._requestTimeout),this._requestTimeout=null)}createXhr(){const e=new XMLHttpRequest;return this._parent.isProtobufSupported()&&!this._parent.isJsonRpc()&&(e.responseType="arraybuffer"),e.addEventListener("readystatechange",this.onXhrReadyStateChange.bind(this)),e}}const Yr=19,tu=1800,fy=5e3,py=60*1e3,ru=10,su=10,gy="ping",my="pong",nu="bx-pull-session",yy=20,iu={api:{},channels:{},publicChannels:{},server:{timeShift:0},clientId:null,jwt:null,exp:0};class ou{_logger;_restClient;_status;_context;_guestMode;_guestUserId;_userId;_configGetMethod;_getPublicListMethod;_siteId;_enabled;_unloading=!1;_starting=!1;_debug=!1;_connectionAttempt=0;_connectionType=he.WebSocket;_skipStorageInit;_skipCheckRevision;_subscribers=Object.create(null);_watchTagsQueue=new Map;_watchUpdateInterval=174e4;_watchForceUpdateInterval=5e3;_configTimestamp=0;_session={mid:null,tag:null,time:null,history:{},lastMessageIds:[],messageCount:0};_connectors={[he.Undefined]:null,[he.WebSocket]:null,[he.LongPolling]:null};_isSecure;_config=null;_storage=null;_sharedConfig;_channelManager;_jsonRpcAdapter=null;_useLiteProtobuf=!0;_reconnectTimeout=null;_restartTimeout=null;_restoreWebSocketTimeout=null;_checkInterval=null;_offlineTimeout=null;_watchUpdateTimeout=null;_pingWaitTimeout=null;_timerFields=["_reconnectTimeout","_restartTimeout","_restoreWebSocketTimeout","_checkInterval","_offlineTimeout","_watchUpdateTimeout","_pingWaitTimeout"];_windowListeners=[];_isManualDisconnect=!1;_disposed=!1;_loggingEnabled=!1;_onPingTimeoutHandler;_onBeforeUnloadHandler;_onOfflineHandler;_onOnlineHandler;_userStatusCallbacks=Object.create(null);_connectPromises=[];_startingPromise=null;_startGeneration=0;constructor(e){this._logger=oe.createNullLogger(),this._restClient=e.b24,this._status=Ke.Offline,this._context="master",this._useLiteProtobuf=e.protobufCodec!=="vendored",e.restApplication&&(typeof e.configGetMethod>"u"&&(e.configGetMethod="pull.application.config.get"),typeof e.skipCheckRevision>"u"&&(e.skipCheckRevision=!0),L.isStringFilled(e.restApplication)&&(e.siteId=e.restApplication),e.serverEnabled=!0),this._guestMode=e.guestMode?ws(e.guestMode):!1,this._guestUserId=e.guestUserId?pt(e.guestUserId):0,this._guestMode&&this._guestUserId>0?this._userId=this._guestUserId:(this._guestMode=!1,this._userId=e.userId?pt(e.userId):0),this._siteId=e.siteId??"none",this._enabled=L.isUndefined(e.serverEnabled)?!0:e.serverEnabled===!0,this._configGetMethod=L.isStringFilled(e.configGetMethod)?e.configGetMethod||"":"pull.config.get",this._getPublicListMethod=L.isStringFilled(e.getPublicListMethod)?e.getPublicListMethod||"":"pull.channel.public.list",this._skipStorageInit=e.skipStorageInit===!0,this._skipCheckRevision=e.skipCheckRevision===!0,L.isUndefined(e.configTimestamp)||(this._configTimestamp=pt(e.configTimestamp)),this._isSecure=typeof document<"u"&&document?.location.href.indexOf("https")===0,this._userId&&!this._skipStorageInit&&(this._storage=new Gl({userId:this._userId,siteId:this._siteId})),this._sharedConfig=new Hm({onWebSocketBlockChanged:this.onWebSocketBlockChanged.bind(this),storage:this._storage}),this._channelManager=new Wm({b24:this._restClient,getPublicListMethod:this._getPublicListMethod}),this._loggingEnabled=this._sharedConfig.isLoggingEnabled(),this._onPingTimeoutHandler=this.onPingTimeout.bind(this),this._onBeforeUnloadHandler=this.onBeforeUnload.bind(this),this._onOfflineHandler=this.onOffline.bind(this),this._onOnlineHandler=this.onOnline.bind(this)}setLogger(e){this._logger=e,this._jsonRpcAdapter?.setLogger(this.getLogger()),this._storage?.setLogger(this.getLogger()),this._sharedConfig.setLogger(this.getLogger()),this._channelManager.setLogger(this.getLogger()),this._connectors.webSocket?.setLogger(this.getLogger()),this._connectors.longPolling?.setLogger(this.getLogger())}getLogger(){return this._logger}destroy(){this._disposed=!0,this._startGeneration++,this.stop(xe.NORMAL_CLOSURE,"manual stop"),this.rejectConnectPromises(new Error("PullClient has been destroyed")),this.removeAllWindowListeners(),this._storage&&this._storage.remove(Ve.PullConfig),this.persistSession()}init(){this._disposed||(this._connectors.webSocket=new uy({parent:this,onOpen:this.onWebSocketOpen.bind(this),onMessage:this.onIncomingMessage.bind(this),onDisconnect:this.onWebSocketDisconnect.bind(this),onError:this.onWebSocketError.bind(this)}),this._connectors.longPolling=new dy({parent:this,onOpen:this.onLongPollingOpen.bind(this),onMessage:this.onIncomingMessage.bind(this),onDisconnect:this.onLongPollingDisconnect.bind(this),onError:this.onLongPollingError.bind(this)}),this._connectionType=this.isWebSocketAllowed()?he.WebSocket:he.LongPolling,this.addWindowListener("beforeunload",this._onBeforeUnloadHandler),this.addWindowListener("offline",this._onOfflineHandler),this.addWindowListener("online",this._onOnlineHandler),this._jsonRpcAdapter=new qm({connector:this._connectors.webSocket,handlers:{"incoming.message":this.handleRpcIncomingMessage.bind(this)}}))}get connector(){return this._connectors[this._connectionType]}get status(){return this._status}set status(e){this._status!==e&&(this._status=e,this._offlineTimeout&&(clearTimeout(this._offlineTimeout),this._offlineTimeout=null),e===Ke.Offline?this.sendPullStatusDelayed(e,fy):this.sendPullStatus(e))}get session(){return this._session}subscribe(e){if(!L.isPlainObject(e))return this.attachCommandHandler(e);if(e=e,e.type=e.type||Ge.Server,e.command=e.command||null,e.type==Ge.Server||e.type==Ge.Client){if(typeof e.moduleId>"u")throw new TypeError(`${ie()}: Pull.subscribe: parameter moduleId is not specified`);return typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]=Object.create(null)),typeof this._subscribers[e.type][e.moduleId]>"u"&&(this._subscribers[e.type][e.moduleId]={callbacks:[],commands:Object.create(null)}),e.command?(typeof this._subscribers[e.type][e.moduleId].commands[e.command]>"u"&&(this._subscribers[e.type][e.moduleId].commands[e.command]=[]),this._subscribers[e.type][e.moduleId].commands[e.command].push(e.callback),()=>{typeof e.type>"u"||typeof e.moduleId>"u"||typeof e.command>"u"||e.command===null||(this._subscribers[e.type][e.moduleId].commands[e.command]=this._subscribers[e.type][e.moduleId].commands[e.command].filter(t=>t!==e.callback))}):(this._subscribers[e.type][e.moduleId].callbacks.push(e.callback),()=>{typeof e.type>"u"||typeof e.moduleId>"u"||(this._subscribers[e.type][e.moduleId].callbacks=this._subscribers[e.type][e.moduleId].callbacks.filter(t=>t!==e.callback))})}else return typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]=[]),this._subscribers[e.type].push(e.callback),()=>{typeof e.type>"u"||(this._subscribers[e.type]=this._subscribers[e.type].filter(t=>t!==e.callback))}}attachCommandHandler(e){if(typeof e.getModuleId!="function"||typeof e.getModuleId()!="string")return this.getLogger().error(`${ie()}: Pull.attachCommandHandler: result of handler.getModuleId() is not a string.`).catch(()=>{}),()=>{};let t=Ge.Server;return typeof e.getSubscriptionType=="function"&&(t=e.getSubscriptionType()),this.subscribe({type:t,moduleId:e.getModuleId(),callback:s=>{let n=null;if(typeof e.getMap=="function"){const i=e.getMap();if(i&&typeof i=="object"){const o=Object.prototype.hasOwnProperty.call(i,s.command)?i[s.command]:void 0;typeof o=="function"?n=o.bind(e):typeof o=="string"&&typeof e[o]=="function"&&(n=e[o].bind(e))}}if(!n){const i=`handle${ka(s.command)}`;typeof e[i]=="function"&&(n=e[i].bind(e))}n&&(this._debug&&this._context!=="master"&&this.getLogger().warning(`${ie()}: Pull.attachCommandHandler: result of handler.getModuleId() is not a string`,qe({data:s})).catch(()=>{}),n(s.params,s.extra,s.command))}})}async start(e=null){if(this._disposed)return Promise.reject({ex:{error:"PULL_DISPOSED",error_description:"PullClient has been destroyed; create a new instance"}});let t=!0;if(this.isConnected())return Promise.resolve(!0);if(this._starting&&this._startingPromise)return this._startingPromise;if(this._restartTimeout&&(clearTimeout(this._restartTimeout),this._restartTimeout=null),!this._userId)throw new Error("Not set userId");if(this._siteId==="none")throw new Error("Not set siteId");let s=!1;if(e&&L.isPlainObject(e)&&(typeof e?.skipReconnectToLastSession<"u"&&(s=e.skipReconnectToLastSession,delete e.skipReconnectToLastSession),this._config=e,t=!1,!this._configTimestamp&&e.server?.config_timestamp&&(this._configTimestamp=Number(e.server.config_timestamp))),!this._enabled)return Promise.reject({ex:{error:"PULL_DISABLED",error_description:"Push & Pull server is disabled"}});const n=Date.now();let i;!s&&this._storage&&(i=this._storage.get(nu,null)),L.isPlainObject(i)&&Object.prototype.hasOwnProperty.call(i,"ttl")&&i.ttl>=n&&(this._session.mid=i.mid),this._starting=!0;const o=++this._startGeneration;return this._startingPromise=new Promise((a,c)=>{this.loadConfig("client_start").then(u=>{if(this._disposed||this._startGeneration!==o){this._starting=!1,c({ex:{error:"PULL_DISPOSED",error_description:"PullClient has been destroyed; create a new instance"}});return}this.setConfig(u,t),!this._connectors.webSocket&&!this._connectors.longPolling?this.init():this._connectionType=this.isWebSocketAllowed()?he.WebSocket:he.LongPolling,this.updateWatch(!0),this.startCheckConfig(),this.connect().then(()=>a(!0),l=>c(l))}).catch(u=>{this._starting=!1,this.status=Ke.Offline,this.stopCheckConfig(),this.getLogger().error(`${ie()}: Pull: could not read push-server config`,{error:u}).catch(()=>{}),c(u)})})}restart(e=xe.NORMAL_CLOSURE,t="manual restart"){if(this._disposed)return;this._restartTimeout&&(clearTimeout(this._restartTimeout),this._restartTimeout=null),this.getLogger().debug(`${ie()}: Pull: restarting with code ${e}`).catch(()=>{}),this.disconnect(e,t),this._storage&&this._storage.remove(Ve.PullConfig),this._config=null;const s=`${e}_${t.replaceAll(" ","_")}`,n=this._startGeneration,i=()=>this._disposed||this._startGeneration!==n;this.loadConfig(s).then(o=>{i()||(this.setConfig(o,!0),!this._connectors.webSocket&&!this._connectors.longPolling&&this.init(),this.updateWatch(),this.startCheckConfig(),this.connect().catch(a=>{this.getLogger().error("restart error",{error:a}).catch(()=>{})}))},o=>{i()||(this.getLogger().error(`${ie()}: Pull: could not read push-server config `,{error:o}).catch(()=>{}),this.status=Ke.Offline,this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),(o?.status==401||o?.status==403||o?.code==="AUTHORIZE_ERROR"||o?.code==="WRONG_AUTH_TYPE")&&(this.stopCheckConfig(),this.onCustomEvent("onPullError",["AUTHORIZE_ERROR"])))})}stop(e=xe.NORMAL_CLOSURE,t="manual stop"){this.disconnect(e,t),this._startGeneration++,this.stopCheckConfig(),this.clearAllTimers()}clearAllTimers(){for(const e of this._timerFields){const t=this[e];t&&(e==="_checkInterval"?clearInterval(t):clearTimeout(t)),this[e]=null}}armTimeout(e,t,s){const n=this[e];n&&clearTimeout(n),this[e]=setTimeout(t,s)}addWindowListener(e,t){typeof window>"u"||(window.addEventListener(e,t),this._windowListeners.push({type:e,handler:t}))}removeAllWindowListeners(){if(typeof window<"u")for(const{type:e,handler:t}of this._windowListeners)window.removeEventListener(e,t);this._windowListeners=[]}reconnect(e,t,s=1){this.disconnect(e,t),this.scheduleReconnect(s)}setLastMessageId(e){this._session.mid=e}async sendMessage(e,t,s,n,i){const o={userList:e,body:{module_id:t,command:s,params:n},expiry:i};return this.isJsonRpc()?this.requireJsonRpcAdapter().executeOutgoingRpcCommand(gt.Publish,o):this.sendMessageBatch([o])}async sendMessageToChannels(e,t,s,n,i){const o={channelList:e,body:{module_id:t,command:s,params:n},expiry:i};return this.isJsonRpc()?this.requireJsonRpcAdapter().executeOutgoingRpcCommand(gt.Publish,o):this.sendMessageBatch([o])}capturePullEvent(e=!0){this._debug=e}enableLogging(e=!0){this._sharedConfig.setLoggingEnabled(e),this._loggingEnabled=e}async listChannels(){return this._jsonRpcAdapter?.executeOutgoingRpcCommand(gt.ListChannels,{})||Promise.reject(new Error("jsonRpcAdapter not init"))}async getUsersLastSeen(e){if(!L.isArray(e)||!e.every(s=>typeof s=="number"))throw new Error("userList must be an array of numbers");const t={};if(!this._jsonRpcAdapter)throw new Error("jsonRpcAdapter not init");return new Promise((s,n)=>{this._jsonRpcAdapter.executeOutgoingRpcCommand(gt.GetUsersLastSeen,{userList:e}).then(i=>{const o=[],a=i!==null&&typeof i=="object"?i:{};for(let u=0;u<e.length;u++){const l=e[u];Object.prototype.hasOwnProperty.call(a,l)?t[l]=Number(a[l]):o.push(l)}if(o.length===0)return s(t);const c={userIds:o,sendToQueueSever:!0};this._restClient.actions.v2.call.make({method:"pull.api.user.getLastSeen",params:c}).then(u=>{const l=u.getData().result;for(const h in l)t[Number(h)]=Number(l[h]);return s(t)}).catch(u=>{this.getLogger().error("getUsersLastSeen",{error:u}).catch(()=>{}),n(u)})}).catch(i=>{this.getLogger().error("getUsersLastSeen",{error:i}).catch(()=>{}),n(i)})})}async ping(e=5){return this._jsonRpcAdapter?.executeOutgoingRpcCommand(gt.Ping,{},e)}async subscribeUserStatusChange(e,t){return new Promise((s,n)=>{this._jsonRpcAdapter?.executeOutgoingRpcCommand(gt.SubscribeStatusChange,{userId:e}).then(()=>(this._userStatusCallbacks[e]||(this._userStatusCallbacks[e]=[]),L.isFunction(t)&&this._userStatusCallbacks[e].push(t),s())).catch(i=>n(i))})}async unsubscribeUserStatusChange(e,t){return this._userStatusCallbacks[e]&&(this._userStatusCallbacks[e]=this._userStatusCallbacks[e].filter(s=>s!==t),this._userStatusCallbacks[e].length===0)?this._jsonRpcAdapter?.executeOutgoingRpcCommand(gt.UnsubscribeStatusChange,{userId:e}):Promise.resolve()}getRevision(){return this._config&&this._config.api?this._config.api.revision_web:null}getServerVersion(){return this._config&&this._config.server?this._config.server.version:0}getServerMode(){return this._config&&this._config.server?this._config.server.mode:null}getConfig(){return this._config}getDebugInfo(){if(!JSON||!JSON.stringify)return{};let e;this._config&&this._config.channels?e={ChannelID:this._config.channels.private?.id?Mr:"n/a",ChannelDie:this._config.channels.private?.end||"n/a",ChannelDieShared:this._config.channels.shared?.end||"n/a"}:e={ConfigError:"config is not loaded"};let t="-";this._connectors.webSocket&&this._connectors.webSocket?.socket&&(this.isJsonRpc()?t="json-rpc":t=this._connectors.webSocket?.socket?.url.search("binaryMode=true")!=-1?"protobuf":"text");const s=this.connector?.connectionPath;return{UserId:this._userId+(this._userId>0?"":"(guest)"),"Guest userId":this._guestMode&&this._guestUserId!==0?this._guestUserId:"-","Browser online":typeof navigator<"u"&&navigator.onLine?"Y":"N",Connect:this.isConnected()?"Y":"N","Server type":this.isSharedMode()?"cloud":"local","WebSocket supported":this.isWebSocketSupported()?"Y":"N","WebSocket connected":this._connectors.webSocket&&this._connectors.webSocket.connected?"Y":"N","WebSocket mode":t,"Try connect":this._reconnectTimeout?"Y":"N","Try number":this._connectionAttempt,Path:s?qd(s,["CHANNEL_ID"]):"-",...e,"Last message":this._session.mid||"-","Session history":this._session.history,"Watch tags":this._watchTagsQueue.entries()}}getConnectionPath(e){let t;const s={};switch(e){case he.WebSocket:t=this._isSecure?this._config?.server.websocket_secure:this._config?.server.websocket;break;case he.LongPolling:t=this._isSecure?this._config?.server.long_pooling_secure:this._config?.server.long_polling;break;default:throw new Error(`Unknown connection type ${e}`)}if(!L.isStringFilled(t))throw new Error("Empty path");if(typeof this._config?.jwt=="string"&&this._config?.jwt!=="")s.token=this._config?.jwt;else{const n=[];if(this._config?.channels?.private?.id&&n.push(this._config.channels.private.id),this._config?.channels?.shared?.id&&n.push(this._config.channels.shared.id),n.length===0)throw new Error("Empty channels");s.CHANNEL_ID=n.join("/")}if(this.isJsonRpc()?s.jsonRpc="true":this.isProtobufSupported()&&(s.binaryMode="true"),this.isSharedMode()){if(!this._config?.clientId)throw new Error("Push-server is in shared mode, but clientId is not set");s.clientId=this._config.clientId}return typeof this._config?.server?.hostname=="string"&&this._config.server.hostname&&(s.hostname=this._config.server.hostname),this._session.mid&&(s.mid=this._session.mid),this._session.tag&&(s.tag=this._session.tag),this._session.time&&(s.time=this._session.time),s.revision=Yr,`${t}?${kn(s)}`}getPublicationPath(){const e=this._isSecure?this._config?.server.publish_secure:this._config?.server.publish;if(!e)return"";const t=[];this._config?.channels.private?.id&&t.push(this._config.channels.private.id),this._config?.channels.shared?.id&&t.push(this._config.channels.shared.id);const s={CHANNEL_ID:t.join("/")};return e+"?"+kn(s)}isConnected(){return this.connector?this.connector.connected:!1}isWebSocketSupported(){return typeof window<"u"&&typeof window.WebSocket<"u"}isWebSocketAllowed(){return this._sharedConfig.isWebSocketBlocked()?!1:this.isWebSocketEnabled()}isWebSocketEnabled(){return!this.isWebSocketSupported()||!this._config||!this._config.server?!1:this._config.server.websocket_enabled}isPublishingSupported(){return this.getServerVersion()>3}isPublishingEnabled(){return this.isPublishingSupported()?this._config?.server.publish_enabled===!0:!1}isProtobufSupported(){return this.getServerVersion()==4&&!Ra.isIE()}isJsonRpc(){return this.getServerVersion()>=5}isSharedMode(){return this.getServerMode()===Nn.Shared}emit(e){if(e.type==Ge.Server||e.type==Ge.Client){if(typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]=Object.create(null)),typeof e.moduleId>"u")throw new TypeError(`${ie()}: Pull.emit: parameter moduleId is not specified`);return typeof this._subscribers[e.type][e.moduleId]>"u"&&(this._subscribers[e.type][e.moduleId]={callbacks:[],commands:Object.create(null)}),this._subscribers[e.type][e.moduleId].callbacks.length>0&&this._subscribers[e.type][e.moduleId].callbacks.forEach(t=>{t(e.data,{type:e.type,moduleId:e.moduleId??"?"})}),!(typeof e.data>"u")&&!(typeof e.data.command>"u")&&this._subscribers[e.type][e.moduleId].commands[e.data.command]&&this._subscribers[e.type][e.moduleId].commands[e.data.command].length>0&&this._subscribers[e.type][e.moduleId].commands[e.data.command].forEach(t=>{typeof e.data>"u"||t(e.data.params,e.data.extra,e.data.command,{type:e.type,moduleId:e.moduleId})}),!0}else return typeof this._subscribers[e.type]>"u"&&(this._subscribers[e.type]=[]),this._subscribers[e.type].length<=0||this._subscribers[e.type].forEach(t=>{t(e.data,{type:e.type})}),!0}broadcastMessage(e){const t=e.module_id=e.module_id.toLowerCase(),s=e.command;e.extra||(e.extra={}),e.extra.server_time_unix&&(e.extra.server_time_ago=(Date.now()-e.extra.server_time_unix*1e3)/1e3-(this._config?.server.timeShift||0),e.extra.server_time_ago=Math.max(e.extra.server_time_ago,0)),this.logMessage(e);try{e.extra.sender&&e.extra.sender.type===Ss.Client?(this.onCustomEvent("onPullClientEvent-"+t,[s,e.params,e.extra],!0),this.onCustomEvent("onPullClientEvent",[t,s,e.params,e.extra],!0),this.emit({type:Ge.Client,moduleId:t,data:{command:s,params:L.clone(e.params),extra:L.clone(e.extra)}})):t==="pull"?this.handleInternalPullEvent(s,e):t=="online"?((e?.extra?.server_time_ago||0)<240&&(this.onCustomEvent("onPullOnlineEvent",[s,e.params,e.extra],!0),this.emit({type:Ge.Online,data:{command:s,params:L.clone(e.params),extra:L.clone(e.extra)}})),s==="userStatusChange"&&this.emitUserStatusChange(e.params.user_id,e.params.online)):(this.onCustomEvent("onPullEvent-"+t,[s,e.params,e.extra],!0),this.onCustomEvent("onPullEvent",[t,s,e.params,e.extra],!0),this.emit({type:Ge.Server,moduleId:t,data:{command:s,params:L.clone(e.params),extra:L.clone(e.extra)}}))}catch(n){this.getLogger().warning("PULL ERROR",{errorType:"broadcastMessages execute error",errorEvent:n,message:qe(e)}).catch(()=>{})}e.extra&&e.extra.revision_web&&this.checkRevision(pt(e.extra.revision_web))}broadcastMessages(e){for(const t of e)this.broadcastMessage(t)}async sendMessageBatch(e){if(!this.isPublishingEnabled())return this.getLogger().error("Client publishing is not supported or is disabled").catch(()=>{}),Promise.reject(new R({code:"JSSDK_PULL_PUBLISHING_DISABLED",description:"Pull: this portal has not enabled client publishing, so the message cannot be sent. Publish from your back end with `pull.application.event.add` instead.",status:0}));if(this.isJsonRpc()){const t=this.requireJsonRpcAdapter().createPublishRequest(e);return Promise.resolve(this.handOverToConnector(JSON.stringify(t)))}else{const t={};for(const s of e)if(typeof s.userList<"u")for(const n of s.userList){const i=Number(n);t[i]=i}return this._channelManager.getPublicIds(Object.values(t)).then(s=>this.handOverToConnector(this.encodeMessageBatch(e,s)))}}requireJsonRpcAdapter(){if(!this._jsonRpcAdapter)throw new R({code:"JSSDK_PULL_SEND_REFUSED",description:"Pull: the JSON-RPC adapter is not ready, so the message was not sent. The client has not finished starting.",status:0});return this._jsonRpcAdapter}handOverToConnector(e){const t=this.connector;if(!t)throw new R({code:"JSSDK_PULL_SEND_REFUSED",description:"Pull: there is no connector to send through \u2014 the client is not connected.",status:0});if(!t.send(e))throw new R({code:"JSSDK_PULL_SEND_REFUSED",description:"Pull: the connector refused the frame, so it never left \u2014 the socket is not open, or long-polling has no publication path. The connector log carries the specific reason.",status:0});return!0}encodeMessageBatch(e,t){const s=[];return e.forEach(n=>{const i=n.body;let o=[];if(n.userList&&(o=this.createMessageReceivers(n.userList,t)),n.channelList){if(!L.isArray(n.channelList))throw new TypeError("messageFields.publicChannels must be an array");n.channelList.forEach(a=>{let c,u;if(typeof a=="string"&&a.includes(".")){const l=a.toString().split(".");c=l[0],u=l[1]}else if(typeof a=="object"&&"publicId"in a&&"signature"in a)c=a?.publicId,u=a?.signature;else throw new Error(`Public channel MUST be either a string, formatted like "{publicId}.{signature}" or an object with fields 'publicId' and 'signature'`);o.push({id:this.encodeId(c),signature:this.encodeId(u)})})}s.push({receivers:o,body:JSON.stringify(i),expiry:n.expiry||0})}),this._useLiteProtobuf?sy(s):Xl.encode(Xl.create({requests:[{incomingMessages:{messages:s}}]})).finish()}createMessageReceivers(e,t){const s=[];for(const n of e){if(!t[n]||!t[n].publicId)throw new Error(`Could not determine public id for user ${n}`);s.push({id:this.encodeId(t[n].publicId),signature:this.encodeId(t[n].signature)})}return s}emitUserStatusChange(e,t){if(this._userStatusCallbacks[e])for(const s of this._userStatusCallbacks[e])s({userId:e,isOnline:t})}restoreUserStatusSubscription(){for(const e in this._userStatusCallbacks)Object.prototype.hasOwnProperty.call(this._userStatusCallbacks,e)&&this._userStatusCallbacks[e].length>0&&this._jsonRpcAdapter?.executeOutgoingRpcCommand(gt.SubscribeStatusChange,{userId:e})}async loadConfig(e){if(this._config){if(this.isConfigActual(this._config)&&this.checkRevision(this._config.api.revision_web))return Promise.resolve(this._config);this._config=Object.assign({},iu)}else{this._config=Object.assign({},iu);let t;if(this._storage&&(t=this._storage.get(Ve.PullConfig,null)),this.isConfigActual(t)&&this.checkRevision(t.api.revision_web))return Promise.resolve(t);this._storage&&this._storage.remove(Ve.PullConfig)}return new Promise((t,s)=>{this._restClient.actions.v2.call.make({method:this._configGetMethod,params:{CACHE:"N"}}).then(n=>{const i=n.getData().result,o=new Date(i.serverTime).getTime(),a=Number.isFinite(o)?Math.floor((Date.now()-o)/1e3):0;delete i.serverTime;const c=Object.assign({},i);c.server.timeShift=a,t(c)}).catch(n=>{s(n)})})}isConfigActual(e){if(!L.isPlainObject(e)||Number(e.server.config_timestamp)!==this._configTimestamp)return!1;const t=new Date;if(L.isNumber(e.exp)&&e.exp>0&&e.exp<t.getTime()/1e3||Object.keys(e.channels).length===0)return!1;for(const s in e.channels){if(!Object.prototype.hasOwnProperty.call(e.channels,s))continue;const n=e.channels[s];if(new Date(n.end)<t)return!1}return!0}startCheckConfig(){this._disposed||(this._checkInterval&&(clearInterval(this._checkInterval),this._checkInterval=null),this._checkInterval=setInterval(this.checkConfig.bind(this),py))}stopCheckConfig(){this._checkInterval&&clearInterval(this._checkInterval),this._checkInterval=null}checkConfig(){if(this.isConfigActual(this._config)){if(!this.checkRevision(pt(this._config?.api.revision_web)))return!1}else this.logToConsole("Stale config detected. Restarting"),this.restart(xe.CONFIG_EXPIRED,"config expired");return!0}setConfig(e,t){for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&Object.prototype.hasOwnProperty.call(this._config,s)&&(this._config[s]=e[s]);if(e.publicChannels&&this.setPublicIds(Object.values(e.publicChannels)),this._configTimestamp=Number(e.server.config_timestamp),this._storage&&t&&!this._disposed)try{this._storage.set(Ve.PullConfig,e)}catch(s){typeof localStorage<"u"&&localStorage.removeItem&&localStorage.removeItem("history"),this.getLogger().error(`${ie()}: Pull: Could not cache config in local storage.`,{error:s}).catch(()=>{})}}setPublicIds(e){this._channelManager.setPublicIds(e)}checkRevision(e){return this._skipCheckRevision?!0:e>0&&e!==Yr?(this._enabled=!1,this.showNotification("PULL_OLD_REVISION"),this.disconnect(xe.NORMAL_CLOSURE,"check_revision"),this.onCustomEvent("onPullRevisionUp",[e,Yr]),this.emit({type:Ge.Revision,data:{server:e,client:Yr}}),this.logToConsole(`Pull revision changed from ${Yr} to ${e}. Reload required`),!1):!0}disconnect(e,t){this.connector&&(this._isManualDisconnect=!0,this.connector.disconnect(e,t))}restoreWebSocketConnection(){this._connectionType!==he.WebSocket&&this._connectors.webSocket?.connect()}scheduleReconnect(e=0){this._disposed||!this._enabled||(e||(e=this.getConnectionAttemptDelay(this._connectionAttempt)),this.logToConsole(`Pull: scheduling reconnection in ${e} seconds; attempt # ${this._connectionAttempt}`),this.armTimeout("_reconnectTimeout",()=>{this.connect().catch(t=>{this.getLogger().error("scheduleReconnect",{error:t}).catch(()=>{})})},e*1e3))}scheduleRestoreWebSocketConnection(){this._disposed||(this.logToConsole(`Pull: scheduling restoration of websocket connection in ${tu} seconds`),!this._restoreWebSocketTimeout&&this.armTimeout("_restoreWebSocketTimeout",()=>{this._restoreWebSocketTimeout=null,this.restoreWebSocketConnection()},tu*1e3))}async connect(){return this._disposed||!this._enabled?Promise.reject():this.connector?.connected?Promise.resolve():(this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),this.status=Ke.Connecting,this._connectionAttempt++,new Promise((e,t)=>{this._connectPromises.push({resolve:e,reject:t}),this.connector?.connect()}))}resolveConnectPromises(){const e=this._connectPromises;this._connectPromises=[];for(const t of e)t.resolve({})}rejectConnectPromises(e){const t=this._connectPromises;this._connectPromises=[];for(const s of t)s.reject(e)}scheduleRestart(e,t,s=0){this._disposed||(s<1&&(s=Math.ceil(Math.random()*30)+5),this.armTimeout("_restartTimeout",()=>this.restart(e,t),s*1e3))}handleRpcIncomingMessage(e){this._session.mid=e.mid;const t=e.body;return t===null||typeof t!="object"?(this.getLogger().warning(`${ie()}: Pull: an rpc message body was not an object and was skipped`,{bodyType:t===null?"null":typeof t}).catch(()=>{}),{}):((t.extra===null||typeof t.extra!="object")&&(t.extra={}),t.extra.sender=e.sender,(L.isPlainObject(e.user_params)||L.isPlainObject(e.dictionary))&&(t.params===null||typeof t.params!="object")&&(t.params={}),"user_params"in e&&L.isPlainObject(e.user_params)&&Object.assign(t.params,e.user_params),"dictionary"in e&&L.isPlainObject(e.dictionary)&&Object.assign(t.params,e.dictionary),this.checkDuplicate(e.mid)&&(this.addMessageToStat(t),this.trimDuplicates(),this.broadcastMessage(t)),this.connector?.send(`mack:${e.mid}`),{})}handleIncomingEvents(e){const t=[];if(e.length===0){this._session.mid=null;return}for(const s of e)this.updateSessionFromEvent(s),!(s.mid&&!this.checkDuplicate(s.mid))&&(this.addMessageToStat(s.text),t.push(s.text));this.trimDuplicates(),this.broadcastMessages(t)}updateSessionFromEvent(e){this._session.mid=e.mid||null,this._session.tag=e.tag||null,this._session.time=e.time||null}handleInternalPullEvent(e,t){switch(e.toUpperCase()){case Lr.CHANNEL_EXPIRE:{if(t.params.action==="reconnect"){const s=t.params?.channel.type;s==="private"&&this._config?.channels?.private&&(this._config.channels.private=t.params.new_channel,this.logToConsole(`Pull: new config for ${t.params.channel.type} channel set: [updated]`)),s==="shared"&&this._config?.channels?.shared&&(this._config.channels.shared=t.params.new_channel,this.logToConsole(`Pull: new config for ${t.params.channel.type} channel set: [updated]`)),this.reconnect(xe.CONFIG_REPLACED,"config was replaced")}else this.restart(xe.CHANNEL_EXPIRED,"channel expired received");break}case Lr.CONFIG_EXPIRE:{this.restart(xe.CONFIG_EXPIRED,"config expired received");break}case Lr.SERVER_RESTART:{this.reconnect(xe.SERVER_RESTARTED,"server was restarted",15);break}}}onIncomingMessage(e){if(this.isJsonRpc())e===gy?this.onJsonRpcPing():this._jsonRpcAdapter?.parseJsonRpcMessage(e);else{const t=this.extractMessages(e);this.handleIncomingEvents(t)}}onLongPollingOpen(){this._unloading=!1,this._starting=!1,this._connectionAttempt=0,this._isManualDisconnect=!1,this.status=Ke.Online,this.logToConsole("Pull: Long polling connection with push-server opened"),this.isWebSocketEnabled()&&this.scheduleRestoreWebSocketConnection(),this.resolveConnectPromises()}onLongPollingDisconnect(e){this._connectionType===he.LongPolling&&(this.status=Ke.Offline),this.logToConsole(`Pull: Long polling connection with push-server closed. Code: ${e.code}, reason: ${e.reason}`),this._isManualDisconnect||this.scheduleReconnect(),this._isManualDisconnect=!1,this.clearPingWaitTimeout()}onLongPollingError(e){this._starting=!1,this._connectionType===he.LongPolling&&(this.status=Ke.Offline),this.getLogger().error(`${ie()}: Pull: Long polling connection error`,{error:e}).catch(()=>{}),this.scheduleReconnect(),this.rejectConnectPromises(e),this.clearPingWaitTimeout()}onWebSocketBlockChanged(e){const t=e.isWebSocketBlocked;t&&this._connectionType===he.WebSocket&&!this.isConnected()?(this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),this._connectionAttempt=0,this._connectionType=he.LongPolling,this.scheduleReconnect(1)):!t&&this._connectionType===he.LongPolling&&(this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null),this._restoreWebSocketTimeout&&(clearTimeout(this._restoreWebSocketTimeout),this._restoreWebSocketTimeout=null),this._connectionAttempt=0,this._connectionType=he.WebSocket,this.scheduleReconnect(1))}onWebSocketOpen(){this._unloading=!1,this._starting=!1,this._connectionAttempt=0,this._isManualDisconnect=!1,this.status=Ke.Online,this._sharedConfig.setWebSocketBlocked(!1),this._sharedConfig.setLongPollingBlocked(!0),this._connectionType==he.LongPolling&&(this._connectionType=he.WebSocket,this._connectors.longPolling?.disconnect(xe.CONFIG_REPLACED,"Fire at onWebSocketOpen")),this._restoreWebSocketTimeout&&(clearTimeout(this._restoreWebSocketTimeout),this._restoreWebSocketTimeout=null),this.logToConsole("Pull: Websocket connection with push-server opened"),this.resolveConnectPromises(),this.restoreUserStatusSubscription()}onWebSocketDisconnect(e){this._connectionType===he.WebSocket&&(this.status=Ke.Offline),this.logToConsole(`Pull: Websocket connection with push-server closed. Code: ${e.code}, reason: ${e.reason}`,!0),this._isManualDisconnect||(e.code==xe.WRONG_CHANNEL_ID?this.scheduleRestart(xe.WRONG_CHANNEL_ID,"wrong channel signature"):this.scheduleReconnect()),this._sharedConfig.setLongPollingBlocked(!0),this._isManualDisconnect=!1,this.clearPingWaitTimeout()}onWebSocketError(e){this._starting=!1,this._connectionType===he.WebSocket&&(this.status=Ke.Offline),this.getLogger().error(`${ie()}: Pull: WebSocket connection error`,{error:e}).catch(()=>{}),this.scheduleReconnect(),this.rejectConnectPromises(e),this.clearPingWaitTimeout()}extractMessages(e){if(e instanceof ArrayBuffer)return this.extractProtobufMessages(e);if(L.isStringFilled(e))return this.extractPlainTextMessages(e);throw new Error("Error pullEvent type")}extractProtobufMessages(e){const t=[];try{const s=this._useLiteProtobuf?cy(new Uint8Array(e)):Gm.decode(new Uint8Array(e));"damaged"in s&&s.damaged&&this.getLogger().warning(`${ie()}: Pull: a protobuf frame was damaged; whatever could not be read was dropped`,{byteLength:e.byteLength}).catch(()=>{});for(let n=0;n<s.responses.length;n++){const i=s.responses[n];if(i.command!=="outgoingMessages")continue;const o=i.outgoingMessages.messages;for(const a of o){let c;try{c=JSON.parse(a.body)}catch(l){this.getLogger().error(`${ie()}: Pull: Could not parse message body`,{error:l}).catch(()=>{});continue}if(c===null||typeof c!="object"){this.getLogger().warning(`${ie()}: Pull: a message body was not a JSON object and was skipped`,{responseIndex:n,bodyType:c===null?"null":typeof c}).catch(()=>{});continue}if((c.extra===null||typeof c.extra!="object")&&(c.extra={}),!a.sender){this.getLogger().warning(`${ie()}: Pull: a protobuf message arrived with no sender and was skipped`,{responseIndex:n,moduleId:typeof c.module_id=="string"?c.module_id:null}).catch(()=>{});continue}c.extra.sender={type:a.sender.type},a.sender.id instanceof Uint8Array&&(c.extra.sender.id=this.decodeId(a.sender.id));const u={mid:this.decodeId(a.id),text:c};t.push(u)}}}catch(s){this.getLogger().error(`${ie()}: Pull: Could not parse message`,{error:s}).catch(()=>{})}return t}extractPlainTextMessages(e){const t=[],s=e.match(/#!NGINXNMS!#(.*?)#!NGINXNME!#/g);if(s===null)return this.getLogger().warning("PULL ERROR",{errorType:"parseResponse error parsing message",byteLength:e.length}).catch(()=>{}),[];for(let n=0;n<s.length;n++){if(s[n]=s[n].substring(12,s[n].length-12),s[n].length<=0)continue;let i;try{i=JSON.parse(s[n])}catch{continue}t.push(i)}return t}decodeId(e){let t="";for(const s of e){const n=s.toString(16);n.length===1&&(t+="0"),t+=n}return t}encodeId(e){if(!e)return new Uint8Array;const t=[];for(let s=0;s<e.length;s+=2)t.push(Number.parseInt(e.slice(s,s+2),16));return new Uint8Array(t)}onOffline(){this._disposed||this.disconnect(xe.NORMAL_CLOSURE,"offline")}onOnline(){this._disposed||this.connect().catch(e=>{this.getLogger().error("onOnline",{error:e}).catch(()=>{})})}onBeforeUnload(){this._unloading=!0,this.persistSession(),this.scheduleReconnect(15)}persistSession(){const e=L.clone(this.session);if(e.ttl=Date.now()+yy*1e3,this._storage)try{this._storage.set(nu,JSON.stringify(e))}catch(t){this.getLogger().error(`${ie()}: Pull: Could not save session info in local storage. Error: `,{error:t}).catch(()=>{})}}sendPullStatusDelayed(e,t){this._disposed||this.armTimeout("_offlineTimeout",()=>{this._offlineTimeout=null,this.sendPullStatus(e)},t)}sendPullStatus(e){this._unloading||(this.onCustomEvent("onPullStatus",[e]),this.emit({type:Ge.Status,data:{status:e}}))}extendWatch(e,t=!1){this._watchTagsQueue.get(e)||(this._watchTagsQueue.set(e,!0),t&&this.updateWatch(t))}updateWatch(e=!1){this._disposed||this.armTimeout("_watchUpdateTimeout",()=>{const t=[...this._watchTagsQueue.keys()];t.length>0?this._restClient.actions.v2.call.make({method:"pull.watch.extend",params:{tags:t}}).then(s=>{const n=s.getData().result;for(const i of n)this.clearWatch(i);this.updateWatch()}).catch(()=>{this.updateWatch()}):this.updateWatch()},e?this._watchForceUpdateInterval:this._watchUpdateInterval)}clearWatch(e){this._watchTagsQueue.delete(e)}onJsonRpcPing(){this.updatePingWaitTimeout(),this.connector?.send(my)}updatePingWaitTimeout(){this._disposed||this.armTimeout("_pingWaitTimeout",this._onPingTimeoutHandler,su*2*1e3)}clearPingWaitTimeout(){this._pingWaitTimeout&&clearTimeout(this._pingWaitTimeout),this._pingWaitTimeout=null}onPingTimeout(){this._pingWaitTimeout=null,!(this._disposed||!this._enabled||!this.isConnected())&&(this.getLogger().warning(`No pings are received in ${su*2} seconds. Reconnecting`).catch(()=>{}),this.disconnect(xe.STUCK,"connection stuck"),this.scheduleReconnect())}getConnectionAttemptDelay(e){let t;return e<1?t=.5:e<3?t=15:e<5?t=45:e<10?t=600:t=3600,t+t*Math.random()*.2}checkDuplicate(e){return this._session.lastMessageIds.includes(e)?(this.getLogger().warning(`Duplicate message ${e} skipped`).catch(()=>{}),!1):(this._session.lastMessageIds.push(e),!0)}trimDuplicates(){this._session.lastMessageIds.length>ru&&(this._session.lastMessageIds=this._session.lastMessageIds.slice(-ru))}logMessage(e){this._debug&&(e.extra?.sender&&e.extra.sender.type===Ss.Client?this.getLogger().info(`onPullClientEvent-${e.module_id}`,qe({command:e.command,params:e.params,extra:e.extra})).catch(()=>{}):e.module_id=="online"?this.getLogger().info("onPullOnlineEvent",qe({command:e.command,params:e.params,extra:e.extra})).catch(()=>{}):this.getLogger().info("onPullEvent",qe({moduleId:e.module_id,command:e.command,params:e.params,extra:e.extra})).catch(()=>{}))}logToConsole(e,t=!1){(this._loggingEnabled||t)&&this.getLogger().debug(`${ie()}: ${e}`).catch(()=>{})}addMessageToStat(e){this._session.history[e.module_id]||(this._session.history[e.module_id]={}),this._session.history[e.module_id][e.command]||(this.session.history[e.module_id][e.command]=0),this._session.history[e.module_id][e.command]++,this._session.messageCount++}showNotification(e){this.getLogger().notice(e).catch(()=>{})}onCustomEvent(e,t,s=!1){}}class au{_b24;_isInit=!1;_profile=null;_app=null;_payment=null;_license=null;_currency=null;_appOptions=null;_userOptions=null;_b24PullClient=null;_pullClientUnSubscribe=[];_pullClientModuleId="";_logger;constructor(e){this._logger=oe.createNullLogger(),this._b24=e}setLogger(e){this._logger=e,this._profile!==null&&this._profile.setLogger(this.getLogger()),this._app!==null&&this._app.setLogger(this.getLogger()),this._payment!==null&&this._payment.setLogger(this.getLogger()),this._license!==null&&this._license.setLogger(this.getLogger()),this._currency!==null&&this._currency.setLogger(this.getLogger()),this._appOptions!==null&&this._appOptions.setLogger(this.getLogger()),this._userOptions!==null&&this._userOptions.setLogger(this.getLogger())}getLogger(){return this._logger}destroy(){this._destroyPullClient()}async loadData(e=[de.App,de.Profile],t="helper-load-data"){const s={[de.App]:{method:"app.info"},[de.Profile]:{method:"profile"},[de.Currency]:[{method:"crm.currency.base.get"},{method:"crm.currency.list"}],[de.AppOptions]:{method:"app.option.get"},[de.UserOptions]:{method:"user.option.get"}},n=e.reduce((i,o)=>{if(s[o])if(Array.isArray(s[o]))for(const[a,c]of s[o].entries())i[`get_${o}_${a}`]=c;else i[`get_${o}`]=s[o];return i},{});try{const i=(await this._b24.actions.v2.batch.make({calls:n,options:{isHaltOnError:!0,returnAjaxResult:!1,requestId:t}})).getData();i[`get_${de.App}`]&&(this._app=await this.parseAppData(i[`get_${de.App}`]),this._payment=await this.parsePaymentData(i[`get_${de.App}`]),this._license=await this.parseLicenseData(i[`get_${de.App}`])),i[`get_${de.Profile}`]&&(this._profile=await this.parseUserData(i[`get_${de.Profile}`])),i[`get_${de.Currency}_0`]&&i[`get_${de.Currency}_1`]&&(this._currency=await this.parseCurrencyData({currencyBase:i[`get_${de.Currency}_0`],currencyList:i[`get_${de.Currency}_1`]})),i[`get_${de.AppOptions}`]&&(this._appOptions=await this.parseOptionsData("app",i[`get_${de.AppOptions}`])),i[`get_${de.UserOptions}`]&&(this._userOptions=await this.parseOptionsData("user",i[`get_${de.UserOptions}`])),this._isInit=!0}catch(i){throw i instanceof Error?i:(this.getLogger().error("Failed to load data",{error:i}).catch(()=>{}),new Error("Failed to load data",{cause:i}))}}async parseUserData(e){const t=new xm(this._b24);return t.setLogger(this.getLogger()),t.initData({id:Number(e.ID),isAdmin:e.ADMIN===!0,lastName:e?.LAST_NAME||"",name:e?.NAME||"",gender:e?.PERSONAL_GENDER||"",photo:e?.PERSONAL_PHOTO||"",TimeZone:e?.TIME_ZONE||"",TimeZoneOffset:e?.TIME_ZONE_OFFSET}).then(()=>t)}async parseAppData(e){const t=new Fm(this._b24);return t.setLogger(this.getLogger()),t.initData({id:Number.parseInt(e.ID),code:e.CODE,version:Number.parseInt(e.VERSION),status:e.STATUS,isInstalled:e.INSTALLED}).then(()=>t)}async parsePaymentData(e){const t=new Bm(this._b24);return t.setLogger(this.getLogger()),t.initData({isExpired:e.PAYMENT_EXPIRED==="Y",days:Number.parseInt(e.DAYS||"0")}).then(()=>t)}async parseLicenseData(e){const t=new $m(this._b24);return t.setLogger(this.getLogger()),t.initData({languageId:e.LANGUAGE_ID,license:e.LICENSE,licensePrevious:e.LICENSE_PREVIOUS,licenseType:e.LICENSE_TYPE,licenseFamily:e.LICENSE_FAMILY,isSelfHosted:e.LICENSE.includes("selfhosted")}).then(()=>t)}async parseCurrencyData(e){const t=new jm(this._b24);return t.setLogger(this.getLogger()),t.initData(e).then(()=>t)}async parseOptionsData(e,t){const s=new Vi(this._b24,e);return s.setLogger(this.getLogger()),s.initData(t).then(()=>s)}get isInit(){return this._isInit}get forB24Form(){if(this.ensureInitialized(),this._profile===null)throw new Error("B24HelperManager.profileInfo not initialized");if(this._app===null)throw new Error("B24HelperManager.appInfo not initialized");return{app_code:this.appInfo.data.code,app_status:this.appInfo.data.status,payment_expired:this.paymentInfo.data.isExpired?"Y":"N",days:this.paymentInfo.data.days,b24_plan:this.licenseInfo.data.license,c_name:this.profileInfo.data.name,c_last_name:this.profileInfo.data.lastName,hostname:this.hostName}}get hostName(){return this._b24.getTargetOrigin()}get profileInfo(){if(this.ensureInitialized(),this._profile===null)throw new Error("B24HelperManager.profileInfo not initialized");return this._profile}get appInfo(){if(this.ensureInitialized(),this._app===null)throw new Error("B24HelperManager.appInfo not initialized");return this._app}get paymentInfo(){if(this.ensureInitialized(),this._payment===null)throw new Error("B24HelperManager.paymentInfo not initialized");return this._payment}get licenseInfo(){if(this.ensureInitialized(),this._license===null)throw new Error("B24HelperManager.licenseInfo not initialized");return this._license}get currency(){if(this.ensureInitialized(),this._currency===null)throw new Error("B24HelperManager.currency not initialized");return this._currency}get appOptions(){if(this.ensureInitialized(),this._appOptions===null)throw new Error("B24HelperManager.appOptions not initialized");return this._appOptions}get userOptions(){if(this.ensureInitialized(),this._userOptions===null)throw new Error("B24HelperManager.userOptions not initialized");return this._userOptions}get isSelfHosted(){return this.licenseInfo.data.isSelfHosted}get primaryKeyIncrementValue(){return this.isSelfHosted?1:2}get b24SpecificUrl(){return this.isSelfHosted?{[Ut.MainSettings]:"/configs/",[Ut.UfList]:"/configs/userfield_list.php",[Ut.UfPage]:"/configs/userfield.php"}:{[Ut.MainSettings]:"/settings/configs/",[Ut.UfList]:"/settings/configs/userfield_list.php",[Ut.UfPage]:"/settings/configs/userfield.php"}}usePullClient(e="prefix",t,s){return this._b24PullClient?this:(this.initializePullClient(typeof t>"u"?this.profileInfo.data.id||0:t,e,s),this)}initializePullClient(e,t="prefix",s){this._b24PullClient=new ou({b24:this._b24,restApplication:this._b24.auth.getUniq(t),userId:e,...s===void 0?{}:{protobufCodec:s}})}subscribePullClient(e,t="application"){if(!this._b24PullClient)throw new Error("PullClient not init");return this._pullClientModuleId=t,this._pullClientUnSubscribe.push(this._b24PullClient.subscribe({moduleId:this._pullClientModuleId,callback:e})),this}startPullClient(){if(!this._b24PullClient)throw new Error("PullClient not init");this._b24PullClient.start().catch(e=>{this.getLogger().error(`${ie()}: Pull not running`,{error:e}).catch(()=>{})})}getModuleIdPullClient(){if(!this._b24PullClient)throw new Error("PullClient not init");return this._pullClientModuleId}_destroyPullClient(){for(const e of this._pullClientUnSubscribe)e();this._b24PullClient?.destroy(),this._b24PullClient=null}ensureInitialized(){if(!this._isInit)throw new Error("B24HelperManager not initialized")}}const _y=()=>{let r=!1,e=!1,t=null;return{initB24Helper:async(s,n=[de.App,de.Profile],i="helper-load-data")=>(t===null&&(t=new au(s)),r||(await t.loadData(n,i),r=!0),t),isInitB24Helper:()=>r,destroyB24Helper:()=>{t?.destroy(),t=null,r=!1,e=!1},getB24Helper:()=>{if(t===null)throw new R({code:"JSSDK_HELPER_NOT_INIT",description:"B24HelperManager is not initialized. You need to call initB24Helper first.",status:0});return t},usePullClient:(s,n,i)=>{if(t===null)throw new R({code:"JSSDK_HELPER_NOT_INIT",description:"B24HelperManager is not initialized. You need to call initB24Helper first.",status:0});t.usePullClient(s,n,i),e=!0},useSubscribePullClient:(s,n="application")=>{if(!e)throw new R({code:"JSSDK_HELPER_PULL_CLIENT_NOT_INIT",description:"PullClient is not initialized. You need to call usePullClient first.",status:0});t?.subscribePullClient(s,n)},startPullClient:()=>{if(!e)throw new R({code:"JSSDK_HELPER_PULL_CLIENT_NOT_INIT",description:"PullClient is not initialized. You need to call usePullClient first.",status:0});t?.startPullClient()}}};let Jt=null;function wy(){const r={DOMAIN:null,PROTOCOL:!1,APP_SID:null,LANG:null};if(window.name){const[e,t,s]=window.name.split("|");r.DOMAIN=e,r.PROTOCOL=Number.parseInt(t??"0")===1,r.APP_SID=s,r.LANG=null}return r}async function by(r){const e=wy();if(!e.DOMAIN||!e.APP_SID)throw new R({code:"JSSDK_CLIENT_SIDE_WARNING",description:"Well done! Now paste this URL into the Bitrix24 app settings",status:500});const t=new Wl(e,r);try{await t.init()}catch(s){try{t.destroy()}catch{}throw s}return t}async function Sy(r){if(Jt!==null)return Jt;const e=by(r);return Jt=e,e.then(t=>{const s=t.destroy.bind(t);t.destroy=()=>{Jt===e&&(Jt=null),s()}},()=>{Jt===e&&(Jt=null)}),e}A.AbstractB24=vs,A.AbstractLogger=Ys,A.AdaptiveDelayer=Ja,A.AjaxError=ye,A.AjaxResult=Pr,A.ApiVersion=K,A.AppFrame=Ml,A.AuthHookManager=Dl,A.AuthManager=xl,A.AuthOAuthManager=Kl,A.B24Frame=Wl,A.B24HelperManager=au,A.B24Hook=Bi,A.B24LangList=Ln,A.B24LocaleMap=$d,A.B24OAuth=Pm,A.B24PullClientManager=ou,A.BatchRefV3=Cm,A.Browser=Ra,A.CatalogProductImageType=La,A.CatalogProductType=Da,A.CatalogRoundingRuleType=Ma,A.CloseReasons=xe,A.ConnectionType=he,A.ConsolaAdapter=wu,A.ConsoleHandler=zi,A.ConsoleV2Handler=Js,A.DataType=Ji,A.DialogManager=$l,A.EnumAppStatus=wt,A.EnumBitrix24Edition=Pa,A.EnumBizprocBaseType=xa,A.EnumBizprocDocumentType=Fa,A.EnumCrmEntityType=Ca,A.EnumCrmEntityTypeId=at,A.EnumCrmEntityTypeShort=Rn,A.Environment=Ks,A.FilterV3=km,A.HttpV2=js,A.HttpV3=Us,A.JsonFormatter=fu,A.LineFormatter=ts,A.ListRpcError=Dn,A.LoadDataType=de,A.LogLevel=W,A.Logger=Er,A.LoggerFactory=oe,A.LsKeys=Ve,A.MemoryHandler=yu,A.MessageCommands=ce,A.MessageManager=Ll,A.NullLogger=Sr,A.OperatingLimiter=za,A.OptionsManager=Bl,A.ParamsFactory=xr,A.ParentManager=Fl,A.PlacementManager=Vl,A.ProductRowDiscountTypeId=Na,A.PullStatus=Ke,A.RateLimiter=Wa,A.RefreshTokenError=zl,A.RestrictionManager=lr,A.Result=Oe,A.RpcMethod=gt,A.SdkError=R,A.SenderType=Ss,A.ServerMode=Nn,A.SliderManager=jl,A.StatusDescriptions=Ba,A.StreamHandler=_u,A.SubscriptionType=Ge,A.SystemCommands=Lr,A.TelegramFormatter=zs,A.TelegramHandler=Eu,A.Text=bs,A.Type=L,A.TypeOption=bt,A.TypeSpecificUrl=Ut,A.WinstonAdapter=bu,A.convertBizprocDocumentTypeToCrmEntityTypeId=Md,A.getDocumentId=Pd,A.getDocumentType=Cn,A.getDocumentTypeForFilter=xd,A.getEnumCrmEntityTypeShort=Ld,A.getEnumValue=Iu,A.getEnvironment=Gs,A.initializeB24Frame=Sy,A.isArrayOfArray=Au,A.isBrowserLikeRuntime=br,A.isFrameRefusalCloseCode=Fd,A.memoryUsageProcessor=mu,A.omit=Ki,A.pick=Ou,A.pidProcessor=gu,A.useB24Helper=_y,A.useFormatter=Im,A.versionManager=ur}));