UNPKG

@salutejs/client

Version:

Модуль взаимодействия с виртуальным ассистентом

1,307 lines (1,208 loc) 442 kB
'use strict'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ exports.__assign = function() { exports.__assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return exports.__assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } // Unique ID creation requires a high quality random # generator. In the browser we therefore // require the crypto API and do not support built-in fallback to lower quality random number // generators (like Math.random()). var getRandomValues; var rnds8 = new Uint8Array(16); function rng() { // lazy load so that environments that need to polyfill have a chance to do so if (!getRandomValues) { // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, // find the complete implementation of crypto (msCrypto) on IE11. getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); if (!getRandomValues) { throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); } } return getRandomValues(rnds8); } var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; function validate(uuid) { return typeof uuid === 'string' && REGEX.test(uuid); } /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex.push((i + 0x100).toString(16).substr(1)); } function stringify(arr) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; // Note: Be careful editing this code! It's been tuned for performance // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one // of the following: // - One or more input array values don't map to a hex octet (leading to // "undefined" in the uuid) // - Invalid input values for the RFC `version` or `variant` fields if (!validate(uuid)) { throw TypeError('Stringified UUID is invalid'); } return uuid; } function v4(options, buf, offset) { options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided if (buf) { offset = offset || 0; for (var i = 0; i < 16; ++i) { buf[offset + i] = rnds[i]; } return buf; } return stringify(rnds); } var createNanoEvents = function () { var events = {}; var emit = function (event) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } for (var _a = 0, _b = events[event] || []; _a < _b.length; _a++) { var listener = _b[_a]; listener.apply(void 0, args); } }; var on = function (event, cb) { (events[event] = events[event] || []).push(cb); return function () { events[event] = events[event].filter(function (i) { return i !== cb; }); }; }; var once = function (event, cb) { // eslint-disable-next-line // @ts-ignore И вот тут я сдался var off = on(event, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } cb.apply(void 0, args); off(); }); return off; }; var clear = function () { events = {}; }; return { events: events, emit: emit, on: on, once: once, clear: clear, }; }; var createNanoObservable = function (observerFunc) { var _a = createNanoEvents(), on = _a.on, emit = _a.emit; var subscribe = function (_a) { var next = _a.next; var unsubscribe = on('next', next); return { unsubscribe: unsubscribe }; }; observerFunc({ next: function (data) { emit('next', data); }, }); return { subscribe: subscribe, }; }; var isDeepEqual = function (a, b) { // Простое значение if (typeof a !== 'object' || a === null) { return a === b; } // Массив if (Array.isArray(a)) { if (!Array.isArray(b) || a.length !== b.length) { return false; } return !a.some(function (valA, key) { return !isDeepEqual(valA, b[key]); }); } // Словарь if (typeof b !== 'object' || b === null) { return false; } var entriesA = Object.entries(a); var entriesB = Object.entries(b); if (entriesA.length !== entriesB.length) { return false; } return !entriesA.some(function (_a) { var key = _a[0], valA = _a[1]; return !(key in b && isDeepEqual(valA, b[key])); }); }; var findCommandIndex = function (arr, command) { var insets = ['insets', 'minimum_static_insets', 'maximum_static_insets', 'dynamic_insets']; var index = -1; if (command.type === 'character') { index = arr.findIndex(function (c) { return c.type === 'character' && c.character.id === command.character.id; }); } else if (insets.includes(command.type)) { index = arr.findIndex(function (c) { return c.type === command.type; }); } else if (command.type === 'app_context') { index = arr.findIndex(function (c) { return c.type === 'app_context'; }); } else { index = arr.findIndex(function (c) { return isDeepEqual(c, command); }); } return index; }; var appInitialData = (function () { var isPulled = false; var pulled = []; var committed = []; var diff = []; var isCommandWasPulled = function (command) { return findCommandIndex(pulled, command) >= 0; }; return { /** * Прочитать appInitialData. Запоминает состояние на момент прочтения * @returns Массив комманд */ pull: function () { isPulled = true; pulled = __spreadArray([], (window.appInitialData || [])); return __spreadArray([], pulled); }, /** * Прочитать appInitialData * @returns Массив комманд */ get: function () { return __spreadArray([], (window.appInitialData || [])); }, /** * Зафиксировать текущее состояние appInitialData */ commit: function () { committed = __spreadArray([], (window.appInitialData || [])); diff = isPulled === true ? (window.appInitialData || []).filter(function (c) { return !isCommandWasPulled(c); }) : __spreadArray([], (window.appInitialData || [])); }, /** * Возвращает диф appInitialData между pull и commit * @returns Массив комманд */ diff: function () { return __spreadArray([], diff); }, /** * Возвращает флаг наличия command в appInitialData на момент commit * @param command Команда, которую нужно проверить на наличие в appInitialData * @returns true - если команда была в appInitialData */ isCommitted: function (command) { var commandIndex = findCommandIndex(committed, command); var isCommitted = commandIndex >= 0; if (isCommitted) { committed.splice(commandIndex, 1); } return isCommitted; }, /** * Возвращает первое сообщение из appInitialData, подходящее под фильтры param * @param param Параметры: тип сообщения (например, smart_app_data) * и тип команды (значение поля smart_app_data.type) * @returns Первое сообщение, соответствующее параметрам или undefined */ find: function (_a) { var type = _a.type, command = _a.command; var initialCommands = __spreadArray([], (window.appInitialData || [])); var result = initialCommands.find(function (initialCommand) { if (!command && type && type === initialCommand.type) { return true; } var isCommandInSmartAppData = command && 'smart_app_data' in initialCommand; if (!isCommandInSmartAppData) { return; } if (command === initialCommand.smart_app_data.command || command === initialCommand.smart_app_data.type) { return true; } return false; }); return (result && 'smart_app_data' in result ? result.smart_app_data : result); }, }; })(); var excludeTags = ['A', 'AUDIO', 'BUTTON', 'INPUT', 'OPTION', 'SELECT', 'TEXTAREA', 'VIDEO']; function inIframe() { try { return window.self !== window.parent; } catch (e) { return true; } } if (/[a-zA-Z]/.test('1.37.1')) { console.info('%cPlease use the latest version of SaluteJS Client. Your version is 1.37.1', 'color: yellow; font-size: 14px'); } if (typeof window !== 'undefined' && inIframe()) { var postMessage_1 = function (action) { var _a; (_a = window.parent) === null || _a === void 0 ? void 0 : _a.postMessage(JSON.stringify(action), '*'); }; var historyBack_1 = function () { var prevPage = window.location.href; window.history.back(); setTimeout(function () { // закрываем страницу, если переход назад не поменял урл if (window.location.href === prevPage) { postMessage_1({ type: 'close' }); } }, 500); }; window.appInitialData = []; window.AssistantHost = { sendDataContainer: function (json) { postMessage_1({ type: 'sendDataContainer', payload: json }); }, close: function () { postMessage_1({ type: 'close' }); }, sendData: function (json) { postMessage_1({ type: 'sendData', payload: json }); }, setSuggests: function (suggests) { postMessage_1({ type: 'setSuggests', payload: suggests }); }, setHints: function (hints) { postMessage_1({ type: 'setHints', payload: hints }); }, ready: function () { postMessage_1({ type: 'ready' }); }, sendText: function (message) { postMessage_1({ type: 'sendText', payload: message }); }, setHeaderButtons: function (headerButtons) { postMessage_1({ type: 'setHeaderButtons', payload: typeof headerButtons === 'string' ? headerButtons : JSON.stringify(headerButtons), }); }, }; window.addEventListener('message', function (e) { var _a, _b, _c, _d, _e, _f, _g, _h; try { if (typeof e.data === 'string') { var data = JSON.parse(e.data); switch (data.type) { case 'onBack': historyBack_1(); break; case 'onData': (_b = (_a = window.AssistantClient) === null || _a === void 0 ? void 0 : _a.onData) === null || _b === void 0 ? void 0 : _b.call(_a, data.payload); break; case 'onRequestState': { var state = (_d = (_c = window.AssistantClient) === null || _c === void 0 ? void 0 : _c.onRequestState) === null || _d === void 0 ? void 0 : _d.call(_c); postMessage_1({ type: 'state', payload: state, requestId: data.requestId }); break; } case 'onRequestRecoveryState': { var recoverystate = (_f = (_e = window.AssistantClient) === null || _e === void 0 ? void 0 : _e.onRequestRecoveryState) === null || _f === void 0 ? void 0 : _f.call(_e); postMessage_1({ type: 'recoveryState', payload: recoverystate }); break; } case 'onStart': (_h = (_g = window.AssistantClient) === null || _g === void 0 ? void 0 : _g.onStart) === null || _h === void 0 ? void 0 : _h.call(_g); break; default: // eslint-disable-next-line no-console console.error(e, 'Unknown parsed message'); break; } } } catch (err) { // eslint-disable-next-line no-console console.error(err, 'Unknown message'); } }); window.addEventListener('keydown', function (_a) { var _b, _c; var code = _a.code; switch (code) { case 'Enter': if (document.activeElement && !excludeTags.includes(document.activeElement.tagName)) { (_c = (_b = document.activeElement).click) === null || _c === void 0 ? void 0 : _c.call(_b); } break; case 'Escape': historyBack_1(); break; } }); } var createAssistant$1 = function (_a) { var _b, _c; var getState = _a.getState, getRecoveryState = _a.getRecoveryState, _d = _a.ready, ready = _d === void 0 ? true : _d; var _e = createNanoEvents(), on = _e.on, emitOriginal = _e.emit; var _f = createNanoEvents(), subscribeToCommand = _f.on, emitAllCommands = _f.emit; var observables = new Map(); var currentGetState = getState; var currentGetRecoveryState = getRecoveryState; var isInitialCommandsEmitted = false; var readyRetries = 0; var emitCommand = function (command) { if (command.type === 'smart_app_data') { emitOriginal('command', command.smart_app_data); } if (command.type === 'smart_app_error') { emitOriginal('error', command.smart_app_error); } return emitOriginal('data', command); }; var cancelTts = typeof ((_b = window.AssistantHost) === null || _b === void 0 ? void 0 : _b.cancelTts) !== 'undefined' ? function () { var _a, _b; (_b = (_a = window.AssistantHost).cancelTts) === null || _b === void 0 ? void 0 : _b.call(_a, ''); } : undefined; var emitAppInitialData = function () { if (!isInitialCommandsEmitted) { appInitialData.diff().forEach(function (c) { return emitCommand(c); }); isInitialCommandsEmitted = true; } }; var saveFirstSmartAppDataMid = function (mid) { // eslint-disable-next-line no-underscore-dangle if (typeof window.__ASSISTANT_CLIENT__.firstSmartAppDataMid === 'undefined') { // eslint-disable-next-line no-underscore-dangle window.__ASSISTANT_CLIENT__.firstSmartAppDataMid = mid; } }; window.AssistantClient = { onData: function (command) { var _a, _b, _c, _d, _e; if (appInitialData.isCommitted(command)) { return; } emitAllCommands(command.type, command); if (command.type === 'smart_app_data' && (((_a = command.sdk_meta) === null || _a === void 0 ? void 0 : _a.mid) || '-1') !== '-1') { saveFirstSmartAppDataMid((_b = command.sdk_meta) === null || _b === void 0 ? void 0 : _b.mid); } /// фильтр команды 'назад' /// может приходить type='system', но в типах это не отражаем // @ts-ignore if (command.type === 'system' && ((_d = (_c = command.system) === null || _c === void 0 ? void 0 : _c.command) === null || _d === void 0 ? void 0 : _d.toUpperCase()) === 'BACK') { return; } if (command.type === 'tts_state_update') { emitOriginal('tts', { state: command.state, owner: command.owner, }); } if ((command.type === 'smart_app_data' || command.type === 'smart_app_error') && ((_e = command.sdk_meta) === null || _e === void 0 ? void 0 : _e.requestId) && observables.has(command.sdk_meta.requestId)) { // eslint-disable-next-line @typescript-eslint/no-unused-vars var _f = command.sdk_meta; _f.requestId; var meta = __rest(_f, ["requestId"]); var _g = observables.get(command.sdk_meta.requestId) || {}, requestId = _g.requestId, next = _g.next; if (Object.keys(meta).length > 0 || requestId) { // eslint-disable-next-line camelcase command.sdk_meta = exports.__assign({}, meta); if (requestId) { // eslint-disable-next-line camelcase command.sdk_meta = { requestId: requestId }; } } next === null || next === void 0 ? void 0 : next(command.type === 'smart_app_data' ? command : command); } emitCommand(command); }, onRequestState: function () { return currentGetState(); }, onRequestRecoveryState: function () { if (currentGetRecoveryState) { return currentGetRecoveryState(); } return undefined; }, onStart: function () { emitOriginal('start'); emitAppInitialData(); }, }; var readyFn = function () { return __awaiter(void 0, void 0, void 0, function () { var firstSmartAppDataMid; var _a, _b, _c; return __generator(this, function (_d) { readyRetries += 1; if (typeof ((_a = window.AssistantHost) === null || _a === void 0 ? void 0 : _a.ready) !== 'function') { return [2 /*return*/, new Promise(function (resolve, reject) { var _a; if (readyRetries > 3) { throw new Error("window.AssistantHost is not ready. The ready method has the type \"" + typeof ((_a = window.AssistantHost) === null || _a === void 0 ? void 0 : _a.ready) + "\""); } window.setTimeout(function () { readyFn().then(resolve, reject); }, 500); })]; } firstSmartAppDataMid = ((_c = (_b = appInitialData.get().find(function (c) { var _a; return c.type === 'smart_app_data' && (((_a = c.sdk_meta) === null || _a === void 0 ? void 0 : _a.mid) || '-1') !== '-1'; // @ts-ignore })) === null || _b === void 0 ? void 0 : _b.sdk_meta) === null || _c === void 0 ? void 0 : _c.mid) || '-1'; if (firstSmartAppDataMid !== '-1') { saveFirstSmartAppDataMid(firstSmartAppDataMid); } appInitialData.commit(); window.AssistantHost.ready(); return [2 /*return*/]; }); }); }; if (ready) { window.setTimeout(readyFn); // таймаут для подписки на start } var sendData = function (_a, onData) { var _b, _c, _d; var action = _a.action, name = _a.name, requestId = _a.requestId, mode = _a.mode; if ((_b = window.AssistantHost) === null || _b === void 0 ? void 0 : _b.sendDataContainer) { if (onData == null) { (_c = window.AssistantHost) === null || _c === void 0 ? void 0 : _c.sendDataContainer( /* eslint-disable-next-line camelcase */ JSON.stringify({ data: action, message_name: name || '', requestId: requestId, mode: mode })); return function () { }; } if (requestId && observables.has(requestId)) { throw new Error('requestId должен быть уникальным'); } var realRequestId_1 = requestId || v4(); var subscribe = createNanoObservable(function (_a) { var _b; var next = _a.next; (_b = window.AssistantHost) === null || _b === void 0 ? void 0 : _b.sendDataContainer( /* eslint-disable-next-line camelcase */ JSON.stringify({ data: action, message_name: name || '', requestId: realRequestId_1, mode: mode })); observables.set(realRequestId_1, { next: next, requestId: requestId }); }).subscribe; var unsubscribe_1 = subscribe({ next: onData }).unsubscribe; return function () { unsubscribe_1(); observables.delete(realRequestId_1); }; } if (onData != null) { throw new Error('Не поддерживается в данной версии клиента'); } (_d = window.AssistantHost) === null || _d === void 0 ? void 0 : _d.sendData(JSON.stringify(action), name || null); return function () { }; }; var sendAction = function (action, onData, onError, params) { if (params === void 0) { params = {}; } return sendData(exports.__assign(exports.__assign({}, params), { action: action }), function (data) { if (data.type === 'smart_app_data') { onData === null || onData === void 0 ? void 0 : onData(data.smart_app_data); } if (data.type === 'smart_app_error') { // @ts-ignore onError === null || onError === void 0 ? void 0 : onError(data.smart_app_error); } }); }; return { cancelTts: cancelTts, close: function () { var _a; return (_a = window.AssistantHost) === null || _a === void 0 ? void 0 : _a.close(); }, getGeo: typeof ((_c = window.AssistantHost) === null || _c === void 0 ? void 0 : _c.getGeo) !== 'undefined' ? function () { var _a, _b; (_b = (_a = window.AssistantHost).getGeo) === null || _b === void 0 ? void 0 : _b.call(_a); } : undefined, getInitialData: appInitialData.pull, findInInitialData: appInitialData.find, getRecoveryState: function () { return window.appRecoveryState; }, on: on, subscribeToCommand: subscribeToCommand, sendAction: sendAction, sendData: sendData, sendActionPromisified: function (action, params) { if (params === void 0) { params = {}; } return new Promise(function (resolve, reject) { var off = sendAction(action, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } off(); resolve.apply(void 0, args); }, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } off(); reject.apply(void 0, args); }, params); }); }, sendDataPromisified: function (params) { return new Promise(function (resolve) { var off = sendData(params, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } off(); resolve.apply(void 0, args); }); }); }, setGetState: function (nextGetState) { currentGetState = nextGetState; }, setGetRecoveryState: function (nextGetRecoveryState) { currentGetRecoveryState = nextGetRecoveryState; }, setSuggests: function (suggestions) { var _a; (_a = window.AssistantHost) === null || _a === void 0 ? void 0 : _a.setSuggests(JSON.stringify({ suggestions: { buttons: suggestions } })); }, setHints: function (hints) { var _a; (_a = window.AssistantHost) === null || _a === void 0 ? void 0 : _a.setHints(JSON.stringify({ hints: hints })); }, sendText: function (message) { var _a; return (_a = window.AssistantHost) === null || _a === void 0 ? void 0 : _a.sendText(message); }, setHeaderButtons: function (headerButtons) { var _a, _b; if (!((_a = window.AssistantHost) === null || _a === void 0 ? void 0 : _a.setHeaderButtons)) { throw new Error('setHeaderButtons не поддерживается в данной версии клиента'); } (_b = window.AssistantHost) === null || _b === void 0 ? void 0 : _b.setHeaderButtons(JSON.stringify(headerButtons)); }, ready: readyFn, }; }; if (typeof window !== 'undefined') { // eslint-disable-next-line no-underscore-dangle window.__ASSISTANT_CLIENT__ = { version: '1.37.1' }; } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function commonjsRequire(path) { throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); } var proto = {exports: {}}; var indexMinimal = {}; var minimal$1 = {}; var aspromise; var hasRequiredAspromise; function requireAspromise () { if (hasRequiredAspromise) return aspromise; hasRequiredAspromise = 1; aspromise = asPromise; /** * Callback as used by {@link util.asPromise}. * @typedef asPromiseCallback * @type {function} * @param {Error|null} error Error, if any * @param {...*} params Additional arguments * @returns {undefined} */ /** * Returns a promise from a node-style callback function. * @memberof util * @param {asPromiseCallback} fn Function to call * @param {*} ctx Function context * @param {...*} params Function arguments * @returns {Promise<*>} Promisified function */ function asPromise(fn, ctx/*, varargs */) { var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; while (index < arguments.length) params[offset++] = arguments[index++]; return new Promise(function executor(resolve, reject) { params[offset] = function callback(err/*, varargs */) { if (pending) { pending = false; if (err) reject(err); else { var params = new Array(arguments.length - 1), offset = 0; while (offset < params.length) params[offset++] = arguments[offset]; resolve.apply(null, params); } } }; try { fn.apply(ctx || null, params); } catch (err) { if (pending) { pending = false; reject(err); } } }); } return aspromise; } var base64 = {}; var hasRequiredBase64; function requireBase64 () { if (hasRequiredBase64) return base64; hasRequiredBase64 = 1; (function (exports) { /** * A minimal base64 implementation for number arrays. * @memberof util * @namespace */ var base64 = exports; /** * Calculates the byte length of a base64 encoded string. * @param {string} string Base64 encoded string * @returns {number} Byte length */ base64.length = function length(string) { var p = string.length; if (!p) return 0; var n = 0; while (--p % 4 > 1 && string.charAt(p) === "=") ++n; return Math.ceil(string.length * 3) / 4 - n; }; // Base64 encoding table var b64 = new Array(64); // Base64 decoding table var s64 = new Array(123); // 65..90, 97..122, 48..57, 43, 47 for (var i = 0; i < 64;) s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; /** * Encodes a buffer to a base64 encoded string. * @param {Uint8Array} buffer Source buffer * @param {number} start Source start * @param {number} end Source end * @returns {string} Base64 encoded string */ base64.encode = function encode(buffer, start, end) { var parts = null, chunk = []; var i = 0, // output index j = 0, // goto index t; // temporary while (start < end) { var b = buffer[start++]; switch (j) { case 0: chunk[i++] = b64[b >> 2]; t = (b & 3) << 4; j = 1; break; case 1: chunk[i++] = b64[t | b >> 4]; t = (b & 15) << 2; j = 2; break; case 2: chunk[i++] = b64[t | b >> 6]; chunk[i++] = b64[b & 63]; j = 0; break; } if (i > 8191) { (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); i = 0; } } if (j) { chunk[i++] = b64[t]; chunk[i++] = 61; if (j === 1) chunk[i++] = 61; } if (parts) { if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); return parts.join(""); } return String.fromCharCode.apply(String, chunk.slice(0, i)); }; var invalidEncoding = "invalid encoding"; /** * Decodes a base64 encoded string to a buffer. * @param {string} string Source string * @param {Uint8Array} buffer Destination buffer * @param {number} offset Destination offset * @returns {number} Number of bytes written * @throws {Error} If encoding is invalid */ base64.decode = function decode(string, buffer, offset) { var start = offset; var j = 0, // goto index t; // temporary for (var i = 0; i < string.length;) { var c = string.charCodeAt(i++); if (c === 61 && j > 1) break; if ((c = s64[c]) === undefined) throw Error(invalidEncoding); switch (j) { case 0: t = c; j = 1; break; case 1: buffer[offset++] = t << 2 | (c & 48) >> 4; t = c; j = 2; break; case 2: buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; t = c; j = 3; break; case 3: buffer[offset++] = (t & 3) << 6 | c; j = 0; break; } } if (j === 1) throw Error(invalidEncoding); return offset - start; }; /** * Tests if the specified string appears to be base64 encoded. * @param {string} string String to test * @returns {boolean} `true` if probably base64 encoded, otherwise false */ base64.test = function test(string) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); }; } (base64)); return base64; } var eventemitter; var hasRequiredEventemitter; function requireEventemitter () { if (hasRequiredEventemitter) return eventemitter; hasRequiredEventemitter = 1; eventemitter = EventEmitter; /** * Constructs a new event emitter instance. * @classdesc A minimal event emitter. * @memberof util * @constructor */ function EventEmitter() { /** * Registered listeners. * @type {Object.<string,*>} * @private */ this._listeners = {}; } /** * Registers an event listener. * @param {string} evt Event name * @param {function} fn Listener * @param {*} [ctx] Listener context * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.on = function on(evt, fn, ctx) { (this._listeners[evt] || (this._listeners[evt] = [])).push({ fn : fn, ctx : ctx || this }); return this; }; /** * Removes an event listener or any matching listeners if arguments are omitted. * @param {string} [evt] Event name. Removes all listeners if omitted. * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.off = function off(evt, fn) { if (evt === undefined) this._listeners = {}; else { if (fn === undefined) this._listeners[evt] = []; else { var listeners = this._listeners[evt]; for (var i = 0; i < listeners.length;) if (listeners[i].fn === fn) listeners.splice(i, 1); else ++i; } } return this; }; /** * Emits an event by calling its listeners with the specified arguments. * @param {string} evt Event name * @param {...*} args Arguments * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.emit = function emit(evt) { var listeners = this._listeners[evt]; if (listeners) { var args = [], i = 1; for (; i < arguments.length;) args.push(arguments[i++]); for (i = 0; i < listeners.length;) listeners[i].fn.apply(listeners[i++].ctx, args); } return this; }; return eventemitter; } var float; var hasRequiredFloat; function requireFloat () { if (hasRequiredFloat) return float; hasRequiredFloat = 1; float = factory(factory); /** * Reads / writes floats / doubles from / to buffers. * @name util.float * @namespace */ /** * Writes a 32 bit float to a buffer using little endian byte order. * @name util.float.writeFloatLE * @function * @param {number} val Value to write * @param {Uint8Array} buf Target buffer * @param {number} pos Target buffer offset * @returns {undefined} */ /** * Writes a 32 bit float to a buffer using big endian byte order. * @name util.float.writeFloatBE * @function * @param {number} val Value to write * @param {Uint8Array} buf Target buffer * @param {number} pos Target buffer offset * @returns {undefined} */ /** * Reads a 32 bit float from a buffer using little endian byte order. * @name util.float.readFloatLE * @function * @param {Uint8Array} buf Source buffer * @param {number} pos Source buffer offset * @returns {number} Value read */ /** * Reads a 32 bit float from a buffer using big endian byte order. * @name util.float.readFloatBE * @function * @param {Uint8Array} buf Source buffer * @param {number} pos Source buffer offset * @returns {number} Value read */ /** * Writes a 64 bit double to a buffer using little endian byte order. * @name util.float.writeDoubleLE * @function * @param {number} val Value to write * @param {Uint8Array} buf Target buffer * @param {number} pos Target buffer offset * @returns {undefined} */ /** * Writes a 64 bit double to a buffer using big endian byte order. * @name util.float.writeDoubleBE * @function * @param {number} val Value to write * @param {Uint8Array} buf Target buffer * @param {number} pos Target buffer offset * @returns {undefined} */ /** * Reads a 64 bit double from a buffer using little endian byte order. * @name util.float.readDoubleLE * @function * @param {Uint8Array} buf Source buffer * @param {number} pos Source buffer offset * @returns {number} Value read */ /** * Reads a 64 bit double from a buffer using big endian byte order. * @name util.float.readDoubleBE * @function * @param {Uint8Array} buf Source buffer * @param {number} pos Source buffer offset * @returns {number} Value read */ // Factory function for the purpose of node-based testing in modified global environments function factory(exports) { // float: typed array if (typeof Float32Array !== "undefined") (function() { var f32 = new Float32Array([ -0 ]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; function writeFloat_f32_cpy(val, buf, pos) { f32[0] = val; buf[pos ] = f8b[0]; buf[pos + 1] = f8b[1]; buf[pos + 2] = f8b[2]; buf[pos + 3] = f8b[3]; } function writeFloat_f32_rev(val, buf, pos) { f32[0] = val; buf[pos ] = f8b[3]; buf[pos + 1] = f8b[2]; buf[pos + 2] = f8b[1]; buf[pos + 3] = f8b[0]; } /* istanbul ignore next */ exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; /* istanbul ignore next */ exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; function readFloat_f32_cpy(buf, pos) { f8b[0] = buf[pos ]; f8b[1] = buf[pos + 1]; f8b[2] = buf[pos + 2]; f8b[3] = buf[pos + 3]; return f32[0]; } function readFloat_f32_rev(buf, pos) { f8b[3] = buf[pos ]; f8b[2] = buf[pos + 1]; f8b[1] = buf[pos + 2]; f8b[0] = buf[pos + 3]; return f32[0]; } /* istanbul ignore next */ exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; /* istanbul ignore next */ exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; // float: ieee754 })(); else (function() { function writeFloat_ieee754(writeUint, val, buf, pos) { var sign = val < 0 ? 1 : 0; if (sign) val = -val; if (val === 0) writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); else if (isNaN(val)) writeUint(2143289344, buf, pos); else if (val > 3.4028234663852886e+38) // +-Infinity writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); else if (val < 1.1754943508222875e-38) // denormal writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); else { var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); } } exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); function readFloat_ieee754(readUint, buf, pos) { var uint = readUint(buf, pos), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 // denormal ? sign * 1.401298464324817e-45 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); } exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); })(); // double: typed array if (typeof Float64Array !== "undefined") (function() { var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; function writeDouble_f64_cpy(val, buf, pos) { f64[0] = val; buf[pos ] = f8b[0]; buf[pos + 1] = f8b[1]; buf[pos + 2] = f8b[2]; buf[pos + 3] = f8b[3]; buf[pos + 4] = f8b[4]; buf[pos + 5] = f8b[5]; buf[pos + 6] = f8b[6]; buf[pos + 7] = f8b[7]; } function writeDouble_f64_rev(val, buf, pos) { f64[0] = val; buf[pos ] = f8b[7]; buf[pos + 1] = f8b[6]; buf[pos + 2] = f8b[5]; buf[pos + 3] = f8b[4]; buf[pos + 4] = f8b[3]; buf[pos + 5] = f8b[2]; buf[pos + 6] = f8b[1]; buf[pos + 7] = f8b[0]; } /* istanbul ignore next */ exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; /* istanbul ignore next */ exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; function readDouble_f64_cpy(buf, pos) { f8b[0] = buf[pos ]; f8b[1] = buf[pos + 1]; f8b[2] = buf[pos + 2]; f8b[3] = buf[pos + 3]; f8b[4] = buf[pos + 4]; f8b[5] = buf[pos + 5]; f8b[6] = buf[pos + 6]; f8b[7] = buf[pos + 7]; return f64[0]; } function readDouble_f64_rev(buf, pos) { f8b[7] = buf[pos ]; f8b[6] = buf[pos + 1]; f8b[5] = buf[pos + 2]; f8b[4] = buf[pos + 3]; f8b[3] = buf[pos + 4]; f8b[2] = buf[pos + 5]; f8b[1] = buf[pos + 6]; f8b[0] = buf[pos + 7]; return f64[0]; } /* istanbul ignore next */ exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; /* istanbul ignore next */ exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; // double: ieee754 })(); else (function() { function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { var sign = val < 0 ? 1 : 0; if (sign) val = -val; if (val === 0) { writeUint(0, buf, pos + off0); writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); } else if (isNaN(val)) { writeUint(0, buf, pos + off0); writeUint(2146959360, buf, pos + off1); } else if (val > 1.7976931348623157e+308) { // +-Infinity writeUint(0, buf, pos + off0); writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); } else { var mantissa; if (val < 2.2250738585072014e-308) { // denormal mantissa = val / 5e-324; writeUint(mantissa >>> 0, buf, pos + off0); writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); } else { var exponent = Math.floor(Math.log(val) / Math.LN2); if (exponent === 1024) exponent = 1023; mantissa = val * Math.pow(2, -exponent); writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); } } } exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); function readDouble_ieee754(readUint, off0, off1, buf, pos) { var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047,