all files / spreadsheet/integrations/ ai-assist.js

96.77% Statements 360/372
86.38% Branches 184/213
98.28% Functions 57/58
96.33% Lines 315/327
63 statements, 12 functions, 62 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554                  28× 28× 28× 28× 28× 28× 28× 28×   28× 28×   28×     10× 10×                                 10×         12× 12× 12×                                                                                               18×                                                                                                                                                                                                                                                                                 28× 28×   28×   28×   28× 28× 28× 28× 28× 28× 28×   213623×                                      
/* istanbul ignore next */ 
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
/* istanbul ignore next */ 
var __generator = (this && this.__generator) || function (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 (_) 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 };
    }
};
define(["require", "exports", "@syncfusion/ej2-interactive-chat", "../common/index", "../common/index", "../common/index", "@syncfusion/ej2-base", "./command-executor"], function (require, exports, ej2_interactive_chat_1, index_1, index_2, index_3, ej2_base_1, command_executor_1) {
    "use strict";
    var _this = this;
    Object.defineProperty(exports, "__esModule", { value: true });
    var AIAssist = (function () {
        function AIAssist(parent) {
            this.currentPrompt = '';
            this.currentPanelWidth = 328;
            this.isAIPanelResized = false;
            this.storedPrompts = [];
            this.isAIPaneVisible = false;
            this.parent = parent;
            this.executor = new command_executor_1.CommandExecutor(parent);
            this.addEventListener();
        }
        AIAssist.prototype.addEventListener = function () {
            this.parent.on(index_1.showAIAssistPane, this.showAIAssistPane, this);
            this.parent.on(index_1.executePrompt, this.executePromptHandler, this);
        };
        AIAssist.prototype.removeEventListener = function () {
            if (!this.parent.isDestroyed) {
                this.parent.off(index_1.showAIAssistPane, this.showAIAssistPane);
                this.parent.off(index_1.executePrompt, this.executePromptHandler);
            }
        };
        AIAssist.prototype.showAIAssistPane = function (args) {
            this.parent.notify(index_2.renderSidePanel, { show: args.show });
            if (!args.show) {
                this.hideAIAssistPane();
            }
            else {
                this.updatePaneWidth(true);
                var sidePanel = this.parent.element.querySelector("#" + this.parent.element.id + "_ai-assist_panel");
                Eif (sidePanel) {
                    sidePanel.style.width = this.currentPanelWidth + "px";
                    sidePanel.innerHTML = '';
                    this.assistHost = sidePanel;
                    var resizeHandle = this.parent.createElement('div', {
                        id: this.parent.element.id + "_ai_assist_resize",
                        className: 'e-ai-assist-resize-handle'
                    });
                    this.bindResizeEvents(resizeHandle);
                    this.assistHost.appendChild(resizeHandle);
                    this.assistPanel = this.parent.createElement('div', {
                        id: this.parent.element.id + "_ai-assistview_panel",
                        className: 'e-ai-assistview-panel'
                    });
                    this.assistHost.appendChild(this.assistPanel);
                    if (ej2_base_1.isNullOrUndefined(this.aiAssistView)) {
                        this.renderAssistView();
                    }
                    else Eif (this.aiAssistView && this.aiAssistView.element &&
                        this.aiAssistView.element.parentElement !== this.assistPanel) {
                        this.assistPanel.appendChild(this.aiAssistView.element);
                        this.aiAssistView.scrollToBottom();
                    }
                    this.focusAssistTextarea();
                    this.syncRibbonAiButtonState(true);
                    this.isAIPaneVisible = args.show;
                }
            }
        };
        AIAssist.prototype.hideAIAssistPane = function () {
            this.updatePaneWidth(false);
            var sidePanel = this.parent.element.querySelector("#" + this.parent.element.id + "_ai-assist_panel");
            Eif (sidePanel && sidePanel.parentElement) {
                sidePanel.parentElement.removeChild(sidePanel);
            }
            this.syncRibbonAiButtonState(false);
            this.isAIPaneVisible = false;
        };
        AIAssist.prototype.updatePaneWidth = function (show) {
            if (this.isAIPanelResized) {
                var host = this.parent.element;
                var id = host.id;
                var sheetEl = show ? host.querySelector('.e-sheet-with-ai-assist-panel') :
                    host.querySelector("#" + id + "_sheet");
                var sheetTabPanel = show ? host.querySelector('.e-sheet-panel-with-ai-assist-panel') :
                    host.querySelector("#" + id + "_sheet_tab_panel");
                sheetEl.style.width = show ? "calc(100% - " + this.currentPanelWidth + "px)" : '';
                sheetTabPanel.style.width = show ? "calc(100% - " + this.currentPanelWidth + "px)" : '';
            }
        };
        AIAssist.prototype.syncRibbonAiButtonState = function (isVisible) {
            var aiBtn = this.parent.element.querySelector("#" + this.parent.element.id + "_aibtn");
            Eif (aiBtn) {
                if (isVisible) {
                    aiBtn.classList.add('e-active');
                }
                else {
                    aiBtn.classList.remove('e-active');
                }
            }
        };
        AIAssist.prototype.bindResizeEvents = function (handle) {
            var _this = this;
            var startX = 0;
            var startWidth = 0;
            var onMouseMove = function (e) {
                var isRtl = _this.parent.enableRtl;
                var delta = isRtl ? (e.clientX - startX) : (startX - e.clientX);
                var newWidth = startWidth + delta;
                newWidth = Math.max(328, Math.min(656, newWidth));
                _this.currentPanelWidth = newWidth;
                _this.assistHost.style.width = newWidth + "px";
                var host = _this.parent.element;
                var sheetEl = host.querySelector('.e-sheet-with-ai-assist-panel');
                var sheetTabPanel = host.querySelector('.e-sheet-panel-with-ai-assist-panel');
                Eif (sheetEl) {
                    sheetEl.style.width = "calc(100% - " + newWidth + "px)";
                }
                Eif (sheetTabPanel) {
                    sheetTabPanel.style.width = "calc(100% - " + newWidth + "px)";
                }
                _this.isAIPanelResized = true;
            };
            var onMouseUp = function () {
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
                document.body.style.cursor = '';
                document.body.style.userSelect = '';
            };
            handle.addEventListener('mousedown', function (e) {
                e.preventDefault();
                startX = e.clientX;
                startWidth = _this.assistHost.offsetWidth || _this.currentPanelWidth;
                document.body.style.cursor = 'ew-resize';
                document.body.style.userSelect = 'none';
                document.addEventListener('mousemove', onMouseMove);
                document.addEventListener('mouseup', onMouseUp);
            });
        };
        AIAssist.prototype.focusAssistTextarea = function () {
            var textarea = this.assistPanel && this.assistPanel.querySelector('.e-assist-textarea');
            Eif (textarea) {
                index_3.focus(textarea);
            }
        };
        AIAssist.prototype.renderAssistView = function () {
            var _this = this;
            var l10n = this.parent.serviceLocator.getService(index_3.locale);
            var bannerTemplate = function () {
                var bannerContainer = _this.parent.createElement('div', { className: 'e-banner-container' });
                var icon = _this.parent.createElement('div', { className: 'e-icons e-assistview-icon' });
                var header = _this.parent.createElement('div', { className: 'e-banner-header' });
                header.textContent = l10n.getConstant('AIAssistBannerHeader');
                var content = _this.parent.createElement('div', { className: 'e-banner-content' });
                content.textContent = l10n.getConstant('AIAssistBannerContent');
                bannerContainer.appendChild(icon);
                bannerContainer.appendChild(header);
                bannerContainer.appendChild(content);
                return [bannerContainer];
            };
            var options = {
                views: [{ type: 'Assist', name: l10n.getConstant('AIAssistHeader') }],
                enableRtl: this.parent.enableRtl,
                prompts: this.storedPrompts.length > 0 ? this.storedPrompts : [],
                promptPlaceholder: l10n.getConstant('AIAssistInputPlaceHolder'),
                bannerTemplate: bannerTemplate,
                promptRequest: this.onPromptRequest.bind(this),
                toolbarSettings: {
                    items: [{ iconCss: 'e-icons e-refresh', align: 'Right' }, { iconCss: 'e-icons e-close', align: 'Right' }],
                    itemClicked: this.toolbarItemClicked.bind(this)
                }
            };
            Eif (this.parent.aiAssistSettings) {
                if (this.parent.aiAssistSettings.promptSuggestions && this.storedPrompts.length === 0) {
                    options.promptSuggestions = this.parent.aiAssistSettings.promptSuggestions;
                }
                if (this.parent.aiAssistSettings.placeholder) {
                    options.promptPlaceholder = this.parent.aiAssistSettings.placeholder;
                }
            }
            this.aiAssistView = new ej2_interactive_chat_1.AIAssistView(options);
            this.aiAssistView.createElement = this.parent.createElement;
            this.aiAssistView.isInternalTemplate = true;
            this.aiAssistView.appendTo(this.assistPanel);
            Eif (this.aiAssistView.element) {
                this.aiAssistView.element.addEventListener('click', function () {
                    _this.focusAssistTextarea();
                });
            }
        };
        AIAssist.prototype.toolbarItemClicked = function (args) {
            if (args.item.iconCss === 'e-icons e-refresh') {
                this.aiAssistView.prompts = [];
                this.storedPrompts = [];
                Iif (this.parent.aiAssistSettings.promptSuggestions) {
                    this.aiAssistView.promptSuggestions = this.parent.aiAssistSettings.promptSuggestions;
                }
            }
            if (args.item.iconCss === 'e-icons e-close') {
                this.showAIAssistPane({ show: false });
            }
        };
        AIAssist.prototype.onPromptRequest = function (args) {
            return __awaiter(this, void 0, void 0, function () {
                var prompt, command, error_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            prompt = args.prompt.trim();
                            if (!prompt) {
                                return [2];
                            }
                            this.currentPrompt = prompt;
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 4, , 5]);
                            return [4, this.requestAssistCommand(prompt)];
                        case 2:
                            command = _a.sent();
                            return [4, this.executeCommand(command)];
                        case 3:
                            _a.sent();
                            this.aiAssistView.promptSuggestions = [];
                            return [3, 5];
                        case 4:
                            error_1 = _a.sent();
                            this.appendResponse('Unable to process the request.', false);
                            return [3, 5];
                        case 5: return [2];
                    }
                });
            });
        };
        AIAssist.prototype.executePromptHandler = function (args) {
            return __awaiter(this, void 0, void 0, function () {
                var prompt, promptModel, command, responseText, error_2;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            prompt = args.prompt.trim();
                            this.currentPrompt = prompt;
                            if (!(this.aiAssistView && !this.aiAssistView.isDestroyed)) return [3, 1];
                            this.aiAssistView.executePrompt(prompt);
                            return [3, 6];
                        case 1:
                            promptModel = { prompt: prompt };
                            this.storedPrompts = this.storedPrompts.concat([promptModel]);
                            _a.label = 2;
                        case 2:
                            _a.trys.push([2, 5, , 6]);
                            return [4, this.requestAssistCommand(prompt)];
                        case 3:
                            command = _a.sent();
                            return [4, this.executeCommand(command)];
                        case 4:
                            responseText = _a.sent();
                            Eif (responseText && this.storedPrompts && this.storedPrompts[this.storedPrompts.length - 1]) {
                                this.storedPrompts[this.storedPrompts.length - 1].response = responseText;
                            }
                            return [3, 6];
                        case 5:
                            error_2 = _a.sent();
                            if (this.storedPrompts && this.storedPrompts[this.storedPrompts.length - 1]) {
                                this.storedPrompts[this.storedPrompts.length - 1].response = 'Unable to process the request.';
                            }
                            return [3, 6];
                        case 6: return [2];
                    }
                });
            });
        };
        AIAssist.prototype.requestAssistCommand = function (prompt) {
            return __awaiter(this, void 0, void 0, function () {
                var actions, error_3;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 3, , 4]);
                            return [4, this.requestActionList(prompt)];
                        case 1:
                            actions = _a.sent();
                            Eif (!actions || actions.length === 0) {
                                return [2, [{ action: 'unknown' }]];
                            }
                            return [4, this.requestCommandsForActions(actions, prompt)];
                        case 2: return [2, _a.sent()];
                        case 3:
                            error_3 = _a.sent();
                            return [2, [{ action: 'unknown', message: error_3.message }]];
                        case 4: return [2];
                    }
                });
            });
        };
        AIAssist.prototype.requestActionList = function (prompt) {
            return __awaiter(this, void 0, void 0, function () {
                var request, response, cleaned, parsed;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            request = 'You are a spreadsheet assistant. Identify which actions are needed to fulfill the user request. ' +
                                'Return ONLY a valid JSON array of action name strings. No explanation, no extra text. ' +
                                '\n\nAvailable actions: analysis, query, reportGeneration, edit, findAndReplace, numberFormat, cellFormat, ' +
                                'conditionalFormat, merge, wrap, cut, copy, paste, chart, dataValidation, filter, sort, insert, ' +
                                'delete, autofill, freezePanes, hyperlink, save, unknown' +
                                '\n\nRules:' +
                                '\n- Return ["analysis"] for open-ended analysis or insight requests.' +
                                '\n- Return ["query"] for requests asking about specific data values, details from the current sheet. Only if the question can be answered from the loaded sheet data.' +
                                '\n- Return ["unknown"] if the question is about data not in the sheet, unrelated topics, or no action applies.' +
                                '\n- Insert and delete actions supports only for rows and columns.' +
                                '\n- Multiple actions are allowed e.g. ["edit", "cell_format"].' +
                                '\n- Return valid JSON array only.' +
                                ("\n\nUser request: " + prompt);
                            return [4, serverAIRequest(this.parent, { messages: [{ role: 'user', content: request }] })];
                        case 1:
                            response = _a.sent();
                            Eif (typeof response === 'string' && response.trim()) {
                                try {
                                    cleaned = response.trim()
                                        .replace(/^```json\s*/i, '').replace(/^```\s*/i, '').replace(/\s*```$/, '');
                                    parsed = JSON.parse(cleaned);
                                    if (Array.isArray(parsed)) {
                                        return [2, parsed];
                                    }
                                }
                                catch (_b) {
                                    throw new Error(response);
                                }
                            }
                            return [2, ['unknown']];
                    }
                });
            });
        };
        AIAssist.prototype.requestCommandsForActions = function (actions, prompt) {
            return __awaiter(this, void 0, void 0, function () {
                var combinedSchema, sheetData, request, response, cleaned, parsed;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            combinedSchema = actions.map(function (a) { return a + ": " + _this.getActionSchema(a); }).join('\n\n');
                            sheetData = index_1.getSheetProperties(this.parent, ['rows', 'cells'], this.parent.activeSheetIndex, ['value']);
                            request = 'You are a spreadsheet command parser. ' +
                                'Return a JSON array of command objects — one per action needed. ' +
                                ("\n\nACTION SCHEMAS (populate \"args\" exactly as described):\n" + combinedSchema) +
                                '\n\nCOMMAND FORMAT:' +
                                '\nReturn a JSON array: [{ "action": "<action>", "args": { ... } }, ...]' +
                                '\nDo NOT wrap in any object. Return ONLY the JSON array.' +
                                '\n\nRules:' +
                                '\n- For analysis analyze the current spreadsheet sheet data in detail. Identify key patterns, trends, and inconsistencies in the data; summarize important formulas and their purpose; highlight potential issues such as errors, redundant calculations, broken references, performance bottlenecks, or data quality gaps; and provide clear, actionable recommendations for optimization or improvement. Keep the summary not too long, structured, and business - relevant and append the report message ' +
                                '\n- For query: Answer only from current sheet data. Detect format keywords (table, list, markdown) and respond accordingly in that format. Be direct, concise, factual, deterministic—no invented data. Return unknown if unanswerable.' +
                                '\n- For reportGeneration: base conclusions strictly on provided sheet data — do not invent values. Keep each section concise (prefer bullets). Include up to 5 topRows. For KPIs include a short formula when possible (e.g. "SUM(A2:A100)"). Visual suggestions must include chartType, a valid bounded A1 range, and a one-sentence reason. Do NOT include executable commands or UI actions in the report.' +
                                '\n- Use A1, A1:B11, or "Selected" for range references.' +
                                '\n- If the user does not mention a specific range, omit the range field entirely — except for chart and autofill which must always have a precise bounded range derived from the sheet data (e.g. "A1:C12"). Never use open-ended references like "A:A", "1:1", or "B:B" under any circumstance.' +
                                '\n- Discontinuous chart ranges are supported using e.g. "A1:A10 C1:C10" — use this when the user specifies non-adjacent columns.' +
                                '\n- If you cannot map to any action, return {"action":"unknown","message":"<explanation>"}. ' +
                                '\n- Preserve formulas with "=" prefix.' +
                                '\n- Do not invent missing details.' +
                                '\n- Return valid JSON only.' +
                                ("\n\nCurrent sheet data: " + sheetData) +
                                ("\n\nUser request: " + prompt);
                            return [4, serverAIRequest(this.parent, { messages: [{ role: 'user', content: request }] })];
                        case 1:
                            response = _a.sent();
                            Eif (typeof response === 'string' && response.trim()) {
                                try {
                                    cleaned = response.trim()
                                        .replace(/^```json\s*/i, '').replace(/^```\s*/i, '').replace(/\s*```$/, '');
                                    parsed = JSON.parse(cleaned);
                                    Eif (Array.isArray(parsed)) {
                                        return [2, parsed];
                                    }
                                }
                                catch (_b) {
                                    return [2, [{ action: 'unknown', message: response }]];
                                }
                            }
                            return [2, [{ action: 'unknown' }]];
                    }
                });
            });
        };
        AIAssist.prototype.getActionSchema = function (action) {
            var schemas = {
                analysis: '{ message: string }',
                query: '{ message: string }',
                reportGeneration: '{ reportStructure: {' +
                    '  summary: string,' +
                    '  sections: [{ heading: string, content: string }],' +
                    '  kpis: [{ name: string, value: string, formula?: string }],' +
                    '  topRows: [{ row: number, values: { [header: string]: string|number } }],' +
                    '  visualSuggestions: [{ chartType: string, range: string, reason: string }]' +
                    '} }',
                edit: '{ address: string, value: string (preserve "=" prefix for formulas) }',
                findAndReplace: '{ findValue: string, replaceValue: string, caseSensitive?: boolean (default false), exactMatch?: boolean (default false) }',
                numberFormat: '{ range: string, format: General|Number|Currency|Accounting|ShortDate|LongDate|Time|Percentage|Fraction|Scientific|Text }',
                cellFormat: '{ range: string, formatting: { bold?: boolean, italic?: boolean, underline?: boolean, strikethrough?: boolean, fontSize?: number, fontFamily?: string, color?: string (hex), backgroundColor?: string (hex) } }',
                conditionalFormat: '{ range: string, type: GreaterThan|LessThan|Between|EqualTo|ContainsText|DateOccur|Duplicate|Unique|Top10Items|Bottom10Items|Top10Percentage|Bottom10Percentage|AboveAverage|BelowAverage, value: string (for Between use "min,max"), cFColor: RedFT|YellowFT|GreenFT }',
                merge: '{ range: string, direction: "All"|"Vertically"|"Horizontally" (default "All") }',
                wrap: '{ range: string, wrap: boolean }',
                cut: '{ range: string }',
                copy: '{ range: string }',
                paste: '{ range: string }',
                chart: '{ range: string, chartType: Column|Bar|Line|Area|Pie|Doughnut|Scatter|StackingColumn|StackingColumn100|StackingBar|StackingBar100|StackingLine|StackingLine100|StackingArea|StackingArea100, theme?: Material|Bootstrap|Fabric|Office365|Tailwind, title?: string, isSeriesInRows?: boolean, height?: number, width?: number }',
                dataValidation: '{ range: string, dvType: WholeNumber|Decimal|Date|Time|TextLength|List|Custom, dvOperator?: Between|NotBetween|EqualTo|NotEqualTo|GreaterThan|LessThan|GreaterThanOrEqualTo|LessThanOrEqualTo, dvValue1?: string, dvValue2?: string, dvIgnoreBlank?: boolean, dvInCellDropDown?: boolean, isHighlighted?: boolean }',
                filter: '{ range: string, filterColumn: string (column letter e.g. "A"), ' +
                    'filterOperator: equal|notequal|greaterthan|lessthan|greaterthanorequal|lessthanorequal|contains|startswith|endswith|isempty|isnotempty, ' +
                    'filterValue: string, clearFilter?: boolean (true to remove filter) }',
                sort: '{ range?: string (omit if user does not mention a specific range), ' +
                    'sortColumn?: string (column letter e.g. "A", omit if not specified — first column of range will be used), ' +
                    'sortOrder: "Ascending"|"Descending" (default "Ascending"), ' +
                    'sortContainsHeader?: boolean (default true) }',
                insert: '{ modelType: "Row"|"Column", startIndex: number (1-based row or column number), ' +
                    'count?: number (number of rows/columns to insert, default 1) }',
                delete: '{ modelType: "Row"|"Column", startIndex: number (1-based row or column number), ' +
                    'count?: number (number of rows/columns to delete, default 1) }',
                autofill: '{ dataRange: string (source range e.g. "A1:A3"), fillRange: string (target range to fill e.g. "A4:A10"), ' +
                    'direction?: "Down"|"Up"|"Left"|"Right" (auto-detected if omitted), ' +
                    'fillType?: "FillSeries"|"CopyCells"|"FillFormattingOnly"|"FillWithoutFormatting" (default "FillSeries") }',
                freezePanes: '{ freezeType: "Rows"|"Columns"|"Panes"|"Unfreeze", ' +
                    'row?: number (number of rows to freeze, 0 to unfreeze rows, default 0), ' +
                    'column?: number (number of columns to freeze, 0 to unfreeze columns, default 0) }',
                hyperlink: '{ address: string (URL e.g. "https://example.com" or cell/sheet reference e.g. "Sheet1!A1" or defined name), ' +
                    'displayText?: string (text to display in the cell, omit to keep existing), ' +
                    'range?: string (target cell or range, defaults to selected cell) }',
                save: '{ saveType: "xlsx"|"xls"|"csv"|"pdf" (default "xlsx") }'
            };
            return schemas[action];
        };
        AIAssist.prototype.executeCommand = function (commands) {
            return __awaiter(this, void 0, void 0, function () {
                var results, messages, responseText;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.executor.executeHandler(commands)];
                        case 1:
                            results = _a.sent();
                            messages = results
                                .map(function (r) { return r.message; })
                                .filter(function (m) { return !ej2_base_1.isNullOrUndefined(m) && m !== ''; });
                            responseText = messages.join('\n\n');
                            Eif (messages.length > 0) {
                                this.appendResponse(responseText);
                            }
                            return [2, responseText];
                    }
                });
            });
        };
        AIAssist.prototype.appendResponse = function (response, isSuccess) {
            Eif (isSuccess === void 0) { isSuccess = true; }
            Eif (response) {
                Eif (isSuccess) {
                    this.parent.trigger('promptResponse', { prompt: this.currentPrompt, response: response });
                }
                if (!ej2_base_1.isNullOrUndefined(this.aiAssistView)) {
                    this.aiAssistView.addPromptResponse(response);
                }
            }
        };
        AIAssist.prototype.destroy = function () {
            this.removeEventListener();
            if (this.aiAssistView) {
                this.aiAssistView.destroy();
                this.aiAssistView = null;
            }
            if (this.assistPanel) {
                this.assistPanel.innerHTML = '';
                this.assistPanel = null;
            }
            if (this.assistHost && this.assistHost.parentElement) {
                this.assistHost.parentElement.removeChild(this.assistHost);
                this.assistHost = null;
            }
            this.currentPrompt = '';
            this.currentPanelWidth = 328;
            this.isAIPaneVisible = false;
            this.isAIPanelResized = false;
            this.storedPrompts = null;
            this.executor = null;
            this.parent = null;
        };
        AIAssist.prototype.getModuleName = function () {
            return 'AIAssist';
        };
        return AIAssist;
    }());
    exports.AIAssist = AIAssist;
    var serverAIRequest = function (context, settings) { return __awaiter(_this, void 0, void 0, function () {
        var eventArgs, response, result, error_4;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, , 4]);
                    eventArgs = {
                        requestData: {
                            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: settings
                        }
                    };
                    context.trigger('promptRequest', eventArgs);
                    if (eventArgs.cancel) {
                        return [2, 'Request has been cancelled'];
                    }
                    eventArgs.requestData.body = JSON.stringify(eventArgs.requestData.body);
                    return [4, fetch(context.aiAssistSettings.requestUrl, eventArgs.requestData)];
                case 1:
                    response = _a.sent();
                    return [4, response.json()];
                case 2:
                    result = _a.sent();
                    Iif (!response.ok) {
                        throw new Error(result.error || 'Network response was not ok');
                    }
                    return [2, result.response.replace('END_INSERTION', '')];
                case 3:
                    error_4 = _a.sent();
                    return [2, error_4.message];
                case 4: return [2];
            }
        });
    }); };
});