UNPKG

@bitrix24/b24jssdk

Version:
1,683 lines (1,663 loc) 452 kB
/** * @version @bitrix24/b24jssdk v0.5.1 * @copyright (c) 2025 Bitrix24 * @licence MIT * @links https://github.com/bitrix24/b24jssdk - GitHub * @links https://bitrix24.github.io/b24jssdk/ - Documentation */ import { DateTime } from 'luxon'; import axios, { AxiosError } from 'axios'; import * as qs from 'qs-esm'; var LoggerType = /* @__PURE__ */ ((LoggerType2) => { LoggerType2["desktop"] = "desktop"; LoggerType2["log"] = "log"; LoggerType2["info"] = "info"; LoggerType2["warn"] = "warn"; LoggerType2["error"] = "error"; LoggerType2["trace"] = "trace"; return LoggerType2; })(LoggerType || {}); const styleCollection = /* @__PURE__ */ new Map(); styleCollection.set("title", [ "%c#title#", "color: #959ca4; font-style: italic; padding: 0 6px; border-top: 1px solid #ccc; border-left: 1px solid #ccc; border-bottom: 1px solid #ccc" ]); styleCollection.set("desktop" /* desktop */, [ `%cDESKTOP`, "color: white; font-style: italic; background-color: #29619b; padding: 0 6px; border: 1px solid #29619b" ]); styleCollection.set("log" /* log */, [ `%cLOG`, "color: #2a323b; font-style: italic; background-color: #ccc; padding: 0 6px; border: 1px solid #ccc" ]); styleCollection.set("info" /* info */, [ `%cINFO`, "color: #fff; font-style: italic; background-color: #6b7f96; padding: 0 6px; border: 1px solid #6b7f96" ]); styleCollection.set("warn" /* warn */, [ `%cWARNING`, "color: #f0a74f; font-style: italic; padding: 0 6px; border: 1px solid #f0a74f" ]); styleCollection.set("error" /* error */, [ `%cERROR`, "color: white; font-style: italic; background-color: #8a3232; padding: 0 6px; border: 1px solid #8a3232" ]); styleCollection.set("trace" /* trace */, [ `%cTRACE`, "color: #2a323b; font-style: italic; background-color: #ccc; padding: 0 6px; border: 1px solid #ccc" ]); class LoggerBrowser { #title; #types = { desktop: true, log: false, info: false, warn: false, error: true, trace: true }; static build(title, isDevelopment = false) { const logger = new LoggerBrowser(title); if (isDevelopment) { logger.enable("log" /* log */); logger.enable("info" /* info */); logger.enable("warn" /* warn */); } return logger; } constructor(title) { this.#title = title; } // region Styles //// #getStyle(type) { const resultText = []; const resultStyle = []; if (styleCollection.has("title")) { const styleTitle = styleCollection.get("title"); if (styleTitle[0]) { resultText.push(styleTitle[0].replace("#title#", this.#title)); resultStyle.push(styleTitle[1] || ""); } } if (styleCollection.has(type)) { const styleBadge = styleCollection.get(type); if (styleBadge[0]) { resultText.push(styleBadge[0]); resultStyle.push(styleBadge[1] || ""); } } return [resultText.join(""), ...resultStyle]; } // endregion //// // region Config //// setConfig(types) { for (const type in types) { this.#types[type] = types[type]; } } enable(type) { if (typeof this.#types[type] === "undefined") { return false; } this.#types[type] = true; return true; } disable(type) { if (typeof this.#types[type] === "undefined") { return false; } this.#types[type] = false; return true; } isEnabled(type) { return this.#types[type]; } // endregion //// // region Functions //// desktop(...params) { if (this.isEnabled("desktop" /* desktop */)) { console.log(...this.#getStyle("desktop" /* desktop */), ...params); } } log(...params) { if (this.isEnabled("log" /* log */)) { console.log(...this.#getStyle("log" /* log */), ...params); } } info(...params) { if (this.isEnabled("info" /* info */)) { console.info(...this.#getStyle("info" /* info */), ...params); } } warn(...params) { if (this.isEnabled("warn" /* warn */)) { console.warn(...this.#getStyle("warn" /* warn */), ...params); } } error(...params) { if (this.isEnabled("error" /* error */)) { console.error(...this.#getStyle("error" /* error */), ...params); } } trace(...params) { if (this.isEnabled("trace" /* trace */)) { console.trace(...this.#getStyle("trace" /* trace */), ...params); } } // endregion //// } var DataType = /* @__PURE__ */ ((DataType2) => { DataType2["undefined"] = "undefined"; DataType2["any"] = "any"; DataType2["integer"] = "integer"; DataType2["boolean"] = "boolean"; DataType2["double"] = "double"; DataType2["date"] = "date"; DataType2["datetime"] = "datetime"; DataType2["string"] = "string"; DataType2["text"] = "text"; DataType2["file"] = "file"; DataType2["array"] = "array"; DataType2["object"] = "object"; DataType2["user"] = "user"; DataType2["location"] = "location"; DataType2["crmCategory"] = "crm_category"; DataType2["crmStatus"] = "crm_status"; DataType2["crmCurrency"] = "crm_currency"; return DataType2; })(DataType || {}); const OBJECT_CONSTRUCTOR_STRING = Function.prototype.toString.call(Object); class TypeManager { getTag(value) { return Object.prototype.toString.call(value); } /** * Checks that value is string * @param value * @return {boolean} * * @memo get from pull.client.Utils */ isString(value) { return typeof value === "string" || value instanceof String; } /** * Returns true if a value is not an empty string * @param value * @returns {boolean} */ isStringFilled(value) { return this.isString(value) && value !== ""; } /** * Checks that value is function * @param value * @return {boolean} * * @memo get from pull.client.Utils */ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type isFunction(value) { return value === null ? false : ( // eslint-disable-next-line unicorn/no-instanceof-builtins typeof value === "function" || value instanceof Function ); } /** * Checks that value is an object * @param value * @return {boolean} */ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type isObject(value) { return !!value && (typeof value === "object" || typeof value === "function"); } /** * Checks that value is object like * @param value * @return {boolean} */ isObjectLike(value) { return !!value && typeof value === "object"; } /** * Checks that value is plain object * @param value * @return {boolean} */ isPlainObject(value) { if (!this.isObjectLike(value) || this.getTag(value) !== "[object Object]") { return false; } const proto = Object.getPrototypeOf(value); if (proto === null) { return true; } const ctor = proto.hasOwnProperty("constructor") && proto.constructor; return typeof ctor === "function" && Function.prototype.toString.call(ctor) === OBJECT_CONSTRUCTOR_STRING; } isJsonRpcRequest(value) { return typeof value === "object" && value && "jsonrpc" in value && this.isStringFilled(value.jsonrpc) && "method" in value && this.isStringFilled(value.method); } isJsonRpcResponse(value) { return typeof value === "object" && value && "jsonrpc" in value && this.isStringFilled(value.jsonrpc) && "id" in value && ("result" in value || "error" in value); } /** * Checks that value is boolean * @param value * @return {boolean} */ isBoolean(value) { return value === true || value === false; } /** * Checks that value is number * @param value * @return {boolean} */ isNumber(value) { return typeof value === "number" && !Number.isNaN(value); } /** * Checks that value is integer * @param value * @return {boolean} */ isInteger(value) { return Number.isInteger(value); } /** * Checks that value is float * @param value * @return {boolean} */ isFloat(value) { return this.isNumber(value) && !this.isInteger(value); } /** * Checks that value is nil * @param value * @return {boolean} */ isNil(value) { return value === null || value === void 0; } /** * Checks that value is an array * @param value * @return {boolean} */ isArray(value) { return !this.isNil(value) && Array.isArray(value); } /** * Returns true if a value is an array, and it has at least one element * @param value * @returns {boolean} */ isArrayFilled(value) { return this.isArray(value) && value.length > 0; } /** * Checks that value is array like * @param value * @return {boolean} */ isArrayLike(value) { return !this.isNil(value) && !this.isFunction(value) && value.length > -1 && value.length <= Number.MAX_SAFE_INTEGER; } /** * Checks that value is Date * @param value * @return {boolean} */ isDate(value) { return value instanceof Date; } /** * Checks that is a DOM node * @param value * @return {boolean} */ isDomNode(value) { return this.isObjectLike(value) && !this.isPlainObject(value) && "nodeType" in value; } /** * Checks that value is element node * @param value * @return {boolean} */ isElementNode(value) { return this.isDomNode(value) && value.nodeType === Node.ELEMENT_NODE; } /** * Checks that value is a text node * @param value * @return {boolean} */ isTextNode(value) { return this.isDomNode(value) && value.nodeType === Node.TEXT_NODE; } /** * Checks that value is Map * @param value * @return {boolean} */ isMap(value) { return this.isObjectLike(value) && this.getTag(value) === "[object Map]"; } /** * Checks that value is Set * @param value * @return {boolean} */ isSet(value) { return this.isObjectLike(value) && this.getTag(value) === "[object Set]"; } /** * Checks that value is WeakMap * @param value * @return {boolean} */ isWeakMap(value) { return this.isObjectLike(value) && this.getTag(value) === "[object WeakMap]"; } /** * Checks that value is WeakSet * @param value * @return {boolean} */ isWeakSet(value) { return this.isObjectLike(value) && this.getTag(value) === "[object WeakSet]"; } /** * Checks that value is prototype * @param value * @return {boolean} */ isPrototype(value) { return (typeof (value && value.constructor) === "function" && value.constructor.prototype || Object.prototype) === value; } /** * Checks that value is regexp * @param value * @return {boolean} */ isRegExp(value) { return this.isObjectLike(value) && this.getTag(value) === "[object RegExp]"; } /** * Checks that value is null * @param value * @return {boolean} */ isNull(value) { return value === null; } /** * Checks that value is undefined * @param value * @return {boolean} */ isUndefined(value) { return typeof value === "undefined"; } /** * Checks that value is ArrayBuffer * @param value * @return {boolean} */ isArrayBuffer(value) { return this.isObjectLike(value) && this.getTag(value) === "[object ArrayBuffer]"; } /** * Checks that value is typed array * @param value * @return {boolean} */ isTypedArray(value) { const regExpTypedTag = /^\[object (?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)]$/; return this.isObjectLike(value) && regExpTypedTag.test(this.getTag(value)); } /** * Checks that value is Blob * @param value * @return {boolean} */ isBlob(value) { return this.isObjectLike(value) && this.isNumber(value.size) && this.isString(value.type) && this.isFunction(value.slice); } /** * Checks that value is File * @param value * @return {boolean} */ isFile(value) { return this.isBlob(value) && this.isString(value.name) && (this.isNumber(value.lastModified) || this.isObjectLike(value.lastModifiedDate)); } /** * Checks that value is FormData * @param value * @return {boolean} */ isFormData(value) { if (typeof FormData !== "undefined" && value instanceof FormData) { return true; } return this.isObjectLike(value) && this.getTag(value) === "[object FormData]"; } clone(obj, bCopyObj = true) { let _obj, i, l; if (this.isNil(obj) || typeof obj !== "object") { return obj; } if (this.isDomNode(obj)) { _obj = obj.cloneNode(bCopyObj); } else if (typeof obj == "object") { if (this.isArray(obj)) { _obj = []; for (i = 0, l = obj.length; i < l; i++) { if (typeof obj[i] == "object" && bCopyObj) { _obj[i] = this.clone(obj[i], bCopyObj); } else { _obj[i] = obj[i]; } } } else { _obj = {}; if (obj.constructor) { if (this.isDate(obj)) { _obj = new Date(obj); } else { _obj = new obj.constructor(); } } for (i in obj) { if (!obj.hasOwnProperty(i)) { continue; } if (typeof obj[i] === "object" && bCopyObj) { _obj[i] = this.clone(obj[i], bCopyObj); } else { _obj[i] = obj[i]; } } } } else { _obj = obj; } return _obj; } } const Type = new TypeManager(); function pick(data, keys) { const result = {}; for (const key of keys) { result[key] = data[key]; } return result; } function omit(data, keys) { const result = { ...data }; for (const key of keys) { delete result[key]; } return result; } function isArrayOfArray(item) { return Array.isArray(item[0]); } function getEnumValue(enumObj, value) { return Object.values(enumObj).includes(value) ? value : void 0; } const byteToHex = []; for (let i = 0; i < 256; ++i) { byteToHex.push((i + 256).toString(16).slice(1)); } function sfc32(a, b, c, d) { return () => { a |= 0; b |= 0; c |= 0; d |= 0; const t = (a + b | 0) + d | 0; d = d + 1 | 0; a = b ^ b >>> 9; b = c + (c << 3) | 0; c = (c << 21 | c >>> 11) + t | 0; return t >>> 0; }; } function uuidv7() { const bytes = new Uint8Array(16); const timestamp = BigInt(Date.now()); const perf = BigInt(Math.floor(performance.now() * 1e3) % 65535); const combinedTime = timestamp << 16n | perf; bytes[0] = Number(combinedTime >> 40n & 0xffn); bytes[1] = Number(combinedTime >> 32n & 0xffn); bytes[2] = Number(combinedTime >> 24n & 0xffn); bytes[3] = Number(combinedTime >> 16n & 0xffn); bytes[4] = Number(combinedTime >> 8n & 0xffn); bytes[5] = Number(combinedTime & 0xffn); const seed = (Math.random() * 4294967295 ^ Date.now() ^ performance.now()) >>> 0; const rand = sfc32(2654435769, 608135816, 3084996962, seed); const randView = new DataView(bytes.buffer); randView.setUint32(6, rand()); randView.setUint32(10, rand()); randView.setUint16(14, rand()); bytes[6] = 112 | bytes[6] & 15; bytes[8] = 128 | bytes[8] & 63; return (byteToHex[bytes[0]] + byteToHex[bytes[1]] + byteToHex[bytes[2]] + byteToHex[bytes[3]] + "-" + byteToHex[bytes[4]] + byteToHex[bytes[5]] + "-" + byteToHex[bytes[6]] + byteToHex[bytes[7]] + "-" + byteToHex[bytes[8]] + byteToHex[bytes[9]] + "-" + byteToHex[bytes[10]] + byteToHex[bytes[11]] + byteToHex[bytes[12]] + byteToHex[bytes[13]] + byteToHex[bytes[14]] + byteToHex[bytes[15]]).toLowerCase(); } const reEscape = /[&<>'"]/g; const reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34)/g; const escapeEntities = { "&": "&amp", "<": "&lt", ">": "&gt", "'": "&#39", '"': "&quot" }; const unescapeEntities = { "&amp": "&", "&#38": "&", "&lt": "<", "&#60": "<", "&gt": ">", "&#62": ">", "&apos": "'", "&#39": "'", "&quot": '"', "&#34": '"' }; class TextManager { getRandom(length = 8) { return [...Array(length)].map(() => Math.trunc(Math.random() * 36).toString(36)).join(""); } /** * Generates UUID */ getUniqId() { return "xxxxxxxx-xlsx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = Math.trunc(Math.random() * 16); const v = c === "x" ? r : r & 3 | 8; return v.toString(16); }); } /** * Generate uuid v7 * @return {string} */ getUuidRfc4122() { return uuidv7(); } /** * Encodes all unsafe entities * @param {string} value * @return {string} */ encode(value) { if (Type.isString(value)) { return value.replace(reEscape, (item) => escapeEntities[item]); } return value; } /** * Decodes all encoded entities * @param {string} value * @return {string} */ decode(value) { if (Type.isString(value)) { return value.replace(reUnescape, (item) => unescapeEntities[item]); } return value; } toNumber(value) { const parsedValue = Number.parseFloat(value); if (Type.isNumber(parsedValue)) { return parsedValue; } return 0; } toInteger(value) { return this.toNumber(Number.parseInt(value, 10)); } toBoolean(value, trueValues = []) { const transformedValue = Type.isString(value) ? value.toLowerCase() : value; return ["true", "y", "1", 1, true, ...trueValues].includes(transformedValue); } toCamelCase(str) { if (!Type.isStringFilled(str)) { return str; } const regex = /[-_\s]+(.)?/g; if (!regex.test(str)) { return str.match(/^[A-Z]+$/) ? str.toLowerCase() : str[0].toLowerCase() + str.slice(1); } str = str.toLowerCase(); str = str.replace( regex, (_match, letter) => letter ? letter.toUpperCase() : "" ); return str[0].toLowerCase() + str.substring(1); } toPascalCase(str) { if (!Type.isStringFilled(str)) { return str; } return this.capitalize(this.toCamelCase(str)); } toKebabCase(str) { if (!Type.isStringFilled(str)) { return str; } const matches = str.match( /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g ); if (!matches) { return str; } return matches.map((x) => x.toLowerCase()).join("-"); } capitalize(str) { if (!Type.isStringFilled(str)) { return str; } return str[0].toUpperCase() + str.substring(1); } numberFormat(number, decimals = 0, decPoint = ".", thousandsSep = ",") { const n = !Number.isFinite(number) ? 0 : number; const fractionDigits = !Number.isFinite(decimals) ? 0 : Math.abs(decimals); const toFixedFix = (n2, fractionDigits2) => { const k = Math.pow(10, fractionDigits2); return Math.round(n2 * k) / k; }; const s = (fractionDigits ? toFixedFix(n, fractionDigits) : Math.round(n)).toString().split("."); if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, thousandsSep); } if ((s[1] || "").length < fractionDigits) { s[1] = s[1] || ""; s[1] += new Array(fractionDigits - s[1].length + 1).join("0"); } return s.join(decPoint); } /** * Convert string to DateTime from ISO 8601 or self template * * @param {string} dateString * @param {string} template * @param opts * @returns {DateTime} * * @link https://moment.github.io/luxon/#/parsing?id=parsing-technical-formats */ toDateTime(dateString, template, opts) { if (!(typeof template === "undefined") && Type.isStringFilled(template)) { return DateTime.fromFormat(dateString, template, opts); } return DateTime.fromISO(dateString, opts); } getDateForLog() { const now = DateTime.now(); return now.toFormat("y-MM-dd HH:mm:ss"); } buildQueryString(params) { let result = ""; for (const key in params) { if (!params.hasOwnProperty(key)) { continue; } const value = params[key]; if (Type.isArray(value)) { value.forEach((valueElement, index) => { result += encodeURIComponent(key + "[" + index + "]") + "=" + encodeURIComponent(valueElement) + "&"; }); } else { result += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&"; } } if (result.length > 0) { result = result.substring(0, result.length - 1); } return result; } } const Text = new TextManager(); let UA = ""; try { UA = navigator?.userAgent.toLowerCase(); } catch { UA = "?"; } class BrowserManager { isOpera() { return UA.includes("opera"); } isIE() { return "attachEvent" in document && !this.isOpera(); } isIE6() { return UA.includes("msie 6"); } isIE7() { return UA.includes("msie 7"); } isIE8() { return UA.includes("msie 8"); } isIE9() { return "documentMode" in document && document.documentMode >= 9; } isIE10() { return "documentMode" in document && document.documentMode >= 10; } isSafari() { return UA.includes("safari") && !UA.includes("chrome"); } isFirefox() { return UA.includes("firefox"); } isChrome() { return UA.includes("chrome"); } detectIEVersion() { if (this.isOpera() || this.isSafari() || this.isFirefox() || this.isChrome()) { return -1; } let rv = -1; if ( // @ts-ignore //// !!window.MSStream && // @ts-ignore //// !window.ActiveXObject && "ActiveXObject" in window ) { rv = 11; } else if (this.isIE10()) { rv = 10; } else if (this.isIE9()) { rv = 9; } else if (this.isIE()) { rv = 8; } if (rv === -1 || rv === 8) { if (navigator.appName === "Microsoft Internet Explorer") { const re = new RegExp("MSIE ([0-9]+[.0-9]*)"); const res = navigator.userAgent.match(re); if (Type.isArrayLike(res) && res.length > 0) { rv = Number.parseFloat(res[1]); } } if (navigator.appName === "Netscape") { rv = 11; const re = new RegExp("Trident/.*rv:([0-9]+[.0-9]*)"); if (re.exec(navigator.userAgent) != null) { const res = navigator.userAgent.match(re); if (Type.isArrayLike(res) && res.length > 0) { rv = Number.parseFloat(res[1]); } } } } return rv; } isIE11() { return this.detectIEVersion() >= 11; } isMac() { return UA.includes("macintosh"); } isWin() { return UA.includes("windows"); } isLinux() { return UA.includes("linux") && !this.isAndroid(); } isAndroid() { return UA.includes("android"); } isIPad() { return UA.includes("ipad;") || this.isMac() && this.isTouchDevice(); } isIPhone() { return UA.includes("iphone;"); } isIOS() { return this.isIPad() || this.isIPhone(); } isMobile() { return this.isIPhone() || this.isIPad() || this.isAndroid() || UA.includes("mobile") || UA.includes("touch"); } isRetina() { return (window.devicePixelRatio && window.devicePixelRatio >= 2) === true; } isTouchDevice() { return "ontouchstart" in window || navigator.maxTouchPoints > 0 || // @ts-ignore //// navigator.msMaxTouchPoints > 0; } isDoctype(target) { const doc = target || document; if (doc.compatMode) { return doc.compatMode === "CSS1Compat"; } return doc.documentElement && doc.documentElement.clientHeight; } isLocalStorageSupported() { try { localStorage.setItem("test", "test"); localStorage.removeItem("test"); return true; } catch { return false; } } detectAndroidVersion() { const re = new RegExp("Android ([0-9]+[.0-9]*)"); if (re.exec(navigator.userAgent) != null) { const res = navigator.userAgent.match(re); if (Type.isArrayLike(res) && res.length > 0) { return Number.parseFloat(res[1]); } } return 0; } } const Browser = new BrowserManager(); const RestrictionManagerParamsBase = { sleep: 1e3, speed: 1e-3, amount: 30 }; const RestrictionManagerParamsForEnterprise = { sleep: 600, speed: 0.01, amount: 30 * 5 }; var EnumCrmEntityType = /* @__PURE__ */ ((EnumCrmEntityType2) => { EnumCrmEntityType2["undefined"] = "UNDEFINED"; EnumCrmEntityType2["lead"] = "CRM_LEAD"; EnumCrmEntityType2["deal"] = "CRM_DEAL"; EnumCrmEntityType2["contact"] = "CRM_CONTACT"; EnumCrmEntityType2["company"] = "CRM_COMPANY"; EnumCrmEntityType2["oldInvoice"] = "CRM_INVOICE"; EnumCrmEntityType2["invoice"] = "CRM_SMART_INVOICE"; EnumCrmEntityType2["quote"] = "CRM_QUOTE"; EnumCrmEntityType2["requisite"] = "CRM_REQUISITE"; EnumCrmEntityType2["order"] = "ORDER"; return EnumCrmEntityType2; })(EnumCrmEntityType || {}); var EnumCrmEntityTypeId = /* @__PURE__ */ ((EnumCrmEntityTypeId2) => { EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["undefined"] = 0] = "undefined"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["lead"] = 1] = "lead"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["deal"] = 2] = "deal"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["contact"] = 3] = "contact"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["company"] = 4] = "company"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["oldInvoice"] = 5] = "oldInvoice"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["invoice"] = 31] = "invoice"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["quote"] = 7] = "quote"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["requisite"] = 8] = "requisite"; EnumCrmEntityTypeId2[EnumCrmEntityTypeId2["order"] = 14] = "order"; return EnumCrmEntityTypeId2; })(EnumCrmEntityTypeId || {}); var EnumCrmEntityTypeShort = /* @__PURE__ */ ((EnumCrmEntityTypeShort2) => { EnumCrmEntityTypeShort2["undefined"] = "?"; EnumCrmEntityTypeShort2["lead"] = "L"; EnumCrmEntityTypeShort2["deal"] = "D"; EnumCrmEntityTypeShort2["contact"] = "C"; EnumCrmEntityTypeShort2["company"] = "CO"; EnumCrmEntityTypeShort2["oldInvoice"] = "I"; EnumCrmEntityTypeShort2["invoice"] = "SI"; EnumCrmEntityTypeShort2["quote"] = "Q"; EnumCrmEntityTypeShort2["requisite"] = "RQ"; EnumCrmEntityTypeShort2["order"] = "O"; return EnumCrmEntityTypeShort2; })(EnumCrmEntityTypeShort || {}); function getEnumCrmEntityTypeShort(id) { const key = EnumCrmEntityTypeId[id]; return EnumCrmEntityTypeShort[key] || "?" /* undefined */; } var ProductRowDiscountTypeId = /* @__PURE__ */ ((ProductRowDiscountTypeId2) => { ProductRowDiscountTypeId2[ProductRowDiscountTypeId2["undefined"] = 0] = "undefined"; ProductRowDiscountTypeId2[ProductRowDiscountTypeId2["absolute"] = 1] = "absolute"; ProductRowDiscountTypeId2[ProductRowDiscountTypeId2["percentage"] = 2] = "percentage"; return ProductRowDiscountTypeId2; })(ProductRowDiscountTypeId || {}); var CatalogProductType = /* @__PURE__ */ ((CatalogProductType2) => { CatalogProductType2[CatalogProductType2["undefined"] = 0] = "undefined"; CatalogProductType2[CatalogProductType2["product"] = 1] = "product"; CatalogProductType2[CatalogProductType2["service"] = 7] = "service"; CatalogProductType2[CatalogProductType2["sku"] = 3] = "sku"; CatalogProductType2[CatalogProductType2["skuEmpty"] = 6] = "skuEmpty"; CatalogProductType2[CatalogProductType2["offer"] = 4] = "offer"; CatalogProductType2[CatalogProductType2["offerEmpty"] = 5] = "offerEmpty"; return CatalogProductType2; })(CatalogProductType || {}); var CatalogProductImageType = /* @__PURE__ */ ((CatalogProductImageType2) => { CatalogProductImageType2["undefined"] = "UNDEFINED"; CatalogProductImageType2["detail"] = "DETAIL_PICTURE"; CatalogProductImageType2["preview"] = "PREVIEW_PICTURE"; CatalogProductImageType2["morePhoto"] = "MORE_PHOTO"; return CatalogProductImageType2; })(CatalogProductImageType || {}); var CatalogRoundingRuleType = /* @__PURE__ */ ((CatalogRoundingRuleType2) => { CatalogRoundingRuleType2[CatalogRoundingRuleType2["undefined"] = 0] = "undefined"; CatalogRoundingRuleType2[CatalogRoundingRuleType2["mathematical"] = 1] = "mathematical"; CatalogRoundingRuleType2[CatalogRoundingRuleType2["roundingUp"] = 2] = "roundingUp"; CatalogRoundingRuleType2[CatalogRoundingRuleType2["roundingDown"] = 4] = "roundingDown"; return CatalogRoundingRuleType2; })(CatalogRoundingRuleType || {}); var EnumBitrix24Edition = /* @__PURE__ */ ((EnumBitrix24Edition2) => { EnumBitrix24Edition2["undefined"] = "undefined"; EnumBitrix24Edition2["b24"] = "b24"; EnumBitrix24Edition2["box"] = "box"; return EnumBitrix24Edition2; })(EnumBitrix24Edition || {}); var EnumBizprocBaseType = /* @__PURE__ */ ((EnumBizprocBaseType2) => { EnumBizprocBaseType2["undefined"] = "undefined"; EnumBizprocBaseType2["crm"] = "crm"; EnumBizprocBaseType2["disk"] = "disk"; EnumBizprocBaseType2["lists"] = "lists"; return EnumBizprocBaseType2; })(EnumBizprocBaseType || {}); var EnumBizprocDocumentType = /* @__PURE__ */ ((EnumBizprocDocumentType2) => { EnumBizprocDocumentType2["undefined"] = "undefined"; EnumBizprocDocumentType2["lead"] = "CCrmDocumentLead"; EnumBizprocDocumentType2["company"] = "CCrmDocumentCompany"; EnumBizprocDocumentType2["contact"] = "CCrmDocumentContact"; EnumBizprocDocumentType2["deal"] = "CCrmDocumentDeal"; EnumBizprocDocumentType2["invoice"] = "Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice"; EnumBizprocDocumentType2["quote"] = "Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote"; EnumBizprocDocumentType2["order"] = "Bitrix\\Crm\\Integration\\BizProc\\Document\\Order"; EnumBizprocDocumentType2["dynamic"] = "Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic"; EnumBizprocDocumentType2["disk"] = "Bitrix\\Disk\\BizProcDocument"; EnumBizprocDocumentType2["lists"] = "BizprocDocument"; EnumBizprocDocumentType2["listsList"] = "Bitrix\\Lists\\BizprocDocumentLists"; return EnumBizprocDocumentType2; })(EnumBizprocDocumentType || {}); function convertBizprocDocumentTypeToCrmEntityTypeId(documentType) { switch (documentType) { case "CCrmDocumentLead" /* lead */: return EnumCrmEntityTypeId.lead; case "CCrmDocumentCompany" /* company */: return EnumCrmEntityTypeId.company; case "CCrmDocumentContact" /* contact */: return EnumCrmEntityTypeId.contact; case "CCrmDocumentDeal" /* deal */: return EnumCrmEntityTypeId.deal; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice" /* invoice */: return EnumCrmEntityTypeId.invoice; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote" /* quote */: return EnumCrmEntityTypeId.quote; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Order" /* order */: return EnumCrmEntityTypeId.order; } return EnumCrmEntityTypeId.undefined; } function getDocumentType(documentType, entityId) { let entityIdFormatted = ""; let base = "undefined" /* undefined */; switch (documentType) { case "CCrmDocumentLead" /* lead */: base = "crm" /* crm */; entityIdFormatted = "LEAD"; break; case "CCrmDocumentCompany" /* company */: base = "crm" /* crm */; entityIdFormatted = "COMPANY"; break; case "CCrmDocumentContact" /* contact */: base = "crm" /* crm */; entityIdFormatted = "CONTACT"; break; case "CCrmDocumentDeal" /* deal */: base = "crm" /* crm */; entityIdFormatted = "DEAL"; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice" /* invoice */: base = "crm" /* crm */; entityIdFormatted = "SMART_INVOICE"; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote" /* quote */: base = "crm" /* crm */; entityIdFormatted = "QUOTE"; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Order" /* order */: base = "crm" /* crm */; entityIdFormatted = "ORDER"; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic" /* dynamic */: base = "crm" /* crm */; entityIdFormatted = `DYNAMIC_${entityId || 0}`; if ((entityId || 0) < 1) { throw new Error("Need set entityId"); } break; case "Bitrix\\Disk\\BizProcDocument" /* disk */: base = "disk" /* disk */; entityIdFormatted = `STORAGE_${entityId || 0}`; if ((entityId || 0) < 1) { throw new Error("Need set entityId"); } break; case "BizprocDocument" /* lists */: base = "lists" /* lists */; entityIdFormatted = `iblock_${entityId || 0}`; if ((entityId || 0) < 1) { throw new Error("Need set entityId"); } break; case "Bitrix\\Lists\\BizprocDocumentLists" /* listsList */: base = "lists" /* lists */; entityIdFormatted = `iblock_${entityId || 0}`; if ((entityId || 0) < 1) { throw new Error("Need set entityId"); } break; } return [ base, documentType, entityIdFormatted ]; } function getDocumentId(documentType, id, dynamicId) { let entityIdFormatted = ""; const tmp = getDocumentType(documentType, 1); switch (documentType) { case "CCrmDocumentLead" /* lead */: entityIdFormatted = `LEAD_${id}`; break; case "CCrmDocumentCompany" /* company */: entityIdFormatted = `COMPANY_${id}`; break; case "CCrmDocumentContact" /* contact */: entityIdFormatted = `CONTACT_${id}`; break; case "CCrmDocumentDeal" /* deal */: entityIdFormatted = `DEAL_${id}`; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\SmartInvoice" /* invoice */: entityIdFormatted = `SMART_INVOICE_${id}`; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Quote" /* quote */: entityIdFormatted = `QUOTE_${id}`; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Order" /* order */: entityIdFormatted = `ORDER_${id}`; break; case "Bitrix\\Crm\\Integration\\BizProc\\Document\\Dynamic" /* dynamic */: entityIdFormatted = `DYNAMIC_${dynamicId || 0}_${id}`; if ((dynamicId || 0) < 1) { throw new Error("Need set dynamicId"); } break; case "Bitrix\\Disk\\BizProcDocument" /* disk */: entityIdFormatted = `${id}`; break; case "BizprocDocument" /* lists */: entityIdFormatted = `${id}`; break; case "Bitrix\\Lists\\BizprocDocumentLists" /* listsList */: entityIdFormatted = `${id}`; break; } return [ tmp[0], tmp[1], entityIdFormatted ]; } function getDocumentTypeForFilter(documentType) { const result = getDocumentType(documentType, 1); return [ result[0], result[1] ]; } var LoadDataType = /* @__PURE__ */ ((LoadDataType2) => { LoadDataType2["App"] = "app"; LoadDataType2["Profile"] = "profile"; LoadDataType2["Currency"] = "currency"; LoadDataType2["AppOptions"] = "appOptions"; LoadDataType2["UserOptions"] = "userOptions"; return LoadDataType2; })(LoadDataType || {}); const EnumAppStatus = { // free //// Free: "F", // demo version //// Demo: "D", // trial version (limited time) //// Trial: "T", // paid application //// Paid: "P", // local application //// Local: "L", // subscription application //// Subscription: "S" }; const StatusDescriptions = { [EnumAppStatus.Free]: "Free", [EnumAppStatus.Demo]: "Demo", [EnumAppStatus.Trial]: "Trial", [EnumAppStatus.Paid]: "Paid", [EnumAppStatus.Local]: "Local", [EnumAppStatus.Subscription]: "Subscription" }; const TypeSpecificUrl = { MainSettings: "MainSettings", UfList: "UfList", UfPage: "UfPage" }; var TypeOption = /* @__PURE__ */ ((TypeOption2) => { TypeOption2["NotSet"] = "notSet"; TypeOption2["JsonArray"] = "jsonArray"; TypeOption2["JsonObject"] = "jsonObject"; TypeOption2["FloatVal"] = "float"; TypeOption2["IntegerVal"] = "integer"; TypeOption2["BoolYN"] = "boolYN"; TypeOption2["StringVal"] = "string"; return TypeOption2; })(TypeOption || {}); var ConnectionType = /* @__PURE__ */ ((ConnectionType2) => { ConnectionType2["Undefined"] = "undefined"; ConnectionType2["WebSocket"] = "webSocket"; ConnectionType2["LongPolling"] = "longPolling"; return ConnectionType2; })(ConnectionType || {}); var LsKeys = /* @__PURE__ */ ((LsKeys2) => { LsKeys2["PullConfig"] = "bx-pull-config"; LsKeys2["WebsocketBlocked"] = "bx-pull-websocket-blocked"; LsKeys2["LongPollingBlocked"] = "bx-pull-longpolling-blocked"; LsKeys2["LoggingEnabled"] = "bx-pull-logging-enabled"; return LsKeys2; })(LsKeys || {}); var PullStatus = /* @__PURE__ */ ((PullStatus2) => { PullStatus2["Online"] = "online"; PullStatus2["Offline"] = "offline"; PullStatus2["Connecting"] = "connect"; return PullStatus2; })(PullStatus || {}); var SenderType = /* @__PURE__ */ ((SenderType2) => { SenderType2[SenderType2["Unknown"] = 0] = "Unknown"; SenderType2[SenderType2["Client"] = 1] = "Client"; SenderType2[SenderType2["Backend"] = 2] = "Backend"; return SenderType2; })(SenderType || {}); var SubscriptionType = /* @__PURE__ */ ((SubscriptionType2) => { SubscriptionType2["Server"] = "server"; SubscriptionType2["Client"] = "client"; SubscriptionType2["Online"] = "online"; SubscriptionType2["Status"] = "status"; SubscriptionType2["Revision"] = "revision"; return SubscriptionType2; })(SubscriptionType || {}); var CloseReasons = /* @__PURE__ */ ((CloseReasons2) => { CloseReasons2[CloseReasons2["NORMAL_CLOSURE"] = 1e3] = "NORMAL_CLOSURE"; CloseReasons2[CloseReasons2["SERVER_DIE"] = 1001] = "SERVER_DIE"; CloseReasons2[CloseReasons2["CONFIG_REPLACED"] = 3e3] = "CONFIG_REPLACED"; CloseReasons2[CloseReasons2["CHANNEL_EXPIRED"] = 3001] = "CHANNEL_EXPIRED"; CloseReasons2[CloseReasons2["SERVER_RESTARTED"] = 3002] = "SERVER_RESTARTED"; CloseReasons2[CloseReasons2["CONFIG_EXPIRED"] = 3003] = "CONFIG_EXPIRED"; CloseReasons2[CloseReasons2["MANUAL"] = 3004] = "MANUAL"; CloseReasons2[CloseReasons2["STUCK"] = 3005] = "STUCK"; CloseReasons2[CloseReasons2["WRONG_CHANNEL_ID"] = 4010] = "WRONG_CHANNEL_ID"; return CloseReasons2; })(CloseReasons || {}); var SystemCommands = /* @__PURE__ */ ((SystemCommands2) => { SystemCommands2["CHANNEL_EXPIRE"] = "CHANNEL_EXPIRE"; SystemCommands2["CONFIG_EXPIRE"] = "CONFIG_EXPIRE"; SystemCommands2["SERVER_RESTART"] = "SERVER_RESTART"; return SystemCommands2; })(SystemCommands || {}); var ServerMode = /* @__PURE__ */ ((ServerMode2) => { ServerMode2["Shared"] = "shared"; ServerMode2["Personal"] = "personal"; return ServerMode2; })(ServerMode || {}); const ListRpcError = { 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 RpcMethod = /* @__PURE__ */ ((RpcMethod2) => { RpcMethod2["Publish"] = "publish"; RpcMethod2["GetUsersLastSeen"] = "getUsersLastSeen"; RpcMethod2["Ping"] = "ping"; RpcMethod2["ListChannels"] = "listChannels"; RpcMethod2["SubscribeStatusChange"] = "subscribeStatusChange"; RpcMethod2["UnsubscribeStatusChange"] = "unsubscribeStatusChange"; return RpcMethod2; })(RpcMethod || {}); class Result { _errors; _data; constructor(data) { this._errors = /* @__PURE__ */ new Map(); this._data = data ?? null; } get isSuccess() { return this._errors.size === 0; } get errors() { return this._errors; } setData(data) { this._data = data; return this; } getData() { return this._data; } addError(error, key) { const errorKey = key ?? Text.getUuidRfc4122(); const errorObj = typeof error === "string" ? new Error(error) : error; this._errors.set(errorKey, errorObj); return this; } addErrors(errors) { for (const error of errors) { this.addError(error); } return this; } getErrors() { return this._errors.values(); } hasError(key) { return this._errors.has(key); } /** * Retrieves an array of error messages from the collected errors. * * @returns An array of strings representing the error messages. Each string * contains the message of a corresponding error object. */ getErrorMessages() { return Array.from(this._errors.values(), (e) => e.message); } /** * Converts the Result object to a string. * * @returns {string} Returns a string representation of the result operation */ toString() { const status = this.isSuccess ? "success" : "failure"; const data = this.safeStringify(this._data); return this.isSuccess ? `Result(${status}): ${data}` : `Result(${status}): ${data} Errors: ${this.getErrorMessages().join(", ")}`; } safeStringify(data) { try { return JSON.stringify(data, this.replacer, 2); } catch { return "[Unable to serialize data]"; } } replacer(_, value) { if (value instanceof Error) { return { name: value.name, message: value.message, stack: value.stack }; } return value; } // Static constructors static ok(data) { return new Result(data); } static fail(error, key) { return new Result().addError(error, key); } } class AjaxError extends Error { code; _status; requestInfo; timestamp; originalError; // override cause: null | Error // private _status: number // private _answerError: AnswerError constructor(details) { const message = AjaxError.formatErrorMessage(details); super(message); this.name = "AjaxError"; this.code = details.code; this._status = details.status; this.requestInfo = details.requestInfo; this.originalError = details.originalError; this.timestamp = /* @__PURE__ */ new Date(); this.cleanErrorStack(); } // constructor(params: AjaxErrorParams) { // const message = `${ params.answerError.error }${ // params.answerError.errorDescription // ? ': ' + params.answerError.errorDescription // : '' // }` // // super(message) // this.cause = params.cause || null // this.name = this.constructor.name // // this._status = params.status // this._answerError = params.answerError // } /** * @deprecated */ get answerError() { return { error: this.message, errorDescription: "" }; } get status() { return this._status; } /** * @deprecated */ set status(status) { this._status = status; } /** * Creates AjaxError from HTTP response */ static fromResponse(response) { return new AjaxError({ code: response.data?.error || "unknown_error", description: response.data?.error_description, status: response.status, requestInfo: { method: response.config?.method?.toUpperCase(), url: response.config?.url, params: response.config?.params } }); } /** * Creates AjaxError from exception */ static fromException(error, context) { if (error instanceof AjaxError) return error; return new AjaxError({ code: context?.code || "internal_error", status: context?.status || 500, description: error instanceof Error ? error.message : String(error), requestInfo: context?.requestInfo, originalError: error }); } /** * Serializes error for logging and debugging */ toJSON() { return { name: this.name, code: this.code, message: this.message, status: this._status, timestamp: this.timestamp.toISOString(), requestInfo: this.requestInfo, stack: this.stack }; } // override toString(): string { // return `${ this.answerError.error }${ // this.answerError.errorDescription // ? ': ' + this.answerError.errorDescription // : '' // } (${ this.status })` // } /** * Formats error information for human-readable output */ toString() { let output = `[${this.name}] ${this.code} (${this._status}): ${this.message}`; if (this.requestInfo) { output += ` Request: ${this.requestInfo.method} ${this.requestInfo.url}`; } if (this.stack) { output += ` Stack trace: ${this.stack}`; } return output; } static formatErrorMessage(details) { const parts = [details.code]; if (details.description) { parts.push(`- ${details.description}`); } if (details.requestInfo?.method && details.requestInfo.url) { parts.push(`(on ${details.requestInfo.method} ${details.requestInfo.url})`); } return parts.join(" "); } cleanErrorStack() { if (typeof this.stack === "string") { this.stack = this.stack.split("\n").filter((line) => !line.includes("AjaxError.constructor")).join("\n"); } } } class AjaxResult extends Result { _status; _query; _data; constructor(options) { super(); this._data = Object.freeze(options.answer); this._query = Object.freeze(structuredClone(options.query)); this._status = options.status; this.#processErrors(); } #processErrors() { const { error } = this._data; if (!error) return; const errorParams = this.#normalizeError(error); this.addError(this.#createAjaxError(errorParams), "base-error"); } #normalizeError(error) { return typeof error === "string" ? { code: error, description: this._data.error_description || "" } : { code: error.error, description: error.error_description || "" }; } #createAjaxError(params) { return new AjaxError({ code: String(this._status), description: params.description, status: this._status, requestInfo: { method: this._query.method, // url: '?', params: this._query.params } // request: }); } getData() { return Object.freeze({ result: this._data.result, next: this._data.next, total: this._data.total, time: this._data.time }); } /** * Alias for isMore */ hasMore() { return this.isMore(); } isMore() { return Type.isNumber(this._data?.next); } getTotal() { return Text.toInteger(this._data?.total); } getStatus() { return this._status; } getQuery() { return this._query; } /** * Alias for getNext * @param http */ async fetchNext(http) { const data = await this.getNext(http); if (data === false) { return null; } return data; } async getNext(http) { if (!this.isMore() || !this.isSuccess) return false; const nextPageQuery = this.#buildNextPageQuery(); return http.call( nextPageQuery.method, nextPageQuery.params, nextPageQuery.start ); } #buildNextPageQuery() { return { ...this._query, start: Text.toInteger(this._data.next) }; } // Immutable API setData() { throw new ReferenceError("AjaxResult does not allow data modification"); } } class RestrictionManager { #params; #lastDecrement; #currentAmount; _logger = null; constructor() { this.#params = RestrictionManagerParamsBase; this.#currentAmount = 0; this.#lastDecrement = 0; } setLogger(logger) { this._logger = logger; } getLogger() { if (null === this._logger) { this._logger = LoggerBrowser.build(`NullLogger`); this._logger.setConfig({ [LoggerType.desktop]: false, [LoggerType.log]: false, [LoggerType.info]: false, [LoggerType.warn]: false, [LoggerType.error]: true, [LoggerType.trace]: false }); } return this._logger; } get params() { return { ...this.#params }; } set params(params) { this.#params = params; this.getLogger().log(`new restriction manager params`, params); } check(hash = "") { return new Promise((resolve) => { this.#decrementStorage(); if (this.#checkStorage()) { this.getLogger().log( `>> no sleep >>> ${hash}`, this.#getStorageStatus() ); this.#incrementStorage(); return resolve(null); } else { const sleep = (callback) => { this.getLogger().info( `>> go sleep >>> ${hash}`, this.#getStorageStatus() ); setTimeout(() => { callback(); }, this.#params.sleep); }; const wait = () => { this.#decrementStorage(); if (this.#checkStorage()) { this.getLogger().info( `<< stop sleep <<< ${hash}`, this.#getStorageStatus() ); this.#incrementStorage(); return resolve(null); } else { sleep(wait); } }; sleep(wait); } }); } #getStorageStatus() { return `${this.#currentAmount.toFixed(4)} from ${this.#params.amount}`; } #decrementStorage() { if (this.#lastDecrement > 0) { this.#currentAmount -= (Date.now() - this.#lastDecrement) * this.#params.speed; if (this.#currentAmount < 0) { this.#currentAmount = 0; } } this.#lastDecrement = Date.now(); } #incrementStorage() { this.#currentAmount++; } #checkStorage() { return this.#currentAmount < this.#params.amount; } } const DEFAULT_REQUEST_ID_HEADER_FIELD_NAME = "X-Request-ID"; const DEFAULT_QUERY_STRING_PARAMETER_NAME = "bx24_request_id"; const DEFAULT_QUERY_STRING_SDK_VER_PARAMETER_NAME = "bx24_sdk_ver"; const DEFAULT_QUERY_STRING_SDK_TYPE_PARAMETER_NAME = "bx24_sdk_type"; class DefaultRequestIdGenerator { getQueryStringParameterName() { return DEFAULT_QUERY_STRING_PARAMETER_NAME; } getQueryStringSdkParameterName() { return DEFAULT_QUERY_STRING_SDK_VER_PARAMETER_NAME; } getQueryStringSdkTypeParameterName() { return DEFAULT_QUERY_STRING_SDK_TYPE_PARAMETER_NAME; } generate() { return Text.getUuidRfc4122(); } getRequestId() { return this.generate(); } getHeaderFieldName() { return DEFAULT_REQUEST_ID_HEADER_FIELD_NAME; } } class Http { #clientAxios; #authActions; #restrictionManager; #requestIdGenerator; _logger = null; _loggerSystem = null; #logTag = ""; #isClientSideWarning = false; #clientSideWarningMessa