all files / integrations/ webmcp-adapter.js

95.67% Statements 376/393
90.06% Branches 290/322
96.83% Functions 61/63
95.28% Lines 323/339
10 statements, 1 function, 11 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986                       106× 55× 161× 106×       159× 159× 477× 261× 687× 687× 640× 640× 267× 57× 53×   263× 104× 31× 27× 27× 27×   344× 687× 159×                                                                                                                                                                                                                                                                                                                                                                                                                                   62× 62× 62×             62× 62×             63×                     13× 13× 21×     70×   13×                                               69× 69× 69× 69× 69× 69×   69×                 68×     20×     10×     16×                                                       20× 20× 20× 20× 54×   20× 20× 20× 20×                                                                                                                                                       16×                                                                                             10× 10× 10×                                                                                                                                                   16× 16× 16×                                                                                                                                                                                           62× 62×   62×             12259×   74×     72× 72×   13×   13× 13×   12× 12×           106×   53× 53× 98×   53× 51×   50×       48×         46× 44× 44×     45×   45× 45×         54× 53×   51× 51× 45×                           36×               33×        
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(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 __assign.apply(this, arguments);
};
/* 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) {
        Iif (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; }
                    Iif (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    Iif (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", "../base/constant", "@syncfusion/ej2-base"], function (require, exports, constant_1, ej2_base_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    /**
     * Define FileManager's WebMCP tools
     * Each tool includes name, description, input/output schemas, and execution handlers
     */
    var webMcpTools = [
        {
            name: 'getSelectedFiles',
            description: 'Retrieve the list of currently selected files and folders in the FileManager. Returns file metadata including IDs, names, types, and paths.',
            inputSchema: {
                type: 'object',
                properties: {},
                required: []
            },
            outputSchema: {
                type: 'object',
                properties: {
                    success: { type: 'boolean' },
                    data: {
                        type: 'array',
                        items: {
                            type: 'object',
                            properties: {
                                id: { type: 'string' },
                                name: { type: 'string' },
                                type: { type: 'string' },
                                size: { type: 'number' },
                                modified: { type: 'string' }
                            }
                        }
                    },
                    message: { type: 'string' }
                }
            },
            annotations: { readOnlyHint: true }
        },
        {
            name: 'manageFileSystemItems',
            description: 'Create folders, rename files/folders, or delete files/folders by ID. Supports batch operations for deletion.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['create', 'rename', 'delete'] },
                    name: { type: 'string' },
                    id: { type: 'string' },
                    ids: { type: 'array', items: { type: 'string' } }
                },
                required: ['action']
            },
            outputSchema: {
                type: 'object',
                properties: {
                    success: { type: 'boolean' },
                    data: {
                        type: 'object',
                        properties: {
                            action: { type: 'string' },
                            id: { type: 'string' },
                            name: { type: 'string' }
                        }
                    },
                    message: { type: 'string' }
                }
            },
            annotations: { readOnlyHint: false }
        },
        {
            name: 'manageFileUploadAndDownload',
            description: 'Upload files to the current folder or download/export selected files to local system.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['upload', 'download'] },
                    ids: { type: 'array', items: { type: 'string' } }
                },
                required: ['action']
            },
            outputSchema: {
                type: 'object',
                properties: {
                    success: { type: 'boolean' },
                    data: {
                        type: 'object',
                        properties: {
                            action: { type: 'string' },
                            filesProcessed: { type: 'number' },
                            totalSize: { type: 'number' }
                        }
                    },
                    message: { type: 'string' }
                }
            },
            annotations: { readOnlyHint: false }
        },
        {
            name: 'navigateAndOpenFiles',
            description: 'Navigate backward in folder hierarchy, open files/folders, and refresh file list. Returns current directory state after navigation.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['backward', 'openFile', 'refresh'] },
                    fileId: { type: 'string' }
                },
                required: ['action']
            },
            outputSchema: {
                type: 'object',
                properties: {
                    success: { type: 'boolean' },
                    data: {
                        type: 'object',
                        properties: {
                            action: { type: 'string' },
                            currentPath: { type: 'string' },
                            filesCount: { type: 'number' }
                        }
                    },
                    message: { type: 'string' }
                }
            },
            annotations: { readOnlyHint: true }
        },
        {
            name: 'searchAndFilterFiles',
            description: 'Filter files based on custom criteria (name, type, date, size, etc.). Returns filtered file list matching the specified conditions.',
            inputSchema: {
                type: 'object',
                properties: {
                    filterData: { type: 'object' }
                },
                required: []
            },
            outputSchema: {
                type: 'object',
                properties: {
                    success: { type: 'boolean' },
                    data: {
                        type: 'object',
                        properties: {
                            filterApplied: { type: 'boolean' },
                            matchCount: { type: 'number' },
                            files: { type: 'array' }
                        }
                    },
                    message: { type: 'string' }
                }
            },
            annotations: { readOnlyHint: true }
        },
        {
            name: 'manageUserInterface',
            description: 'Enable/disable menu items and toolbar items, close dialogs, refresh layout. Controls UI state for workflow management.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['enableMenu', 'disableMenu', 'enableToolbar', 'disableToolbar', 'closeDialog', 'refreshLayout'] },
                    items: { type: 'array', items: { type: 'string' } }
                },
                required: ['action']
            },
            outputSchema: {
                type: 'object',
                properties: {
                    success: { type: 'boolean' },
                    data: {
                        type: 'object',
                        properties: {
                            action: { type: 'string' },
                            itemsAffected: { type: 'number' },
                            items: { type: 'array' }
                        }
                    },
                    message: { type: 'string' }
                }
            },
            annotations: { readOnlyHint: false }
        },
        {
            name: 'manageSelection',
            description: 'Select all files in current folder or clear the current selection. Prepares files for bulk operations.',
            inputSchema: {
                type: 'object',
                properties: {
                    action: { type: 'string', enum: ['selectAll', 'clearSelection'] }
                },
                required: ['action']
            },
            outputSchema: {
                type: 'object',
                properties: {
                    success: { type: 'boolean' },
                    data: {
                        type: 'object',
                        properties: {
                            action: { type: 'string' },
                            filesSelected: { type: 'number' }
                        }
                    },
                    message: { type: 'string' }
                }
            },
            annotations: { readOnlyHint: false }
        }
    ];
    /**
     * WebMcpAdapter — Integrates FileManager with WebMCP protocol.
     * Inject this module to enable AI tool execution capabilities.
     */
    var WebMcpAdapter = /** @class */ (function () {
        function WebMcpAdapter(parent) {
            this.webMcpAbortController = null;
            this.parent = parent;
            this.addEventListener();
        }
        /**
         * Attaches event listeners for WebMCP communication.
         *
         * @returns {void}
         */
        WebMcpAdapter.prototype.addEventListener = function () {
            this.parent.on(constant_1.getWebMcpTools, this.getTools, this);
            this.parent.on(constant_1.registerWebMcpTools, this.registerTools, this);
        };
        /**
         * Removes event listeners when component is destroyed.
         *
         * @returns {void}
         */
        WebMcpAdapter.prototype.removeEventListener = function () {
            if (!this.parent.isDestroyed) {
                this.parent.off(constant_1.getWebMcpTools, this.getTools);
                this.parent.off(constant_1.registerWebMcpTools, this.registerTools);
            }
        };
        /**
         * Retrieves available tools, optionally filtered by names.
         *
         * @param {Object} args - The arguments object
         * @param {string[]} args.toolNames - Optional array of tool names to filter
         * @param {WebMcpTool[]} args.tools - Optional array to store filtered tools
         * @returns {WebMcpTool[]} Array of WebMCP tools
         */
        WebMcpAdapter.prototype.getTools = function (args) {
            var toolNames = args.toolNames;
            if (toolNames && toolNames.length !== 0) {
                args.tools = webMcpTools.filter(function (webMcpTool) { return toolNames.indexOf(webMcpTool.name) !== -1; })
                    .map(function (webMcpTool) { return (__assign({}, webMcpTool)); });
            }
            else {
                args.tools = webMcpTools.map(function (webMcpTool) { return (__assign({}, webMcpTool)); });
            }
            return args.tools;
        };
        /**
         * Registers tools with document.modelContext for AI access.
         *
         * @param {Object} args - The arguments object
         * @param {string} args.prefix - Optional prefix for tool names
         * @param {string[]|WebMcpTool[]} args.tools - Array of tool names or tool objects
         * @param {string[]} args.exposedTo - Optional array of entities to expose tools to
         * @returns {void}
         */
        WebMcpAdapter.prototype.registerTools = function (args) {
            var _this = this;
            var modelContext = document.modelContext;
            if (!modelContext || typeof modelContext.registerTool !== 'function') {
                return;
            }
            this.webMcpAbortController = new AbortController();
            var toolPrefix = (ej2_base_1.isNullOrUndefined(args.prefix) ? this.parent.element.id : args.prefix);
            var tools = args.tools && args.tools.length && typeof args.tools[0] === 'object' ? args.tools :
                this.getTools({ toolNames: args.tools });
            tools.forEach(function (tool) {
                tool.name = toolPrefix + "_" + tool.name;
                tool.execute = tool.execute || (function (args) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
                    return [2 /*return*/, this.executeHandler(tool.name, args || {})];
                }); }); });
                modelContext.registerTool(tool, { signal: _this.webMcpAbortController.signal, exposedTo: args.exposedTo });
            });
        };
        /**
         * Executes a WebMCP tool handler based on command name.
         * Fires beforeWebMcpToolExecute event for cancellation/confirmation.
         *
         * @param {string} command - The command name to execute
         * @param {object} args - The arguments for the command
         * @returns {Promise<WebMcpToolResponse>} Promise that resolves to the tool response
         */
        WebMcpAdapter.prototype.executeHandler = function (command, args) {
            return __awaiter(this, void 0, void 0, function () {
                var baseCommand, eventArgs;
                return __generator(this, function (_a) {
                    baseCommand = command.includes('_') ? command.substring(command.indexOf('_') + 1) : command;
                    eventArgs = { toolName: command, toolArgs: args };
                    this.parent.trigger('beforeWebMcpToolExecute', eventArgs);
                    // Check if tool execution was cancelled
                    if (eventArgs.cancel) {
                        return [2 /*return*/, this.message({
                                action: command,
                                cancelled: true,
                                success: false,
                                message: eventArgs.cancellationResponse ||
                                    "[USER_CANCELLED] Tool \"" + command + "\" was cancelled. This is final. Do NOT retry."
                            })];
                    }
                    // Route to appropriate tool handler
                    switch (baseCommand) {
                        case 'getSelectedFiles':
                            return [2 /*return*/, this.handleGetSelectedFiles()];
                        case 'manageFileSystemItems':
                            return [2 /*return*/, this.handleManageFileSystemItems(args)];
                        case 'manageFileUploadAndDownload':
                            return [2 /*return*/, this.handleFileUploadAndDownload(args)];
                        case 'navigateAndOpenFiles':
                            return [2 /*return*/, this.handleNavigateAndOpenFiles(args)];
                        case 'searchAndFilterFiles':
                            return [2 /*return*/, this.handleSearchAndFilterFiles(args)];
                        case 'manageUserInterface':
                            return [2 /*return*/, this.handleUserInterface(args)];
                        case 'manageSelection':
                            return [2 /*return*/, this.handleSelection(args)];
                        default:
                            return [2 /*return*/, this.error("Tool \"" + baseCommand + "\" not found.")];
                    }
                    return [2 /*return*/];
                });
            });
        };
        /**
         * Tool Handler: Retrieve currently selected files
         *
         * @returns {WebMcpToolResponse} The response with selected files data
         */
        WebMcpAdapter.prototype.handleGetSelectedFiles = function () {
            try {
                var selectedFiles = this.parent.getSelectedFiles() || [];
                return this.message({
                    action: 'getSelectedFiles',
                    success: true,
                    data: selectedFiles,
                    message: "Retrieved " + (selectedFiles.length || 0) + " selected files"
                });
            }
            catch (error) {
                return this.error("Failed to retrieve selected files: " + error.message);
            }
        };
        /**
         * Tool Handler: Manage file system items (create/rename/delete)
         *
         * @param {ManageFileSystemItemsArgs} args - The arguments for the file system operation
         * @returns {WebMcpToolResponse} The response with operation result
         */
        WebMcpAdapter.prototype.handleManageFileSystemItems = function (args) {
            return __awaiter(this, void 0, void 0, function () {
                var action, name_1, id, ids, _a, createOutcome, renameOutcome, missingIds, deleteOutcome, error_1;
                var _this = this;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _b.trys.push([0, 9, , 10]);
                            action = args.action, name_1 = args.name, id = args.id, ids = args.ids;
                            _a = action;
                            switch (_a) {
                                case 'create': return [3 /*break*/, 1];
                                case 'rename': return [3 /*break*/, 3];
                                case 'delete': return [3 /*break*/, 5];
                            }
                            return [3 /*break*/, 7];
                        case 1:
                            if (!name_1 || !name_1.trim()) {
                                return [2 /*return*/, this.error('Create requires a non-empty name')];
                            }
                            Iif (this.itemNameExists(name_1, true)) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileSystemItems',
                                        success: false,
                                        data: { action: 'create', name: name_1 },
                                        message: "A file or folder named \"" + name_1 + "\" already exists in the current folder."
                                    })];
                            }
                            this.parent.createFolder(name_1);
                            return [4 /*yield*/, this.waitForOperation('create', 2500, name_1)];
                        case 2:
                            createOutcome = _b.sent();
                            if (!createOutcome.success) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileSystemItems',
                                        success: false,
                                        data: { action: 'create', name: name_1 },
                                        message: createOutcome.message || "Folder \"" + name_1 + "\" was not created."
                                    })];
                            }
                            return [2 /*return*/, this.message({
                                    action: 'manageFileSystemItems',
                                    success: true,
                                    data: { action: 'create', name: name_1 },
                                    message: "Folder \"" + name_1 + "\" created successfully"
                                })];
                        case 3:
                            if (!id || !name_1) {
                                return [2 /*return*/, this.error('Rename requires both id and name parameters')];
                            }
                            if (this.itemNameExists(name_1, false, id)) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileSystemItems',
                                        success: false,
                                        data: { action: 'rename', id: id, name: name_1 },
                                        message: "A file or folder named \"" + name_1 + "\" already exists in the current folder."
                                    })];
                            }
                            this.parent.renameFile(id, name_1);
                            return [4 /*yield*/, this.waitForOperation('rename', 2500, name_1)];
                        case 4:
                            renameOutcome = _b.sent();
                            if (!renameOutcome.success) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileSystemItems',
                                        success: false,
                                        data: { action: 'rename', id: id, name: name_1 },
                                        message: renameOutcome.message || "Item \"" + name_1 + "\" was not renamed."
                                    })];
                            }
                            return [2 /*return*/, this.message({
                                    action: 'manageFileSystemItems',
                                    success: true,
                                    data: { action: 'rename', id: id, name: name_1 },
                                    message: "Item renamed to \"" + name_1 + "\" successfully"
                                })];
                        case 5:
                            if (!ids || !Array.isArray(ids) || ids.length === 0) {
                                return [2 /*return*/, this.error('Delete requires ids array')];
                            }
                            missingIds = ids.filter(function (idValue) { return !_this.itemExistsById(idValue); });
                            if (missingIds.length > 0) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileSystemItems',
                                        success: false,
                                        data: { action: 'delete', count: ids.length },
                                        message: "Unable to delete missing item id(s): " + missingIds.join(', ')
                                    })];
                            }
                            this.parent.deleteFiles(ids);
                            return [4 /*yield*/, this.waitForOperation('delete', 2500, undefined, ids)];
                        case 6:
                            deleteOutcome = _b.sent();
                            if (!deleteOutcome.success) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileSystemItems',
                                        success: false,
                                        data: { action: 'delete', count: ids.length },
                                        message: deleteOutcome.message || "Delete request for " + ids.length + " item(s) did not complete."
                                    })];
                            }
                            return [2 /*return*/, this.message({
                                    action: 'manageFileSystemItems',
                                    success: true,
                                    data: { action: 'delete', count: ids.length },
                                    message: "Deleted " + ids.length + " item(s) successfully"
                                })];
                        case 7: return [2 /*return*/, this.error("Unknown action \"" + action + "\" for manageFileSystemItems")];
                        case 8: return [3 /*break*/, 10];
                        case 9:
                            error_1 = _b.sent();
                            return [2 /*return*/, this.error("Failed to manage file system items: " + error_1.message)];
                        case 10: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Tool Handler: Upload/Download files
         *
         * @param {FileUploadAndDownloadArgs} args - The arguments for the upload/download operation
         * @returns {WebMcpToolResponse} The response with operation result
         */
        WebMcpAdapter.prototype.handleFileUploadAndDownload = function (args) {
            return __awaiter(this, void 0, void 0, function () {
                var action, ids, _a, currentItems_1, invalidIds, downloadOutcome, error_2;
                var _this = this;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _b.trys.push([0, 6, , 7]);
                            action = args.action, ids = args.ids;
                            _a = action;
                            switch (_a) {
                                case 'upload': return [3 /*break*/, 1];
                                case 'download': return [3 /*break*/, 2];
                            }
                            return [3 /*break*/, 4];
                        case 1:
                            {
                                this.parent.uploadFiles();
                                return [2 /*return*/, this.message({
                                        action: 'manageFileUploadAndDownload',
                                        success: false,
                                        requiresUserInteraction: true,
                                        data: { action: 'upload' },
                                        message: 'Upload dialog opening requires a user gesture in the browser. Please invoke the upload workflow from the UI to continue.'
                                    })];
                            }
                            _b.label = 2;
                        case 2:
                            if (!(ids && Array.isArray(ids) && ids.length > 0)) {
                                return [2 /*return*/, this.error('Download requires ids array with at least one item')];
                            }
                            currentItems_1 = this.getCurrentItems();
                            invalidIds = ids.filter(function (idValue) { return !_this.itemExistsById(idValue, currentItems_1); });
                            if (invalidIds.length > 0) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileUploadAndDownload',
                                        success: false,
                                        data: { action: 'download', filesProcessed: 0 },
                                        message: "Unable to download missing item id(s): " + invalidIds.join(', ')
                                    })];
                            }
                            this.parent.downloadFiles(ids);
                            return [4 /*yield*/, this.waitForOperation('download', 2500)];
                        case 3:
                            downloadOutcome = _b.sent();
                            Iif (!downloadOutcome.success) {
                                return [2 /*return*/, this.message({
                                        action: 'manageFileUploadAndDownload',
                                        success: false,
                                        data: { action: 'download', filesProcessed: ids.length },
                                        message: downloadOutcome.message || "Download request for " + ids.length + " item(s) did not complete."
                                    })];
                            }
                            return [2 /*return*/, this.message({
                                    action: 'manageFileUploadAndDownload',
                                    success: true,
                                    data: { action: 'download', filesProcessed: ids.length },
                                    message: "Downloaded " + ids.length + " file(s)"
                                })];
                        case 4: return [2 /*return*/, this.error("Unknown action \"" + action + "\" for manageFileUploadAndDownload")];
                        case 5: return [3 /*break*/, 7];
                        case 6:
                            error_2 = _b.sent();
                            return [2 /*return*/, this.error("Failed to handle file upload/download: " + error_2.message)];
                        case 7: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * Tool Handler: Navigate and open files
         *
         * @param {NavigateAndOpenFilesArgs} args - The arguments for the navigation/open operation
         * @returns {WebMcpToolResponse} The response with operation result
         */
        WebMcpAdapter.prototype.handleNavigateAndOpenFiles = function (args) {
            try {
                var action = args.action, fileId = args.fileId;
                switch (action) {
                    case 'backward': {
                        var previousPath = this.parent.path;
                        var previousDepth = this.parent.pathNames ? this.parent.pathNames.length : 0;
                        this.parent.traverseBackward();
                        var currentPath = this.parent.path;
                        Eif (currentPath === previousPath && (this.parent.pathNames ? this.parent.pathNames.length : 0) === previousDepth) {
                            return this.message({
                                action: 'navigateAndOpenFiles',
                                success: false,
                                data: { action: 'backward', currentPath: previousPath },
                                message: 'Navigation did not change the current path.'
                            });
                        }
                        return this.message({
                            action: 'navigateAndOpenFiles',
                            success: true,
                            data: { action: 'backward', currentPath: currentPath },
                            message: 'Navigated to parent folder'
                        });
                    }
                    case 'openFile': {
                        if (!fileId) {
                            return this.error('openFile requires fileId parameter');
                        }
                        var item = this.findItemById(fileId);
                        if (!item) {
                            return this.message({
                                action: 'navigateAndOpenFiles',
                                success: false,
                                data: { action: 'openFile', fileId: fileId },
                                message: "Item \"" + fileId + "\" was not found in the current folder."
                            });
                        }
                        var previousPath = this.parent.path;
                        this.parent.openFile(fileId);
                        var currentPath = this.parent.path;
                        if (!item.isFile && currentPath === previousPath) {
                            return this.message({
                                action: 'navigateAndOpenFiles',
                                success: false,
                                data: { action: 'openFile', fileId: fileId, currentPath: currentPath },
                                message: 'Open request did not change the current path.'
                            });
                        }
                        return this.message({
                            action: 'navigateAndOpenFiles',
                            success: true,
                            data: { action: 'openFile', fileId: fileId, currentPath: currentPath },
                            message: item.isFile ? 'File opened' : 'Folder opened'
                        });
                    }
                    case 'refresh': {
                        this.parent.refreshFiles();
                        return this.message({
                            action: 'navigateAndOpenFiles',
                            success: true,
                            data: { action: 'refresh', currentPath: this.parent.path, filesCount: this.getCurrentItems().length },
                            message: 'File list refreshed'
                        });
                    }
                    default:
                        return this.error("Unknown action \"" + action + "\" for navigateAndOpenFiles");
                }
            }
            catch (error) {
                return this.error("Failed to navigate/open files: " + error.message);
            }
        };
        /**
         * Tool Handler: Filter and search files
         *
         * @param {FilterAndSearchFilesArgs} args - The arguments for the filter/search operation
         * @returns {WebMcpToolResponse} The response with operation result
         */
        WebMcpAdapter.prototype.handleSearchAndFilterFiles = function (args) {
            try {
                var filterData = args.filterData;
                if (filterData) {
                    this.parent.filterFiles(filterData);
                }
                return this.message({
                    action: 'searchAndFilterFiles',
                    success: true,
                    data: {
                        filterApplied: !!filterData,
                        matchCount: 0,
                        files: []
                    },
                    message: filterData ? 'Filter applied successfully' : 'Filter cleared'
                });
            }
            catch (error) {
                return this.error("Failed to filter files: " + error.message);
            }
        };
        /**
         * Tool Handler: Control UI elements
         *
         * @param {ControlUserInterfaceArgs} args - The arguments for the UI control operation
         * @returns {WebMcpToolResponse} The response with operation result
         */
        WebMcpAdapter.prototype.handleUserInterface = function (args) {
            try {
                var action = args.action, items = args.items;
                switch (action) {
                    case 'enableMenu':
                        if (items && Array.isArray(items)) {
                            if (items.length === 0) {
                                return this.error('enableMenu requires at least one item');
                            }
                            this.parent.enableMenuItems(items);
                            return this.message({
                                action: 'manageUserInterface',
                                success: true,
                                data: { action: 'enableMenu', itemsAffected: items.length, items: items },
                                message: "Enabled " + items.length + " menu item(s)"
                            });
                        }
                        return this.error('enableMenu requires items array');
                    case 'disableMenu':
                        if (items && Array.isArray(items)) {
                            if (items.length === 0) {
                                return this.error('disableMenu requires at least one item');
                            }
                            this.parent.disableMenuItems(items);
                            return this.message({
                                action: 'manageUserInterface',
                                success: true,
                                data: { action: 'disableMenu', itemsAffected: items.length, items: items },
                                message: "Disabled " + items.length + " menu item(s)"
                            });
                        }
                        return this.error('disableMenu requires items array');
                    case 'enableToolbar':
                        if (items && Array.isArray(items)) {
                            if (items.length === 0) {
                                return this.error('enableToolbar requires at least one item');
                            }
                            this.parent.enableToolbarItems(items);
                            return this.message({
                                action: 'manageUserInterface',
                                success: true,
                                data: { action: 'enableToolbar', itemsAffected: items.length, items: items },
                                message: "Enabled " + items.length + " toolbar item(s)"
                            });
                        }
                        return this.error('enableToolbar requires items array');
                    case 'disableToolbar':
                        if (items && Array.isArray(items)) {
                            if (items.length === 0) {
                                return this.error('disableToolbar requires at least one item');
                            }
                            this.parent.disableToolbarItems(items);
                            return this.message({
                                action: 'manageUserInterface',
                                success: true,
                                data: { action: 'disableToolbar', itemsAffected: items.length, items: items },
                                message: "Disabled " + items.length + " toolbar item(s)"
                            });
                        }
                        return this.error('disableToolbar requires items array');
                    case 'closeDialog':
                        this.parent.closeDialog();
                        return this.message({
                            action: 'manageUserInterface',
                            success: true,
                            data: { action: 'closeDialog' },
                            message: 'Dialog closed'
                        });
                    case 'refreshLayout':
                        this.parent.refreshLayout();
                        return this.message({
                            action: 'manageUserInterface',
                            success: true,
                            data: { action: 'refreshLayout' },
                            message: 'Layout refreshed'
                        });
                    default:
                        return this.error("Unknown action \"" + action + "\" for manageUserInterface");
                }
            }
            catch (error) {
                return this.error("Failed to control UI: " + error.message);
            }
        };
        /**
         * Tool Handler: Select files in batch
         *
         * @param {SelectFilesInBatchArgs} args - The arguments for the batch selection operation
         * @returns {WebMcpToolResponse} The response with operation result
         */
        WebMcpAdapter.prototype.handleSelection = function (args) {
            try {
                var action = args.action;
                switch (action) {
                    case 'selectAll': {
                        this.parent.selectAll();
                        var selectedFiles = this.parent.getSelectedFiles() || [];
                        if (selectedFiles.length === 0) {
                            return this.message({
                                action: 'manageSelection',
                                success: false,
                                data: { action: 'selectAll', filesSelected: 0 },
                                message: 'Selection did not update. No items were selected.'
                            });
                        }
                        return this.message({
                            action: 'manageSelection',
                            success: true,
                            data: { action: 'selectAll', filesSelected: selectedFiles.length },
                            message: "Selected all " + selectedFiles.length + " file(s)"
                        });
                    }
                    case 'clearSelection': {
                        this.parent.clearSelection();
                        var selectedFiles = this.parent.getSelectedFiles() || [];
                        if (selectedFiles.length !== 0) {
                            return this.message({
                                action: 'manageSelection',
                                success: false,
                                data: { action: 'clearSelection', filesSelected: selectedFiles.length },
                                message: 'Selection was not cleared.'
                            });
                        }
                        return this.message({
                            action: 'manageSelection',
                            success: true,
                            data: { action: 'clearSelection', filesSelected: 0 },
                            message: 'Selection cleared'
                        });
                    }
                    default:
                        return this.error("Unknown action \"" + action + "\" for manageSelection");
                }
            }
            catch (error) {
                return this.error("Failed to manage file selection: " + error.message);
            }
        };
        /**
         * Removes event listeners and cleanup.
         *
         * @returns {void} Nothing returned
         */
        WebMcpAdapter.prototype.destroy = function () {
            this.removeEventListener();
            if (this.webMcpAbortController) {
                this.webMcpAbortController.abort();
                this.webMcpAbortController = null;
            }
            this.parent = null;
        };
        /**
         * Returns module name for identification.
         *
         * @returns {string} The module name
         */
        WebMcpAdapter.prototype.getModuleName = function () {
            return 'webmcpadapter';
        };
        WebMcpAdapter.prototype.getCurrentItems = function () {
            var fileSystemItems = (this.parent.fileSystemData && Array.isArray(this.parent.fileSystemData)
                && this.parent.fileSystemData.length > 0)
                ? this.parent.fileSystemData.slice() : (this.parent.itemData || []);
            var items = fileSystemItems;
            return Array.isArray(items) ? items.slice() : [];
        };
        WebMcpAdapter.prototype.itemExistsById = function (idValue, items) {
            if (items === void 0) { items = this.getCurrentItems(); }
            return items.some(function (item) { return String(item.id) === String(idValue) || String(item.name) === String(idValue); });
        };
        WebMcpAdapter.prototype.itemNameExists = function (name, shouldValidateCurrentFolder, idToExclude) {
            var normalizedName = (name || '').trim().toLowerCase();
            if (!normalizedName) {
                return false;
            }
            var items = this.getCurrentItems();
            return items.some(function (item) {
                var itemName = (item && item.name) ? String(item.name).trim().toLowerCase() : '';
                if (shouldValidateCurrentFolder) {
                    return itemName === normalizedName;
                }
                var sameItemId = String(item.id) !== String(idToExclude);
                return itemName === normalizedName && sameItemId;
            });
        };
        WebMcpAdapter.prototype.findItemById = function (idValue) {
            return this.getCurrentItems().find(function (item) {
                return String(item.id) === String(idValue) || String(item.name) === String(idValue);
            });
        };
        WebMcpAdapter.prototype.waitForOperation = function (action, timeoutMs, targetName, targetIds) {
            if (timeoutMs === void 0) { timeoutMs = 2500; }
            return __awaiter(this, void 0, void 0, function () {
                var startTime, _loop_1, this_1, state_1;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            startTime = Date.now();
                            _loop_1 = function () {
                                var currentItems, createdItemName, renamedItemName, renameMatched, remainingIds;
                                return __generator(this, function (_a) {
                                    switch (_a.label) {
                                        case 0:
                                            currentItems = this_1.getCurrentItems();
                                            if (action === 'download') {
                                                return [2 /*return*/, { value: { success: true, message: 'Download request initiated.' } }];
                                            }
                                            if (action === 'create' && targetName) {
                                                createdItemName = this_1.parent.createdItem && this_1.parent.createdItem.name ?
                                                    String(this_1.parent.createdItem.name).trim().toLowerCase() : '';
                                                if (this_1.itemNameExists(targetName, true) || createdItemName === targetName.trim().toLowerCase()) {
                                                    return [2 /*return*/, { value: { success: true, message: "Folder \"" + targetName + "\" exists." } }];
                                                }
                                            }
                                            if (action === 'rename' && targetName) {
                                                renamedItemName = this_1.parent.renamedItem && this_1.parent.renamedItem.name ?
                                                    String(this_1.parent.renamedItem.name).trim().toLowerCase() : '';
                                                renameMatched = currentItems.some(function (item) {
                                                    var itemName = item.name ? String(item.name).trim().toLowerCase() : '';
                                                    return itemName === targetName.trim().toLowerCase();
                                                });
                                                if (renameMatched || renamedItemName === targetName.trim().toLowerCase()) {
                                                    return [2 /*return*/, { value: { success: true, message: "Item renamed to \"" + targetName + "\"." } }];
                                                }
                                            }
                                            if (action === 'delete' && targetIds && targetIds.length > 0) {
                                                remainingIds = targetIds.filter(function (idValue) { return _this.itemExistsById(idValue, currentItems); });
                                                if (remainingIds.length === 0) {
                                                    return [2 /*return*/, { value: { success: true, message: 'Delete operation completed.' } }];
                                                }
                                            }
                                            return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 50); })];
                                        case 1:
                                            _a.sent();
                                            return [2 /*return*/];
                                    }
                                });
                            };
                            this_1 = this;
                            _a.label = 1;
                        case 1:
                            if (!(Date.now() - startTime < timeoutMs)) return [3 /*break*/, 3];
                            return [5 /*yield**/, _loop_1()];
                        case 2:
                            state_1 = _a.sent();
                            if (typeof state_1 === "object")
                                return [2 /*return*/, state_1.value];
                            return [3 /*break*/, 1];
                        case 3: return [2 /*return*/, {
                                success: false,
                                message: "The " + action + " operation did not complete in time."
                            }];
                    }
                });
            });
        };
        /**
         * Formats successful response in WebMCP standard format.
         *
         * @param {Record<string, string | number | boolean | object | null>} data - The data to format
         * @returns {WebMcpToolResponse} The formatted response
         */
        WebMcpAdapter.prototype.message = function (data) {
            return { content: [{ type: 'text', text: JSON.stringify(data) }] };
        };
        /**
         * Formats error response in WebMCP standard format.
         *
         * @param {string} text - The error text
         * @returns {WebMcpToolResponse} The formatted error response
         */
        WebMcpAdapter.prototype.error = function (text) {
            return { content: [{ type: 'text', text: text }], isError: true };
        };
        return WebMcpAdapter;
    }());
    exports.WebMcpAdapter = WebMcpAdapter;
});