From 167eb9ac9ce88f45a4d74c1de78768da9309b709 Mon Sep 17 00:00:00 2001 From: windyboy Date: Wed, 4 Feb 2026 13:41:36 +0800 Subject: [PATCH 1/3] vault backup: 2026-02-04 13:41:36 --- .claude/claudian-settings.json | 77 + .claude/settings.json | 79 +- .failed_images.txt | 41 + .obsidian/community-plugins.json | 3 +- .obsidian/plugins/advanced-canvas/main.js | 152 +- .../plugins/advanced-canvas/manifest.json | 2 +- .obsidian/plugins/advanced-canvas/styles.css | 8 +- .obsidian/plugins/claudian/main.js | 83119 +++++++++++----- .obsidian/plugins/claudian/styles.css | 2581 +- .obsidian/plugins/note-buddy/main.js | 595 +- .../obsidian-excalidraw-plugin/data.json | 2 +- .../obsidian-excalidraw-plugin/main.js | 4 +- .../obsidian-excalidraw-plugin/manifest.json | 2 +- .../obsidian-excalidraw-plugin/styles.css | 2 +- .obsidian/plugins/quickadd/data.json | 57 +- 00_Inbox/2026-01-30.md | 26 + ...nana pro(Nano banana 2) AI image model..md | 142 +- ... built and used in production by Google.md | 151 + 03_Resources/Network/Wireguard/mac-config.md | 0 .../Network/Wireguard/server-config.md | 27 + .../CIIMS Configuration.md | 0 .../Chengdu/Maintenance.md | 0 .../Chengdu/MsgExchangeApi patch.md | 0 .../Chengdu/Office Test Env.md | 10 +- .../Chengdu/Single Node Server for Test.md | 0 .../{Airport-CIIMS => Airport}/Dev Env.md | 0 .../Guangzhou/New Telegram-MacBook Pro.md | 0 .../Guangzhou/New Telegram.md | 0 .../Guangzhou/Telegram Parse.md | 0 .../Guangzhou/meilisearch.md | 0 .../{Airport-CIIMS => Airport}/Maintenance.md | 0 .../Micronaut XML.md | 0 .../POC/Telegram.md | 0 .../Refactor/CIIMS/proxy.md | 0 .../Requirement/Message Distributor.md | 0 .../oracle/docker can't run.md | 0 .../oracle/files.md | 0 .../oracle/oracheck.md | 0 05_Attachments/nanobanana-pro/README.md | 47 + .../nanobanana-pro/nanobanana-pro-001.png | 0 .../nanobanana-pro/nanobanana-pro-002.png | 0 .../nanobanana-pro/nanobanana-pro-003.jpg | 0 .../nanobanana-pro/nanobanana-pro-004.jpg | 0 .../nanobanana-pro/nanobanana-pro-005.jpg | 0 .../nanobanana-pro/nanobanana-pro-006.png | 0 .../nanobanana-pro/nanobanana-pro-007.png | 0 .../nanobanana-pro/nanobanana-pro-008.png | 0 .../nanobanana-pro/nanobanana-pro-009.png | 0 .../nanobanana-pro/nanobanana-pro-010.png | Bin 0 -> 68416 bytes .../nanobanana-pro/nanobanana-pro-011.png | Bin 0 -> 68416 bytes .../nanobanana-pro/nanobanana-pro-012.png | 0 .../nanobanana-pro/nanobanana-pro-013.jpg | 0 .../nanobanana-pro/nanobanana-pro-014.png | 0 .../nanobanana-pro/nanobanana-pro-015.png | 0 .../nanobanana-pro/nanobanana-pro-016.png | 0 .../nanobanana-pro/nanobanana-pro-017.png | 0 .../nanobanana-pro/nanobanana-pro-018.png | Bin 0 -> 696602 bytes .../nanobanana-pro/nanobanana-pro-019.png | Bin 0 -> 696602 bytes .../nanobanana-pro/nanobanana-pro-020.png | Bin 0 -> 923878 bytes .../nanobanana-pro/nanobanana-pro-021.png | Bin 0 -> 923878 bytes .../nanobanana-pro/nanobanana-pro-022.png | Bin 0 -> 475129 bytes .../nanobanana-pro/nanobanana-pro-023.png | Bin 0 -> 475129 bytes .../nanobanana-pro/nanobanana-pro-024.png | Bin 0 -> 396760 bytes .../nanobanana-pro/nanobanana-pro-025.png | Bin 0 -> 396760 bytes .../nanobanana-pro/nanobanana-pro-026.png | Bin 0 -> 812426 bytes .../nanobanana-pro/nanobanana-pro-027.png | Bin 0 -> 812426 bytes .../nanobanana-pro/nanobanana-pro-028.png | 0 .../nanobanana-pro/nanobanana-pro-029.png | 0 .../nanobanana-pro/nanobanana-pro-030.png | 0 .../nanobanana-pro/nanobanana-pro-031.png | 0 .../nanobanana-pro/nanobanana-pro-032.png | 0 .../nanobanana-pro/nanobanana-pro-033.png | 0 .../nanobanana-pro/nanobanana-pro-034.png | 0 .../nanobanana-pro/nanobanana-pro-035.png | Bin 0 -> 137855 bytes .../nanobanana-pro/nanobanana-pro-036.png | Bin 0 -> 137855 bytes .../nanobanana-pro/nanobanana-pro-037.png | 0 .../nanobanana-pro/nanobanana-pro-038.png | 0 .../nanobanana-pro/nanobanana-pro-039.png | 0 .../nanobanana-pro/nanobanana-pro-040.png | 0 .../nanobanana-pro/nanobanana-pro-041.png | 0 .../nanobanana-pro/nanobanana-pro-042.png | 0 .../nanobanana-pro/nanobanana-pro-043.png | 0 .../nanobanana-pro/nanobanana-pro-044.png | 0 .../nanobanana-pro/nanobanana-pro-045.png | 0 .../nanobanana-pro/nanobanana-pro-046.png | 0 .../nanobanana-pro/nanobanana-pro-047.png | 0 .../nanobanana-pro/nanobanana-pro-048.png | 0 .../nanobanana-pro/nanobanana-pro-049.png | 0 .../nanobanana-pro/nanobanana-pro-050.png | 0 .../nanobanana-pro/nanobanana-pro-051.png | 0 .../nanobanana-pro/nanobanana-pro-052.png | 0 .../nanobanana-pro/nanobanana-pro-053.png | 0 .../nanobanana-pro/nanobanana-pro-054.png | 0 .../nanobanana-pro/nanobanana-pro-055.jpg | Bin 0 -> 28193 bytes .../nanobanana-pro/nanobanana-pro-056.jpg | Bin 0 -> 514711 bytes .../nanobanana-pro/nanobanana-pro-057.jpg | Bin 0 -> 181029 bytes .../nanobanana-pro/nanobanana-pro-058.jpg | Bin 0 -> 191740 bytes .../nanobanana-pro/nanobanana-pro-059.jpg | Bin 0 -> 292303 bytes .../nanobanana-pro/nanobanana-pro-060.jpg | Bin 0 -> 44284 bytes .../nanobanana-pro/nanobanana-pro-061.jpg | Bin 0 -> 70338 bytes .../nanobanana-pro/nanobanana-pro-062.jpg | Bin 0 -> 243268 bytes .../nanobanana-pro/nanobanana-pro-063.jpg | Bin 0 -> 187395 bytes .../nanobanana-pro/nanobanana-pro-064.jpg | Bin 0 -> 170953 bytes .../nanobanana-pro/nanobanana-pro-065.jpg | Bin 0 -> 156230 bytes .../nanobanana-pro/nanobanana-pro-066.jpg | Bin 0 -> 338926 bytes .../nanobanana-pro/nanobanana-pro-067.jpg | Bin 0 -> 133111 bytes .../nanobanana-pro/nanobanana-pro-068.jpg | Bin 0 -> 48582 bytes .../nanobanana-pro/nanobanana-pro-069.jpg | Bin 0 -> 269473 bytes .../nanobanana-pro/nanobanana-pro-070.jpg | Bin 0 -> 70410 bytes .../nanobanana-pro/nanobanana-pro-071.jpg | Bin 0 -> 129008 bytes .../nanobanana-pro/nanobanana-pro-072.jpg | Bin 0 -> 82806 bytes .../nanobanana-pro/nanobanana-pro-073.jpg | Bin 0 -> 42325 bytes .../nanobanana-pro/nanobanana-pro-074.jpg | Bin 0 -> 157688 bytes .../nanobanana-pro/nanobanana-pro-075.jpg | Bin 0 -> 31640 bytes .../nanobanana-pro/nanobanana-pro-076.jpg | Bin 0 -> 398841 bytes .../nanobanana-pro/nanobanana-pro-077.jpg | Bin 0 -> 113298 bytes .../nanobanana-pro/nanobanana-pro-078.jpg | Bin 0 -> 320245 bytes .../nanobanana-pro/nanobanana-pro-079.jpg | Bin 0 -> 108744 bytes .../nanobanana-pro/nanobanana-pro-080.jpg | Bin 0 -> 98952 bytes .../nanobanana-pro/nanobanana-pro-081.jpg | Bin 0 -> 634505 bytes .../nanobanana-pro/nanobanana-pro-082.jpg | Bin 0 -> 112737 bytes .../nanobanana-pro/nanobanana-pro-083.jpg | Bin 0 -> 186774 bytes .../nanobanana-pro/nanobanana-pro-084.jpg | Bin 0 -> 167955 bytes .../nanobanana-pro/nanobanana-pro-085.jpg | 1 + .../nanobanana-pro/nanobanana-pro-086.jpg | Bin 0 -> 73243 bytes .../nanobanana-pro/nanobanana-pro-087.jpg | Bin 0 -> 94778 bytes .../nanobanana-pro/nanobanana-pro-088.jpg | 1 + .../nanobanana-pro/nanobanana-pro-089.jpg | Bin 0 -> 125653 bytes .../nanobanana-pro/nanobanana-pro-090.jpg | Bin 0 -> 593082 bytes .../nanobanana-pro/nanobanana-pro-091.jpg | Bin 0 -> 128584 bytes .../nanobanana-pro/nanobanana-pro-092.jpg | Bin 0 -> 96644 bytes .../nanobanana-pro/nanobanana-pro-093.jpg | Bin 0 -> 77872 bytes 06_Metadata/Reference/DAILY_NOTE_GUIDE.md | 13 +- 06_Metadata/Templates/Daily Note Template.md | 14 +- 134 files changed, 57854 insertions(+), 29302 deletions(-) create mode 100644 .claude/claudian-settings.json create mode 100644 .failed_images.txt create mode 100644 00_Inbox/2026-01-30.md create mode 100644 00_Inbox/Clippings/2026/01/firebasegenkit Open-source framework for building AI-powered apps in JavaScript, Go, and Python, built and used in production by Google.md create mode 100644 03_Resources/Network/Wireguard/mac-config.md create mode 100644 03_Resources/Network/Wireguard/server-config.md rename 04_Archive/Projects/{Airport-CIIMS => Airport}/CIIMS Configuration.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Chengdu/Maintenance.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Chengdu/MsgExchangeApi patch.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Chengdu/Office Test Env.md (87%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Chengdu/Single Node Server for Test.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Dev Env.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Guangzhou/New Telegram-MacBook Pro.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Guangzhou/New Telegram.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Guangzhou/Telegram Parse.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Guangzhou/meilisearch.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Maintenance.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Micronaut XML.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/POC/Telegram.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Refactor/CIIMS/proxy.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/Refactor/Requirement/Message Distributor.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/oracle/docker can't run.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/oracle/files.md (100%) rename 04_Archive/Projects/{Airport-CIIMS => Airport}/oracle/oracheck.md (100%) create mode 100644 05_Attachments/nanobanana-pro/README.md create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-001.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-002.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-003.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-004.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-005.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-006.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-007.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-008.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-009.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-010.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-011.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-012.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-013.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-014.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-015.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-016.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-017.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-018.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-019.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-020.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-021.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-022.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-023.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-024.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-025.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-026.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-027.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-028.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-029.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-030.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-031.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-032.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-033.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-034.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-035.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-036.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-037.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-038.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-039.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-040.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-041.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-042.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-043.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-044.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-045.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-046.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-047.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-048.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-049.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-050.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-051.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-052.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-053.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-054.png create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-055.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-056.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-057.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-058.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-059.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-060.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-061.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-062.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-063.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-064.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-065.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-066.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-067.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-068.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-069.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-070.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-071.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-072.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-073.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-074.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-075.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-076.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-077.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-078.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-079.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-080.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-081.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-082.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-083.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-084.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-085.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-086.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-087.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-088.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-089.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-090.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-091.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-092.jpg create mode 100644 05_Attachments/nanobanana-pro/nanobanana-pro-093.jpg diff --git a/.claude/claudian-settings.json b/.claude/claudian-settings.json new file mode 100644 index 0000000..955017e --- /dev/null +++ b/.claude/claudian-settings.json @@ -0,0 +1,77 @@ +{ + "userName": "windy", + "enableBlocklist": true, + "blockedCommands": { + "unix": [ + "rm -rf", + "chmod 777", + "chmod -R 777" + ], + "windows": [ + "del /s /q", + "rd /s /q", + "rmdir /s /q", + "format", + "diskpart", + "Remove-Item -Recurse -Force", + "Remove-Item -Force -Recurse", + "Remove-Item -r -fo", + "Remove-Item -fo -r", + "Remove-Item -Recurse", + "Remove-Item -r", + "ri -Recurse", + "ri -r", + "ri -Force", + "ri -fo", + "rm -r -fo", + "rm -Recurse", + "rm -Force", + "del -Recurse", + "del -Force", + "erase -Recurse", + "erase -Force", + "rd -Recurse", + "rmdir -Recurse", + "Format-Volume", + "Clear-Disk", + "Initialize-Disk", + "Remove-Partition" + ] + }, + "permissionMode": "normal", + "model": "sonnet", + "thinkingBudget": "low", + "enableAutoTitleGeneration": true, + "titleGenerationModel": "", + "show1MModel": false, + "enableChrome": false, + "excludedTags": [], + "mediaFolder": "05_Attachments", + "systemPrompt": "", + "allowedExportPaths": [ + "~/Downloads" + ], + "persistentExternalContextPaths": [], + "environmentVariables": "", + "envSnippets": [], + "customContextLimits": {}, + "keyboardNavigation": { + "scrollUpKey": "w", + "scrollDownKey": "s", + "focusInputKey": "i" + }, + "locale": "en", + "claudeCliPath": "", + "claudeCliPathsByHost": { + "MacBook-Pro.local": "/Users/windy/.local/bin/claude" + }, + "loadUserClaudeSettings": true, + "lastClaudeModel": "haiku", + "lastCustomModel": "", + "lastEnvHash": "", + "maxTabs": 3, + "tabBarPosition": "input", + "enableAutoScroll": true, + "openInMainTab": false, + "hiddenSlashCommands": [] +} \ No newline at end of file diff --git a/.claude/settings.json b/.claude/settings.json index eb3dd18..7222d25 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,63 +1,20 @@ { - "userName": "windy", - "enableBlocklist": true, - "blockedCommands": { - "unix": [ - "rm -rf", - "chmod 777", - "chmod -R 777" + "$schema": "https://json.schemastore.org/claude-code-settings.json", + "permissions": { + "allow": [ + "Bash(npm run | grep daily-note)", + "Edit(06_Metadata/Templates/Daily Note Template.md)", + "Edit(06_Metadata/Reference/DAILY_NOTE_GUIDE.md)", + "Edit(.obsidian/plugins/quickadd/data.json)", + "Edit(04_Archive/Projects/Airport/Chengdu/Office Test Env.md)", + "Bash(wc:*)", + "Bash(cat > .replace_urls.py << 'PYEOF'\n#!/usr/bin/env python3\nimport re\n\n# Read the mapping\nmappings = []\nwith open\\('.url_mapping.txt', 'r'\\) as f:\n for line in f:\n if '|' in line:\n url, filename = line.strip\\(\\).split\\('|', 1\\)\n mappings.append\\(\\(url, filename\\)\\)\n\n# Read the markdown file\nnote_path = \"00_Inbox/Clippings/2026/01/ZeroLuawesome-nanobanana-pro 🚀 An awesome list of curated Nano Banana pro prompts and examples. Your go-to resource for mastering prompt engineering and exploring the creative potential of the Nano banana pro\\(Nano banana 2\\) AI image model..md\"\n\nwith open\\(note_path, 'r', encoding='utf-8'\\) as f:\n content = f.read\\(\\)\n\n# Perform replacements\nreplacements_made = 0\nfor url, filename in mappings:\n # Escape special regex characters in URL\n escaped_url = re.escape\\(url\\)\n # Replace markdown image syntax: ![alt]\\(url\\) -> ![[path/filename]]\n pattern = r'!\\\\[\\([^\\\\]]*\\)\\\\]\\\\\\(' + escaped_url + r'\\\\\\)'\n replacement = f'![[05_Attachments/nanobanana-pro/{filename}]]'\n new_content, count = re.subn\\(pattern, replacement, content\\)\n if count > 0:\n content = new_content\n replacements_made += count\n print\\(f\"✓ Replaced {count}x: {filename}\"\\)\n\n# Write back\nwith open\\(note_path, 'w', encoding='utf-8'\\) as f:\n f.write\\(content\\)\n\nprint\\(f\"\\\\nTotal replacements: {replacements_made}\"\\)\nPYEOF\npython3 .replace_urls.py)", + "Bash(cat > .fix_links.py << 'PYEOF'\n#!/usr/bin/env python3\nimport re\n\nnote_path = \"00_Inbox/Clippings/2026/01/ZeroLuawesome-nanobanana-pro 🚀 An awesome list of curated Nano Banana pro prompts and examples. Your go-to resource for mastering prompt engineering and exploring the creative potential of the Nano banana pro\\(Nano banana 2\\) AI image model..md\"\n\nwith open\\(note_path, 'r', encoding='utf-8'\\) as f:\n content = f.read\\(\\)\n\n# Pattern: [![[wikilink]]]\\(url\\) -> ![[wikilink]]\n# Remove the clickable link wrapper around wikilinks\npattern = r'\\\\[\\(!!\\\\[\\\\[05_Attachments/nanobanana-pro/[^\\\\]]+\\\\]\\\\]\\)\\\\]\\\\\\([^\\)]+\\\\\\)'\nreplacement = r'\\\\1'\nnew_content, count = re.subn\\(pattern, replacement, content\\)\n\nprint\\(f\"Fixed {count} clickable link wrappers\"\\)\n\nwith open\\(note_path, 'w', encoding='utf-8'\\) as f:\n f.write\\(new_content\\)\nPYEOF\npython3 .fix_links.py)", + "Bash(ls -lh 05_Attachments/nanobanana-pro/ | awk '{if \\($5 ~ /^[0-9]+$/ && $5 < 1024\\) print $9, $5}' | head -20)", + "Bash(find:*)", + "Bash(find 05_Attachments/nanobanana-pro/ -type f \\\\\\( -size 0 -o -size -100c \\\\\\) | sort > .failed_images.txt && head -10 .failed_images.txt)" ], - "windows": [ - "del /s /q", - "rd /s /q", - "rmdir /s /q", - "format", - "diskpart", - "Remove-Item -Recurse -Force", - "Remove-Item -Force -Recurse", - "Remove-Item -r -fo", - "Remove-Item -fo -r", - "Remove-Item -Recurse", - "Remove-Item -r", - "ri -Recurse", - "ri -r", - "ri -Force", - "ri -fo", - "rm -r -fo", - "rm -Recurse", - "rm -Force", - "del -Recurse", - "del -Force", - "erase -Recurse", - "erase -Force", - "rd -Recurse", - "rmdir -Recurse", - "Format-Volume", - "Clear-Disk", - "Initialize-Disk", - "Remove-Partition" - ] - }, - "model": "haiku", - "enableAutoTitleGeneration": true, - "titleGenerationModel": "", - "thinkingBudget": "off", - "permissionMode": "normal", - "lastNonPlanPermissionMode": "normal", - "permissions": [], - "excludedTags": [], - "mediaFolder": "05_Attachments", - "environmentVariables": "", - "envSnippets": [], - "systemPrompt": "", - "allowedExportPaths": [ - "~/Downloads" - ], - "allowedContextPaths": [], - "keyboardNavigation": { - "scrollUpKey": "w", - "scrollDownKey": "s", - "focusInputKey": "i" - }, - "claudeCliPath": "/Users/windy/.local/bin/claude" -} \ No newline at end of file + "deny": [], + "ask": [] + } +} diff --git a/.failed_images.txt b/.failed_images.txt new file mode 100644 index 0000000..b58e521 --- /dev/null +++ b/.failed_images.txt @@ -0,0 +1,41 @@ +05_Attachments/nanobanana-pro/nanobanana-pro-001.png +05_Attachments/nanobanana-pro/nanobanana-pro-002.png +05_Attachments/nanobanana-pro/nanobanana-pro-003.jpg +05_Attachments/nanobanana-pro/nanobanana-pro-004.jpg +05_Attachments/nanobanana-pro/nanobanana-pro-005.jpg +05_Attachments/nanobanana-pro/nanobanana-pro-006.png +05_Attachments/nanobanana-pro/nanobanana-pro-007.png +05_Attachments/nanobanana-pro/nanobanana-pro-008.png +05_Attachments/nanobanana-pro/nanobanana-pro-009.png +05_Attachments/nanobanana-pro/nanobanana-pro-012.png +05_Attachments/nanobanana-pro/nanobanana-pro-013.jpg +05_Attachments/nanobanana-pro/nanobanana-pro-014.png +05_Attachments/nanobanana-pro/nanobanana-pro-015.png +05_Attachments/nanobanana-pro/nanobanana-pro-016.png +05_Attachments/nanobanana-pro/nanobanana-pro-017.png +05_Attachments/nanobanana-pro/nanobanana-pro-028.png +05_Attachments/nanobanana-pro/nanobanana-pro-029.png +05_Attachments/nanobanana-pro/nanobanana-pro-030.png +05_Attachments/nanobanana-pro/nanobanana-pro-031.png +05_Attachments/nanobanana-pro/nanobanana-pro-032.png +05_Attachments/nanobanana-pro/nanobanana-pro-033.png +05_Attachments/nanobanana-pro/nanobanana-pro-034.png +05_Attachments/nanobanana-pro/nanobanana-pro-037.png +05_Attachments/nanobanana-pro/nanobanana-pro-038.png +05_Attachments/nanobanana-pro/nanobanana-pro-039.png +05_Attachments/nanobanana-pro/nanobanana-pro-040.png +05_Attachments/nanobanana-pro/nanobanana-pro-041.png +05_Attachments/nanobanana-pro/nanobanana-pro-042.png +05_Attachments/nanobanana-pro/nanobanana-pro-043.png +05_Attachments/nanobanana-pro/nanobanana-pro-044.png +05_Attachments/nanobanana-pro/nanobanana-pro-045.png +05_Attachments/nanobanana-pro/nanobanana-pro-046.png +05_Attachments/nanobanana-pro/nanobanana-pro-047.png +05_Attachments/nanobanana-pro/nanobanana-pro-048.png +05_Attachments/nanobanana-pro/nanobanana-pro-049.png +05_Attachments/nanobanana-pro/nanobanana-pro-050.png +05_Attachments/nanobanana-pro/nanobanana-pro-051.png +05_Attachments/nanobanana-pro/nanobanana-pro-052.png +05_Attachments/nanobanana-pro/nanobanana-pro-053.png +05_Attachments/nanobanana-pro/nanobanana-pro-054.png +05_Attachments/nanobanana-pro/nanobanana-pro-085.jpg diff --git a/.obsidian/community-plugins.json b/.obsidian/community-plugins.json index 28644d0..c32391d 100644 --- a/.obsidian/community-plugins.json +++ b/.obsidian/community-plugins.json @@ -24,6 +24,5 @@ "obsidian-opencode", "opencode-obsidian", "highlightr-plugin", - "code-styler", - "note-buddy" + "code-styler" ] \ No newline at end of file diff --git a/.obsidian/plugins/advanced-canvas/main.js b/.obsidian/plugins/advanced-canvas/main.js index 1110599..049d1a5 100644 --- a/.obsidian/plugins/advanced-canvas/main.js +++ b/.obsidian/plugins/advanced-canvas/main.js @@ -197,7 +197,7 @@ var BBoxHelper = class { let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity; - for (let bbox of bboxes) { + for (const bbox of bboxes) { minX = Math.min(minX, bbox.minX); minY = Math.min(minY, bbox.minY); maxX = Math.max(maxX, bbox.maxX); @@ -206,8 +206,8 @@ var BBoxHelper = class { return { minX, minY, maxX, maxY }; } static scaleBBox(bbox, scale) { - let diffX = (scale - 1) * (bbox.maxX - bbox.minX); - let diffY = (scale - 1) * (bbox.maxY - bbox.minY); + const diffX = (scale - 1) * (bbox.maxX - bbox.minX); + const diffY = (scale - 1) * (bbox.maxY - bbox.minY); return { minX: bbox.minX - diffX / 2, maxX: bbox.maxX + diffX / 2, @@ -428,6 +428,10 @@ var _CanvasHelper = class _CanvasHelper { var _a; for (const stylableAttribute of stylableAttributes) { const selectedStyle = (_a = stylableAttribute.options.find((option) => currentStyleAttributes[stylableAttribute.key] === option.value)) != null ? _a : stylableAttribute.options.find((value) => value.value === null); + if (!selectedStyle) { + console.warn(`No "null" style option found for stylable attribute "${stylableAttribute.key}"`); + continue; + } const menuOption = _CanvasHelper.createExpandablePopupMenuOption({ id: `menu-option-${stylableAttribute.key}`, label: stylableAttribute.label, @@ -486,6 +490,7 @@ var _CanvasHelper = class _CanvasHelper { const iconElement = document.createElement("div"); iconElement.classList.add("menu-item-icon"); let selectedStyle = (_c = stylableAttribute.options.find((option) => currentStyleAttributes[stylableAttribute.key] === option.value)) != null ? _c : stylableAttribute.options.find((value) => value.value === null); + if (!selectedStyle) continue; (0, import_obsidian2.setIcon)(iconElement, selectedStyle.icon); stylableAttributeElement.appendChild(iconElement); const labelElement = document.createElement("div"); @@ -783,7 +788,7 @@ var EdgePathfindingAStar = class extends EdgePathfindingMethod { const fromPosWithMargin = BBoxHelper.moveInDirection(this.fromPos, this.fromSide, 10); const toPosWithMargin = BBoxHelper.moveInDirection(this.toPos, this.toSide, 10); const allowDiagonal = this.plugin.settings.getSetting("edgeStylePathfinderAllowDiagonal"); - let pathArray = this.aStarAlgorithm(fromPosWithMargin, toPosWithMargin, nodeBBoxes, CanvasHelper.GRID_SIZE / 2, allowDiagonal); + const pathArray = this.aStarAlgorithm(fromPosWithMargin, toPosWithMargin, nodeBBoxes, CanvasHelper.GRID_SIZE / 2, allowDiagonal); if (!pathArray) return null; pathArray.splice(0, 0, this.fromPos); pathArray.splice(pathArray.length, 0, this.toPos); @@ -1652,9 +1657,9 @@ var VariableBreakpointCanvasExtension = class extends CanvasExtension { // src/settings.ts var README_URL = "https://github.com/Developer-Mike/obsidian-advanced-canvas?tab=readme-ov-file"; -var SPENT_HOURS = 200; -var RECEIVED_DONATIONS = 357; -var HOURLY_RATE_GOAL = 20; +var SPENT_HOURS = 250; +var RECEIVED_DONATIONS = 606; +var HOURLY_RATE_GOAL = 15; var KOFI_PAGE_URL = "https://ko-fi.com/X8X27IA08"; var KOFI_BADGE_URI = "data:image/webp;base64,UklGRrosAABXRUJQVlA4TK4sAAAv1wNDEL/CoJEkRXUCbvwrekfM/BYQspGkHsCNw/nbvcAzahtJkue7R/GnubUAykDaNvFv9r2CqU3bgHHKGHIH7H9DeOynEYZHCKFOj1neMfXZ0SmmUzuYgs6P2cH0fjuY11JBq5hO7ejVDqZTnWJ29Op+1twlRYq6rzLHZ6dIkSJFCnjb/mlP41jbjKzG2JjQKAiRUTrz/JCnNasnK3MmnnWm07aORtgyyHpA3/+r2BiOqvpXifW0bRH9h4ZtO9DqlUuZ7LSRz/d9JOv8Ofs/iSZZzKPZdHr9ykynsyheLEGwfD6k6WTvcCZ7h/M/ZfHNZ9ejcOBthqPJLJaMLokmw8DraK6m8fJ/tMJGk5FXbvfL/7NYgjyYXQXEg5nE/zP12uw6GPCaYBQlrD5vRzzHchX9VwTLOJpcj4bhixmOriazeIFImh44snA0mkzni1MR8SQcyJjhZMF1XCPGQwmvk/9qlDKhZ1kyjWFOVvNn0tT7yE5An2AgacIoYQjPflwjQ4IvkyRZxHE8j17MbLpvJtdSZnrARHsmfjHPR7a0rJRBp+liKvEYXp9yHslzZpc31zF1TeYkpfTksYijaPZyuhi9EKPBQJV5Ia1HL6ecaB7Hiigl8fQSXC/gi7HwBKkPitLlWPl/FsgdiZ6TSBw9VyqvhuHAGBM+n12ms7neU0t8hU7TLd8O94qWE26FowTHXomHktQH+tstF9Hs+uqZFjDQBKOraRQvDStmwgi+xhlGJ9ka9sryM+kjeYvLV/ZhQtkY3UQNdzoZs38kVwk8cXqdnJhr4l97DJBpwwTxtclwYKZRy52WSZFv4aucYXRarkmnqxlG/pmBfdyzZ22fPjCj2QIZiyH4mT8ZydGMJxEiplwlna6WVygH8hmUz6BHTHg9hwJIITBjKsckP+qr5cmDxet8he2ZAFWchwm0wMH2qgCkx3IEfuafB8IJ8MRYIHhoAtybYxYhCozqjt1Gl77IQjq1DJcce52Uiz8PDTrUIgA7joU4W9m+NWktQyDMA+wz/wzh2x+dMPhMC2kawB3Hol/j1it8mmGTdMkIhMlzsuiqahIt4S2SIuBeNCOMqN9i19XmMCXM7DTB54HlZG4iWZ/vyZUIxwLUvcHJ0yA5VYL10cJTkzyJArwF4tYSydMTIIwVopO027WvzK5LwfD6iLpUnAnLWJM8bd7u8/3DB617x69O6yepF7/AK93V22Ll7o4aty7KZiePtK0eDh9Stt7WLAfzmYjv6bSywDr6zz3ZgEBeJ8ZbLQLW3F64O5rJ1ts2FfSp1pnfwbjHlqGEwPHtN2mbaGGDVPcGr3V+dpLFv3vJ7UxmXXUiaNekQ3GPHZlX02ucSd1agUsW2zVVuS2Ksmw4ypKRTK0z3e0f2basyUeWnBKWK7Nv3R2vWdWdwBrZUFdGnJzJXjdvBTCmlzJPx0qZFZ2mm7ETIGm9XXGWVtenlU2f/Hw48j/vGsCRzHRrB6Tdntm1B0xTs5n2iOn2jSEii7f0CpsATRckrDZ9WvsmwNPn5c8Z8zr0SrplOxBXi3stxCupXde2dV2VZVEUD+v1yjmX3eGa7PmoVuv1+oXuLav6RdwBUbGOmANRM3smk+JGr5hJwil+6/+3Tk8mW++tga/sWKmQh47ihRpH2rV1VRbF2rk7E8zzGebhpXrbdjp4WiEJFe1MmlWUPzg+YMlnK+Ln7/25BydCAxOGNYA89MSAirmkdTtKOmVQrmYXI5bFwzMZYJjJVutt1e5EQkH4dfRyZt0Rjvu5HONak1nik0BeTj5ZtyuMgq2jouQ/kIrg4KhrdfX2WeRgqFk9VNwyzXAB4Fdnogku+hyjjHGpJyanghoMS0kA7llCHUcMYdP6sGaAqUG3TYqnEBZKp5bMn4ShM1dax1UX7MdNQInoE1JJuSVapGXEYvn4yla/1DIK2oT9HtkqKDshmcYj3+fceP7di97HFZGHtgJL6CnBCpna3xG27b2ZRD9Rb6jFiT4JSJZt6STQvP7y5bxm/QixDFY9l2Aqlp0cp2rH78w4wq/uTDV8KoGimiNjipXJ8XyiVgAWz+UJE3v6TAXrWLqjNWiEdLr0xpyF7dsrZl3zLGL7MOf49UFwiVoBjio8XWLYOcwkzlHgQKTTqb/AgXGtP4JvO/FlhFJlq44DjDxtPQuVXseIT3QCHVl9+DBQ3i/0FjjQ2b79ZDiivhahIxv+qlrK+m4onNt5rweC4owLck2Fs3GWcgYecogR+3rlM+pbgFTZHhm1FVYw5OKsz/2wrBxTtsaUxk8FOJMm7IX8VT/R35TuQpQBLV8cOKXKpMcRErCFTt0PHi6iM/S6IBIvZ7KH3q6WUowZUUsbuV0Aa52706KN6FuSxTbtURfTWYpxJvt7pwWv2wknN0yBbu2FixNEHb2EF/scdTGdyIMzyaAd0POeYcIqM3fyao6ACb48KaIa0yy646EKAxjJxEcRhvwx977nkJPvU0uzVjFTwPaUQKQ5f60pMnOcCuOQLDE/fuR96bnjjnzsHaO4LBQywRd+x3Fq7NOqSNjdwW0Ek3K8MLY/fhVt+eY+LZHQsv0a2N7d++HEcDunK1l3GEdRMTCgIoI1XQsdr3IdJMSkCZFUUqIFpBVPC8XV1CkhRL32hiP+IiZB4sOdeQa1ZQBXM50hXn2pItoTEW9Jb6hjE6tS7egaMW855Ii9GkXHJj1fEFzBTSrTFG+jp10YFqu4nDO/u4N94ZplnxKsr9JP+bMp9s2mPGpqX1OVPmZTvDL5nnHPBm1h6xV4DMjezMiykFMwyFv/QOqqlxmKvI7a7HeMJy/P3Kf7YlNWL72Ne/Uujtsl+u6lG/SX802euwx0uWKoNHXCKWVH11wAk5v3s6te1rR6lUlgqA6/1HRE+x4ka7i8KKtm1w2MMOmubaqyyJ3YQm+nMycQkoAvNKApb8iYC1+bZQ/EAuKHQAnuUFASMQbgTGb5pmq6gV1m12zyDCWykE5dSROShfeJHZRSvGAYm+fkehQeLVnD4ctQV+2+243Q30+ROSCjx90xOOQK00SfNvXhfS0Lytxx65pjlwCyxHG4yT3lbW+yiCZXDBeaGV5ZPGD6yAKNrw4fA7Jb89AHRZ0OTDVdfS8vPw+Wvtsw/FVYie6Kr43wMp7wDuMxGM1iUzH0TY13/YREkCbKG2t82Ppbv+eUYdNy4Rg0aXqRXA+4CW/uNTJ6saFwGt9HYt43kKaJsvII1W/t7o6pD1mqE4AKJBtUGWfNoOm4jOl3xNIHN0Mw9t6np+Dt0tfSge2mzXn6kKU5MSG09I6obXM78oVGDvj0m8fS9wNzKrFTECSW+ZDzQyEMD15whPF3/MocmNP/1qvOCfvKBeAIwsIoMS40govDOO2gIxKkibJmYKmR7XymJTkhKkO38JL84Lb8xxzDo23BR55YacOro0XWhxnSYnY94ctxVWUhr4DwfTkArI8BpnFu56/as5yFiMP9Mbbz01Zda6bDlQ5obYjI1+XqJagHd9oSlN0i2LS54mwXIK8EsHw9hMfeXJnZ0FByffBwsbUhRvzl3dPAToPRrejOv53opR82CHDH1VaB976AHphnGNkpNO/UditQAbNrphSaqKbbfvF0IupuC99YHQQ81SpBe7gO0AffZuX2ozo0B6odwNoQlO2cZHvIpPcSu0yPSy+QhCaQnKRC67D6FjZuO3XoXqf2DFgbgrC9I+3RT2Yj4AQzP1QYgGx03ykeS7oxe8vHjEax57CvDCgaAo+kq0P3lCkFnABYD/IwgxgqtFbPmX3KMLk6VIcKH+z+jeeeyGgFTl+tguTGOwwgtllslQ+13Q7MfUNr3D6wibo9ISjD1H0XiJ9t0/KhBQEgI2mlfiScduiky25jkmz3CCIbQsihHx4Y/v5eimyFcN3cDRYqqB76tJuRFZ6hDduNTPHDXbwn/iKHlJIwe810GfOF7oETZybYM4thpUA4NwELG7YdVjp1HfcrDcHtOVPLyxRTrCS3hrsm7AkQKhLdhk0DrbxLeGXiWcXtV5ennrXW9YqD61f6Xvz+NvaH2rpevR7S7l6HmKnFocYm6K4WQoQlpXjnlpq7vnVZGKMtHVDngBUcXdrJfQttVawy0l02VG1q69sO/ZCx+8ER7Dtxdg2hcejACzuC23+mkt7MkTi1DrhoYhyaJ95QOIPYIql5C+sy5twNYIKKCDyMmiAz70HjhCVUGRC9XsIWTWw32rBiPv+VfGPPnBnUo1qlDE9+PWHiJahkLyRrXWdtM0VfFc/10TXjfRfVskT0DqadEZhfJeCTyQy9bWdg9FMDYn30TKwZGhf2+owQcuWdMk2m5w9/WdlDLVnUVyxogHrUWd1pfYv0SfCIV3Vn3XIJ+QrGBS4qsRiJV8G5ZJUS7cTw5Z+//+HHn25ubn784fs/f8WIr755/+OPz3/tTz++/+Z3XwihlBiHaSnKzN7AVP6EqFKGxKJhEL2PHctiTMidrvVUx/ioQ8qH3ELt/dX3Nx9vj5iPP339JQN+9/fjf+6/fvyzwEudJ+dNKpJMUci7tlO6T7uGYDW2hi1LLVJzmfaXj1BHEe2DlSC5F8AXf/9w62l++jPxz/3+xv/P5cajDAOr4HoBmpjcPULtw72mY+WtKSE3epBVxAwCZENSxxUblFd+9/MtxfzyNeUk9JH25/JiJVNHb7mEi9DEJFThVUutiUdj1DJTEFK0f9EN/6tkN2b9kFvuyvxeWU9b8Y3mu701lBXK9yGyudUT0kH58Q6gXNPKTB0onGmNvv47oBzGNa0lrHeGSnnxXNgzmB+8z0IMJyI+SJWfD3KS89KiUXywCSv0jYQz1rknckiM6/HUDmMAZAlNlogQ8st/3d7eipwZ/vbxlsf8nQ1Sd/FRyQV8QAGkH8/YmHV5BokVezZq1pi+/5wtDtJxTGlE0Y5XG8afhucyv/75CP5xu2d4PDkhUOp3cgHtGYbXlstX60g4FSJQqeWWFQcqzTCeqwMHIjA8hlZeUvOPW07z9UH8eHvLuHzFBpkw3jmM4YpJ9vilLHE+gMuJKWZoRFyFvMSkLj6RBpnQpnDXqXM1240JjziJopIPP97ymm8P8N9vblnNr1+LI0v56fiajJ05YAm0c4rZCp/piwtzz3R/ZCVlkX/KDo/U6H5z4K7v+FdIKSHfS/k0PyIqb1ENrxVZ/Zn/72WBlLOROqE2WiHa8q3O4MlfWlr93IS+Eh3WKTsFua/itM59v8PNXlWCjfQ652QnN3yv8puvXp2G+M3vpJFRsplUBagyBsXABrnBkyERzIRrbMoaVnbHaxVZXnLwB8JECi2/5WS+Sf29v34lXdFu/dFK6fltzH2vR/U8w6EBrcg6bIhH2zZluTdmwpptcFcLOnOyEMWfbkXMzTPn/lbE/PIFGWJJvZMSnOdGBdI/NuaHlBKGa452X6Zo92p0wFy9mjPFBKHzpRahMY8qw6tjNOBExyMv/0UGt//+5Uehv/dGGCv2v9eZGlfFYFcmjF03Jk4BH8P4toIR6/C2LjHRqgI9Bmz8eCtlfrmVMt/K4i7ljiqzNK4tj7VgCZeEKT7lnk7BpdQlwWoAWGKx8fWtOvPrl7LYvYCVPUvmspgSiMfqWji9llJzvzqcxCJqbiUADLGi4PHTZ25kURMoeRm0psTAaNXswOcVXwWi0zJH9DgHhR0WHP+41Wh+J4qSwHmTQW0IdgxvpLA+whMhYcwOIDMmHGBKTlozLDi+vFWJG1FswVAaGkOpUjmHxD4GGwrTVQyqvmpah99BdCYNln10OpIowLCxU7+ttKVJW7DEm6LG0esVDhLkAQ16hyIBj1+U4sYO5FbgfmCU+ny2I+2y/AxxbA48FYu8D3CxPJMHRyxaHTOwsrLxWOfM+UAWkDPV9XZ5dBJK+wCEyR7Ax41a/GAGMjvUVhlPe1ZEPhxhUsUvOx2oWfQZBjME0EOrxa9fWLGbEffYzGBLu/iIgJ4H7re65zD4HAAM23o35VBhobMBLUMg5Sc7baRxsjdrbeCoTNgNPsiNYvwghwYLOyO10dUEMuK6cmESBwN0lDZElIDjo2L8Aqi/uhJBa0sPDsRbq+snL/8BgPULKNr90PjjrWbzBQPY2484kfYmtYm2s4DtoMz0E7ju+SbAwfeq8RcprMHah1Ym9nq656fc63RCtz/HdW3bSUV+jtOfw3+oxndSqNiL07UN6quyQ+CqTGAonkJ4mdzO4zPfxRAGGDeq8SMd7IRPK4NCO3KWsseZINfvGxSAPkXmWXEiz6DTiAcbGXxQjf8vhDV/ebplv8iI2qbV1t3rf9UzeGjZx+MkOYVArmbwwuwv8VY1fhFCjda/cW6BtbG/iUwi/3X7ldzXtzrMPWeKKtKKWz9sq6ZN5fGUiU6U47KXcCsDJ5DMGiq0K6Mb5EIM7LVrymLl/OdT8DkTi+fhVCqtEAfcJRmPE54ox88EUdPwziiwdHoANPwPp/xynUyurU7LNaGzq0efGzLVPsV8623TiaDkSmEN2+TCDvsbW5pmi7XNTVw34HLNcPCGwrTa8mfg9mmlbQ74kDqbfuLaZdTbcLScJ9RtuW7L5drhcHCtRMbAxMwV0zZRdDwSEoyJcmTo9bUP4ToJSv7eKrhuYJjrnYAxc7t74hvoh6qJomO0IBPlKIaKht8YBSeTB1shyVBn1xu9Hmu1JVijXoHQ1bhrwh8Foj5DxdKg7JITpWG7/crOG79PZUrUlgr91qZOWvm/wfQBYDgtmmatjY/Bhti2b+eLyeGrJbHCYn2YWmbwME6oOrozzg6cLdjiKuK5nUWz1vZITxpbHHFqsBS6CtqWiP/chzldJq4khhlSSzWVaNWnVaZrJVgX8S7D5hmkj1YxXiqkE/JUCAUR/0+3XjrjNPXlVSpXolaKwXm3I3ZOF1Xlz3pAXrqV5tNnA1hvbP0v7iAyXp3CsnZktGL/9Q7Zp02dilaAd2QYpzG2F9qUwNCtYVqT2trUeBUzl5IjnuI0j/xGNX5PnjoV3t9+wok1gKq1WrtCS1xBdY3dZ0TqzLqiU412QyGI+K1qvFNxxzBbOlRbiwe0VkF/b2uT6j9ZB8ehzFJq4IhTL9vZ1a/aB6gWeoTvd8cPvSPB8U5I5m12DvtkVdmlK7CFK05i4i0PCeFGMX5CQsnXDwFwkhWa9GmOATLZt7nFZvN3mV0sSllZBnFzDjRMhPeK8Q1Sb1aSHc+XGnVWTdyb73tMHXbV6NEumeKjMA+QNq0eMdAwEf5o8yuMqbqzBikznEUosGtPGXRTG2GCHYt+WRM3F6zddnfkF3rglS2p/yxjcPfAi51Nk3oL3hlGaxKZlOHxgnY0lZjED7k/jJKc/4CDSrb7zlJ/92Tmzjhqh12SFza1jG196Te0wCOR4QO0Vm1+BYOdcHfbpWU9++c2ocJmKGY2KQ1sJVWoWPlsryNlRT0gbxq7zSvhqVmgsKUJr5KbeS9sAMtkk06nDo+N2tLmjyrgzBvVwKadv8Gx0p1tFwqLHRtfYfsuc2gqJLVLppiCakRNSB0mVlIXVfiN1r0V2LvaJty1QsqrRuUubCqkMQQNXHpY014YMY8j2CKVmH9qsOsBI2x6q0er0GBz1JxNo+Ct8JSKU5Lk/JJ5HMEWBX6nwN51nLDprVZWocJug5dp51YylcewczWxoDT87uSqtzdWu02GcO2nQjFBqeWuKMwl0VPlykA85XELy9qZURqSpXI3wvNHo92SrCtqGLKOK6R9AWtssbwpjWwA56/J8yLcEsO3Tzkci91uTR+SjHqIcxwaCHza1Luu69oK69oc4Ao7rU2j4D1eLQN9YUhqSObkKrh/NNitMvp1b03DXYUm0Ge5oY22QCzKS2i0ZqEDqQBSAi6YL3jH4VirutquGfTJOGGV14N8bbSDvXegpufRABcnCUUxvRAsld7pUnb7IO52jywDA+OEVV45Yr8RGxQap4cB+N3dkzTd/LAhqVaZouz2F/E1Hk4nK6zyyiA7Ai8xsD0UBBpNv6n2OdKO516oRW88+4OV+7RrpvbVvLDKS/6ggJeif7E+mhxgA14L3Aao48EfTfRrtxlbdyj8MEgrpiNBtPZzj5W9mr7cWCNKPf3IuEuaQozoHSr/h3UNTbqq4COJGwnhu0FaMa0whX4cWDPb5bBF+51JKHxD4p3wQ4nb7Obqpe8/DfHrDpuXaVYvVqz54GlgAaQqKRwJF4BMqhBqLj60DKRQvrMEpSzLk7UJmITgvGbCu4/a/YhpCcJen1szbLQtDTWSH55aNXTLdGdT3861VEgB3eqE0hPqgzBb+mszNGEaUDtIyDCmpWiJywksoRRiHHQVOjPqssQrFKwoLU4SP2wow2+0Isx3TC0jQe30zB6sBCHaziaFQgFNOuX91tLdkaZsIuCkGjO+Wu4NPP6dq2Ukpg1hb+0Mi6YBqUA29G8ViYlcQfMwN0eg/ayPyKH0FJxLTP9Mx4Z3H8DxM9PBp6AZNKEN8sci4XkBUqwN0G96q4Mskg0SnG+Fa6asJ4IJJaqUpM5pQQQfvuBqzi1qSX4m4W4tCx6aEP6mMjPkryG16ZUKm6VzTZqKDSevz/lHCxRhNpDX0rug3Tqp7l0AsWY4XUNhg8zxHuQ9oZXOWsBfkqIqAMat/bUB+m054uBIwoQKi4TnD8j3/wWFFvBLwN1EYX8+YGNIutRIhTBa1veo+Miotir1DeW0jzY+o8GmXXLBPenoFHQujvKRpVZE2h2lXbB/DBTKji1hPOrql4+/ZVQ+FwpGbJc1pQ7eSfsu+tAigOYg6eeVRrjHq9fYPwYKZccUQ6fzvUYrzhNZ7aj3b0GF9l3wvFUA1ak8Br9hg3uchNXwI0SMWQOuB8qXDy8W+JWsJN9vDXmKENTvgganIQjq95ZbeItGKXopkpC6TCxAhqP+XnWT0AxuDrfC5Mw4rLDl5hpuxnyD5nfsmKyIBbLh3MobAlNh2Q64F0CL+4prGe/JZGIU7io0tGxiDpwDy6H5Gyv9TBd6IgWj5hakgB3MbKp/rbcDhw37zIyxPjArU/3dg7PScBs4zj6UDssOsvqd7bBulQZXCtagIyZdG2yQwdzIzW8/wOBf74AHfeE4hn8Y8Uyti/53kKLS9Q5Ys/PI9CCvWrQ8ITN3MxomvIRjy7+8Q1n+SZotR+lyO3/+KHnt2cwfJr1DdQe7+QiAlPXXJQCYErNuZcE6ZvsaWiaJ/FARIuU3v/kZpuWY+DZhGpfY7VlEhyl9rNWwwz7tQLNCKezb4vIX8T6NUguWngmGeAuE6qL/+DX/oTpGH07LMNg2k96hkSXQwV3nO1l1yHNX2GKEEhHugCOlZZNz3hzZiSx/+YAgLsfbzjet2DPmMzcMazA+4prkAvdCUX8SyrZMfVuWcqqscCe5AkrPxhO0Fza0TWVR/Ow9ybSCxZi7L9tUcqIrYj9kVjhgGb8h4AFClYN0D4nsPhVfIuoK6OThOcZ2nZgRCdoW7dYm3wv3tYSznRdl7XHLg3Q1GCY4Kxxbr0dAMQ3fBUOzT5smZf8d03StKcWU+ntqZISdhcw3H3CDsXKpUoz560g4YAnT10HIq0DlQyXDTfbltKqA+/RSNAhdjaIQSiNQtEsOD+oMshdwP/TLO5m3/UFoopdXOMzG6dkZCTZ1G+BDqUsvEhbrag97vc2XxSGzKcu6BvhZQNvNJ3Cf8uVzMQET3s0slfsav5Plv2PortbcCOa+c+FDgUVarIW8eAhX6tuq/9Epmo1EUuH8WST1oCUi9kOaEe8xWMWb3exf+gspdIfyyPQYcd/ZhLM9XO7fdqg3yZQODDAl3Feev/r5Qg2B7089VUD+aizvWX353s2L94wxE9UTypxUGQEuOUkDdiuI7SNQ5hvYCyqT4fVvDGsNLj3JaBLpJurJ6ivmYmyHMf8cklnldCg3cFo1bV1hSafW/YCs2FT1gaf7xiREvjuDpoX3fL54ruP1XbLP+Vx1Z5aTmfVbrJuACmb+BywCNdISldfy7obJF9AtOKVqscgcDZrlrKxCrQ+YaWVrGWhtRFuOO0EDlaF//DPoTUR0OM/s39gLzZ1ZzsYq7PoBpRScJsy4T2id+Df57p9kWTmku2Zbmy6l5kDULKe2CgMFuOhHdJ6gb9YUR9781d/zX3/AvecX6R9MjqFDB0tMhfuBmBoyiM9mdiHHB30zzaiO9HuS+XRw35VD+hn0ZubdHJezMOAW3zfZe+yq4FFbiMg3MNFB3Onnd8BVtVo2HnUNv8HS+YNNaNB9Z0xPY17TVzjClloGng66+uEfjnHkb573EocTHCvWcLaUnutru6jryiak2DhYLkQ0z7YXwND9yMTz0Av4itm7f3vl8fHm/TtsDYcnasEyieV/8LSVXbdivzMJq4EUJOpwyRgarQFIGRD7fuQq2gu8+8Mf3sHcRoTUoIouoiXCz3X6YBg7LOvVV4JJ4pFKLnoNLN2FDX35X7b+gJtrCTcY03yYG5zY5RQWoYXl0vlyZmLvlZ1a4X+BjvlRqRH7ufTJIFT87gXx4SdlV0w3Bo+gknP0xiazS2Gck+pwsechdQC1ajEo6Lf8WGBuJ+sM/R0X754IU3APhNqwuVNIDUIx8L0OfBJdiJH9DCXDFBOpfjie6SyfsDtrc+DuaHUVrIeF59LanyshN1IpffL68SN+w/7aJc9zKB1hYkDHcIpOUq54ZsYy5h9ba2UMSgE5SIL1iyLuLCOxKyNjjQ9PkvzlRcBC8V+OZ/NEta7DgEO4g441U3YaeTO3jfRqaFQSkEu6yxrLNE5SteDuV8Ojm6t4PpuOLy7enJ8Hr3Po+fn5m4vL8WQaRYvXpYFmOCLrkDJYkgodyzMup7wzMcLOaXLPInMnOyM3UcntQuXvgZKhSv/fTKIlW1ti1Ef+hMtJMwt/hOzUET90tgRsgqIbUtZvgXkOoMVrpBIOspSexktNbYm3XA8/XOQvtzIwzANNCsLzI03ZoRBT5pBpLc2M2VvnU+e48ATkgy/D3JZYz6O84q3FuzKmm1p2DsgTjEtvTbtBQYsZ8cYW7PB/HRQ9nc0XflDWlrj2zFCMTktKtZ151mH+pmLnwFyYapBDVp9bA3XSZzrxAFlKK2tL3HgWlL4OexnoLFhqER3Da7N+HLF60PZe4Frrw58JqZhS+eVmZW2JW88c5en472JZ5DWZowGZfsfAVF0DlfdTmxyn9kf6CRDR+IGpLTF6dw6sTkOciwDLrEsx3bMpcFQtVN5/skn69yS6N16VrYQspZW1JeasSc397+iIuNhl7zqiiyY4X+Ews3LIzdIOdNjPYCl/Z/MaSukEWzHdsT7SdCOCF20H7VagrdsEU1pToGQ3KKc9HLFtMV9ofWYWahWltB822GpuMffTHNfeGbAIUHA57s8VuER/Fh4KSFq7NMNVtK1AgJ15ltLcIhtIwX1COqEKnNzcTim2d/SzHGzyPYfdMQObISd3hNCzzA3PtGKHKCiMdf2ulCXvkyOVBEK/0lClEd2agZ+Cm3wvYXdcoRXq7WHHMvda7w/VBtmIi0lkAy02D3mZzDyl11Yfdo6D44vLHJrA7rhGG9PzkznjhH5S9eTiYgiwJTIaVy6GFptfkB8aT1/2hilRVCxfN3CpFMFqphdoFOLamp5knL+rF04WlV8pzXq8sE+Yk8hzaLmhf8IKg4mo6YQJbvOFDVRNLYdMcbl+1Lp+Jl0mAbYG5dEFctukjP9hsR3J9cy61uNZZZJP/irwz3baQNXUugwxB7cmqLhpesYFFQiwd0wPpmeCHNXa/4mc5NqFuW74pMtXphnMNbJ6RYpVU6sg+d4b/fvoilmBAJuhlCbdyCIItgKPqOpsIDjQZAdypXT5uX5ugX9pX+JdW2DR6zkiiZhm+t9C1aN/xiTAxotrzlXydMj93XBoBcnN8u2qhd+L54JNyH60u7bAyv5dhlg2N7r3UecyCbABlczYSp4MAzvvhjuMXvyVwzXySu2YxDj+mICzf2p9F+oTOLPeq95H2IVVdcCjvpd8Pzw8bshLpnJQMNOsa9R4nPhd6C6Bfu/mAJOs2wImumJghtdWmnBDVXVI8WYjhvFBAcANOeV+RHIlyi9Xd4j1eYC70EVvvzBwCGWpnxdU7bPV65cqcGVKSIdGfV8wPg8buNqrc/5HGlhEE/KhgfJpngcYKG9n+L///gatptZA6kxsjIlxECvCHE6AzVi9PIftgqmVKjHjAcBylz2CeKQvY+FGsBMFybOFq6ltIJk6K514Iko7NQvON2h7zhhFNjnqKyEnwSTPmHqod9I+9UPGO3QBzEB8ZF2awdXUVohssk5lmC21QqZZcF6jfZQxY/4tUV+5ZKq60p4EY+ZK3YPYL6DS1dzP5nnWavqN+IeIp/9y4Jn54Y6lVRnIhifk+xyshWjN+Fj1LlBfqAVruEuwx5Z1/Vi1HfOTbu9FH4i2eIl1PGANNV5NrYXUQqkUSsyJlJvuqFIdQusAVHLeiWWu1088ONotjq3WRVk3/jOcnnZdW1fbYuWEjmnP6imSYt9NvJpaBdmXR2nGrFNHCh/8FKAKlmOlvkeYulMr2QcYO6LR5jlECXLQQPx8B/CWZ/wBOeD1LTeQ1b9HjYowFjysuBHWt3rPSn3PMDe3wk13ptROzWwxFdd/DQK85LxFzHg5BFRHXlEfigf1O9ZYaSRmpijFt6UFyGNVD2gB8l3WDZd6FCwGGaBsOV0hIlW0PA0s8KPd2C1WGiEcMCL9t5J/3sBH5vymcZTf7oUndrhItdxhaueE4b3osfJ+Rqkmrpip7zHiZi2vNLgcDgwMlVUDPZZjLKui9V/M5X7gv2ix8n5WqSZWzLyjCLFe1/Geos1+Aq7zjsUq2swlR1OBuWwHhEWHtcOP8qxcqRBuLT1RAbahn4M90/KFAb4sVtNmK5hEiIs4G1Pp+9QIusQqVBNVCLdGeIE778d0nn+xzDPveCzsJpbTDUCXVnHlLaPNLM2ZTnOOk0xqduHWTMkkb12fwS2DUjX7nccq22zlXMwlo/YRjZ0kOoTUYJdqYsdeo1kGaE7nvS2zmLRTVqbqLNPQGO+lxgIJutzTnxATpZKRuSkPwFya4YzMRYCiLPGuwiS3ENXeFKJMB/os09AYu0zWRZvDgFptcuGYMB6lL6Ds3PlhKNHYOnVoV2ECXQa1tvcougG+lWsbXyEQy+wpX/SuK0qF1bKJNQ+YYIuiijCj6uL4VhWxRCuLM9hlUCsKkG061v+nIuzAbLugXKGllDsebUpN25SYHOx5IBRzEBZoIqMIngu1toX4Otn/VUzaQlF9ngFjJTVFEK+ccZSaToL80OfpWjLxZv5z1FnIZOflAKiq2OApIky4Hg0biagF7/ffgspj4E0xCWV7wEK9ZjwaLF8Aq1AiqmJIAGPvAgJHxyiUbzmrPeps0yL+L45AfhUl8Hj3SxnyQxFTJt8NAKxGiaiKawzHMDTaCrP4nAds5U6JGjyvU3Oe9MtlgKBEVgtebxzqgskpxixl5C3ffyaU3p3ZGKGQg3L2rz7fo5CU0ufpJGRM9Xj32J/lVcp5O2aqSh7/BfkukUqp297A131w9YDJWrSZOvn8HHPIbAjtAzDstfyJdszb22Ge4fCAPB7uJEPksqF0rs9qmX4kV6Dnqa50wiEssHK5usukq2oXPDIbhMV1yNWqKXMSbUuAl1zB/b/9E8YKU6ik+NztYK+PltVSxyNF3WX37cAgyzzgQWmaLpL9J0RK7xkrdOQSVD4Ue0W0LnIxmv9+c+BnnFYXDKPHi84xMa3lVlAHBrUrnJxkREVswMVhLWtDcTlWydcfKHiHssuJTDJtOJ4Tb4hnMCqY6XzeJymeTo5kHl6xrMiep6jzEcM+myAQVj+DtckkabqI7ZCFxSBb4Eb05NuNZJwJk01xn+e5O272HiH1sqoPPx2QKnzBa0Rd5aQqwsnZmEf9KCNMeZj81KLkTHQcY9Vs+GKNcOSoupxSTPPxdkWZpXnLrDnYM/83ZcHMpv+6mKbIKCQzraI2ZivTeR8KsVHIejW28v4TaeqAioq1jjHW8Ryay5fWpZPS3osxOinsCkERB9apeh4CQ7Mv7r9l1q7a5O7QZHxw1GxCXtborn59VC6nyyuSJBR4kKWK/JM7/Fy/F75PDjpDyzE7HKIggvYMfQHItpKAQUVUhO6bYpO9Pf9sjc7Yaj+MuTAR+WpTnnzNxpXxvgiMHP1mzZP+G3LzNDIy5yJIkBJoU3zyqWLtJSiOPm9s3kngZtAVRghmZoL/RGE8SW+m8MmitfZfRiltq02Rv5h7nnnnmrH/R+1wHHW5f9R79Bjntwq+U28/R77LEAsT/v+6KXbyIwl1YWLQI15/BVbrVJJA9XUoG9mwchGb8P/FBFWuLuW0FPhKtOVEEwE3N+npE8dKJAleAjWDYxKFBqwZ8f9AhZdCEfP+5Ehq0cZDNcdLdTEdcUJ95wZRqH3NChMBFjxwUQyPMmW0CDytMhPVxfSUEQZ0RRSFutfsWNDoSbxQYSKWWHrqX/FyBPPJCgmwTOWERhcqee8Ta56n6ggrheCFChN9EtIwNu6/mEF1MT1VJ+Aw9t9sMpwaVArNA+AUEoWYB5SM0fcyblGdn6fGyi2XmoIHl3E/JdKLJUlJATTpJRd9osbAzxBXnZ+nIHuo+pImoY7a/Myu1JoMhRnluCerC9L3FIfAa323OlwqJynH+mQX47AXfFSWAMEcly06IaeUC8i1HlzGS+VnM53Vq8X0DSzZ/+xjYSpFljAnE1SNlMUYfa2XqLopQG15bDMvNIkAo30zia1MqlPoBJKMUTVSkmkII+801kx15+cotFpwuYjGAm9DmyoDS8ufMXThmoxhW9fNxwDh1Sm1geRp1fk5GRsuuFzG00vpoOfjA/NiYusKNMmcRCHmETHMRwzTlE1ZnEJ05+d5aHsFaxnPJhcCuwZvxtNo8RzW7HQaQvMf55ewKS+JLgORqpmRPgQRI39+1k2oXFuQEf1nwuT8nEYWnF9cjqfRXG18YEmFI9OfTw9nRLAy/WIuKEmZXQS8dFxkfxKJLnSX0lHYK8zQZeJnlv3z/+Y3H4c0ocJC/qje4MorFjMWnkxwOZn3RVKJx3yyXfVH/V8Jk8x9OBvnl5NoAXtU55dAfJDF/KXeFnjRBm/Gk8gsbosk3cVB0yGriDJUuy6mi7P/kpjlIp5HeyZeJIiZIY73jmm+SEDz2uLluPaPLI6TXiqt6HMddT6eJQpolclFQKpi/Y+PiZ8Jr4vz4BBFdDmZaarkLObPjK83R45ahOo7Aw=="; var DEFAULT_SETTINGS_VALUES = { @@ -1732,7 +1737,6 @@ var DEFAULT_SETTINGS_VALUES = { selectEdgeByDirection: false }; var SETTINGS = { - // @ts-ignore general: { label: "General", description: "General settings of the Advanced Canvas plugin.", @@ -2206,7 +2210,7 @@ var AdvancedCanvasPluginSettingTab = class extends import_obsidian4.PluginSettin this.settingsManager = settingsManager; } display() { - let { containerEl } = this; + const { containerEl } = this; containerEl.empty(); this.createKofiBanner(containerEl); for (const [headingId, heading] of Object.entries(SETTINGS)) { @@ -2221,7 +2225,7 @@ var AdvancedCanvasPluginSettingTab = class extends import_obsidian4.PluginSettin settingsHeaderChildrenContainerEl.classList.add("settings-header-children"); settingsHeaderChildrenContainerEl.appendChild(document.createElement("span")); containerEl.appendChild(settingsHeaderChildrenContainerEl); - for (let [settingId, setting] of Object.entries(heading.children)) { + for (const [settingId, setting] of Object.entries(heading.children)) { if (!(settingId in DEFAULT_SETTINGS_VALUES)) continue; switch (setting.type) { case "text": @@ -2811,7 +2815,8 @@ var CanvasPatcher = class extends Patcher { return result; }), importData: Patcher.OverrideExisting((next) => function(data, clearCanvas, silent) { - const targetFilePath = this.view.file.path; + var _a; + const targetFilePath = (_a = this.view.file) == null ? void 0 : _a.path; const setData = (data2) => { if (!this.view.file || this.view.file.path !== targetFilePath) return; this.importData(data2, true, true); @@ -3002,7 +3007,6 @@ var LinkSuggestionsPatcher = class extends Patcher { if (!this.plugin.settings.getSetting("enableSingleNodeLinks")) return; const suggestManager = (_a = this.plugin.app.workspace.editorSuggest.suggests.find((s) => s.suggestManager)) == null ? void 0 : _a.suggestManager; if (!suggestManager) return console.warn("LinkSuggestionsPatcher: No suggest manager found."); - const that = this; Patcher.patchThisAndPrototype(this.plugin, suggestManager, { getHeadingSuggestions: Patcher.OverrideExisting((next) => async function(context, path, subpath) { const result = await next.call(this, context, path, subpath); @@ -3015,7 +3019,7 @@ var LinkSuggestionsPatcher = class extends Patcher { if (!fileCache) return result; const canvasNodeCaches = fileCache.nodes; if (!canvasNodeCaches) return result; - for (const [nodeId, nodeCache] of Object.entries(canvasNodeCaches)) { + for (const nodeId of Object.keys(canvasNodeCaches)) { if (nodeId === subpath) continue; const suggestion = { file: targetFile, @@ -3168,7 +3172,7 @@ var MetadataCachePatcher = class extends Patcher { if (typeof value === "string") return getLinks([value]); else if (Array.isArray(value)) return getLinks(value); return []; - }); + }).filter((v) => v !== null); } const fileNodesEmbeds = (_d = (_c = (_b = content.nodes) == null ? void 0 : _b.map((nodeData, index) => nodeData.type === "file" && nodeData.file ? { link: nodeData.file, @@ -3193,7 +3197,7 @@ var MetadataCachePatcher = class extends Patcher { position: { nodeId: (_b2 = (_a3 = content.nodes) == null ? void 0 : _a3[index]) == null ? void 0 : _b2.id, start: { line: 0, col: 1, offset: 0 }, - // 0 for node + // 0 for node end: { line: 0, col: 1, offset: index } // index of node } @@ -3209,7 +3213,7 @@ var MetadataCachePatcher = class extends Patcher { position: { nodeId: (_b2 = (_a3 = content.nodes) == null ? void 0 : _a3[index]) == null ? void 0 : _b2.id, start: { line: 0, col: 1, offset: 0 }, - // 0 for node + // 0 for node end: { line: 0, col: 1, offset: index } // index of node } @@ -3257,7 +3261,6 @@ var MetadataCachePatcher = class extends Patcher { return acc; }, {}); if (that.plugin.settings.getSetting("treatFileNodeEdgesAsLinks")) { - ; ((_b = cachedContent.edges) != null ? _b : []).forEach((edge) => { var _a2, _b2; const from = (_a2 = cachedContent.nodes) == null ? void 0 : _a2.find((node) => node.id === edge.fromNode); @@ -3359,7 +3362,6 @@ var BacklinksPatcher = class extends Patcher { var OutgoingLinksPatcher = class extends Patcher { async patch() { if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; - const that = this; await Patcher.waitForViewRequest(this.plugin, "outgoing-link", (view) => { Patcher.patchPrototype(this.plugin, view.outgoingLink, { recomputeLinks: Patcher.OverrideExisting((next) => function(...args) { @@ -3388,7 +3390,6 @@ var PropertiesPatcher = class extends Patcher { async patch() { if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; if (!this.plugin.app.viewRegistry.viewByType["file-properties"]) return; - const that = this; await Patcher.waitForViewRequest(this.plugin, "file-properties", (view) => { Patcher.patchPrototype(this.plugin, view, { isSupportedFile: Patcher.OverrideExisting((next) => function(file) { @@ -3607,7 +3608,7 @@ var MetadataCanvasExtension = class extends CanvasExtension { } onCanvasChanged(canvas) { var _a; - let metadata = (_a = canvas.data) == null ? void 0 : _a.metadata; + const metadata = (_a = canvas.data) == null ? void 0 : _a.metadata; if (!metadata || metadata.version !== CURRENT_SPEC_VERSION) return new import_obsidian11.Notice("Metadata node not found or version mismatch. Should have been migrated (but wasn't)."); const that = this; @@ -3629,8 +3630,8 @@ var MetadataCanvasExtension = class extends CanvasExtension { } onMetadataChanged(canvas) { var _a, _b, _c; - if (this.canvasCssclassesCache.has(canvas.view)) - canvas.wrapperEl.classList.remove(...this.canvasCssclassesCache.get(canvas.view)); + const oldCssClasses = this.canvasCssclassesCache.get(canvas.view); + if (oldCssClasses) canvas.wrapperEl.classList.remove(...oldCssClasses); const currentClasses = (_c = (_b = (_a = canvas.metadata) == null ? void 0 : _a.frontmatter) == null ? void 0 : _b.cssclasses) != null ? _c : []; this.canvasCssclassesCache.set(canvas.view, currentClasses); if (currentClasses.length > 0) canvas.wrapperEl.classList.add(...currentClasses); @@ -4070,7 +4071,7 @@ var PresentationCanvasExtension = class extends CanvasExtension { if (shouldEnterFullscreen) { try { await canvas.wrapperEl.requestFullscreen(); - } catch (_err) { + } catch (e) { this.presentationUsesFullscreen = false; } } @@ -4244,7 +4245,7 @@ var ZOrderingCanvasExtension = class extends CanvasExtension { this.setNodesZIndex([selectedNode], targetZIndex); } moveMaxLayers(canvas, selectedNodes, forward) { - let targetZIndex = forward ? Math.max(...this.getAllZIndexes(canvas)) + 1 : Math.min(...this.getAllZIndexes(canvas)) - selectedNodes.length; + const targetZIndex = forward ? Math.max(...this.getAllZIndexes(canvas)) + 1 : Math.min(...this.getAllZIndexes(canvas)) - selectedNodes.length; this.setNodesZIndex(selectedNodes, targetZIndex); } removePersistentZIndexes(_canvas, nodes) { @@ -4665,7 +4666,7 @@ var CommandsCanvasExtension = class extends CanvasExtension { (canvas) => { const canvasFile = canvas.view.file; if (!canvasFile) return; - let selectedNodesData = canvas.getSelectionData().nodes.map((node) => node); + const selectedNodesData = canvas.getSelectionData().nodes.map((node) => node); const backlinks = /* @__PURE__ */ new Set(); if (selectedNodesData.length > 0) { for (const nodeData of selectedNodesData) { @@ -4931,7 +4932,7 @@ var AutoResizeNodeCanvasExtension = class extends CanvasExtension { const renderedMarkdownContainer = node.nodeEl.querySelector(".markdown-preview-view.markdown-rendered"); if (!renderedMarkdownContainer) return; renderedMarkdownContainer.style.height = "min-content"; - let newHeight = renderedMarkdownContainer.clientHeight; + const newHeight = renderedMarkdownContainer.clientHeight; renderedMarkdownContainer.style.removeProperty("height"); this.setNodeHeight(node, newHeight); } @@ -4962,6 +4963,8 @@ var AutoResizeNodeCanvasExtension = class extends CanvasExtension { // src/canvas-extensions/portals-canvas-extension.ts var import_obsidian15 = require("obsidian"); +var PORTAL_ID_DELIMITER = "||"; +var PORTAL_ID_PREFIX = `acportal${PORTAL_ID_DELIMITER}`; var PORTAL_PADDING = 50; var MIN_OPEN_PORTAL_SIZE = { width: 200, height: 200 }; var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtension { @@ -5033,12 +5036,12 @@ var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtensi canvas.history.data.pop(); } onContainingNodesRequested(_canvas, _bbox, nodes) { - const filteredNodes = nodes.filter((node) => !_PortalsCanvasExtension.isPortalElement(node)); + const filteredNodes = nodes.filter((node) => !_PortalsCanvasExtension.isPortalElement(node.id)); nodes.splice(0, nodes.length, ...filteredNodes); } onSelectionChanged(canvas, _oldSelection, updateSelection) { updateSelection(() => { - const updatedSelection = Array.from(canvas.selection).filter((canvasElement) => !_PortalsCanvasExtension.isPortalElement(canvasElement)); + const updatedSelection = Array.from(canvas.selection).filter((canvasElement) => !_PortalsCanvasExtension.isPortalElement(canvasElement.id)); canvas.selection = new Set(updatedSelection); }); } @@ -5096,13 +5099,13 @@ var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtensi canvas.removeEdge(edge); } onEdgeConnectionTryDraggingBefore(_canvas, edge, _event, cancelRef) { - if (!_PortalsCanvasExtension.isPortalElement(edge)) return; + if (!_PortalsCanvasExtension.isPortalElement(edge.id)) return; cancelRef.value = true; new import_obsidian15.Notice("Updating edges from portals is not supported yet."); } onEdgeConnectionDraggingAfter(canvas, edge, _event, _newEdge, _side, _previousEnds) { - if (_PortalsCanvasExtension.isPortalElement(edge)) return; - if (!_PortalsCanvasExtension.isPortalElement(edge.from.node) || !_PortalsCanvasExtension.isPortalElement(edge.to.node)) return; + if (_PortalsCanvasExtension.isPortalElement(edge.id)) return; + if (!_PortalsCanvasExtension.isPortalElement(edge.from.node.id) || !_PortalsCanvasExtension.isPortalElement(edge.to.node.id)) return; canvas.removeEdge(edge); new import_obsidian15.Notice("Creating edges with both ends in portals are not supported yet."); } @@ -5146,14 +5149,14 @@ var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtensi } // Remove all edges and nodes from portals onGetData(_canvas, data) { - data.nodes = data.nodes.filter((nodeData) => _PortalsCanvasExtension.getNestedIds(nodeData.id).length === 1); + data.nodes = data.nodes.filter((nodeData) => !_PortalsCanvasExtension.isPortalElement(nodeData.id)); for (const nodeData of data.nodes) delete nodeData.isPortalLoaded; const portalsIdMap = new Map( data.nodes.filter((nodeData) => nodeData.portal).map((nodeData) => [nodeData.id, nodeData]) ); data.edges = data.edges.filter((edgeData) => { var _a; - if (_PortalsCanvasExtension.getNestedIds(edgeData.id).length > 1) return false; + if (_PortalsCanvasExtension.isPortalElement(edgeData.id)) return false; const isFromNodeFromPortal = _PortalsCanvasExtension.getNestedIds(edgeData.fromNode).length > 1; const isToNodeFromPortal = _PortalsCanvasExtension.getNestedIds(edgeData.toNode).length > 1; if (!isFromNodeFromPortal && !isToNodeFromPortal) return true; @@ -5168,6 +5171,7 @@ var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtensi } // Add all edges and nodes from portals async onSetData(canvas, dataRef) { + if (!(dataRef == null ? void 0 : dataRef.nodes)) return dataRef; const data = JSON.parse(JSON.stringify(dataRef)); const addedData = await Promise.all(data.nodes.map((nodeData) => this.tryOpenPortal(canvas, nodeData))); for (const newData of addedData) { @@ -5202,7 +5206,9 @@ var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtensi y: portalNodeData.y - sourceMinCoordinates.minY + PORTAL_PADDING }; for (const nodeDataFromPortal of portalFileData.nodes) { - const newNodeId = `${portalNodeData.id}-${nodeDataFromPortal.id}`; + let newNodeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${nodeDataFromPortal.id}`; + if (!newNodeId.startsWith(PORTAL_ID_PREFIX)) + newNodeId = PORTAL_ID_PREFIX + newNodeId; const addedNode = { ...nodeDataFromPortal, id: newNodeId, @@ -5215,9 +5221,11 @@ var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtensi addedData.edges.push(...nestedNodes.edges); } for (const edgeDataFromPortal of portalFileData.edges) { - const newEdgeId = `${portalNodeData.id}-${edgeDataFromPortal.id}`; - const fromNodeId = `${portalNodeData.id}-${edgeDataFromPortal.fromNode}`; - const toNodeId = `${portalNodeData.id}-${edgeDataFromPortal.toNode}`; + let newEdgeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${edgeDataFromPortal.id}`; + if (!newEdgeId.startsWith(PORTAL_ID_PREFIX)) + newEdgeId = PORTAL_ID_PREFIX + newEdgeId; + const fromNodeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${edgeDataFromPortal.fromNode}`; + const toNodeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${edgeDataFromPortal.toNode}`; addedData.edges.push({ ...edgeDataFromPortal, id: newEdgeId, @@ -5253,18 +5261,22 @@ var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtensi getParentPortalId(elementId) { const nestedIds = _PortalsCanvasExtension.getNestedIds(elementId); if (nestedIds.length < 2) return void 0; - return nestedIds.slice(0, -1).join("-"); + return nestedIds.slice(0, -1).join(PORTAL_ID_DELIMITER); } static getNestedIds(id) { - return id.split("-"); + if (!this.isPortalElement(id)) return [id]; + const trimmedId = id.substring(PORTAL_ID_PREFIX.length); + return trimmedId.split(PORTAL_ID_DELIMITER); } - static isPortalElement(canvasElement) { - return this.getNestedIds(canvasElement.id).length > 1; + static isPortalElement(id) { + return id.startsWith(PORTAL_ID_PREFIX); } isChildOfPortal(portal, canvasElement, directChild = true) { + const nestedIds = _PortalsCanvasExtension.getNestedIds(canvasElement.id); + if (nestedIds.length < 2) return false; return canvasElement.id !== portal.id && // Not the portal itself - canvasElement.id.startsWith(portal.id) && // Is a child of the portal - (!directChild || _PortalsCanvasExtension.getNestedIds(canvasElement.id).length === _PortalsCanvasExtension.getNestedIds(portal.id).length + 1); + nestedIds.contains(portal.id) && // Is a child of the portal + (!directChild || nestedIds[nestedIds.length - 2] === portal.id); } }; @@ -5362,9 +5374,9 @@ var BetterDefaultSettingsCanvasExtension = class extends CanvasExtension { async onDoubleClick(canvas, event, preventDefault) { if (event.defaultPrevented || event.target !== canvas.wrapperEl || canvas.isDragging || canvas.readonly) return; preventDefault.value = true; - let pos = canvas.posFromEvt(event); + const pos = canvas.posFromEvt(event); switch (this.plugin.settings.getSetting("nodeTypeOnDoubleClick")) { - case "file": + case "file": { const file = await new FileSelectModal(this.plugin.app, void 0, true).awaitInput(); canvas.createFileNode({ pos, @@ -5372,6 +5384,7 @@ var BetterDefaultSettingsCanvasExtension = class extends CanvasExtension { file }); break; + } default: canvas.createTextNode({ pos, @@ -5530,10 +5543,11 @@ var ColorPaletteCanvasExtension = class extends CanvasExtension { } getCustomColors() { const colors = []; - while (true) { - const colorId = (DEFAULT_COLORS_COUNT + colors.length + 1).toString(); - if (!getComputedStyle(document.body).getPropertyValue(`--canvas-color-${colorId}`)) break; - colors.push(colorId); + const style = getComputedStyle(document.body); + let colorIndex = DEFAULT_COLORS_COUNT + 1; + while (style.getPropertyValue(`--canvas-color-${colorIndex}`)) { + colors.push(colorIndex.toString()); + colorIndex++; } return colors; } @@ -5618,7 +5632,9 @@ var CollapsibleGroupsCanvasExtension = class extends CanvasExtension { bbox.maxY = maxPos.y; } expandNodes(data) { - data.nodes = data.nodes.flatMap((groupNodeData) => { + var _a; + if (!data) return; + data.nodes = (_a = data.nodes) == null ? void 0 : _a.flatMap((groupNodeData) => { const collapsedData = groupNodeData.collapsedData; if (collapsedData === void 0) return [groupNodeData]; delete groupNodeData.collapsedData; @@ -5632,8 +5648,9 @@ var CollapsibleGroupsCanvasExtension = class extends CanvasExtension { }); } collapseNodes(data) { - data.nodes.forEach((groupNodeData) => { - var _a, _b, _c, _d; + var _a; + (_a = data == null ? void 0 : data.nodes) == null ? void 0 : _a.forEach((groupNodeData) => { + var _a2, _b, _c, _d; if (!groupNodeData.collapsed) return; const groupNodeBBox = CanvasHelper.getBBox([groupNodeData]); const containedNodesData = data.nodes.filter( @@ -5645,16 +5662,16 @@ var CollapsibleGroupsCanvasExtension = class extends CanvasExtension { data.nodes = data.nodes.filter((nodeData) => !containedNodesData.includes(nodeData)); data.edges = data.edges.filter((edgeData) => !containedEdgesData.includes(edgeData)); const newContainedNodesData = containedNodesData.filter((nodeData) => { - var _a2, _b2, _c2; - return !((_c2 = (_b2 = (_a2 = groupNodeData.collapsedData) == null ? void 0 : _a2.nodes) == null ? void 0 : _b2.some((e) => e.id === nodeData.id)) != null ? _c2 : false); + var _a3, _b2, _c2; + return !((_c2 = (_b2 = (_a3 = groupNodeData.collapsedData) == null ? void 0 : _a3.nodes) == null ? void 0 : _b2.some((e) => e.id === nodeData.id)) != null ? _c2 : false); }); const newContainedEdgesData = containedEdgesData.filter((edgeData) => { - var _a2, _b2, _c2; - return !((_c2 = (_b2 = (_a2 = groupNodeData.collapsedData) == null ? void 0 : _a2.edges) == null ? void 0 : _b2.some((n) => n.id === edgeData.id)) != null ? _c2 : false); + var _a3, _b2, _c2; + return !((_c2 = (_b2 = (_a3 = groupNodeData.collapsedData) == null ? void 0 : _a3.edges) == null ? void 0 : _b2.some((n) => n.id === edgeData.id)) != null ? _c2 : false); }); groupNodeData.collapsedData = { nodes: [ - ...(_b = (_a = groupNodeData.collapsedData) == null ? void 0 : _a.nodes) != null ? _b : [], + ...(_b = (_a2 = groupNodeData.collapsedData) == null ? void 0 : _a2.nodes) != null ? _b : [], ...newContainedNodesData.map((nodeData) => ({ ...nodeData, // Store the relative position of the node to the group @@ -7077,18 +7094,19 @@ var EdgeHighlightCanvasExtension = class extends CanvasExtension { )); } onSelectionChanged(canvas, oldSelection) { + var _a, _b, _c, _d, _e; const connectedEdgesToBeHighlighted = new Set(canvas.getSelectionData().nodes.flatMap((nodeData) => { - var _a, _b; + var _a2, _b2; return [ - ...(_a = canvas.edgeFrom.get(canvas.nodes.get(nodeData.id))) != null ? _a : [], - ...this.plugin.settings.getSetting("highlightIncomingEdges") ? (_b = canvas.edgeTo.get(canvas.nodes.get(nodeData.id))) != null ? _b : [] : [] + ...(_a2 = canvas.edgeFrom.get(canvas.nodes.get(nodeData.id))) != null ? _a2 : [], + ...this.plugin.settings.getSetting("highlightIncomingEdges") ? (_b2 = canvas.edgeTo.get(canvas.nodes.get(nodeData.id))) != null ? _b2 : [] : [] ]; })); for (const edge of canvas.edges.values()) { - edge.lineGroupEl.classList.toggle( - "is-focused", - canvas.selection.has(edge) || connectedEdgesToBeHighlighted.has(edge) - ); + const isFocused = canvas.selection.has(edge) || connectedEdgesToBeHighlighted.has(edge); + edge.lineGroupEl.classList.toggle("is-focused", isFocused); + (_b = (_a = edge.lineEndGroupEl) == null ? void 0 : _a.classList) == null ? void 0 : _b.toggle("is-focused", isFocused); + (_e = (_d = (_c = edge.labelElement) == null ? void 0 : _c.textareaEl) == null ? void 0 : _d.classList) == null ? void 0 : _e.toggle("is-focused", isFocused); } } }; @@ -7159,7 +7177,7 @@ var NodeExposerExtension = class extends CanvasExtension { } setDataAttributes(element, nodeData) { for (const exposedDataKey of getExposedNodeData(this.plugin.settings)) { - const datasetPairs = nodeData[exposedDataKey] instanceof Object ? Object.entries(nodeData[exposedDataKey]) : [[exposedDataKey, nodeData[exposedDataKey]]]; + const datasetPairs = nodeData[exposedDataKey] && typeof nodeData[exposedDataKey] === "object" ? Object.entries(nodeData[exposedDataKey]) : [[exposedDataKey, nodeData[exposedDataKey]]]; for (const [key, value] of datasetPairs) { if (!value) delete element.dataset[key]; else element.dataset[key] = value; @@ -7190,7 +7208,7 @@ var NodeInteractionExposerExtension = class extends CanvasExtension { else interactionEl.dataset[modifiedKey] = value; } } - if (PortalsCanvasExtension.isPortalElement(node)) interactionEl.dataset.isFromPortal = "true"; + if (PortalsCanvasExtension.isPortalElement(node.id)) interactionEl.dataset.isFromPortal = "true"; else delete interactionEl.dataset.isFromPortal; } )); @@ -7215,7 +7233,7 @@ var EdgeExposerExtension = class extends CanvasExtension { const edgeData = edge == null ? void 0 : edge.getData(); if (!edgeData) return; for (const exposedDataKey of getExposedEdgeData(this.plugin.settings)) { - const datasetPairs = edgeData[exposedDataKey] instanceof Object ? Object.entries(edgeData[exposedDataKey]) : [[exposedDataKey, edgeData[exposedDataKey]]]; + const datasetPairs = edgeData[exposedDataKey] && typeof edgeData[exposedDataKey] === "object" ? Object.entries(edgeData[exposedDataKey]) : [[exposedDataKey, edgeData[exposedDataKey]]]; for (const [key, value] of datasetPairs) { const stringifiedKey = key == null ? void 0 : key.toString(); if (!stringifiedKey) continue; diff --git a/.obsidian/plugins/advanced-canvas/manifest.json b/.obsidian/plugins/advanced-canvas/manifest.json index ab70d2d..fe98a26 100644 --- a/.obsidian/plugins/advanced-canvas/manifest.json +++ b/.obsidian/plugins/advanced-canvas/manifest.json @@ -1,7 +1,7 @@ { "id": "advanced-canvas", "name": "Advanced Canvas", - "version": "5.6.5", + "version": "5.6.6", "minAppVersion": "1.1.0", "description": "Supercharge your canvas experience! Create presentations, flowcharts and more!", "author": "Developer-Mike", diff --git a/.obsidian/plugins/advanced-canvas/styles.css b/.obsidian/plugins/advanced-canvas/styles.css index 5592a62..514a19c 100644 --- a/.obsidian/plugins/advanced-canvas/styles.css +++ b/.obsidian/plugins/advanced-canvas/styles.css @@ -10,9 +10,6 @@ width: 100%; border-radius: 0 var(--input-radius) var(--input-radius) 0; } -.ac-settings-heading { - border-bottom: 1px solid var(--color-accent); -} .ac-settings-heading:not(:first-child) { margin-top: var(--size-4-10) !important; } @@ -154,7 +151,6 @@ details.setting-item > *:not(summary) { display: flex; flex-direction: column; justify-content: center; - min-height: 0 !important; text-align: center; vertical-align: middle; } @@ -457,10 +453,10 @@ details.setting-item > *:not(summary) { .canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-node:not(.is-focused) { filter: blur(5px); } -.canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-edges { +.canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-edges > g:not(.is-focused) { filter: blur(5px); } -.canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-path-label-wrapper { +.canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-path-label-wrapper > .canvas-path-label:not(.is-focused) { filter: blur(5px); } .canvas-wrapper.presentation-mode .canvas-controls { diff --git a/.obsidian/plugins/claudian/main.js b/.obsidian/plugins/claudian/main.js index fdc5813..9712e69 100644 --- a/.obsidian/plugins/claudian/main.js +++ b/.obsidian/plugins/claudian/main.js @@ -5,6 +5,9 @@ var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -28,13476 +31,14461 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/code.js +var require_code = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a3; + return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s, c3) => `${s}${c3}`, ""); + } + get names() { + var _a3; + return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names, c3) => { + if (c3 instanceof Name) + names[c3.str] = (names[c3.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i2 = 0; + while (i2 < args.length) { + addCodeArg(code, args[i2]); + code.push(strs[++i2]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i2 = 0; + while (i2 < args.length) { + expr.push(plus); + addCodeArg(expr, args[i2]); + expr.push(plus, safeStringify(strs[++i2])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i2 = 1; + while (i2 < expr.length - 1) { + if (expr[i2] === plus) { + const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]); + if (res !== void 0) { + expr.splice(i2 - 1, 3, res); + continue; + } + expr[i2++] = "+"; + } + i2++; + } + } + function mergeExprItems(a, b3) { + if (b3 === '""') + return a; + if (a === '""') + return b3; + if (typeof a == "string") { + if (b3 instanceof Name || a[a.length - 1] !== '"') + return; + if (typeof b3 != "string") + return `${a.slice(0, -1)}${b3}"`; + if (b3[0] === '"') + return a.slice(0, -1) + b3.slice(1); + return; + } + if (typeof b3 == "string" && b3[0] === '"' && !(a instanceof Name)) + return `"${a}${b3.slice(1)}`; + return; + } + function strConcat(c1, c22) { + return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str`${c1}${c22}`; + } + exports.strConcat = strConcat; + function interpolate(x3) { + return typeof x3 == "number" || typeof x3 == "boolean" || x3 === null ? x3 : safeStringify(Array.isArray(x3) ? x3.join(",") : x3); + } + function stringify(x3) { + return new _Code(safeStringify(x3)); + } + exports.stringify = stringify; + function safeStringify(x3) { + return JSON.stringify(x3).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a3, _b; + if (((_b = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return this._names[prefix] = { prefix, index: 0 }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a3; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c3 = valueCode(name); + if (c3) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c3};${this.opts._n}`; + } else if (c3 = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { + code = (0, code_1._)`${code}${c3}${this.opts._n}`; + } else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code(); + var scope_1 = require_scope(); + var code_2 = require_code(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + }; + var Throw = class extends Node { + constructor(error48) { + super(); + this.error = error48; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n2) => code + n2.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i2 = nodes.length; + while (i2--) { + const n2 = nodes[i2].optimizeNodes(); + if (Array.isArray(n2)) + nodes.splice(i2, 1, ...n2); + else if (n2) + nodes[i2] = n2; + else + nodes.splice(i2, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i2 = nodes.length; + while (i2--) { + const n2 = nodes[i2]; + if (n2.optimizeNames(names, constants)) + continue; + subtractNames(names, n2.names); + nodes.splice(i2, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n2) => addNames(names, n2.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class _If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e2 = this.else; + if (e2) { + const ns = e2.optimizeNodes(); + e2 = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e2) { + if (cond === false) + return e2 instanceof _If ? e2 : e2.nodes; + if (this.nodes.length) + return this; + return new _If(not(cond), e2 instanceof _If ? [e2] : e2.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; + } + optimizeNames(names, constants) { + var _a3; + this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a3, _b; + super.optimizeNodes(); + (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a3, _b; + super.optimizeNames(names, constants); + (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error48) { + super(); + this.error = error48; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c3) { + if (typeof c3 == "function") + c3(); + else if (c3 !== code_1.nil) + this._leafNode(new AnyCode(c3)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => { + this.var(name, (0, code_1._)`${arr}[${i2}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error48 = this.name("e"); + this._currNode = node.catch = new Catch(error48); + catchCode(error48); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error48) { + return this._leafNode(new Throw(error48)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n2 = 1) { + while (n2-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N12, N22) { + const n2 = this._currNode; + if (n2 instanceof N12 || N22 && n2 instanceof N22) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N22 ? `${N12.kind}/${N22.kind}` : N12.kind}"`); + } + _elseNode(node) { + const n2 = this._currNode; + if (!(n2 instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n2.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n2 in from) + names[n2] = (names[n2] || 0) + (from[n2] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c3) => { + if (c3 instanceof code_1.Name) + c3 = replaceName(c3); + if (c3 instanceof code_1._Code) + items.push(...c3._items); + else + items.push(c3); + return items; + }, [])); + function replaceName(n2) { + const c3 = constants[n2.str]; + if (c3 === void 0 || names[n2.str] !== 1) + return n2; + delete names[n2.str]; + return c3; + } + function canOptimize(e2) { + return e2 instanceof code_1._Code && e2._items.some((c3) => c3 instanceof code_1.Name && names[c3.str] === 1 && constants[c3.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n2 in from) + names[n2] = (names[n2] || 0) - (from[n2] || 0); + } + function not(x3) { + return typeof x3 == "boolean" || typeof x3 == "number" || x3 === null ? !x3 : (0, code_1._)`!${par(x3)}`; + } + exports.not = not; + var andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + var orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x3, y3) => x3 === code_1.nil ? y3 : y3 === code_1.nil ? x3 : (0, code_1._)`${par(x3)} ${op} ${par(y3)}`; + } + function par(x3) { + return x3 instanceof code_1.Name ? x3 : (0, code_1._)`(${x3})`; + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/util.js +var require_util = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code(); + function toHash(arr) { + const hash2 = {}; + for (const item of arr) + hash2[item] = true; + return hash2; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self: self2 } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self2.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f3) { + if (Array.isArray(xs)) { + for (const x3 of xs) + f3(x3); + } else { + f3(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { ...from, ...to }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f3) { + return gen.scopeValue("func", { + ref: f3, + code: snippets[f3.code] || (snippets[f3.code] = new code_1._Code(f3.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/names.js +var require_names = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var names = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/errors.js +var require_errors = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + }; + function reportError(cxt, error48 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error48, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error48 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error48, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i2) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E3 = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error48, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error48, errorPaths); + } + function errorObject(cxt, error48, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error48, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E3.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E3.keyword, keyword], [E3.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E3.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E3.schema, schemaValue], [E3.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E3.propertyName, propertyName]); + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { + message: "boolean schema is false" + }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); + } + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/rules.js +var require_rules = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x3) { + return typeof x3 == "string" && jsonTypes.has(x3); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self: self2 }, type) { + const group = self2.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a3; + return schema[rule.keyword] !== void 0 || ((_a3 = rule.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + const hasNull = types.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) + return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t2) => COERCIBLE.has(t2) || coerceTypes === "array" && t2 === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t2 of coerceTo) { + if (COERCIBLE.has(t2) || t2 === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t2); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t2) { + switch (t2) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ2 = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ2} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ2} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else { + cond = codegen_1.nil; + } + if (types.number) + delete types.integer; + for (const t2 in types) + cond = (0, codegen_1.and)(cond, checkDataType(t2, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i2) => assignDefault(it, i2, sch.default)); + } + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + } + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/code.js +var require_code2 = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + var util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p2) => p2 !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p2])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i2) => { + cxt.subschema({ + keyword, + dataProp: i2, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i2) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i2, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code2(); + var errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a3; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a4; + gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self2.logger.error(msg); + else + throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports, module2) { + "use strict"; + module2.exports = function equal(a, b3) { + if (a === b3) return true; + if (a && b3 && typeof a == "object" && typeof b3 == "object") { + if (a.constructor !== b3.constructor) return false; + var length, i2, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b3.length) return false; + for (i2 = length; i2-- !== 0; ) + if (!equal(a[i2], b3[i2])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b3.source && a.flags === b3.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b3.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b3.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b3).length) return false; + for (i2 = length; i2-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b3, keys[i2])) return false; + for (i2 = length; i2-- !== 0; ) { + var key = keys[i2]; + if (!equal(a[key], b3[key])) return false; + } + return true; + } + return a !== a && b3 !== b3; + }; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/node_modules/json-schema-traverse/index.js"(exports, module2) { + "use strict"; + var traverse = module2.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post = cb.post || function() { + }; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i2 = 0; i2 < sch.length; i2++) + _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2); + } + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { + _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/resolve.js +var require_resolve = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/resolve.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util(); + var equal = require_fast_deep_equal(); + var traverse = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") + return true; + if (limit === true) + return !hasRef(schema); + if (!limit) + return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + } + if (count === Infinity) + return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize2) { + if (normalize2 !== false) + id = normalizeId(id); + const p2 = resolver.parse(id); + return _getFullPath(resolver, p2); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p2) { + const serialized = resolver.serialize(p2); + return serialized.split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/index.js +var require_validate = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/validate/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self: self2 }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self2.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); + schemaKeywords(it, types, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self: self2 } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) { + self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self: self2 } = it; + const { RULES } = self2; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) + checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t2) => { + if (!includesType(it.dataTypes, t2)) { + strictTypesError(it, `type "${t2}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t2) => hasApplicableType(ts, t2))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t2) { + return ts.includes(t2) || t2 === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t2 of it.dataTypes) { + if (includesType(withTypes, t2)) + ts.push(t2); + else if (withTypes.includes("integer") && t2 === "number") + ts.push("integer"); + } + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/index.js +var require_compile = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a3; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e2) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e2; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a3; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve4.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref]; + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s12, s2) { + return s12.schema === s2.schema && s12.root === s2.root && s12.baseId === s2.baseId; + } + function resolve4(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p2 = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p2); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p2, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p2, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p2, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a3; + if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return void 0; + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/data.json +var require_data = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/data.json"(exports, module2) { + module2.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false + }; + } +}); + +// node_modules/fast-uri/lib/utils.js +var require_utils = __commonJS({ + "node_modules/fast-uri/lib/utils.js"(exports, module2) { + "use strict"; + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i2 = 0; + for (i2 = 0; i2 < input.length; i2++) { + code = input[i2].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i2]; + break; + } + for (i2 += 1; i2 < input.length; i2++) { + code = input[i2].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i2]; + } + return acc; + } + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex3 = stringArrayToHexStripped(buffer); + if (hex3 !== "") { + address.push(hex3); + } else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + function getIPV6(input) { + let tokenCount = 0; + const output = { error: false, address: "", zone: "" }; + const address = []; + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i2 = 0; i2 < input.length; i2++) { + const cursor = input[i2]; + if (cursor === "[" || cursor === "]") { + continue; + } + if (cursor === ":") { + if (endipv6Encountered === true) { + endIpv6 = true; + } + if (!consume(buffer, address, output)) { + break; + } + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i2 > 0 && input[i2 - 1] === ":") { + endipv6Encountered = true; + } + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) { + break; + } + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) { + if (consume === consumeIsZone) { + output.zone = buffer.join(""); + } else if (endIpv6) { + address.push(buffer.join("")); + } else { + address.push(stringArrayToHexStripped(buffer)); + } + } + output.address = address.join(""); + return output; + } + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) { + return { host, isIPV6: false }; + } + const ipv63 = getIPV6(host); + if (!ipv63.error) { + let newHost = ipv63.address; + let escapedHost = ipv63.address; + if (ipv63.zone) { + newHost += "%" + ipv63.zone; + escapedHost += "%25" + ipv63.zone; + } + return { host: newHost, isIPV6: true, escapedHost }; + } else { + return { host, isIPV6: false }; + } + } + function findToken(str, token) { + let ind = 0; + for (let i2 = 0; i2 < str.length; i2++) { + if (str[i2] === token) ind++; + } + return ind; + } + function removeDotSegments(path10) { + let input = path10; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + function normalizeComponentEncoding(component, esc2) { + const func = esc2 !== true ? escape : unescape; + if (component.scheme !== void 0) { + component.scheme = func(component.scheme); + } + if (component.userinfo !== void 0) { + component.userinfo = func(component.userinfo); + } + if (component.host !== void 0) { + component.host = func(component.host); + } + if (component.path !== void 0) { + component.path = func(component.path); + } + if (component.query !== void 0) { + component.query = func(component.query); + } + if (component.fragment !== void 0) { + component.fragment = func(component.fragment); + } + return component; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = component.host; + } + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module2.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; + } +}); + +// node_modules/fast-uri/lib/schemes.js +var require_schemes = __commonJS({ + "node_modules/fast-uri/lib/schemes.js"(exports, module2) { + "use strict"; + var { isUUID } = require_utils(); + var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ] + ); + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; + } + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; + } + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; + } + if (!component.path) { + component.path = "/"; + } + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; + } + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path10, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path10 && path10 !== "/" ? path10 : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); + } + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; + } + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); + } + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); + } + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; + } + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + } + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + } + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + } + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + } + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + } + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + ); + var SCHEMES = ( + /** @type {Record} */ + { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + } + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module2.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// node_modules/fast-uri/index.js +var require_fast_uri = __commonJS({ + "node_modules/fast-uri/index.js"(exports, module2) { + "use strict"; + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + function normalize2(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + serialize(parse3(uri, options), options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse3(serialize(uri, options), options); + } + return uri; + } + function resolve4(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function resolveComponent(base, relative3, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse3(serialize(base, options), options); + relative3 = parse3(serialize(relative3, options), options); + } + options = options || {}; + if (!options.tolerant && relative3.scheme) { + target.scheme = relative3.scheme; + target.userinfo = relative3.userinfo; + target.host = relative3.host; + target.port = relative3.port; + target.path = removeDotSegments(relative3.path || ""); + target.query = relative3.query; + } else { + if (relative3.userinfo !== void 0 || relative3.host !== void 0 || relative3.port !== void 0) { + target.userinfo = relative3.userinfo; + target.host = relative3.host; + target.port = relative3.port; + target.path = removeDotSegments(relative3.path || ""); + target.query = relative3.query; + } else { + if (!relative3.path) { + target.path = base.path; + if (relative3.query !== void 0) { + target.query = relative3.query; + } else { + target.query = base.query; + } + } else { + if (relative3.path[0] === "/") { + target.path = removeDotSegments(relative3.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative3.path; + } else if (!base.path) { + target.path = relative3.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative3.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative3.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative3.fragment; + return target; + } + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse3(uriA, options), true), { ...options, skipEscape: true }); + } else if (typeof uriA === "object") { + uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); + } + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse3(uriB, options), true), { ...options, skipEscape: true }); + } else if (typeof uriB === "object") { + uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); + } + return uriA.toLowerCase() === uriB.toLowerCase(); + } + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) { + component.path = component.path.split("%3A").join(":"); + } + } else { + component.path = unescape(component.path); + } + } + if (options.reference !== "suffix" && component.scheme) { + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); + } + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === void 0 && s[0] === "/" && s[1] === "/") { + s = "/%2F" + s.slice(2); + } + uriTokens.push(s); + } + if (component.query !== void 0) { + uriTokens.push("?", component.query); + } + if (component.fragment !== void 0) { + uriTokens.push("#", component.fragment); + } + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + function parse3(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else { + isIP = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { + try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e2) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e2; + } + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) { + parsed.scheme = unescape(parsed.scheme); + } + if (parsed.host !== void 0) { + parsed.host = unescape(parsed.host); + } + } + if (parsed.path) { + parsed.path = escape(unescape(parsed.path)); + } + if (parsed.fragment) { + parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; + } + return parsed; + } + var fastUri = { + SCHEMES, + normalize: normalize2, + resolve: resolve4, + resolveComponent, + equal, + serialize, + parse: parse3 + }; + module2.exports = fastUri; + module2.exports.default = fastUri; + module2.exports.fastUri = fastUri; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/uri.js +var require_uri = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/uri.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/core.js +var require_core = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/core.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); + var util_1 = require_util(); + var $dataRefSchema = require_data(); + var uri_1 = require_uri(); + var defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q2, _r, _s, _t, _u, _v, _w, _x, _y, _z, _02; + const s = o.strict; + const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q2 = o.loopRequired) !== null && _q2 !== void 0 ? _q2 : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_02 = o.int32range) !== null && _02 !== void 0 ? _02 : true, + uriResolver + }; + } + var Ajv2 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta: meta3, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta3 && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta: meta3, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; + } + validate(schemaKeyRef, data) { + let v3; + if (typeof schemaKeyRef == "string") { + v3 = this.getSchema(schemaKeyRef); + if (!v3) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v3 = this.compile(schemaKeyRef); + } + const valid = v3(data); + if (!("$async" in v3)) + this.errors = v3.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta3) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta3); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e2) { + if (!(e2 instanceof ref_error_1.default)) + throw e2; + checkLoaded.call(this, e2); + await loadMissingSchema.call(this, e2.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta3); + } + async function _loadSchema(ref) { + const p2 = this._loading[ref]; + if (p2) + return p2; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t2) => addRule.call(this, k, definition, t2))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i2 = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i2 >= 0) + group.rules.splice(i2, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger) { + if (logger === false) + return noLogs; + if (logger === void 0) + return console; + if (logger.log && logger.warn && logger.error) + return logger; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a3; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i2 >= 0) { + ruleGroup.rules.splice(i2, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v3 = getValidate(cxt, sch); + callRef(cxt, v3, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v3, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v3, passCxt)}`); + addEvaluatedFrom(v3); + if (!allErrors) + gen.assign(valid, true); + }, (e2) => { + gen.if((0, codegen_1._)`!(${e2} instanceof ${it.ValidationError})`, () => gen.throw(e2)); + addErrorsFrom(e2); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v3, passCxt), () => addEvaluatedFrom(v3), () => addErrorsFrom(v3)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a3; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + } + exports.callRef = callRef; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/index.js +var require_core2 = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id(); + var ref_1 = require_ref(); + var core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error48 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error48 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var ucs2length_1 = require_ucs2length(); + var error48 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var error48 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: error48, + code(cxt) { + const { data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error48 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error48 = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: error48, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error48 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error48 = { + message: ({ params: { i: i2, j: j3 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j3} and ${i2} are identical)`, + params: ({ params: { i: i2, j: j3 } }) => (0, codegen_1._)`{i: ${i2}, j: ${j3}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: error48, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i2 = gen.let("i", (0, codegen_1._)`${data}.length`); + const j3 = gen.let("j"); + cxt.setParams({ i: i2, j: j3 }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j3)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t2) => t2 === "object" || t2 === "array"); + } + function loopN(i2, j3) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i2}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i2}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j3, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`); + }); + } + function loopN2(i2, j3) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j3} = ${i2}; ${j3}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i2}], ${data}[${j3}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error48 = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error: error48, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error48 = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: error48, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i2) => equalCode(vSchema, i2))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v3) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v3})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i2) { + const sch = schema[i2]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error48 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: error48, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i2) => { + cxt.subschema({ keyword, dataProp: i2, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i2) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i2}`, () => cxt.subschema({ + keyword, + schemaProp: i2, + dataProp: i2 + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l3 = schArr.length; + const fullTuple = l3 === sch.minItems && (l3 === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l3}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var additionalItems_1 = require_additionalItems(); + var error48 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: error48, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error48 = { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: error48, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ min, max }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) + gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i2) => { + cxt.subschema({ + keyword: "contains", + dataProp: i2, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) { + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error48 = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: error48, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util(); + var error48 = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: error48, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + } + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code2(); + var util_1 = require_util(); + var additionalProperties_1 = require_additionalProperties(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it, schema[p2])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var util_2 = require_util(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it, schema[p2])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error48 = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: error48, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i2) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i2, + compositeRule: true + }, schValid); + } + if (i2 > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i2); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i2) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error48 = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: error48, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/format.js +var require_format = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error48 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: error48, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self: self2 } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self2.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self2.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/index.js +var require_format2 = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var format_1 = require_format(); + var format = [format_1.default]; + exports.default = format; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core2(); + var validation_1 = require_validation(); + var applicator_1 = require_applicator(); + var format_1 = require_format2(); + var metadata_1 = require_metadata(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types(); + var compile_1 = require_compile(); + var ref_error_1 = require_ref_error(); + var util_1 = require_util(); + var error48 = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }; + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: error48, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a3; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i2 = 0; i2 < oneOf.length; i2++) { + let sch = oneOf[i2]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i2); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required: required2 }) { + return Array.isArray(required2) && required2.includes(tagName); + } + function addMappings(sch, i2) { + if (sch.const) { + addMapping(sch.const, i2); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i2); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i2) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i2; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module2) { + module2.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] + } + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] + } + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true + }; + } +}); + +// node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/ajv.js +var require_ajv = __commonJS({ + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv/dist/ajv.js"(exports, module2) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = require_json_schema_draft_07(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv2 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v3) => this.addVocabulary(v3)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv2; + module2.exports = exports = Ajv2; + module2.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// node_modules/ajv-formats/dist/formats.js +var require_formats = __commonJS({ + "node_modules/ajv-formats/dist/formats.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { validate, compare }; + } + exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date7, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function date7(str) { + const matches = DATE.exec(str); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) + return void 0; + if (d1 > d2) + return 1; + if (d1 < d2) + return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time4(str) { + const matches = TIME.exec(str); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) + return false; + if (hr <= 23 && min <= 59 && sec < 60) + return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s12, s2) { + if (!(s12 && s2)) + return void 0; + const t12 = (/* @__PURE__ */ new Date("2020-01-01T" + s12)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t12 && t2)) + return void 0; + return t12 - t2; + } + function compareIsoTime(t12, t2) { + if (!(t12 && t2)) + return void 0; + const a12 = TIME.exec(t12); + const a2 = TIME.exec(t2); + if (!(a12 && a2)) + return void 0; + t12 = a12[1] + a12[2] + a12[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t12 > t2) + return 1; + if (t12 < t2) + return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time4 = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date7(dateTime[0]) && time4(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) + return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const [d1, t12] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) + return void 0; + return res || compareTime(t12, t2); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str); + return true; + } catch (e2) { + return false; + } + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js +var require_code3 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a3; + return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s, c3) => `${s}${c3}`, ""); + } + get names() { + var _a3; + return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names, c3) => { + if (c3 instanceof Name) + names[c3.str] = (names[c3.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i2 = 0; + while (i2 < args.length) { + addCodeArg(code, args[i2]); + code.push(strs[++i2]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i2 = 0; + while (i2 < args.length) { + expr.push(plus); + addCodeArg(expr, args[i2]); + expr.push(plus, safeStringify(strs[++i2])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i2 = 1; + while (i2 < expr.length - 1) { + if (expr[i2] === plus) { + const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]); + if (res !== void 0) { + expr.splice(i2 - 1, 3, res); + continue; + } + expr[i2++] = "+"; + } + i2++; + } + } + function mergeExprItems(a, b3) { + if (b3 === '""') + return a; + if (a === '""') + return b3; + if (typeof a == "string") { + if (b3 instanceof Name || a[a.length - 1] !== '"') + return; + if (typeof b3 != "string") + return `${a.slice(0, -1)}${b3}"`; + if (b3[0] === '"') + return a.slice(0, -1) + b3.slice(1); + return; + } + if (typeof b3 == "string" && b3[0] === '"' && !(a instanceof Name)) + return `"${a}${b3.slice(1)}`; + return; + } + function strConcat(c1, c22) { + return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str`${c1}${c22}`; + } + exports.strConcat = strConcat; + function interpolate(x3) { + return typeof x3 == "number" || typeof x3 == "boolean" || x3 === null ? x3 : safeStringify(Array.isArray(x3) ? x3.join(",") : x3); + } + function stringify(x3) { + return new _Code(safeStringify(x3)); + } + exports.stringify = stringify; + function safeStringify(x3) { + return JSON.stringify(x3).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code3(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a3, _b; + if (((_b = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return this._names[prefix] = { prefix, index: 0 }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a3; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c3 = valueCode(name); + if (c3) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c3};${this.opts._n}`; + } else if (c3 = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { + code = (0, code_1._)`${code}${c3}${this.opts._n}`; + } else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code3(); + var scope_1 = require_scope2(); + var code_2 = require_code3(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope2(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + }; + var Throw = class extends Node { + constructor(error48) { + super(); + this.error = error48; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n2) => code + n2.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i2 = nodes.length; + while (i2--) { + const n2 = nodes[i2].optimizeNodes(); + if (Array.isArray(n2)) + nodes.splice(i2, 1, ...n2); + else if (n2) + nodes[i2] = n2; + else + nodes.splice(i2, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i2 = nodes.length; + while (i2--) { + const n2 = nodes[i2]; + if (n2.optimizeNames(names, constants)) + continue; + subtractNames(names, n2.names); + nodes.splice(i2, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n2) => addNames(names, n2.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class _If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e2 = this.else; + if (e2) { + const ns = e2.optimizeNodes(); + e2 = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e2) { + if (cond === false) + return e2 instanceof _If ? e2 : e2.nodes; + if (this.nodes.length) + return this; + return new _If(not(cond), e2 instanceof _If ? [e2] : e2.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; + } + optimizeNames(names, constants) { + var _a3; + this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a3, _b; + super.optimizeNodes(); + (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a3, _b; + super.optimizeNames(names, constants); + (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error48) { + super(); + this.error = error48; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c3) { + if (typeof c3 == "function") + c3(); + else if (c3 !== code_1.nil) + this._leafNode(new AnyCode(c3)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => { + this.var(name, (0, code_1._)`${arr}[${i2}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error48 = this.name("e"); + this._currNode = node.catch = new Catch(error48); + catchCode(error48); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error48) { + return this._leafNode(new Throw(error48)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n2 = 1) { + while (n2-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N12, N22) { + const n2 = this._currNode; + if (n2 instanceof N12 || N22 && n2 instanceof N22) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N22 ? `${N12.kind}/${N22.kind}` : N12.kind}"`); + } + _elseNode(node) { + const n2 = this._currNode; + if (!(n2 instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n2.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n2 in from) + names[n2] = (names[n2] || 0) + (from[n2] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c3) => { + if (c3 instanceof code_1.Name) + c3 = replaceName(c3); + if (c3 instanceof code_1._Code) + items.push(...c3._items); + else + items.push(c3); + return items; + }, [])); + function replaceName(n2) { + const c3 = constants[n2.str]; + if (c3 === void 0 || names[n2.str] !== 1) + return n2; + delete names[n2.str]; + return c3; + } + function canOptimize(e2) { + return e2 instanceof code_1._Code && e2._items.some((c3) => c3 instanceof code_1.Name && names[c3.str] === 1 && constants[c3.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n2 in from) + names[n2] = (names[n2] || 0) - (from[n2] || 0); + } + function not(x3) { + return typeof x3 == "boolean" || typeof x3 == "number" || x3 === null ? !x3 : (0, code_1._)`!${par(x3)}`; + } + exports.not = not; + var andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + var orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x3, y3) => x3 === code_1.nil ? y3 : y3 === code_1.nil ? x3 : (0, code_1._)`${par(x3)} ${op} ${par(y3)}`; + } + function par(x3) { + return x3 instanceof code_1.Name ? x3 : (0, code_1._)`(${x3})`; + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js +var require_util2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen2(); + var code_1 = require_code3(); + function toHash(arr) { + const hash2 = {}; + for (const item of arr) + hash2[item] = true; + return hash2; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self: self2 } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self2.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f3) { + if (Array.isArray(xs)) { + for (const x3 of xs) + f3(x3); + } else { + f3(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { ...from, ...to }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f3) { + return gen.scopeValue("func", { + ref: f3, + code: snippets[f3.code] || (snippets[f3.code] = new code_1._Code(f3.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js +var require_names2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var names = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js +var require_errors2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var names_1 = require_names2(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + }; + function reportError(cxt, error48 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error48, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error48 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error48, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i2) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E3 = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error48, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error48, errorPaths); + } + function errorObject(cxt, error48, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error48, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E3.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E3.keyword, keyword], [E3.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E3.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E3.schema, schemaValue], [E3.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E3.propertyName, propertyName]); + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors2(); + var codegen_1 = require_codegen2(); + var names_1 = require_names2(); + var boolError = { + message: "boolean schema is false" + }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); + } + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js +var require_rules2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x3) { + return typeof x3 == "string" && jsonTypes.has(x3); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self: self2 }, type) { + const group = self2.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a3; + return schema[rule.keyword] !== void 0 || ((_a3 = rule.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules2(); + var applicability_1 = require_applicability2(); + var errors_1 = require_errors2(); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + const hasNull = types.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) + return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t2) => COERCIBLE.has(t2) || coerceTypes === "array" && t2 === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t2 of coerceTo) { + if (COERCIBLE.has(t2) || t2 === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t2); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t2) { + switch (t2) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ2 = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ2} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ2} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else { + cond = codegen_1.nil; + } + if (types.number) + delete types.integer; + for (const t2 in types) + cond = (0, codegen_1.and)(cond, checkDataType(t2, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i2) => assignDefault(it, i2, sch.default)); + } + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + } + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js +var require_code4 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var names_1 = require_names2(); + var util_2 = require_util2(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p2) => p2 !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p2])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i2) => { + cxt.subschema({ + keyword, + dataProp: i2, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i2) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i2, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen2(); + var names_1 = require_names2(); + var code_1 = require_code4(); + var errors_1 = require_errors2(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a3; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a4; + gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self2.logger.error(msg); + else + throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/node_modules/json-schema-traverse/index.js"(exports, module2) { + "use strict"; + var traverse = module2.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post = cb.post || function() { + }; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i2 = 0; i2 < sch.length; i2++) + _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2); + } + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { + _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js +var require_resolve2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/resolve.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util2(); + var equal = require_fast_deep_equal(); + var traverse = require_json_schema_traverse2(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") + return true; + if (limit === true) + return !hasRef(schema); + if (!limit) + return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + } + if (count === Infinity) + return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize2) { + if (normalize2 !== false) + id = normalizeId(id); + const p2 = resolver.parse(id); + return _getFullPath(resolver, p2); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p2) { + const serialized = resolver.serialize(p2); + return serialized.split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js +var require_validate2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/validate/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema2(); + var dataType_1 = require_dataType2(); + var applicability_1 = require_applicability2(); + var dataType_2 = require_dataType2(); + var defaults_1 = require_defaults2(); + var keyword_1 = require_keyword2(); + var subschema_1 = require_subschema2(); + var codegen_1 = require_codegen2(); + var names_1 = require_names2(); + var resolve_1 = require_resolve2(); + var util_1 = require_util2(); + var errors_1 = require_errors2(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self: self2 }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self2.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); + schemaKeywords(it, types, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self: self2 } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) { + self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self: self2 } = it; + const { RULES } = self2; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) + checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t2) => { + if (!includesType(it.dataTypes, t2)) { + strictTypesError(it, `type "${t2}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t2) => hasApplicableType(ts, t2))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t2) { + return ts.includes(t2) || t2 === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t2 of it.dataTypes) { + if (includesType(withTypes, t2)) + ts.push(t2); + else if (withTypes.includes("integer") && t2 === "number") + ts.push("integer"); + } + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve2(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js +var require_compile2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen2(); + var validation_error_1 = require_validation_error2(); + var names_1 = require_names2(); + var resolve_1 = require_resolve2(); + var util_1 = require_util2(); + var validate_1 = require_validate2(); + var SchemaEnv = class { + constructor(env) { + var _a3; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e2) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e2; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a3; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve4.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref]; + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s12, s2) { + return s12.schema === s2.schema && s12.root === s2.root && s12.baseId === s2.baseId; + } + function resolve4(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p2 = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p2); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p2, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p2, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p2, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a3; + if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return void 0; + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json +var require_data2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/refs/data.json"(exports, module2) { + module2.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false + }; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js +var require_uri2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/runtime/uri.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/core.js +var require_core3 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/core.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate2(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen2(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error2(); + var ref_error_1 = require_ref_error2(); + var rules_1 = require_rules2(); + var compile_1 = require_compile2(); + var codegen_2 = require_codegen2(); + var resolve_1 = require_resolve2(); + var dataType_1 = require_dataType2(); + var util_1 = require_util2(); + var $dataRefSchema = require_data2(); + var uri_1 = require_uri2(); + var defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q2, _r, _s, _t, _u, _v, _w, _x, _y, _z, _02; + const s = o.strict; + const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q2 = o.loopRequired) !== null && _q2 !== void 0 ? _q2 : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_02 = o.int32range) !== null && _02 !== void 0 ? _02 : true, + uriResolver + }; + } + var Ajv2 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta: meta3, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta3 && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta: meta3, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0; + } + validate(schemaKeyRef, data) { + let v3; + if (typeof schemaKeyRef == "string") { + v3 = this.getSchema(schemaKeyRef); + if (!v3) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v3 = this.compile(schemaKeyRef); + } + const valid = v3(data); + if (!("$async" in v3)) + this.errors = v3.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta3) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta3); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e2) { + if (!(e2 instanceof ref_error_1.default)) + throw e2; + checkLoaded.call(this, e2); + await loadMissingSchema.call(this, e2.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta3); + } + async function _loadSchema(ref) { + const p2 = this._loading[ref]; + if (p2) + return p2; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t2) => addRule.call(this, k, definition, t2))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i2 = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i2 >= 0) + group.rules.splice(i2, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger) { + if (logger === false) + return noLogs; + if (logger === void 0) + return console; + if (logger.log && logger.warn && logger.error) + return logger; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a3; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i2 >= 0) { + ruleGroup.rules.splice(i2, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js +var require_id2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error2(); + var code_1 = require_code4(); + var codegen_1 = require_codegen2(); + var names_1 = require_names2(); + var compile_1 = require_compile2(); + var util_1 = require_util2(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v3 = getValidate(cxt, sch); + callRef(cxt, v3, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v3, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v3, passCxt)}`); + addEvaluatedFrom(v3); + if (!allErrors) + gen.assign(valid, true); + }, (e2) => { + gen.if((0, codegen_1._)`!(${e2} instanceof ${it.ValidationError})`, () => gen.throw(e2)); + addErrorsFrom(e2); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v3, passCxt), () => addEvaluatedFrom(v3), () => addErrorsFrom(v3)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a3; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + } + exports.callRef = callRef; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js +var require_core4 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id2(); + var ref_1 = require_ref2(); + var core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error48 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var error48 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var ucs2length_1 = require_ucs2length2(); + var error48 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code4(); + var codegen_1 = require_codegen2(); + var error48 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: error48, + code(cxt) { + const { data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var error48 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code4(); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var error48 = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: error48, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var error48 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: error48, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js +var require_equal2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType2(); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var equal_1 = require_equal2(); + var error48 = { + message: ({ params: { i: i2, j: j3 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j3} and ${i2} are identical)`, + params: ({ params: { i: i2, j: j3 } }) => (0, codegen_1._)`{i: ${i2}, j: ${j3}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: error48, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i2 = gen.let("i", (0, codegen_1._)`${data}.length`); + const j3 = gen.let("j"); + cxt.setParams({ i: i2, j: j3 }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j3)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t2) => t2 === "object" || t2 === "array"); + } + function loopN(i2, j3) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i2}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i2}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j3, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`); + }); + } + function loopN2(i2, j3) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j3} = ${i2}; ${j3}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i2}], ${data}[${j3}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var equal_1 = require_equal2(); + var error48 = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error: error48, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var equal_1 = require_equal2(); + var error48 = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: error48, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i2) => equalCode(vSchema, i2))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v3) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v3})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i2) { + const sch = schema[i2]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber2(); + var multipleOf_1 = require_multipleOf2(); + var limitLength_1 = require_limitLength2(); + var pattern_1 = require_pattern2(); + var limitProperties_1 = require_limitProperties2(); + var required_1 = require_required2(); + var limitItems_1 = require_limitItems2(); + var uniqueItems_1 = require_uniqueItems2(); + var const_1 = require_const2(); + var enum_1 = require_enum2(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var error48 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: error48, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i2) => { + cxt.subschema({ keyword, dataProp: i2, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var code_1 = require_code4(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i2) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i2}`, () => cxt.subschema({ + keyword, + schemaProp: i2, + dataProp: i2 + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l3 = schArr.length; + const fullTuple = l3 === sch.minItems && (l3 === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l3}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items2(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items20202 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var code_1 = require_code4(); + var additionalItems_1 = require_additionalItems2(); + var error48 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: error48, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var error48 = { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: error48, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ min, max }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) + gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i2) => { + cxt.subschema({ + keyword: "contains", + dataProp: i2, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) { + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var code_1 = require_code4(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var error48 = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: error48, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code4(); + var codegen_1 = require_codegen2(); + var names_1 = require_names2(); + var util_1 = require_util2(); + var error48 = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: error48, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + } + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate2(); + var code_1 = require_code4(); + var util_1 = require_util2(); + var additionalProperties_1 = require_additionalProperties2(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it, schema[p2])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code4(); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var util_2 = require_util2(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it, schema[p2])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code4(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var error48 = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: error48, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i2) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i2, + compositeRule: true + }, schValid); + } + if (i2 > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i2); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i2) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var util_1 = require_util2(); + var error48 = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: error48, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems2(); + var prefixItems_1 = require_prefixItems2(); + var items_1 = require_items2(); + var items2020_1 = require_items20202(); + var contains_1 = require_contains2(); + var dependencies_1 = require_dependencies2(); + var propertyNames_1 = require_propertyNames2(); + var additionalProperties_1 = require_additionalProperties2(); + var properties_1 = require_properties2(); + var patternProperties_1 = require_patternProperties2(); + var not_1 = require_not2(); + var anyOf_1 = require_anyOf2(); + var oneOf_1 = require_oneOf2(); + var allOf_1 = require_allOf2(); + var if_1 = require_if2(); + var thenElse_1 = require_thenElse2(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js +var require_format3 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var error48 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: error48, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self: self2 } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self2.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self2.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js +var require_format4 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var format_1 = require_format3(); + var format = [format_1.default]; + exports.default = format; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft72 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core4(); + var validation_1 = require_validation2(); + var applicator_1 = require_applicator2(); + var format_1 = require_format4(); + var metadata_1 = require_metadata2(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen2(); + var types_1 = require_types2(); + var compile_1 = require_compile2(); + var ref_error_1 = require_ref_error2(); + var util_1 = require_util2(); + var error48 = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }; + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: error48, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a3; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i2 = 0; i2 < oneOf.length; i2++) { + let sch = oneOf[i2]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i2); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required: required2 }) { + return Array.isArray(required2) && required2.includes(tagName); + } + function addMappings(sch, i2) { + if (sch.const) { + addMapping(sch.const, i2); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i2); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i2) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i2; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_072 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module2) { + module2.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] + } + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] + } + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true + }; + } +}); + +// node_modules/ajv-formats/node_modules/ajv/dist/ajv.js +var require_ajv2 = __commonJS({ + "node_modules/ajv-formats/node_modules/ajv/dist/ajv.js"(exports, module2) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core3(); + var draft7_1 = require_draft72(); + var discriminator_1 = require_discriminator2(); + var draft7MetaSchema = require_json_schema_draft_072(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv2 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v3) => this.addVocabulary(v3)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv2; + module2.exports = exports = Ajv2; + module2.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + var validate_1 = require_validate2(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen2(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error2(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error2(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// node_modules/ajv-formats/dist/limit.js +var require_limit = __commonJS({ + "node_modules/ajv-formats/dist/limit.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv2(); + var codegen_1 = require_codegen2(); + var ops = codegen_1.operators; + var KWDs = { + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error48 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error: error48, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self: self2 } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self2.formats[format]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + var formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; + } +}); + +// node_modules/ajv-formats/dist/index.js +var require_dist = __commonJS({ + "node_modules/ajv-formats/dist/index.js"(exports, module2) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats(); + var limit_1 = require_limit(); + var codegen_1 = require_codegen2(); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list = opts.formats || formats_1.formatNames; + addFormats(ajv, list, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f3 = formats[name]; + if (!f3) + throw new Error(`Unknown format "${name}"`); + return f3; + }; + function addFormats(ajv, list, fs10, exportName) { + var _a3; + var _b; + (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; + for (const f3 of list) + ajv.addFormat(f3, fs10[f3]); + } + module2.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; + } +}); + +// node_modules/isexe/windows.js +var require_windows = __commonJS({ + "node_modules/isexe/windows.js"(exports, module2) { + module2.exports = isexe; + isexe.sync = sync; + var fs10 = require("fs"); + function checkPathExt(path10, options) { + var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT; + if (!pathext) { + return true; + } + pathext = pathext.split(";"); + if (pathext.indexOf("") !== -1) { + return true; + } + for (var i2 = 0; i2 < pathext.length; i2++) { + var p2 = pathext[i2].toLowerCase(); + if (p2 && path10.substr(-p2.length).toLowerCase() === p2) { + return true; + } + } + return false; + } + function checkStat(stat, path10, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false; + } + return checkPathExt(path10, options); + } + function isexe(path10, options, cb) { + fs10.stat(path10, function(er, stat) { + cb(er, er ? false : checkStat(stat, path10, options)); + }); + } + function sync(path10, options) { + return checkStat(fs10.statSync(path10), path10, options); + } + } +}); + +// node_modules/isexe/mode.js +var require_mode = __commonJS({ + "node_modules/isexe/mode.js"(exports, module2) { + module2.exports = isexe; + isexe.sync = sync; + var fs10 = require("fs"); + function isexe(path10, options, cb) { + fs10.stat(path10, function(er, stat) { + cb(er, er ? false : checkStat(stat, options)); + }); + } + function sync(path10, options) { + return checkStat(fs10.statSync(path10), options); + } + function checkStat(stat, options) { + return stat.isFile() && checkMode(stat, options); + } + function checkMode(stat, options) { + var mod = stat.mode; + var uid = stat.uid; + var gid = stat.gid; + var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid(); + var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid(); + var u = parseInt("100", 8); + var g3 = parseInt("010", 8); + var o = parseInt("001", 8); + var ug = u | g3; + var ret = mod & o || mod & g3 && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0; + return ret; + } + } +}); + +// node_modules/isexe/index.js +var require_isexe = __commonJS({ + "node_modules/isexe/index.js"(exports, module2) { + var fs10 = require("fs"); + var core; + if (process.platform === "win32" || global.TESTING_WINDOWS) { + core = require_windows(); + } else { + core = require_mode(); + } + module2.exports = isexe; + isexe.sync = sync; + function isexe(path10, options, cb) { + if (typeof options === "function") { + cb = options; + options = {}; + } + if (!cb) { + if (typeof Promise !== "function") { + throw new TypeError("callback not provided"); + } + return new Promise(function(resolve4, reject) { + isexe(path10, options || {}, function(er, is) { + if (er) { + reject(er); + } else { + resolve4(is); + } + }); + }); + } + core(path10, options || {}, function(er, is) { + if (er) { + if (er.code === "EACCES" || options && options.ignoreErrors) { + er = null; + is = false; + } + } + cb(er, is); + }); + } + function sync(path10, options) { + try { + return core.sync(path10, options || {}); + } catch (er) { + if (options && options.ignoreErrors || er.code === "EACCES") { + return false; + } else { + throw er; + } + } + } + } +}); + +// node_modules/which/which.js +var require_which = __commonJS({ + "node_modules/which/which.js"(exports, module2) { + var isWindows2 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys"; + var path10 = require("path"); + var COLON = isWindows2 ? ";" : ":"; + var isexe = require_isexe(); + var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }); + var getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON; + const pathEnv = cmd.match(/\//) || isWindows2 && cmd.match(/\\/) ? [""] : [ + // windows always checks the cwd first + ...isWindows2 ? [process.cwd()] : [], + ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */ + "").split(colon) + ]; + const pathExtExe = isWindows2 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : ""; + const pathExt = isWindows2 ? pathExtExe.split(colon) : [""]; + if (isWindows2) { + if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") + pathExt.unshift(""); + } + return { + pathEnv, + pathExt, + pathExtExe + }; + }; + var which = (cmd, opt, cb) => { + if (typeof opt === "function") { + cb = opt; + opt = {}; + } + if (!opt) + opt = {}; + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + const step = (i2) => new Promise((resolve4, reject) => { + if (i2 === pathEnv.length) + return opt.all && found.length ? resolve4(found) : reject(getNotFoundError(cmd)); + const ppRaw = pathEnv[i2]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + const pCmd = path10.join(pathPart, cmd); + const p2 = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; + resolve4(subStep(p2, i2, 0)); + }); + const subStep = (p2, i2, ii) => new Promise((resolve4, reject) => { + if (ii === pathExt.length) + return resolve4(step(i2 + 1)); + const ext = pathExt[ii]; + isexe(p2 + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p2 + ext); + else + return resolve4(p2 + ext); + } + return resolve4(subStep(p2, i2, ii + 1)); + }); + }); + return cb ? step(0).then((res) => cb(null, res), cb) : step(0); + }; + var whichSync = (cmd, opt) => { + opt = opt || {}; + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + for (let i2 = 0; i2 < pathEnv.length; i2++) { + const ppRaw = pathEnv[i2]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + const pCmd = path10.join(pathPart, cmd); + const p2 = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; + for (let j3 = 0; j3 < pathExt.length; j3++) { + const cur = p2 + pathExt[j3]; + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }); + if (is) { + if (opt.all) + found.push(cur); + else + return cur; + } + } catch (ex) { + } + } + } + if (opt.all && found.length) + return found; + if (opt.nothrow) + return null; + throw getNotFoundError(cmd); + }; + module2.exports = which; + which.sync = whichSync; + } +}); + +// node_modules/path-key/index.js +var require_path_key = __commonJS({ + "node_modules/path-key/index.js"(exports, module2) { + "use strict"; + var pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + if (platform !== "win32") { + return "PATH"; + } + return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path"; + }; + module2.exports = pathKey; + module2.exports.default = pathKey; + } +}); + +// node_modules/cross-spawn/lib/util/resolveCommand.js +var require_resolveCommand = __commonJS({ + "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module2) { + "use strict"; + var path10 = require("path"); + var which = require_which(); + var getPathKey = require_path_key(); + function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled; + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + } + } + let resolved; + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path10.delimiter : void 0 + }); + } catch (e2) { + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + if (resolved) { + resolved = path10.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved); + } + return resolved; + } + function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); + } + module2.exports = resolveCommand; + } +}); + +// node_modules/cross-spawn/lib/util/escape.js +var require_escape = __commonJS({ + "node_modules/cross-spawn/lib/util/escape.js"(exports, module2) { + "use strict"; + var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + function escapeCommand(arg) { + arg = arg.replace(metaCharsRegExp, "^$1"); + return arg; + } + function escapeArgument(arg, doubleEscapeMetaChars) { + arg = `${arg}`; + arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); + arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1"); + arg = `"${arg}"`; + arg = arg.replace(metaCharsRegExp, "^$1"); + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, "^$1"); + } + return arg; + } + module2.exports.command = escapeCommand; + module2.exports.argument = escapeArgument; + } +}); + +// node_modules/shebang-regex/index.js +var require_shebang_regex = __commonJS({ + "node_modules/shebang-regex/index.js"(exports, module2) { + "use strict"; + module2.exports = /^#!(.*)/; + } +}); + +// node_modules/shebang-command/index.js +var require_shebang_command = __commonJS({ + "node_modules/shebang-command/index.js"(exports, module2) { + "use strict"; + var shebangRegex = require_shebang_regex(); + module2.exports = (string5 = "") => { + const match = string5.match(shebangRegex); + if (!match) { + return null; + } + const [path10, argument] = match[0].replace(/#! ?/, "").split(" "); + const binary = path10.split("/").pop(); + if (binary === "env") { + return argument; + } + return argument ? `${binary} ${argument}` : binary; + }; + } +}); + +// node_modules/cross-spawn/lib/util/readShebang.js +var require_readShebang = __commonJS({ + "node_modules/cross-spawn/lib/util/readShebang.js"(exports, module2) { + "use strict"; + var fs10 = require("fs"); + var shebangCommand = require_shebang_command(); + function readShebang(command) { + const size = 150; + const buffer = Buffer.alloc(size); + let fd; + try { + fd = fs10.openSync(command, "r"); + fs10.readSync(fd, buffer, 0, size, 0); + fs10.closeSync(fd); + } catch (e2) { + } + return shebangCommand(buffer.toString()); + } + module2.exports = readShebang; + } +}); + +// node_modules/cross-spawn/lib/parse.js +var require_parse = __commonJS({ + "node_modules/cross-spawn/lib/parse.js"(exports, module2) { + "use strict"; + var path10 = require("path"); + var resolveCommand = require_resolveCommand(); + var escape2 = require_escape(); + var readShebang = require_readShebang(); + var isWin = process.platform === "win32"; + var isExecutableRegExp = /\.(?:com|exe)$/i; + var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + const shebang = parsed.file && readShebang(parsed.file); + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + return resolveCommand(parsed); + } + return parsed.file; + } + function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } + const commandFile = detectShebang(parsed); + const needsShell = !isExecutableRegExp.test(commandFile); + if (parsed.options.forceShell || needsShell) { + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + parsed.command = path10.normalize(parsed.command); + parsed.command = escape2.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars)); + const shellCommand = [parsed.command].concat(parsed.args).join(" "); + parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`]; + parsed.command = process.env.comspec || "cmd.exe"; + parsed.options.windowsVerbatimArguments = true; + } + return parsed; + } + function parse3(command, args, options) { + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + args = args ? args.slice(0) : []; + options = Object.assign({}, options); + const parsed = { + command, + args, + options, + file: void 0, + original: { + command, + args + } + }; + return options.shell ? parsed : parseNonShell(parsed); + } + module2.exports = parse3; + } +}); + +// node_modules/cross-spawn/lib/enoent.js +var require_enoent = __commonJS({ + "node_modules/cross-spawn/lib/enoent.js"(exports, module2) { + "use strict"; + var isWin = process.platform === "win32"; + function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: "ENOENT", + errno: "ENOENT", + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args + }); + } + function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + const originalEmit = cp.emit; + cp.emit = function(name, arg1) { + if (name === "exit") { + const err = verifyENOENT(arg1, parsed); + if (err) { + return originalEmit.call(cp, "error", err); + } + } + return originalEmit.apply(cp, arguments); + }; + } + function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, "spawn"); + } + return null; + } + function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, "spawnSync"); + } + return null; + } + module2.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError + }; + } +}); + +// node_modules/cross-spawn/index.js +var require_cross_spawn = __commonJS({ + "node_modules/cross-spawn/index.js"(exports, module2) { + "use strict"; + var cp = require("child_process"); + var parse3 = require_parse(); + var enoent = require_enoent(); + function spawn3(command, args, options) { + const parsed = parse3(command, args, options); + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + enoent.hookChildProcess(spawned, parsed); + return spawned; + } + function spawnSync(command, args, options) { + const parsed = parse3(command, args, options); + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + return result; + } + module2.exports = spawn3; + module2.exports.spawn = spawn3; + module2.exports.sync = spawnSync; + module2.exports._parse = parse3; + module2.exports._enoent = enoent; + } +}); + // src/main.ts var main_exports = {}; __export(main_exports, { default: () => ClaudianPlugin }); module.exports = __toCommonJS(main_exports); -var import_obsidian27 = require("obsidian"); +var import_obsidian30 = require("obsidian"); -// node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs -var import_path = require("path"); -var import_url = require("url"); -var import_events = require("events"); -var import_child_process = require("child_process"); -var import_readline = require("readline"); -var fs = __toESM(require("fs"), 1); -var import_promises = require("fs/promises"); -var import_path2 = require("path"); -var import_os = require("os"); -var import_path3 = require("path"); -var import_process = require("process"); -var import_fs = require("fs"); -var import_crypto = require("crypto"); -var import_crypto2 = require("crypto"); -var import_fs2 = require("fs"); -var import_path4 = require("path"); -var import_crypto3 = require("crypto"); -var import_path5 = require("path"); -var import_url2 = require("url"); -var import_meta = {}; -var __create2 = Object.create; -var __getProtoOf2 = Object.getPrototypeOf; -var __defProp2 = Object.defineProperty; -var __getOwnPropNames2 = Object.getOwnPropertyNames; -var __hasOwnProp2 = Object.prototype.hasOwnProperty; -var __toESM2 = (mod, isNodeMode, target) => { - target = mod != null ? __create2(__getProtoOf2(mod)) : {}; - const to = isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target; - for (let key of __getOwnPropNames2(mod)) - if (!__hasOwnProp2.call(to, key)) - __defProp2(to, key, { - get: () => mod[key], - enumerable: true - }); - return to; -}; -var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); -var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { - get: all[name], - enumerable: true, - configurable: true, - set: (newValue) => all[name] = () => newValue - }); -}; -var require_code = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - class _CodeOrName { - } - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - class Name extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) - throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - } - exports.Name = Name; - class _Code extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) - return false; - const item = this._items[0]; - return item === "" || item === '""'; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) - names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - } - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - var plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) - code.push(...arg._items); - else if (arg instanceof Name) - code.push(arg); - else - code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === '""') - return a; - if (a === '""') - return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== '"') - return; - if (typeof b != "string") - return `${a.slice(0, -1)}${b}"`; - if (b[0] === '"') - return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) - return `"${a}${b.slice(1)}`; - return; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) { - return new _Code(`${key}`); - } - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -}); -var require_scope = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - var code_1 = require_code(); - class ValueError extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - } - var UsedValueState; - (function(UsedValueState2) { - UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; - UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - class Scope { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { - throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - } - return this._names[prefix] = { prefix, index: 0 }; - } - } - exports.Scope = Scope; - class ValueScopeName extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - } - exports.ValueScopeName = ValueScopeName; - var line = (0, code_1._)`\n`; - class ValueScope extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) - throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) - return _name; - } else { - vs = this._values[prefix] = /* @__PURE__ */ new Map(); - } - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { property: prefix, itemIndex }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) - return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) - throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) - throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) - continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) - return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { - code = (0, code_1._)`${code}${c}${this.opts._n}`; - } else { - throw new ValueError(name); - } - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - } - exports.ValueScope = ValueScope; -}); -var require_codegen = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - var code_1 = require_code(); - var scope_1 = require_scope(); - var code_2 = require_code(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return code_2._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return code_2.str; - } }); - Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { - return code_2.strConcat; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return code_2.nil; - } }); - Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { - return code_2.getProperty; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return code_2.stringify; - } }); - Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { - return code_2.regexpCode; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return code_2.Name; - } }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { - return scope_2.Scope; - } }); - Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { - return scope_2.ValueScope; - } }); - Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { - return scope_2.ValueScopeName; - } }); - Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { - return scope_2.varKinds; - } }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - class Node { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - } - class Def extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) - return; - if (this.rhs) - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - } - class Assign extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) - return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; - return addExprNames(names, this.rhs); - } - } - class AssignOp extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - } - class Label extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - } - class Break extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - const label = this.label ? ` ${this.label}` : ""; - return `break${label};` + _n; - } - } - class Throw extends Node { - constructor(error2) { - super(); - this.error = error2; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - } - class AnyCode extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - } - class ParentNode extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) - nodes.splice(i, 1, ...n); - else if (n) - nodes[i] = n; - else - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) - continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - } - class BlockNode extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - } - class Root extends ParentNode { - } - class Else extends BlockNode { - } - Else.kind = "else"; - class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) - code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) - return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) - return e instanceof If ? e : e.nodes; - if (this.nodes.length) - return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) - return; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) - return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) - addNames(names, this.else.names); - return names; - } - } - If.kind = "if"; - class For extends BlockNode { - } - For.kind = "for"; - class ForLoop extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - } - class ForRange extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - const names = addExprNames(super.names, this.from); - return addExprNames(names, this.to); - } - } - class ForIter extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - } - class Func extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - const _async = this.async ? "async " : ""; - return `${_async}function ${this.name}(${this.args})` + super.render(opts); - } - } - Func.kind = "func"; - class Return extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - } - Return.kind = "return"; - class Try extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) - code += this.catch.render(opts); - if (this.finally) - code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) - addNames(names, this.catch.names); - if (this.finally) - addNames(names, this.finally.names); - return names; - } - } - class Catch extends BlockNode { - constructor(error2) { - super(); - this.error = error2; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - } - Catch.kind = "catch"; - class Finally extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - } - Finally.kind = "finally"; - class CodeGen { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { ...opts, _n: opts.lines ? ` -` : "" }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); - vs.add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) - this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") - c(); - else if (c !== code_1.nil) - this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) - code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); +// src/core/agents/AgentManager.ts +var fs3 = __toESM(require("fs")); +var os3 = __toESM(require("os")); +var path3 = __toESM(require("path")); + +// src/utils/frontmatter.ts +var import_obsidian = require("obsidian"); +var FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/; +function parseFrontmatterFallback(yamlContent) { + const result = {}; + const lines = yamlContent.split("\n"); + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const colonIndex = trimmed.indexOf(": "); + if (colonIndex === -1) { + if (trimmed.endsWith(":")) { + const key2 = trimmed.slice(0, -1).trim(); + if (key2 && /^[\w-]+$/.test(key2)) { + result[key2] = ""; } } - code.push("}"); - return new code_1._Code(code); + continue; } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) { - this.code(thenBody).else().code(elseBody).endIf(); - } else if (thenBody) { - this.code(thenBody).endIf(); - } else if (elseBody) { - throw new Error('CodeGen: "else" body without "then" body'); - } - return this; + const key = trimmed.slice(0, colonIndex).trim(); + let value = trimmed.slice(colonIndex + 2); + if (!key || !/^[\w-]+$/.test(key)) continue; + if (value === "true") value = true; + else if (value === "false") value = false; + else if (value === "null" || value === "") value = null; + else if (!isNaN(Number(value)) && value !== "") value = Number(value); + else if (typeof value === "string" && value.startsWith("[") && value.endsWith("]")) { + value = value.slice(1, -1).split(",").map((s) => s.trim()).filter(Boolean); } - elseIf(condition) { - return this._elseNode(new If(condition)); + result[key] = value; + } + return result; +} +function parseFrontmatter(content) { + const match = content.match(FRONTMATTER_PATTERN); + if (!match) return null; + try { + const parsed = (0, import_obsidian.parseYaml)(match[1]); + if (parsed !== null && parsed !== void 0 && typeof parsed !== "object") { + return null; } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) - this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) { - return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - } - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) - throw new Error('CodeGen: "return" should have one node'); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) - throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error2 = this.name("e"); - this._currNode = node.catch = new Catch(error2); - catchCode(error2); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error2) { - return this._leafNode(new Throw(error2)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) - this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) - throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { - throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - } - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) - this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) { - throw new Error('CodeGen: "else" without "if"'); - } - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - } - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) - return replaceName(expr); - if (!canOptimize(expr)) - return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) - c = replaceName(c); - if (c instanceof code_1._Code) - items.push(...c._items); - else - items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) - return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - var andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - var orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -}); -var require_util = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - var codegen_1 = require_codegen(); - var code_1 = require_code(); - function toHash(arr) { - const hash = {}; - for (const item of arr) - hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") - return schema; - if (Object.keys(schema).length === 0) - return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self: self2 } = it; - if (!opts.strictSchema) - return; - if (typeof schema === "boolean") - return; - const rules = self2.RULES.keywords; - for (const key in schema) { - if (!rules[key]) - checkStrictMode(it, `unknown keyword: "${key}"`); - } - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (rules[key]) - return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (key !== "$ref" && RULES.all[key]) - return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") - return schema; - if (typeof schema == "string") - return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") - return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) { - for (const x of xs) - f(x); - } else { - f(xs); - } - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) { - gen.assign(to, true); - } else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { ...from, ...to }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) - return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) - setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - var snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type2) { - Type2[Type2["Num"] = 0] = "Num"; - Type2[Type2["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) - return; - msg = `strict mode: ${msg}`; - if (mode === true) - throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -}); -var require_names = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -}); -var require_errors = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var names_1 = require_names(); - exports.keywordError = { - message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` - }; - exports.keyword$DataError = { - message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` - }; - function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error2, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { - addError(gen, errObj); - } else { - returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - } - exports.reportError = reportError; - function reportExtraError(cxt, error2 = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error2, errorPaths); - addError(gen, errObj); - if (!(compositeRule || allErrors)) { - returnErrors(it, names_1.default.vErrors); - } - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - if (errsCount === void 0) - throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) { - gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - var E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error2, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) - return (0, codegen_1._)`{}`; - return errorObject(cxt, error2, errorPaths); - } - function errorObject(cxt, error2, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [ - errorInstancePath(it, errorPaths), - errorSchemaPath(cxt, errorPaths) - ]; - extraErrorProps(cxt, error2, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) { - schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - } - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) { - keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - } - if (opts.verbose) { - keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - } - if (propertyName) - keyValues.push([E.propertyName, propertyName]); - } -}); -var require_boolSchema = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - var errors_1 = require_errors(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var boolError = { - message: "boolean schema is false" - }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) { - falseSchemaError(it, false); - } else if (typeof schema == "object" && schema.$async === true) { - gen.return(names_1.default.data); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else { - gen.var(valid, true); - } - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -}); -var require_rules = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; - var jsonTypes = new Set(_jsonTypes); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { type: "number", rules: [] }, - string: { type: "string", rules: [] }, - array: { type: "array", rules: [] }, - object: { type: "object", rules: [] } - }; return { - types: { ...groups, integer: true, boolean: true, null: true }, - rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], - post: { rules: [] }, - all: {}, - keywords: {} + frontmatter: parsed != null ? parsed : {}, + body: match[2] }; - } - exports.getRules = getRules; -}); -var require_applicability = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self: self2 }, type) { - const group = self2.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -}); -var require_dataType = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - var rules_1 = require_rules(); - var applicability_1 = require_applicability(); - var errors_1 = require_errors(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var DataType; - (function(DataType2) { - DataType2[DataType2["Correct"] = 0] = "Correct"; - DataType2[DataType2["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - const hasNull = types.includes("null"); - if (hasNull) { - if (schema.nullable === false) - throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) { - throw new Error('"nullable" cannot be used without "type"'); - } - if (schema.nullable === true) - types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) - return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) - coerceData(it, types, coerceTo); - else - reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") { - gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - } - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) { - if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { - coerceSpecificType(t); - } - } - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": - gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": - return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: - return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) { - return checkDataType(dataTypes[0], data, strictNums, correct); - } - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else { - cond = codegen_1.nil; - } - if (types.number) - delete types.integer; - for (const t in types) - cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - var typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -}); -var require_defaults = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) { - for (const key in properties) { - assignDefault(it, key, properties[key].default); - } - } else if (ty === "array" && Array.isArray(items)) { - items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) - return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") { - condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - } - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -}); -var require_code2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var names_1 = require_names(); - var util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) - valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - var newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); - if (alwaysValid && !it.opts.unevaluated) - return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - const merged = cxt.mergeValidEvaluated(schCxt, schValid); - if (!merged) - gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -}); -var require_keyword = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var code_1 = require_code2(); - var errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) - it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors3) { - var _a2; - gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors3); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) - throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) - throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) { - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { - throw new Error("ajv implementation error"); - } - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { - throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - } - if (def.validateSchema) { - const valid = def.validateSchema(schema[keyword]); - if (!valid) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") - self2.logger.error(msg); - else - throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -}); -var require_subschema = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) { - throw new Error('both "keyword" and "schema" passed, only one allowed'); - } - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { - throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); - } + } catch (e2) { + const fallbackParsed = parseFrontmatterFallback(match[1]); + if (Object.keys(fallbackParsed).length > 0) { return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath + frontmatter: fallbackParsed, + body: match[2] }; } - throw new Error('either "keyword" or "schema" must be passed'); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) { - throw new Error('both "data" and "dataProp" passed, only one allowed'); - } - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); - dataContextProps(nextData); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); - dataContextProps(nextData); - if (propertyName !== void 0) - subschema.propertyName = propertyName; - } - if (dataTypes) - subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) - subschema.compositeRule = compositeRule; - if (createErrors !== void 0) - subschema.createErrors = createErrors; - if (allErrors !== void 0) - subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -}); -var require_fast_deep_equal = __commonJS((exports, module2) => { - module2.exports = function equal(a, b) { - if (a === b) - return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) - return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) - return false; - for (i = length; i-- !== 0; ) - if (!equal(a[i], b[i])) - return false; - return true; - } - if (a.constructor === RegExp) - return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) - return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) - return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) - return false; - for (i = length; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) - return false; - for (i = length; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) - return false; - } - return true; - } - return a !== a && b !== b; - }; -}); -var require_json_schema_traverse = __commonJS((exports, module2) => { - var traverse = module2.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() { - }; - var post = cb.post || function() { - }; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i = 0; i < sch.length; i++) - _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") { - for (var prop in sch) - _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { - _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -}); -var require_resolve = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - var util_1 = require_util(); - var equal = require_fast_deep_equal(); - var traverse = require_json_schema_traverse(); - var SIMPLE_INLINED = /* @__PURE__ */ new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") - return true; - if (limit === true) - return !hasRef(schema); - if (!limit) - return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - var REF_KEYWORDS = /* @__PURE__ */ new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) - return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) - return true; - if (typeof sch == "object" && hasRef(sch)) - return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") - return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) - continue; - if (typeof schema[key] == "object") { - (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - } - if (count === Infinity) - return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize2) { - if (normalize2 !== false) - id = normalizeId(id); - const p = resolver.parse(id); - return _getFullPath(resolver, p); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - const serialized = resolver.serialize(p); - return serialized.split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - var TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") - return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) - return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") - innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) - throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") - schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") { - checkAmbiguosRef(sch, schOrRef.schema, ref); - } else if (ref !== normalizeId(fullPath)) { - if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else { - this.refs[ref] = fullPath; - } - } - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) - throw ambiguos(ref); - } - function ambiguos(ref) { - return new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -}); -var require_validate = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - var boolSchema_1 = require_boolSchema(); - var dataType_1 = require_dataType(); - var applicability_1 = require_applicability(); - var dataType_2 = require_dataType(); - var defaults_1 = require_defaults(); - var keyword_1 = require_keyword(); - var subschema_1 = require_subschema(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var resolve_1 = require_resolve(); - var util_1 = require_util(); - var errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - } else { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) - commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) - resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - return; - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self: self2 }) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (self2.RULES.all[key]) - return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) - commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) - return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); - schemaKeywords(it, types, !checkedTypes, errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self: self2 } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) { - self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { - (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) - it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) - throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) { - gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - } else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) { - gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) - assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self: self2 } = it; - const { RULES } = self2; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) - checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) - groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) - return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else { - iterateKeywords(it, group); - } - if (!allErrors) - gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) - (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) { - if ((0, applicability_1.shouldUseRule)(schema, rule)) { - keywordCode(it, rule.keyword, rule.definition, group.type); - } - } - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) - return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) - checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) - return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) { - strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - } - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { - strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) { - strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) { - if (includesType(withTypes, t)) - ts.push(t); - else if (withTypes.includes("integer") && t === "number") - ts.push("integer"); - } - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - class KeywordCxt { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) { - this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - } else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { - throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - } - if ("code" in def ? def.trackErrors : def.errors !== false) { - this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) - failAction(); - else - this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) - this.gen.endIf(); - } else { - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) - this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - fail$data(condition) { - if (!this.$data) - return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) - throw new Error('add "trackErrors" to keyword definition'); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) - this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) - Object.assign(this.params, obj); - else - this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) - return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) - gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) - gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - if (!(schemaCode instanceof codegen_1.Name)) - throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) - return; - if (it.props !== true && schemaCxt.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - } - if (it.items !== true && schemaCxt.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - } - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) { - def.code(cxt, ruleType); - } else if (cxt.$data && def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } else if ("macro" in def) { - (0, keyword_1.macroKeywordCode)(cxt, def); - } else if (def.compile || def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } - } - var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") - return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) - throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) - throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) - throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) - throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) - return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) { - if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -}); -var require_validation_error = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - class ValidationError extends Error { - constructor(errors3) { - super("validation failed"); - this.errors = errors3; - this.ajv = this.validation = true; - } - } - exports.default = ValidationError; -}); -var require_ref_error = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var resolve_1 = require_resolve(); - class MissingRefError extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - } - exports.default = MissingRefError; -}); -var require_compile = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - var codegen_1 = require_codegen(); - var validation_error_1 = require_validation_error(); - var names_1 = require_names(); - var resolve_1 = require_resolve(); - var util_1 = require_util(); - var validate_1 = require_validate(); - class SchemaEnv { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - } - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) - return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); - let _ValidationError; - if (sch.$async) { - _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - } - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) - sourceCode = this.opts.code.process(sourceCode, sch); - const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) - validate.$async = true; - if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; - } - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) - this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root2, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root2.refs[ref]; - if (schOrFunc) - return schOrFunc; - let _sch = resolve7.call(this, root2, ref); - if (_sch === void 0) { - const schema = (_a = root2.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) - _sch = new SchemaEnv({ schema, schemaId, root: root2, baseId }); - } - if (_sch === void 0) - return; - return root2.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) - return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) { - if (sameSchemaEnv(sch, schEnv)) - return sch; - } - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve7(root2, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") - ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root2, ref); - } - function resolveSchema(root2, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root2.baseId, void 0); - if (Object.keys(root2.schema).length > 0 && refPath === baseId) { - return getJsonPointer.call(this, p, root2); - } - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root2, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") - return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") - return; - if (!schOrRef.validate) - compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ schema, schemaId, root: root2, baseId }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root: root2 }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") - return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") - return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) - return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root2, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root: root2, baseId }); - if (env.schema !== env.root.schema) - return env; - return; - } -}); -var require_data = __commonJS((exports, module2) => { - module2.exports = { - $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", - type: "object", - required: ["$data"], - properties: { - $data: { - type: "string", - anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] - } - }, - additionalProperties: false - }; -}); -var require_scopedChars = __commonJS((exports, module2) => { - var HEX = { - 0: 0, - 1: 1, - 2: 2, - 3: 3, - 4: 4, - 5: 5, - 6: 6, - 7: 7, - 8: 8, - 9: 9, - a: 10, - A: 10, - b: 11, - B: 11, - c: 12, - C: 12, - d: 13, - D: 13, - e: 14, - E: 14, - f: 15, - F: 15 - }; - module2.exports = { - HEX - }; -}); -var require_utils = __commonJS((exports, module2) => { - var { HEX } = require_scopedChars(); - var IPV4_REG = /^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u; - function normalizeIPv4(host) { - if (findToken(host, ".") < 3) { - return { host, isIPV4: false }; - } - const matches = host.match(IPV4_REG) || []; - const [address] = matches; - if (address) { - return { host: stripLeadingZeros(address, "."), isIPV4: true }; - } else { - return { host, isIPV4: false }; - } - } - function stringArrayToHexStripped(input, keepZero = false) { - let acc = ""; - let strip = true; - for (const c of input) { - if (HEX[c] === void 0) - return; - if (c !== "0" && strip === true) - strip = false; - if (!strip) - acc += c; - } - if (keepZero && acc.length === 0) - acc = "0"; - return acc; - } - function getIPV6(input) { - let tokenCount = 0; - const output = { error: false, address: "", zone: "" }; - const address = []; - const buffer = []; - let isZone = false; - let endipv6Encountered = false; - let endIpv6 = false; - function consume() { - if (buffer.length) { - if (isZone === false) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== void 0) { - address.push(hex); - } else { - output.error = true; - return false; - } - } - buffer.length = 0; - } - return true; - } - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === "[" || cursor === "]") { - continue; - } - if (cursor === ":") { - if (endipv6Encountered === true) { - endIpv6 = true; - } - if (!consume()) { - break; - } - tokenCount++; - address.push(":"); - if (tokenCount > 7) { - output.error = true; - break; - } - if (i - 1 >= 0 && input[i - 1] === ":") { - endipv6Encountered = true; - } - continue; - } else if (cursor === "%") { - if (!consume()) { - break; - } - isZone = true; - } else { - buffer.push(cursor); - continue; - } - } - if (buffer.length) { - if (isZone) { - output.zone = buffer.join(""); - } else if (endIpv6) { - address.push(buffer.join("")); - } else { - address.push(stringArrayToHexStripped(buffer)); - } - } - output.address = address.join(""); - return output; - } - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) { - return { host, isIPV6: false }; - } - const ipv62 = getIPV6(host); - if (!ipv62.error) { - let newHost = ipv62.address; - let escapedHost = ipv62.address; - if (ipv62.zone) { - newHost += "%" + ipv62.zone; - escapedHost += "%25" + ipv62.zone; - } - return { host: newHost, escapedHost, isIPV6: true }; - } else { - return { host, isIPV6: false }; - } - } - function stripLeadingZeros(str, token) { - let out = ""; - let skip = true; - const l = str.length; - for (let i = 0; i < l; i++) { - const c = str[i]; - if (c === "0" && skip) { - if (i + 1 <= l && str[i + 1] === token || i + 1 === l) { - out += c; - skip = false; - } - } else { - if (c === token) { - skip = true; - } else { - skip = false; - } - out += c; - } - } - return out; - } - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) { - if (str[i] === token) - ind++; - } - return ind; - } - var RDS1 = /^\.\.?\//u; - var RDS2 = /^\/\.(?:\/|$)/u; - var RDS3 = /^\/\.\.(?:\/|$)/u; - var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u; - function removeDotSegments(input) { - const output = []; - while (input.length) { - if (input.match(RDS1)) { - input = input.replace(RDS1, ""); - } else if (input.match(RDS2)) { - input = input.replace(RDS2, "/"); - } else if (input.match(RDS3)) { - input = input.replace(RDS3, "/"); - output.pop(); - } else if (input === "." || input === "..") { - input = ""; - } else { - const im = input.match(RDS5); - if (im) { - const s = im[0]; - input = input.slice(s.length); - output.push(s); - } else { - throw new Error("Unexpected dot segment condition"); - } - } - } - return output.join(""); - } - function normalizeComponentEncoding(components, esc2) { - const func = esc2 !== true ? escape : unescape; - if (components.scheme !== void 0) { - components.scheme = func(components.scheme); - } - if (components.userinfo !== void 0) { - components.userinfo = func(components.userinfo); - } - if (components.host !== void 0) { - components.host = func(components.host); - } - if (components.path !== void 0) { - components.path = func(components.path); - } - if (components.query !== void 0) { - components.query = func(components.query); - } - if (components.fragment !== void 0) { - components.fragment = func(components.fragment); - } - return components; - } - function recomposeAuthority(components) { - const uriTokens = []; - if (components.userinfo !== void 0) { - uriTokens.push(components.userinfo); - uriTokens.push("@"); - } - if (components.host !== void 0) { - let host = unescape(components.host); - const ipV4res = normalizeIPv4(host); - if (ipV4res.isIPV4) { - host = ipV4res.host; - } else { - const ipV6res = normalizeIPv6(ipV4res.host); - if (ipV6res.isIPV6 === true) { - host = `[${ipV6res.escapedHost}]`; - } else { - host = components.host; - } - } - uriTokens.push(host); - } - if (typeof components.port === "number" || typeof components.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(components.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module2.exports = { - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - normalizeIPv4, - normalizeIPv6, - stringArrayToHexStripped - }; -}); -var require_schemes = __commonJS((exports, module2) => { - var UUID_REG = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu; - var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - function isSecure(wsComponents) { - return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; - } - function httpParse(components) { - if (!components.host) { - components.error = components.error || "HTTP URIs must have a host."; - } - return components; - } - function httpSerialize(components) { - const secure = String(components.scheme).toLowerCase() === "https"; - if (components.port === (secure ? 443 : 80) || components.port === "") { - components.port = void 0; - } - if (!components.path) { - components.path = "/"; - } - return components; - } - function wsParse(wsComponents) { - wsComponents.secure = isSecure(wsComponents); - wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : ""); - wsComponents.path = void 0; - wsComponents.query = void 0; - return wsComponents; - } - function wsSerialize(wsComponents) { - if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { - wsComponents.port = void 0; - } - if (typeof wsComponents.secure === "boolean") { - wsComponents.scheme = wsComponents.secure ? "wss" : "ws"; - wsComponents.secure = void 0; - } - if (wsComponents.resourceName) { - const [path12, query2] = wsComponents.resourceName.split("?"); - wsComponents.path = path12 && path12 !== "/" ? path12 : void 0; - wsComponents.query = query2; - wsComponents.resourceName = void 0; - } - wsComponents.fragment = void 0; - return wsComponents; - } - function urnParse(urnComponents, options) { - if (!urnComponents.path) { - urnComponents.error = "URN can not be parsed"; - return urnComponents; - } - const matches = urnComponents.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponents.scheme || "urn"; - urnComponents.nid = matches[1].toLowerCase(); - urnComponents.nss = matches[2]; - const urnScheme = `${scheme}:${options.nid || urnComponents.nid}`; - const schemeHandler = SCHEMES[urnScheme]; - urnComponents.path = void 0; - if (schemeHandler) { - urnComponents = schemeHandler.parse(urnComponents, options); - } - } else { - urnComponents.error = urnComponents.error || "URN can not be parsed."; - } - return urnComponents; - } - function urnSerialize(urnComponents, options) { - const scheme = options.scheme || urnComponents.scheme || "urn"; - const nid = urnComponents.nid.toLowerCase(); - const urnScheme = `${scheme}:${options.nid || nid}`; - const schemeHandler = SCHEMES[urnScheme]; - if (schemeHandler) { - urnComponents = schemeHandler.serialize(urnComponents, options); - } - const uriComponents = urnComponents; - const nss = urnComponents.nss; - uriComponents.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponents; - } - function urnuuidParse(urnComponents, options) { - const uuidComponents = urnComponents; - uuidComponents.uuid = uuidComponents.nss; - uuidComponents.nss = void 0; - if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) { - uuidComponents.error = uuidComponents.error || "UUID is not valid."; - } - return uuidComponents; - } - function urnuuidSerialize(uuidComponents) { - const urnComponents = uuidComponents; - urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); - return urnComponents; - } - var http2 = { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }; - var https2 = { - scheme: "https", - domainHost: http2.domainHost, - parse: httpParse, - serialize: httpSerialize - }; - var ws = { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }; - var wss = { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }; - var urn = { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }; - var urnuuid = { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }; - var SCHEMES = { - http: http2, - https: https2, - ws, - wss, - urn, - "urn:uuid": urnuuid - }; - module2.exports = SCHEMES; -}); -var require_fast_uri = __commonJS((exports, module2) => { - var { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = require_utils(); - var SCHEMES = require_schemes(); - function normalize2(uri, options) { - if (typeof uri === "string") { - uri = serialize(parse6(uri, options), options); - } else if (typeof uri === "object") { - uri = parse6(serialize(uri, options), options); - } - return uri; - } - function resolve7(baseURI, relativeURI, options) { - const schemelessOptions = Object.assign({ scheme: "null" }, options); - const resolved = resolveComponents(parse6(baseURI, schemelessOptions), parse6(relativeURI, schemelessOptions), schemelessOptions, true); - return serialize(resolved, { ...schemelessOptions, skipEscape: true }); - } - function resolveComponents(base, relative5, options, skipNormalization) { - const target = {}; - if (!skipNormalization) { - base = parse6(serialize(base, options), options); - relative5 = parse6(serialize(relative5, options), options); - } - options = options || {}; - if (!options.tolerant && relative5.scheme) { - target.scheme = relative5.scheme; - target.userinfo = relative5.userinfo; - target.host = relative5.host; - target.port = relative5.port; - target.path = removeDotSegments(relative5.path || ""); - target.query = relative5.query; - } else { - if (relative5.userinfo !== void 0 || relative5.host !== void 0 || relative5.port !== void 0) { - target.userinfo = relative5.userinfo; - target.host = relative5.host; - target.port = relative5.port; - target.path = removeDotSegments(relative5.path || ""); - target.query = relative5.query; - } else { - if (!relative5.path) { - target.path = base.path; - if (relative5.query !== void 0) { - target.query = relative5.query; - } else { - target.query = base.query; - } - } else { - if (relative5.path.charAt(0) === "/") { - target.path = removeDotSegments(relative5.path); - } else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { - target.path = "/" + relative5.path; - } else if (!base.path) { - target.path = relative5.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative5.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative5.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative5.fragment; - return target; - } - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse6(uriA, options), true), { ...options, skipEscape: true }); - } else if (typeof uriA === "object") { - uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); - } - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse6(uriB, options), true), { ...options, skipEscape: true }); - } else if (typeof uriB === "object") { - uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); - } - return uriA.toLowerCase() === uriB.toLowerCase(); - } - function serialize(cmpts, opts) { - const components = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - if (schemeHandler && schemeHandler.serialize) - schemeHandler.serialize(components, options); - if (components.path !== void 0) { - if (!options.skipEscape) { - components.path = escape(components.path); - if (components.scheme !== void 0) { - components.path = components.path.split("%3A").join(":"); - } - } else { - components.path = unescape(components.path); - } - } - if (options.reference !== "suffix" && components.scheme) { - uriTokens.push(components.scheme, ":"); - } - const authority = recomposeAuthority(components); - if (authority !== void 0) { - if (options.reference !== "suffix") { - uriTokens.push("//"); - } - uriTokens.push(authority); - if (components.path && components.path.charAt(0) !== "/") { - uriTokens.push("/"); - } - } - if (components.path !== void 0) { - let s = components.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if (authority === void 0) { - s = s.replace(/^\/\//u, "/%2F"); - } - uriTokens.push(s); - } - if (components.query !== void 0) { - uriTokens.push("?", components.query); - } - if (components.fragment !== void 0) { - uriTokens.push("#", components.fragment); - } - return uriTokens.join(""); - } - var hexLookUp = Array.from({ length: 127 }, (_v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k))); - function nonSimpleDomain(value) { - let code = 0; - for (let i = 0, len = value.length; i < len; ++i) { - code = value.charCodeAt(i); - if (code > 126 || hexLookUp[code]) { - return true; - } - } - return false; - } - var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - function parse6(uri, opts) { - const options = Object.assign({}, opts); - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - const gotEncoding = uri.indexOf("%") !== -1; - let isIP = false; - if (options.reference === "suffix") - uri = (options.scheme ? options.scheme + ":" : "") + "//" + uri; - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) { - parsed.port = matches[5]; - } - if (parsed.host) { - const ipv4result = normalizeIPv4(parsed.host); - if (ipv4result.isIPV4 === false) { - const ipv6result = normalizeIPv6(ipv4result.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else { - parsed.host = ipv4result.host; - isIP = true; - } - } - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { - parsed.reference = "same-document"; - } else if (parsed.scheme === void 0) { - parsed.reference = "relative"; - } else if (parsed.fragment === void 0) { - parsed.reference = "absolute"; - } else { - parsed.reference = "uri"; - } - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { - parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - } - const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || "").toLowerCase()]; - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { - try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (gotEncoding && parsed.scheme !== void 0) { - parsed.scheme = unescape(parsed.scheme); - } - if (gotEncoding && parsed.host !== void 0) { - parsed.host = unescape(parsed.host); - } - if (parsed.path) { - parsed.path = escape(unescape(parsed.path)); - } - if (parsed.fragment) { - parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - } - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(parsed, options); - } - } else { - parsed.error = parsed.error || "URI can not be parsed."; - } - return parsed; - } - var fastUri = { - SCHEMES, - normalize: normalize2, - resolve: resolve7, - resolveComponents, - equal, - serialize, - parse: parse6 - }; - module2.exports = fastUri; - module2.exports.default = fastUri; - module2.exports.fastUri = fastUri; -}); -var require_uri = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var uri = require_fast_uri(); - uri.code = 'require("ajv/dist/runtime/uri").default'; - exports.default = uri; -}); -var require_core = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error(); - var ref_error_1 = require_ref_error(); - var rules_1 = require_rules(); - var compile_1 = require_compile(); - var codegen_2 = require_codegen(); - var resolve_1 = require_resolve(); - var dataType_1 = require_dataType(); - var util_1 = require_util(); - var $dataRefSchema = require_data(); - var uri_1 = require_uri(); - var defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; - var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - var removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: '"nullable" keyword is supported by default.', - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: '"uniqueItems" keyword is always validated.', - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now." - }; - var deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: '"minLength"/"maxLength" account for unicode characters by default.' - }; - var MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return null; + } +} +function extractString(fm, key) { + const val = fm[key]; + if (typeof val === "string" && val.length > 0) return val; + return void 0; +} +function normalizeStringArray(val) { + if (val === void 0 || val === null) return void 0; + if (Array.isArray(val)) { + return val.map((v3) => String(v3).trim()).filter(Boolean); + } + if (typeof val === "string") { + const trimmed = val.trim(); + if (!trimmed) return void 0; + return trimmed.split(",").map((s) => s.trim()).filter(Boolean); + } + return void 0; +} +function extractStringArray(fm, key) { + return normalizeStringArray(fm[key]); +} +function extractBoolean(fm, key) { + const val = fm[key]; + if (typeof val === "boolean") return val; + return void 0; +} +function isRecord(value) { + return value != null && typeof value === "object" && !Array.isArray(value); +} +var MAX_SLUG_LENGTH = 64; +var SLUG_PATTERN = /^[a-z0-9-]+$/; +var YAML_RESERVED_WORDS = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off"]); +function validateSlugName(name, label) { + if (!name) { + return `${label} name is required`; + } + if (name.length > MAX_SLUG_LENGTH) { + return `${label} name must be ${MAX_SLUG_LENGTH} characters or fewer`; + } + if (!SLUG_PATTERN.test(name)) { + return `${label} name can only contain lowercase letters, numbers, and hyphens`; + } + if (YAML_RESERVED_WORDS.has(name)) { + return `${label} name cannot be a YAML reserved word (true, false, null, yes, no, on, off)`; + } + return null; +} + +// src/core/types/chat.ts +var VIEW_TYPE_CLAUDIAN = "claudian-view"; + +// src/core/types/models.ts +var DEFAULT_CLAUDE_MODELS = [ + { value: "haiku", label: "Haiku", description: "Fast and efficient" }, + { value: "sonnet", label: "Sonnet", description: "Balanced performance" }, + { value: "opus", label: "Opus", description: "Most capable" } +]; +var BETA_1M_CONTEXT = "context-1m-2025-08-07"; +function resolveModelWithBetas(model, include1MBeta = false) { + if (!model || typeof model !== "string") { + throw new Error("resolveModelWithBetas: model is required and must be a non-empty string"); + } + if (include1MBeta) { return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver + model, + betas: [BETA_1M_CONTEXT] }; } - class Ajv { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { ...opts, ...requiredOptions(opts) }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) - addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) - addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") - this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) - this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) - throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else { - v = this.compile(schemaKeyRef); - } - const valid = v(data); - if (!("$async" in v)) - this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") { - throw new Error("options.loadSchema should be a function"); - } - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) { - await runCompileAsync.call(this, { $ref }, true); - } - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) - throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) { - throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) - await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) - this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) - return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) - this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") { - throw new Error(`schema ${schemaId} must be string`); - } - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") - return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") { - throw new Error("$schema must be a string"); - } - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") - this.logger.error(message); - else - throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") - keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root2 = new compile_1.SchemaEnv({ schema: {}, schemaId }); - sch = compile_1.resolveSchema.call(this, root2, keyRef); - if (!sch) - return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") - this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: - throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) - this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) { - throw new Error("addKeywords: keyword must be string or non-empty array"); - } - } else { - throw new Error("invalid addKeywords parameters"); - } - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) - group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") - format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors3 = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors3 || errors3.length === 0) - return "No errors"; - return errors3.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) - keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") - continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) - keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas4, regex) { - for (const keyRef in schemas4) { - const sch = schemas4[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") { - delete schemas4[keyRef]; - } else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas4[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") { - id = schema[schemaId]; - } else { - if (this.opts.jtd) - throw new Error("schema must be object"); - else if (typeof schema != "boolean") - throw new Error("schema must be object or boolean"); - } - let sch = this._cache.get(schema); - if (sch !== void 0) - return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) - this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) - this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) { - throw new Error(`schema with key or id "${id}" already exists`); - } - } - _compileSchemaEnv(sch) { - if (sch.meta) - this._compileMetaSchema(sch); - else - compile_1.compileSchema.call(this, sch); - if (!sch.validate) - throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } + return { model }; +} +var THINKING_BUDGETS = [ + { value: "off", label: "Off", tokens: 0 }, + { value: "low", label: "Low", tokens: 4e3 }, + { value: "medium", label: "Med", tokens: 8e3 }, + { value: "high", label: "High", tokens: 16e3 }, + { value: "xhigh", label: "Ultra", tokens: 32e3 } +]; +var DEFAULT_THINKING_BUDGET = { + "haiku": "off", + "sonnet": "low", + "opus": "medium" +}; +var CONTEXT_WINDOW_STANDARD = 2e5; +var CONTEXT_WINDOW_1M = 1e6; +function getContextWindowSize(model, is1MEnabled = false, customLimits) { + if (customLimits && model in customLimits) { + const limit = customLimits[model]; + if (typeof limit === "number" && limit > 0 && !isNaN(limit) && isFinite(limit)) { + return limit; } } - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) - this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + if (is1MEnabled && model.includes("sonnet")) { + return CONTEXT_WINDOW_1M; + } + return CONTEXT_WINDOW_STANDARD; +} + +// src/core/types/settings.ts +var UNIX_BLOCKED_COMMANDS = [ + "rm -rf", + "chmod 777", + "chmod -R 777" +]; +var WINDOWS_BLOCKED_COMMANDS = [ + // CMD commands + "del /s /q", + "rd /s /q", + "rmdir /s /q", + "format", + "diskpart", + // PowerShell Remove-Item variants (full and abbreviated flags) + "Remove-Item -Recurse -Force", + "Remove-Item -Force -Recurse", + "Remove-Item -r -fo", + "Remove-Item -fo -r", + "Remove-Item -Recurse", + "Remove-Item -r", + // PowerShell aliases for Remove-Item + "ri -Recurse", + "ri -r", + "ri -Force", + "ri -fo", + "rm -r -fo", + "rm -Recurse", + "rm -Force", + "del -Recurse", + "del -Force", + "erase -Recurse", + "erase -Force", + // PowerShell directory removal aliases + "rd -Recurse", + "rmdir -Recurse", + // Dangerous disk/volume commands + "Format-Volume", + "Clear-Disk", + "Initialize-Disk", + "Remove-Partition" +]; +function getDefaultBlockedCommands() { + return { + unix: [...UNIX_BLOCKED_COMMANDS], + windows: [...WINDOWS_BLOCKED_COMMANDS] + }; +} +function getCurrentPlatformKey() { + return process.platform === "win32" ? "windows" : "unix"; +} +function getCurrentPlatformBlockedCommands(commands) { + return commands[getCurrentPlatformKey()]; +} +function getBashToolBlockedCommands(commands) { + if (process.platform === "win32") { + return Array.from(/* @__PURE__ */ new Set([...commands.unix, ...commands.windows])); + } + return getCurrentPlatformBlockedCommands(commands); +} +function getCliPlatformKey() { + switch (process.platform) { + case "darwin": + return "macos"; + case "win32": + return "windows"; + default: + return "linux"; + } +} +function createPermissionRule(rule) { + return rule; +} +var DEFAULT_SETTINGS = { + // User preferences + userName: "", + // Security + enableBlocklist: true, + blockedCommands: getDefaultBlockedCommands(), + permissionMode: "yolo", + // Model & thinking + model: "haiku", + thinkingBudget: "off", + enableAutoTitleGeneration: true, + titleGenerationModel: "", + // Empty = auto (ANTHROPIC_DEFAULT_HAIKU_MODEL or claude-haiku-4-5) + show1MModel: false, + // Hidden by default + enableChrome: false, + // Disabled by default + // Content settings + excludedTags: [], + mediaFolder: "", + systemPrompt: "", + allowedExportPaths: ["~/Desktop", "~/Downloads"], + persistentExternalContextPaths: [], + // Environment + environmentVariables: "", + envSnippets: [], + customContextLimits: {}, + // UI settings + keyboardNavigation: { + scrollUpKey: "w", + scrollDownKey: "s", + focusInputKey: "i" + }, + // Internationalization + locale: "en", + // Default to English + // CLI paths + claudeCliPath: "", + // Legacy field (empty = not migrated) + claudeCliPathsByHost: {}, + // Per-device paths keyed by hostname + loadUserClaudeSettings: true, + // Default on for compatibility + lastClaudeModel: "haiku", + lastCustomModel: "", + lastEnvHash: "", + // Slash commands (loaded separately) + slashCommands: [], + // UI preferences + maxTabs: 3, + // Default to 3 tabs (safe resource usage) + tabBarPosition: "input", + // Default to input mode (current behavior) + enableAutoScroll: true, + // Default to auto-scroll enabled + openInMainTab: false, + // Default to sidebar (current behavior) + // Slash commands + hiddenSlashCommands: [] + // No commands hidden by default +}; +var DEFAULT_CC_SETTINGS = { + $schema: "https://json.schemastore.org/claude-code-settings.json", + permissions: { + allow: [], + deny: [], + ask: [] + } +}; +var DEFAULT_CC_PERMISSIONS = { + allow: [], + deny: [], + ask: [] +}; +function legacyPermissionToCCRule(legacy) { + const pattern = legacy.pattern.trim(); + if (!pattern || pattern === "*" || pattern.startsWith("{")) { + return createPermissionRule(legacy.toolName); + } + return createPermissionRule(`${legacy.toolName}(${pattern})`); +} +function legacyPermissionsToCCPermissions(legacyPermissions) { + const allow = []; + for (const perm of legacyPermissions) { + if (perm.scope === "always") { + allow.push(legacyPermissionToCCRule(perm)); } } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; + return { + allow: [...new Set(allow)], + // Deduplicate + deny: [], + ask: [] + }; +} + +// src/utils/env.ts +var fs2 = __toESM(require("fs")); +var os2 = __toESM(require("os")); +var path2 = __toESM(require("path")); + +// src/utils/path.ts +var fs = __toESM(require("fs")); +var os = __toESM(require("os")); +var path = __toESM(require("path")); +function getVaultPath(app) { + const adapter = app.vault.adapter; + if ("basePath" in adapter) { + return adapter.basePath; } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) - return; - if (Array.isArray(optsSchemas)) - this.addSchema(optsSchemas); - else - for (const key in optsSchemas) - this.addSchema(optsSchemas[key], key); + return null; +} +function getEnvValue(key) { + const hasKey = (name) => Object.prototype.hasOwnProperty.call(process.env, name); + if (hasKey(key)) { + return process.env[key]; } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) - this.addFormat(name, format); - } + if (process.platform !== "win32") { + return void 0; } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) - def.keyword = keyword; - this.addKeyword(def); - } + const upper = key.toUpperCase(); + if (hasKey(upper)) { + return process.env[upper]; } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) - delete metaOpts[opt]; - return metaOpts; + const lower = key.toLowerCase(); + if (hasKey(lower)) { + return process.env[lower]; } - var noLogs = { log() { - }, warn() { - }, error() { - } }; - function getLogger(logger) { - if (logger === false) - return noLogs; - if (logger === void 0) - return console; - if (logger.log && logger.warn && logger.error) - return logger; - throw new Error("logger must implement log, warn and error methods"); + const matchKey = Object.keys(process.env).find((name) => name.toLowerCase() === key.toLowerCase()); + return matchKey ? process.env[matchKey] : void 0; +} +function expandEnvironmentVariables(value) { + if (!value.includes("%") && !value.includes("$") && !value.includes("!")) { + return value; } - var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) - throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) - throw new Error(`Keyword ${kwd} has invalid name`); + const isWindows2 = process.platform === "win32"; + let expanded = value; + expanded = expanded.replace(/%([A-Za-z_][A-Za-z0-9_]*(?:\([A-Za-z0-9_]+\))?[A-Za-z0-9_]*)%/g, (match, name) => { + const envValue = getEnvValue(name); + return envValue !== void 0 ? envValue : match; + }); + if (isWindows2) { + expanded = expanded.replace(/!([A-Za-z_][A-Za-z0-9_]*)!/g, (match, name) => { + const envValue = getEnvValue(name); + return envValue !== void 0 ? envValue : match; }); - if (!def) - return; - if (def.$data && !("code" in def || "validate" in def)) { - throw new Error('$data keyword must have "code" or "validate" function'); - } - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) - throw new Error('keyword with "post" flag cannot have "type"'); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { type: dataType, rules: [] }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) - return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) - addBeforeRule.call(this, ruleGroup, rule, definition.before); - else - ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) { - ruleGroup.rules.splice(i, 0, rule); - } else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) - return; - if (def.$data && this.opts.$data) - metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - var $dataRef = { - $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" - }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -}); -var require_id = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var def = { - keyword: "id", - code() { - throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); - } - }; - exports.default = def; -}); -var require_ref = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - var ref_error_1 = require_ref_error(); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var compile_1 = require_compile(); - var util_1 = require_util(); - var def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root: root2 } = env; - if (($ref === "#" || $ref === "#/") && baseId === root2.baseId) - return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self2, root2, baseId, $ref); - if (schOrEnv === void 0) - throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) - return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root2) - return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root2 }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root2, root2.$async); - } - function callValidate(sch) { - const v = getValidate(cxt, sch); - callRef(cxt, v, sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) - callAsyncRef(); - else - callSyncRef(); - function callAsyncRef() { - if (!env.$async) - throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) - gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) - gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) - return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) { - if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - } - if (it.items !== true) { - if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - } - exports.callRef = callRef; - exports.default = def; -}); -var require_core2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var id_1 = require_id(); - var ref_1 = require_ref(); - var core2 = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core2; -}); -var require_limitNumber = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var ops = codegen_1.operators; - var KWDs = { - maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } - }; - var error2 = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - var def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -}); -var require_multipleOf = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }; - var def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -}); -var require_ucs2length = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) - pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; -}); -var require_limitLength = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var ucs2length_1 = require_ucs2length(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -}); -var require_pattern = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }; - var def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: error2, - code(cxt) { - const { data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - }; - exports.default = def; -}); -var require_limitProperties = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -}); -var require_required = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }; - var def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: error2, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) - return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) - allErrorsMode(); - else - exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) { - if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - } - function allErrorsMode() { - if (useLoop || $data) { - cxt.block$data(codegen_1.nil, loopAllRequired); - } else { - for (const prop of schema) { - (0, code_1.checkReportMissingProp)(cxt, prop); - } - } - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -}); -var require_limitItems = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -}); -var require_equal = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var equal = require_fast_deep_equal(); - equal.code = 'require("ajv/dist/runtime/equal").default'; - exports.default = equal; -}); -var require_uniqueItems = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var dataType_1 = require_dataType(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error2 = { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }; - var def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) - return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ i, j }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) - gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -}); -var require_const = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error2 = { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }; - var def = { - keyword: "const", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") { - cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - } else { - cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - } - }; - exports.default = def; -}); -var require_enum = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error2 = { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }; - var def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) - throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -}); -var require_validation = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var limitNumber_1 = require_limitNumber(); - var multipleOf_1 = require_multipleOf(); - var limitLength_1 = require_limitLength(); - var pattern_1 = require_pattern(); - var limitProperties_1 = require_limitProperties(); - var required_1 = require_required(); - var limitItems_1 = require_limitItems(); - var uniqueItems_1 = require_uniqueItems(); - var const_1 = require_const(); - var enum_1 = require_enum(); - var validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { keyword: "type", schemaType: ["string", "array"] }, - { keyword: "nullable", schemaType: "boolean" }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -}); -var require_additionalItems = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: error2, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); - if (!it.allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -}); -var require_items = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "array", "boolean"], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) - return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) { - it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - } - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); + expanded = expanded.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (match, name) => { + const envValue = getEnvValue(name); + return envValue !== void 0 ? envValue : match; }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + expanded = expanded.replace(/\$([A-Za-z_][A-Za-z0-9_]*)|\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name1, name2) => { + const key = name1 != null ? name1 : name2; + if (!key) return match; + const envValue = getEnvValue(key); + return envValue !== void 0 ? envValue : match; + }); + return expanded; +} +function expandHomePath(p2) { + const expanded = expandEnvironmentVariables(p2); + if (expanded === "~") { + return os.homedir(); + } + if (expanded.startsWith("~/")) { + return path.join(os.homedir(), expanded.slice(2)); + } + if (expanded.startsWith("~\\")) { + return path.join(os.homedir(), expanded.slice(2)); + } + return expanded; +} +function stripSurroundingQuotes(value) { + if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) { + return value.slice(1, -1); + } + return value; +} +function parsePathEntries(pathValue) { + if (!pathValue) { + return []; + } + const delimiter = process.platform === "win32" ? ";" : ":"; + return pathValue.split(delimiter).map((segment) => stripSurroundingQuotes(segment.trim())).filter((segment) => { + if (!segment) return false; + const upper = segment.toUpperCase(); + return upper !== "$PATH" && upper !== "${PATH}" && upper !== "%PATH%"; + }).map((segment) => translateMsysPath(expandHomePath(segment))); +} +function dedupePaths(entries) { + const seen = /* @__PURE__ */ new Set(); + return entries.filter((entry) => { + const key = process.platform === "win32" ? entry.toLowerCase() : entry; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} +function findFirstExistingPath(entries, candidates) { + for (const dir of entries) { + if (!dir) continue; + for (const candidate of candidates) { + const fullPath = path.join(dir, candidate); + if (isExistingFile(fullPath)) { + return fullPath; } } } - exports.validateTuple = validateTuple; - exports.default = def; -}); -var require_prefixItems = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var items_1 = require_items(); - var def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -}); -var require_items2020 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - var additionalItems_1 = require_additionalItems(); - var error2 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: error2, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - if (prefixItems) - (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else - cxt.ok((0, code_1.validateArray)(cxt)); + return null; +} +function isExistingFile(filePath) { + try { + if (fs.existsSync(filePath)) { + const stat = fs.statSync(filePath); + return stat.isFile(); } - }; - exports.default = def; -}); -var require_contains = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }; - var def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else { - min = 1; - } - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ min, max }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) - cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) { - validateItems(valid, () => gen.if(valid, () => gen.break())); - } else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) - gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) { - gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - } else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) - gen.assign(valid, true); - else - gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -}); -var require_dependencies = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - var def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") - continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; + } catch (e2) { } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) - return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) - continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) { - gen.if(hasProperty, () => { - for (const depProp of deps) { - (0, code_1.checkReportMissingProp)(cxt, depProp); - } - }); - } else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } + return false; +} +function resolveCliJsNearPathEntry(entry, isWindows2) { + const directCandidate = path.join(entry, "node_modules", "@anthropic-ai", "claude-code", "cli.js"); + if (isExistingFile(directCandidate)) { + return directCandidate; + } + const baseName = path.basename(entry).toLowerCase(); + if (baseName === "bin") { + const prefix = path.dirname(entry); + const candidate = isWindows2 ? path.join(prefix, "node_modules", "@anthropic-ai", "claude-code", "cli.js") : path.join(prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js"); + if (isExistingFile(candidate)) { + return candidate; } } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) - continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); + return null; +} +function resolveCliJsFromPathEntries(entries, isWindows2) { + for (const entry of entries) { + const candidate = resolveCliJsNearPathEntry(entry, isWindows2); + if (candidate) { + return candidate; } } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -}); -var require_propertyNames = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }; - var def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: error2, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) - gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -}); -var require_additionalProperties = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var util_1 = require_util(); - var error2 = { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }; - var def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - if (!errsCount) - throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) - return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) - additionalPropertyCode(key); - else - gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) { - definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - } else { - definedProp = codegen_1.nil; - } - if (patProps.length) { - definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - } - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) - gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors3) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors3 === false) { - Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - } - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -}); -var require_properties = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var validate_1 = require_validate(); - var code_1 = require_code2(); - var util_1 = require_util(); - var additionalProperties_1 = require_additionalProperties(); - var def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { - additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - } - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) { - it.definedProperties.add(prop); - } - if (it.opts.unevaluated && allProps.length && it.props !== true) { - it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - } - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) - return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) { - applyPropertySchema(prop); - } else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) - gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -}); -var require_patternProperties = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var util_2 = require_util(); - var def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { - return; - } - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) { - it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - } - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) - checkMatchingProperties(pat); - if (it.allErrors) { - validateProperties(pat); - } else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) { - if (new RegExp(pat).test(prop)) { - (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - } - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) { - cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - } - if (it.opts.unevaluated && props !== true) { - gen.assign((0, codegen_1._)`${props}[${key}]`, true); - } else if (!alwaysValid && !it.allErrors) { - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - }); - }); - } - } - }; - exports.default = def; -}); -var require_not = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -}); -var require_anyOf = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: code_1.validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -}); -var require_oneOf = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }; - var def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) - return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) { - gen.var(schValid, true); - } else { - schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - } - if (i > 0) { - gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - } - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) - cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -}); -var require_allOf = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -}); -var require_if = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }; - var def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: error2, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) { - (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); - } - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) - return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) { - gen.if(schValid, validateClause("then")); - } else { - gen.if((0, codegen_1.not)(schValid), validateClause("else")); - } - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) - gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else - cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + return null; +} +function resolveClaudeFromPathEntries(entries, isWindows2) { + if (entries.length === 0) { + return null; } - exports.default = def; -}); -var require_thenElse = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) - (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + if (!isWindows2) { + const unixCandidate = findFirstExistingPath(entries, ["claude"]); + return unixCandidate; + } + const exeCandidate = findFirstExistingPath(entries, ["claude.exe", "claude"]); + if (exeCandidate) { + return exeCandidate; + } + const cliJsCandidate = resolveCliJsFromPathEntries(entries, isWindows2); + if (cliJsCandidate) { + return cliJsCandidate; + } + return null; +} +function getNpmGlobalPrefix() { + if (process.env.npm_config_prefix) { + return process.env.npm_config_prefix; + } + if (process.platform === "win32") { + const appDataNpm = process.env.APPDATA ? path.join(process.env.APPDATA, "npm") : null; + if (appDataNpm && fs.existsSync(appDataNpm)) { + return appDataNpm; } - }; - exports.default = def; -}); -var require_applicator = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var additionalItems_1 = require_additionalItems(); - var prefixItems_1 = require_prefixItems(); - var items_1 = require_items(); - var items2020_1 = require_items2020(); - var contains_1 = require_contains(); - var dependencies_1 = require_dependencies(); - var propertyNames_1 = require_propertyNames(); - var additionalProperties_1 = require_additionalProperties(); - var properties_1 = require_properties(); - var patternProperties_1 = require_patternProperties(); - var not_1 = require_not(); - var anyOf_1 = require_anyOf(); - var oneOf_1 = require_oneOf(); - var allOf_1 = require_allOf(); - var if_1 = require_if(); - var thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default + } + return null; +} +function getNpmCliJsPaths() { + const homeDir = os.homedir(); + const isWindows2 = process.platform === "win32"; + const cliJsPaths = []; + if (isWindows2) { + cliJsPaths.push( + path.join(homeDir, "AppData", "Roaming", "npm", "node_modules", "@anthropic-ai", "claude-code", "cli.js") + ); + const npmPrefix = getNpmGlobalPrefix(); + if (npmPrefix) { + cliJsPaths.push( + path.join(npmPrefix, "node_modules", "@anthropic-ai", "claude-code", "cli.js") + ); + } + const programFiles = process.env.ProgramFiles || "C:\\Program Files"; + const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"; + cliJsPaths.push( + path.join(programFiles, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js"), + path.join(programFilesX86, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js") + ); + cliJsPaths.push( + path.join("D:", "Program Files", "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js") + ); + } else { + cliJsPaths.push( + path.join(homeDir, ".npm-global", "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js"), + "/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js", + "/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js" + ); + if (process.env.npm_config_prefix) { + cliJsPaths.push( + path.join(process.env.npm_config_prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js") + ); + } + } + return cliJsPaths; +} +function findClaudeCLIPath(pathValue) { + const homeDir = os.homedir(); + const isWindows2 = process.platform === "win32"; + const customEntries = dedupePaths(parsePathEntries(pathValue)); + if (customEntries.length > 0) { + const customResolution = resolveClaudeFromPathEntries(customEntries, isWindows2); + if (customResolution) { + return customResolution; + } + } + if (isWindows2) { + const exePaths = [ + path.join(homeDir, ".claude", "local", "claude.exe"), + path.join(homeDir, "AppData", "Local", "Claude", "claude.exe"), + path.join(process.env.ProgramFiles || "C:\\Program Files", "Claude", "claude.exe"), + path.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Claude", "claude.exe"), + path.join(homeDir, ".local", "bin", "claude.exe") ]; - if (draft2020) - applicator.push(prefixItems_1.default, items2020_1.default); - else - applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -}); -var require_format = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }; - var def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: error2, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self: self2 } = it; - if (!opts.validateFormats) - return; - if ($data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self2.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) - return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self2.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) - return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) - cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self2.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { - return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; - } - return ["string", fmtDef, fmt]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) - throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } + for (const p2 of exePaths) { + if (isExistingFile(p2)) { + return p2; } } - }; - exports.default = def; -}); -var require_format2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var format_1 = require_format(); - var format = [format_1.default]; - exports.default = format; -}); -var require_metadata = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" + const cliJsPaths = getNpmCliJsPaths(); + for (const p2 of cliJsPaths) { + if (isExistingFile(p2)) { + return p2; + } + } + } + const commonPaths = [ + path.join(homeDir, ".claude", "local", "claude"), + path.join(homeDir, ".local", "bin", "claude"), + path.join(homeDir, ".volta", "bin", "claude"), + path.join(homeDir, ".asdf", "shims", "claude"), + path.join(homeDir, ".asdf", "bin", "claude"), + "/usr/local/bin/claude", + "/opt/homebrew/bin/claude", + path.join(homeDir, "bin", "claude"), + path.join(homeDir, ".npm-global", "bin", "claude") ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -}); -var require_draft7 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var core_1 = require_core2(); - var validation_1 = require_validation(); - var applicator_1 = require_applicator(); - var format_1 = require_format2(); - var metadata_1 = require_metadata(); - var draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -}); -var require_types = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError2) { - DiscrError2["Tag"] = "tag"; - DiscrError2["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -}); -var require_discriminator = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var types_1 = require_types(); - var compile_1 = require_compile(); - var ref_error_1 = require_ref_error(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }; - var def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: error2, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) { - throw new Error("discriminator: requires discriminator option"); - } - const tagName = schema.propertyName; - if (typeof tagName != "string") - throw new Error("discriminator: requires propertyName"); - if (schema.mapping) - throw new Error("discriminator: mapping is not supported"); - if (!oneOf) - throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) - sch = sch.schema; - if (sch === void 0) - throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") { - throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - } - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) - throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required: required2 }) { - return Array.isArray(required2) && required2.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) { - addMapping(sch.const, i); - } else if (sch.enum) { - for (const tagValue of sch.enum) { - addMapping(tagValue, i); - } - } else { - throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) { - throw new Error(`discriminator: "${tagName}" values must be unique strings`); - } - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -}); -var require_json_schema_draft_07 = __commonJS((exports, module2) => { - module2.exports = { - $schema: "http://json-schema.org/draft-07/schema#", - $id: "http://json-schema.org/draft-07/schema#", - title: "Core schema meta-schema", - definitions: { - schemaArray: { - type: "array", - minItems: 1, - items: { $ref: "#" } - }, - nonNegativeInteger: { - type: "integer", - minimum: 0 - }, - nonNegativeIntegerDefault0: { - allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] - }, - simpleTypes: { - enum: ["array", "boolean", "integer", "null", "number", "object", "string"] - }, - stringArray: { - type: "array", - items: { type: "string" }, - uniqueItems: true, - default: [] - } - }, - type: ["object", "boolean"], - properties: { - $id: { - type: "string", - format: "uri-reference" - }, - $schema: { - type: "string", - format: "uri" - }, - $ref: { - type: "string", - format: "uri-reference" - }, - $comment: { - type: "string" - }, - title: { - type: "string" - }, - description: { - type: "string" - }, - default: true, - readOnly: { - type: "boolean", - default: false - }, - examples: { - type: "array", - items: true - }, - multipleOf: { - type: "number", - exclusiveMinimum: 0 - }, - maximum: { - type: "number" - }, - exclusiveMaximum: { - type: "number" - }, - minimum: { - type: "number" - }, - exclusiveMinimum: { - type: "number" - }, - maxLength: { $ref: "#/definitions/nonNegativeInteger" }, - minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - pattern: { - type: "string", - format: "regex" - }, - additionalItems: { $ref: "#" }, - items: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], - default: true - }, - maxItems: { $ref: "#/definitions/nonNegativeInteger" }, - minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - uniqueItems: { - type: "boolean", - default: false - }, - contains: { $ref: "#" }, - maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, - minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - required: { $ref: "#/definitions/stringArray" }, - additionalProperties: { $ref: "#" }, - definitions: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - properties: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - patternProperties: { - type: "object", - additionalProperties: { $ref: "#" }, - propertyNames: { format: "regex" }, - default: {} - }, - dependencies: { - type: "object", - additionalProperties: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] - } - }, - propertyNames: { $ref: "#" }, - const: true, - enum: { - type: "array", - items: true, - minItems: 1, - uniqueItems: true - }, - type: { - anyOf: [ - { $ref: "#/definitions/simpleTypes" }, - { - type: "array", - items: { $ref: "#/definitions/simpleTypes" }, - minItems: 1, - uniqueItems: true - } - ] - }, - format: { type: "string" }, - contentMediaType: { type: "string" }, - contentEncoding: { type: "string" }, - if: { $ref: "#" }, - then: { $ref: "#" }, - else: { $ref: "#" }, - allOf: { $ref: "#/definitions/schemaArray" }, - anyOf: { $ref: "#/definitions/schemaArray" }, - oneOf: { $ref: "#/definitions/schemaArray" }, - not: { $ref: "#" } - }, - default: true - }; -}); -var require_ajv = __commonJS((exports, module2) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - var core_1 = require_core(); - var draft7_1 = require_draft7(); - var discriminator_1 = require_discriminator(); - var draft7MetaSchema = require_json_schema_draft_07(); - var META_SUPPORT_DATA = ["/properties"]; - var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - class Ajv extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) - this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) - return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + const npmPrefix = getNpmGlobalPrefix(); + if (npmPrefix) { + commonPaths.push(path.join(npmPrefix, "bin", "claude")); + } + for (const p2 of commonPaths) { + if (isExistingFile(p2)) { + return p2; } } - exports.Ajv = Ajv; - module2.exports = exports = Ajv; - module2.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { - return validation_error_1.default; - } }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { - return ref_error_1.default; - } }); -}); -var require_formats = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { validate, compare }; + if (!isWindows2) { + const cliJsPaths = getNpmCliJsPaths(); + for (const p2 of cliJsPaths) { + if (isExistingFile(p2)) { + return p2; + } + } } - exports.fullFormats = { - date: fmtDef(date4, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, - "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, - "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, - "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, - byte, - int32: { type: "number", validate: validateInt32 }, - int64: { type: "number", validate: validateInt64 }, - float: { type: "number", validate: validateNumber }, - double: { type: "number", validate: validateNumber }, - password: true, - binary: true + const envEntries = dedupePaths(parsePathEntries(getEnvValue("PATH"))); + if (envEntries.length > 0) { + const envResolution = resolveClaudeFromPathEntries(envEntries, isWindows2); + if (envResolution) { + return envResolution; + } + } + return null; +} +function resolveRealPath(p2) { + var _a3; + const realpathFn = (_a3 = fs.realpathSync.native) != null ? _a3 : fs.realpathSync; + try { + return realpathFn(p2); + } catch (e2) { + const absolute = path.resolve(p2); + let current = absolute; + const suffix = []; + while (true) { + try { + if (fs.existsSync(current)) { + const resolvedExisting = realpathFn(current); + return suffix.length > 0 ? path.join(resolvedExisting, ...suffix.reverse()) : resolvedExisting; + } + } catch (e3) { + } + const parent = path.dirname(current); + if (parent === current) { + return absolute; + } + suffix.push(path.basename(current)); + current = parent; + } + } +} +function translateMsysPath(value) { + var _a3; + if (process.platform !== "win32") { + return value; + } + const msysMatch = value.match(/^\/([a-zA-Z])(\/.*)?$/); + if (msysMatch) { + const driveLetter = msysMatch[1].toUpperCase(); + const restOfPath = (_a3 = msysMatch[2]) != null ? _a3 : ""; + return `${driveLetter}:${restOfPath.replace(/\//g, "\\")}`; + } + return value; +} +function normalizePathBeforeResolution(p2) { + const expanded = expandHomePath(p2); + return translateMsysPath(expanded); +} +function normalizeWindowsPathPrefix(value) { + if (process.platform !== "win32") { + return value; + } + const normalized = translateMsysPath(value); + if (normalized.startsWith("\\\\?\\UNC\\")) { + return `\\\\${normalized.slice("\\\\?\\UNC\\".length)}`; + } + if (normalized.startsWith("\\\\?\\")) { + return normalized.slice("\\\\?\\".length); + } + return normalized; +} +function normalizePathForFilesystem(value) { + if (!value || typeof value !== "string") { + return ""; + } + const expanded = normalizePathBeforeResolution(value); + let normalized = expanded; + try { + normalized = process.platform === "win32" ? path.win32.normalize(expanded) : path.normalize(expanded); + } catch (e2) { + normalized = expanded; + } + return normalizeWindowsPathPrefix(normalized); +} +function normalizePathForComparison(value) { + if (!value || typeof value !== "string") { + return ""; + } + const expanded = normalizePathBeforeResolution(value); + let normalized = expanded; + try { + normalized = process.platform === "win32" ? path.win32.normalize(expanded) : path.normalize(expanded); + } catch (e2) { + normalized = expanded; + } + normalized = normalizeWindowsPathPrefix(normalized); + normalized = normalized.replace(/\\/g, "/").replace(/\/+$/, ""); + return process.platform === "win32" ? normalized.toLowerCase() : normalized; +} +function isPathWithinVault(candidatePath, vaultPath) { + const vaultReal = normalizePathForComparison(resolveRealPath(vaultPath)); + const normalizedPath = normalizePathBeforeResolution(candidatePath); + const absCandidate = path.isAbsolute(normalizedPath) ? normalizedPath : path.resolve(vaultPath, normalizedPath); + const resolvedCandidate = normalizePathForComparison(resolveRealPath(absCandidate)); + return resolvedCandidate === vaultReal || resolvedCandidate.startsWith(vaultReal + "/"); +} +function normalizePathForVault(rawPath, vaultPath) { + if (!rawPath) return null; + const normalizedRaw = normalizePathForFilesystem(rawPath); + if (!normalizedRaw) return null; + if (vaultPath && isPathWithinVault(normalizedRaw, vaultPath)) { + const absolute = path.isAbsolute(normalizedRaw) ? normalizedRaw : path.resolve(vaultPath, normalizedRaw); + const relative3 = path.relative(vaultPath, absolute); + return relative3 ? relative3.replace(/\\/g, "/") : null; + } + return normalizedRaw.replace(/\\/g, "/"); +} +function getPathAccessType(candidatePath, allowedContextPaths, allowedExportPaths, vaultPath) { + if (!candidatePath) return "none"; + const vaultReal = normalizePathForComparison(resolveRealPath(vaultPath)); + const normalizedCandidate = normalizePathBeforeResolution(candidatePath); + const absCandidate = path.isAbsolute(normalizedCandidate) ? normalizedCandidate : path.resolve(vaultPath, normalizedCandidate); + const resolvedCandidate = normalizePathForComparison(resolveRealPath(absCandidate)); + if (resolvedCandidate === vaultReal || resolvedCandidate.startsWith(vaultReal + "/")) { + return "vault"; + } + const claudeDir = normalizePathForComparison(resolveRealPath(path.join(os.homedir(), ".claude"))); + if (resolvedCandidate === claudeDir || resolvedCandidate.startsWith(claudeDir + "/")) { + return "vault"; + } + const roots = /* @__PURE__ */ new Map(); + const addRoot = (rawPath, kind) => { + var _a3; + const trimmed = rawPath.trim(); + if (!trimmed) return; + const normalized = normalizePathBeforeResolution(trimmed); + const resolved = normalizePathForComparison(resolveRealPath(normalized)); + const existing = (_a3 = roots.get(resolved)) != null ? _a3 : { context: false, export: false }; + existing[kind] = true; + roots.set(resolved, existing); }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + for (const contextPath of allowedContextPaths != null ? allowedContextPaths : []) { + addRoot(contextPath, "context"); } - var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function date4(str) { - const matches = DATE.exec(str); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + for (const exportPath of allowedExportPaths != null ? allowedExportPaths : []) { + addRoot(exportPath, "export"); } - function compareDate(d1, d2) { - if (!(d1 && d2)) - return; - if (d1 > d2) - return 1; - if (d1 < d2) - return -1; - return 0; + let bestRoot = null; + let bestFlags = null; + for (const [root, flags] of roots) { + if (resolvedCandidate === root || resolvedCandidate.startsWith(root + "/")) { + if (!bestRoot || root.length > bestRoot.length) { + bestRoot = root; + bestFlags = flags; + } + } } - var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time3(str) { - const matches = TIME.exec(str); - if (!matches) - return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) - return false; - if (hr <= 23 && min <= 59 && sec < 60) - return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; + if (!bestRoot || !bestFlags) return "none"; + if (bestFlags.context && bestFlags.export) return "readwrite"; + if (bestFlags.context) return "context"; + if (bestFlags.export) return "export"; + return "none"; +} + +// src/utils/env.ts +var isWindows = process.platform === "win32"; +var PATH_SEPARATOR = isWindows ? ";" : ":"; +var NODE_EXECUTABLE = isWindows ? "node.exe" : "node"; +function getHomeDir() { + return process.env.HOME || process.env.USERPROFILE || ""; +} +function getExtraBinaryPaths() { + const home = getHomeDir(); + if (isWindows) { + const paths = []; + const localAppData = process.env.LOCALAPPDATA; + const appData = process.env.APPDATA; + const programFiles = process.env.ProgramFiles || "C:\\Program Files"; + const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"; + const programData = process.env.ProgramData || "C:\\ProgramData"; + if (appData) { + paths.push(path2.join(appData, "npm")); + } + if (localAppData) { + paths.push(path2.join(localAppData, "Programs", "nodejs")); + paths.push(path2.join(localAppData, "Programs", "node")); + } + paths.push(path2.join(programFiles, "nodejs")); + paths.push(path2.join(programFilesX86, "nodejs")); + const nvmSymlink = process.env.NVM_SYMLINK; + if (nvmSymlink) { + paths.push(nvmSymlink); + } + const nvmHome = process.env.NVM_HOME; + if (nvmHome) { + paths.push(nvmHome); + } else if (appData) { + paths.push(path2.join(appData, "nvm")); + } + const voltaHome = process.env.VOLTA_HOME; + if (voltaHome) { + paths.push(path2.join(voltaHome, "bin")); + } else if (home) { + paths.push(path2.join(home, ".volta", "bin")); + } + const fnmMultishell = process.env.FNM_MULTISHELL_PATH; + if (fnmMultishell) { + paths.push(fnmMultishell); + } + const fnmDir = process.env.FNM_DIR; + if (fnmDir) { + paths.push(fnmDir); + } else if (localAppData) { + paths.push(path2.join(localAppData, "fnm")); + } + const chocolateyInstall = process.env.ChocolateyInstall; + if (chocolateyInstall) { + paths.push(path2.join(chocolateyInstall, "bin")); + } else { + paths.push(path2.join(programData, "chocolatey", "bin")); + } + const scoopDir = process.env.SCOOP; + if (scoopDir) { + paths.push(path2.join(scoopDir, "shims")); + paths.push(path2.join(scoopDir, "apps", "nodejs", "current", "bin")); + paths.push(path2.join(scoopDir, "apps", "nodejs", "current")); + } else if (home) { + paths.push(path2.join(home, "scoop", "shims")); + paths.push(path2.join(home, "scoop", "apps", "nodejs", "current", "bin")); + paths.push(path2.join(home, "scoop", "apps", "nodejs", "current")); + } + paths.push(path2.join(programFiles, "Docker", "Docker", "resources", "bin")); + if (home) { + paths.push(path2.join(home, ".local", "bin")); + } + return paths; + } else { + const paths = [ + "/usr/local/bin", + "/opt/homebrew/bin", + // macOS ARM Homebrew + "/usr/bin", + "/bin" + ]; + const voltaHome = process.env.VOLTA_HOME; + if (voltaHome) { + paths.push(path2.join(voltaHome, "bin")); + } + const asdfRoot = process.env.ASDF_DATA_DIR || process.env.ASDF_DIR; + if (asdfRoot) { + paths.push(path2.join(asdfRoot, "shims")); + paths.push(path2.join(asdfRoot, "bin")); + } + const fnmMultishell = process.env.FNM_MULTISHELL_PATH; + if (fnmMultishell) { + paths.push(fnmMultishell); + } + const fnmDir = process.env.FNM_DIR; + if (fnmDir) { + paths.push(fnmDir); + } + if (home) { + paths.push(path2.join(home, ".local", "bin")); + paths.push(path2.join(home, ".docker", "bin")); + paths.push(path2.join(home, ".volta", "bin")); + paths.push(path2.join(home, ".asdf", "shims")); + paths.push(path2.join(home, ".asdf", "bin")); + paths.push(path2.join(home, ".fnm")); + const nvmBin = process.env.NVM_BIN; + if (nvmBin) { + paths.push(nvmBin); + } + } + return paths; } - function compareTime(s1, s2) { - if (!(s1 && s2)) - return; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) - return; - return t1 - t2; +} +function findNodeDirectory(additionalPaths) { + const searchPaths = getExtraBinaryPaths(); + const currentPath = process.env.PATH || ""; + const pathDirs = parsePathEntries(currentPath); + const additionalDirs = additionalPaths ? parsePathEntries(additionalPaths) : []; + const allPaths = [...additionalDirs, ...searchPaths, ...pathDirs]; + for (const dir of allPaths) { + if (!dir) continue; + try { + const nodePath = path2.join(dir, NODE_EXECUTABLE); + if (fs2.existsSync(nodePath)) { + const stat = fs2.statSync(nodePath); + if (stat.isFile()) { + return dir; + } + } + } catch (e2) { + } } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) - return; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) - return; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) - return 1; - if (t1 < t2) - return -1; - return 0; + return null; +} +function findNodeExecutable(additionalPaths) { + const nodeDir = findNodeDirectory(additionalPaths); + if (nodeDir) { + return path2.join(nodeDir, NODE_EXECUTABLE); } - var DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time3 = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date4(dateTime[0]) && time3(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) - return; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) - return; - return res || compareTime(t1, t2); - } - var NOT_URI_FRAGMENT = /\/|:/; - var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - var MIN_INT32 = -(2 ** 31); - var MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { + return null; +} +function cliPathRequiresNode(cliPath) { + const jsExtensions = [".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"]; + const lower = cliPath.toLowerCase(); + if (jsExtensions.some((ext) => lower.endsWith(ext))) { return true; } - var Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } -}); -var require_code3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - class _CodeOrName { - } - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - class Name extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) - throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - } - exports.Name = Name; - class _Code extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) - return false; - const item = this._items[0]; - return item === "" || item === '""'; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) - names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - } - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - var plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) - code.push(...arg._items); - else if (arg instanceof Name) - code.push(arg); - else - code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === '""') - return a; - if (a === '""') - return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== '"') - return; - if (typeof b != "string") - return `${a.slice(0, -1)}${b}"`; - if (b[0] === '"') - return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) - return `"${a}${b.slice(1)}`; - return; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) { - return new _Code(`${key}`); - } - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -}); -var require_scope2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - var code_1 = require_code3(); - class ValueError extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - } - var UsedValueState; - (function(UsedValueState2) { - UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; - UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - class Scope { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { - throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - } - return this._names[prefix] = { prefix, index: 0 }; - } - } - exports.Scope = Scope; - class ValueScopeName extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - } - exports.ValueScopeName = ValueScopeName; - var line = (0, code_1._)`\n`; - class ValueScope extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) - throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) - return _name; - } else { - vs = this._values[prefix] = /* @__PURE__ */ new Map(); - } - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { property: prefix, itemIndex }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) - return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) - throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) - throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) - continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) - return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { - code = (0, code_1._)`${code}${c}${this.opts._n}`; - } else { - throw new ValueError(name); - } - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - } - exports.ValueScope = ValueScope; -}); -var require_codegen2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - var code_1 = require_code3(); - var scope_1 = require_scope2(); - var code_2 = require_code3(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return code_2._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return code_2.str; - } }); - Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { - return code_2.strConcat; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return code_2.nil; - } }); - Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { - return code_2.getProperty; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return code_2.stringify; - } }); - Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { - return code_2.regexpCode; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return code_2.Name; - } }); - var scope_2 = require_scope2(); - Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { - return scope_2.Scope; - } }); - Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { - return scope_2.ValueScope; - } }); - Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { - return scope_2.ValueScopeName; - } }); - Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { - return scope_2.varKinds; - } }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - class Node { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - } - class Def extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) - return; - if (this.rhs) - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - } - class Assign extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) - return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; - return addExprNames(names, this.rhs); - } - } - class AssignOp extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - } - class Label extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - } - class Break extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - const label = this.label ? ` ${this.label}` : ""; - return `break${label};` + _n; - } - } - class Throw extends Node { - constructor(error2) { - super(); - this.error = error2; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - } - class AnyCode extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - } - class ParentNode extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) - nodes.splice(i, 1, ...n); - else if (n) - nodes[i] = n; - else - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) - continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - } - class BlockNode extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - } - class Root extends ParentNode { - } - class Else extends BlockNode { - } - Else.kind = "else"; - class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) - code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) - return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) - return e instanceof If ? e : e.nodes; - if (this.nodes.length) - return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) - return; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) - return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) - addNames(names, this.else.names); - return names; - } - } - If.kind = "if"; - class For extends BlockNode { - } - For.kind = "for"; - class ForLoop extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - } - class ForRange extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - const names = addExprNames(super.names, this.from); - return addExprNames(names, this.to); - } - } - class ForIter extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - } - class Func extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - const _async = this.async ? "async " : ""; - return `${_async}function ${this.name}(${this.args})` + super.render(opts); - } - } - Func.kind = "func"; - class Return extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - } - Return.kind = "return"; - class Try extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) - code += this.catch.render(opts); - if (this.finally) - code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) - addNames(names, this.catch.names); - if (this.finally) - addNames(names, this.finally.names); - return names; - } - } - class Catch extends BlockNode { - constructor(error2) { - super(); - this.error = error2; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - } - Catch.kind = "catch"; - class Finally extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - } - Finally.kind = "finally"; - class CodeGen { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { ...opts, _n: opts.lines ? ` -` : "" }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); - vs.add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) - this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") - c(); - else if (c !== code_1.nil) - this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) - code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) { - this.code(thenBody).else().code(elseBody).endIf(); - } else if (thenBody) { - this.code(thenBody).endIf(); - } else if (elseBody) { - throw new Error('CodeGen: "else" body without "then" body'); - } - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) - this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) { - return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - } - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) - throw new Error('CodeGen: "return" should have one node'); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) - throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error2 = this.name("e"); - this._currNode = node.catch = new Catch(error2); - catchCode(error2); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error2) { - return this._leafNode(new Throw(error2)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) - this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) - throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { - throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - } - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) - this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) { - throw new Error('CodeGen: "else" without "if"'); - } - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - } - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) - return replaceName(expr); - if (!canOptimize(expr)) - return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) - c = replaceName(c); - if (c instanceof code_1._Code) - items.push(...c._items); - else - items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) - return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - var andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - var orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -}); -var require_util2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - var codegen_1 = require_codegen2(); - var code_1 = require_code3(); - function toHash(arr) { - const hash = {}; - for (const item of arr) - hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") - return schema; - if (Object.keys(schema).length === 0) - return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self: self2 } = it; - if (!opts.strictSchema) - return; - if (typeof schema === "boolean") - return; - const rules = self2.RULES.keywords; - for (const key in schema) { - if (!rules[key]) - checkStrictMode(it, `unknown keyword: "${key}"`); - } - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (rules[key]) - return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (key !== "$ref" && RULES.all[key]) - return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") - return schema; - if (typeof schema == "string") - return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") - return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) { - for (const x of xs) - f(x); - } else { - f(xs); - } - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) { - gen.assign(to, true); - } else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { ...from, ...to }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) - return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) - setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - var snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type2) { - Type2[Type2["Num"] = 0] = "Num"; - Type2[Type2["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) - return; - msg = `strict mode: ${msg}`; - if (mode === true) - throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -}); -var require_names2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -}); -var require_errors2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var names_1 = require_names2(); - exports.keywordError = { - message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` - }; - exports.keyword$DataError = { - message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` - }; - function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error2, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { - addError(gen, errObj); - } else { - returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - } - exports.reportError = reportError; - function reportExtraError(cxt, error2 = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error2, errorPaths); - addError(gen, errObj); - if (!(compositeRule || allErrors)) { - returnErrors(it, names_1.default.vErrors); - } - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - if (errsCount === void 0) - throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) { - gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - var E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error2, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) - return (0, codegen_1._)`{}`; - return errorObject(cxt, error2, errorPaths); - } - function errorObject(cxt, error2, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [ - errorInstancePath(it, errorPaths), - errorSchemaPath(cxt, errorPaths) - ]; - extraErrorProps(cxt, error2, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) { - schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - } - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) { - keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - } - if (opts.verbose) { - keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - } - if (propertyName) - keyValues.push([E.propertyName, propertyName]); - } -}); -var require_boolSchema2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - var errors_1 = require_errors2(); - var codegen_1 = require_codegen2(); - var names_1 = require_names2(); - var boolError = { - message: "boolean schema is false" - }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) { - falseSchemaError(it, false); - } else if (typeof schema == "object" && schema.$async === true) { - gen.return(names_1.default.data); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else { - gen.var(valid, true); - } - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -}); -var require_rules2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; - var jsonTypes = new Set(_jsonTypes); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { type: "number", rules: [] }, - string: { type: "string", rules: [] }, - array: { type: "array", rules: [] }, - object: { type: "object", rules: [] } - }; - return { - types: { ...groups, integer: true, boolean: true, null: true }, - rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; -}); -var require_applicability2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self: self2 }, type) { - const group = self2.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -}); -var require_dataType2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - var rules_1 = require_rules2(); - var applicability_1 = require_applicability2(); - var errors_1 = require_errors2(); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var DataType; - (function(DataType2) { - DataType2[DataType2["Correct"] = 0] = "Correct"; - DataType2[DataType2["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - const hasNull = types.includes("null"); - if (hasNull) { - if (schema.nullable === false) - throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) { - throw new Error('"nullable" cannot be used without "type"'); - } - if (schema.nullable === true) - types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) - return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) - coerceData(it, types, coerceTo); - else - reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") { - gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - } - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) { - if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { - coerceSpecificType(t); - } - } - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": - gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": - return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: - return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) { - return checkDataType(dataTypes[0], data, strictNums, correct); - } - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else { - cond = codegen_1.nil; - } - if (types.number) - delete types.integer; - for (const t in types) - cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - var typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -}); -var require_defaults2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) { - for (const key in properties) { - assignDefault(it, key, properties[key].default); - } - } else if (ty === "array" && Array.isArray(items)) { - items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) - return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") { - condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - } - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -}); -var require_code4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var names_1 = require_names2(); - var util_2 = require_util2(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) - valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - var newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); - if (alwaysValid && !it.opts.unevaluated) - return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - const merged = cxt.mergeValidEvaluated(schCxt, schValid); - if (!merged) - gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -}); -var require_keyword2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - var codegen_1 = require_codegen2(); - var names_1 = require_names2(); - var code_1 = require_code4(); - var errors_1 = require_errors2(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) - it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors3) { - var _a2; - gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors3); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) - throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) - throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) { - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { - throw new Error("ajv implementation error"); - } - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { - throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - } - if (def.validateSchema) { - const valid = def.validateSchema(schema[keyword]); - if (!valid) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") - self2.logger.error(msg); - else - throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -}); -var require_subschema2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) { - throw new Error('both "keyword" and "schema" passed, only one allowed'); - } - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { - throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); - } - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error('either "keyword" or "schema" must be passed'); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) { - throw new Error('both "data" and "dataProp" passed, only one allowed'); - } - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); - dataContextProps(nextData); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); - dataContextProps(nextData); - if (propertyName !== void 0) - subschema.propertyName = propertyName; - } - if (dataTypes) - subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) - subschema.compositeRule = compositeRule; - if (createErrors !== void 0) - subschema.createErrors = createErrors; - if (allErrors !== void 0) - subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -}); -var require_json_schema_traverse2 = __commonJS((exports, module2) => { - var traverse = module2.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() { - }; - var post = cb.post || function() { - }; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i = 0; i < sch.length; i++) - _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") { - for (var prop in sch) - _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { - _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -}); -var require_resolve2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - var util_1 = require_util2(); - var equal = require_fast_deep_equal(); - var traverse = require_json_schema_traverse2(); - var SIMPLE_INLINED = /* @__PURE__ */ new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") - return true; - if (limit === true) - return !hasRef(schema); - if (!limit) - return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - var REF_KEYWORDS = /* @__PURE__ */ new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) - return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) - return true; - if (typeof sch == "object" && hasRef(sch)) - return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") - return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) - continue; - if (typeof schema[key] == "object") { - (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - } - if (count === Infinity) - return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize2) { - if (normalize2 !== false) - id = normalizeId(id); - const p = resolver.parse(id); - return _getFullPath(resolver, p); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - const serialized = resolver.serialize(p); - return serialized.split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - var TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") - return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) - return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") - innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) - throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") - schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") { - checkAmbiguosRef(sch, schOrRef.schema, ref); - } else if (ref !== normalizeId(fullPath)) { - if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else { - this.refs[ref] = fullPath; - } - } - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) - throw ambiguos(ref); - } - function ambiguos(ref) { - return new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -}); -var require_validate2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - var boolSchema_1 = require_boolSchema2(); - var dataType_1 = require_dataType2(); - var applicability_1 = require_applicability2(); - var dataType_2 = require_dataType2(); - var defaults_1 = require_defaults2(); - var keyword_1 = require_keyword2(); - var subschema_1 = require_subschema2(); - var codegen_1 = require_codegen2(); - var names_1 = require_names2(); - var resolve_1 = require_resolve2(); - var util_1 = require_util2(); - var errors_1 = require_errors2(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - } else { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) - commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) - resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - return; - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self: self2 }) { - if (typeof schema == "boolean") - return !schema; - for (const key in schema) - if (self2.RULES.all[key]) - return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) - commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) - return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); - schemaKeywords(it, types, !checkedTypes, errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self: self2 } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) { - self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { - (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) - it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) - throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) { - gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - } else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) { - gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) - assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self: self2 } = it; - const { RULES } = self2; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) - checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) - groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) - return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else { - iterateKeywords(it, group); - } - if (!allErrors) - gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) - (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) { - if ((0, applicability_1.shouldUseRule)(schema, rule)) { - keywordCode(it, rule.keyword, rule.definition, group.type); - } - } - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) - return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) - checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) - return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) { - strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - } - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { - strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) { - strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) { - if (includesType(withTypes, t)) - ts.push(t); - else if (withTypes.includes("integer") && t === "number") - ts.push("integer"); - } - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - class KeywordCxt { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) { - this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - } else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { - throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - } - if ("code" in def ? def.trackErrors : def.errors !== false) { - this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) - failAction(); - else - this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) - this.gen.endIf(); - } else { - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) - this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - fail$data(condition) { - if (!this.$data) - return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) - throw new Error('add "trackErrors" to keyword definition'); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) - this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) - Object.assign(this.params, obj); - else - this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) - return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) - gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) - gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - if (!(schemaCode instanceof codegen_1.Name)) - throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) - return; - if (it.props !== true && schemaCxt.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - } - if (it.items !== true && schemaCxt.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - } - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) { - def.code(cxt, ruleType); - } else if (cxt.$data && def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } else if ("macro" in def) { - (0, keyword_1.macroKeywordCode)(cxt, def); - } else if (def.compile || def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } - } - var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") - return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) - throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) - throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) - throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) - throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) - return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) { - if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -}); -var require_validation_error2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - class ValidationError extends Error { - constructor(errors3) { - super("validation failed"); - this.errors = errors3; - this.ajv = this.validation = true; - } - } - exports.default = ValidationError; -}); -var require_ref_error2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var resolve_1 = require_resolve2(); - class MissingRefError extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - } - exports.default = MissingRefError; -}); -var require_compile2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - var codegen_1 = require_codegen2(); - var validation_error_1 = require_validation_error2(); - var names_1 = require_names2(); - var resolve_1 = require_resolve2(); - var util_1 = require_util2(); - var validate_1 = require_validate2(); - class SchemaEnv { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") - schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - } - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) - return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); - let _ValidationError; - if (sch.$async) { - _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - } - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) - sourceCode = this.opts.code.process(sourceCode, sch); - const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) - validate.$async = true; - if (this.opts.code.source === true) { - validate.source = { validateName, validateCode, scopeValues: gen._values }; - } - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) - validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) - this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root2, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root2.refs[ref]; - if (schOrFunc) - return schOrFunc; - let _sch = resolve7.call(this, root2, ref); - if (_sch === void 0) { - const schema = (_a = root2.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) - _sch = new SchemaEnv({ schema, schemaId, root: root2, baseId }); - } - if (_sch === void 0) - return; - return root2.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) - return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) { - if (sameSchemaEnv(sch, schEnv)) - return sch; - } - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve7(root2, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") - ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root2, ref); - } - function resolveSchema(root2, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root2.baseId, void 0); - if (Object.keys(root2.schema).length > 0 && refPath === baseId) { - return getJsonPointer.call(this, p, root2); - } - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root2, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") - return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") - return; - if (!schOrRef.validate) - compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ schema, schemaId, root: root2, baseId }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root: root2 }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") - return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") - return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) - return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root2, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema, schemaId, root: root2, baseId }); - if (env.schema !== env.root.schema) - return env; - return; - } -}); -var require_data2 = __commonJS((exports, module2) => { - module2.exports = { - $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", - type: "object", - required: ["$data"], - properties: { - $data: { - type: "string", - anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] - } - }, - additionalProperties: false - }; -}); -var require_uri2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var uri = require_fast_uri(); - uri.code = 'require("ajv/dist/runtime/uri").default'; - exports.default = uri; -}); -var require_core3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate2(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen2(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error2(); - var ref_error_1 = require_ref_error2(); - var rules_1 = require_rules2(); - var compile_1 = require_compile2(); - var codegen_2 = require_codegen2(); - var resolve_1 = require_resolve2(); - var dataType_1 = require_dataType2(); - var util_1 = require_util2(); - var $dataRefSchema = require_data2(); - var uri_1 = require_uri2(); - var defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; - var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - var removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: '"nullable" keyword is supported by default.', - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: '"uniqueItems" keyword is always validated.', - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now." - }; - var deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: '"minLength"/"maxLength" account for unicode characters by default.' - }; - var MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - class Ajv { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { ...opts, ...requiredOptions(opts) }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) - addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) - addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") - this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) - this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) - throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else { - v = this.compile(schemaKeyRef); - } - const valid = v(data); - if (!("$async" in v)) - this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") { - throw new Error("options.loadSchema should be a function"); - } - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) { - await runCompileAsync.call(this, { $ref }, true); - } - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) - throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) { - throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) - await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) - this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) - return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) - this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") { - throw new Error(`schema ${schemaId} must be string`); - } - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") - return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") { - throw new Error("$schema must be a string"); - } - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") - this.logger.error(message); - else - throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") - keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root2 = new compile_1.SchemaEnv({ schema: {}, schemaId }); - sch = compile_1.resolveSchema.call(this, root2, keyRef); - if (!sch) - return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") - this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: - throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) - this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) { - throw new Error("addKeywords: keyword must be string or non-empty array"); - } - } else { - throw new Error("invalid addKeywords parameters"); - } - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) - group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") - format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors3 = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors3 || errors3.length === 0) - return "No errors"; - return errors3.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) - keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") - continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) - keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas4, regex) { - for (const keyRef in schemas4) { - const sch = schemas4[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") { - delete schemas4[keyRef]; - } else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas4[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") { - id = schema[schemaId]; - } else { - if (this.opts.jtd) - throw new Error("schema must be object"); - else if (typeof schema != "boolean") - throw new Error("schema must be object or boolean"); - } - let sch = this._cache.get(schema); - if (sch !== void 0) - return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) - this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) - this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) { - throw new Error(`schema with key or id "${id}" already exists`); - } - } - _compileSchemaEnv(sch) { - if (sch.meta) - this._compileMetaSchema(sch); - else - compile_1.compileSchema.call(this, sch); - if (!sch.validate) - throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - } - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) - this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) - return; - if (Array.isArray(optsSchemas)) - this.addSchema(optsSchemas); - else - for (const key in optsSchemas) - this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) - this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) - def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) - delete metaOpts[opt]; - return metaOpts; - } - var noLogs = { log() { - }, warn() { - }, error() { - } }; - function getLogger(logger) { - if (logger === false) - return noLogs; - if (logger === void 0) - return console; - if (logger.log && logger.warn && logger.error) - return logger; - throw new Error("logger must implement log, warn and error methods"); - } - var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) - throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) - throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) - return; - if (def.$data && !("code" in def || "validate" in def)) { - throw new Error('$data keyword must have "code" or "validate" function'); - } - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) - throw new Error('keyword with "post" flag cannot have "type"'); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { type: dataType, rules: [] }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) - return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) - addBeforeRule.call(this, ruleGroup, rule, definition.before); - else - ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) { - ruleGroup.rules.splice(i, 0, rule); - } else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) - return; - if (def.$data && this.opts.$data) - metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - var $dataRef = { - $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" - }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -}); -var require_id2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var def = { - keyword: "id", - code() { - throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); - } - }; - exports.default = def; -}); -var require_ref2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - var ref_error_1 = require_ref_error2(); - var code_1 = require_code4(); - var codegen_1 = require_codegen2(); - var names_1 = require_names2(); - var compile_1 = require_compile2(); - var util_1 = require_util2(); - var def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root: root2 } = env; - if (($ref === "#" || $ref === "#/") && baseId === root2.baseId) - return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self2, root2, baseId, $ref); - if (schOrEnv === void 0) - throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) - return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root2) - return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root2 }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root2, root2.$async); - } - function callValidate(sch) { - const v = getValidate(cxt, sch); - callRef(cxt, v, sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) - callAsyncRef(); - else - callSyncRef(); - function callAsyncRef() { - if (!env.$async) - throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) - gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) - gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) - return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) { - if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - } - if (it.items !== true) { - if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - } - exports.callRef = callRef; - exports.default = def; -}); -var require_core4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var id_1 = require_id2(); - var ref_1 = require_ref2(); - var core2 = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core2; -}); -var require_limitNumber2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var ops = codegen_1.operators; - var KWDs = { - maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } - }; - var error2 = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - var def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -}); -var require_multipleOf2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }; - var def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -}); -var require_ucs2length2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) - pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; -}); -var require_limitLength2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var ucs2length_1 = require_ucs2length2(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -}); -var require_pattern2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code4(); - var codegen_1 = require_codegen2(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }; - var def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: error2, - code(cxt) { - const { data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - }; - exports.default = def; -}); -var require_limitProperties2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -}); -var require_required2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code4(); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var error2 = { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }; - var def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: error2, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) - return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) - allErrorsMode(); - else - exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) { - if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - } - function allErrorsMode() { - if (useLoop || $data) { - cxt.block$data(codegen_1.nil, loopAllRequired); - } else { - for (const prop of schema) { - (0, code_1.checkReportMissingProp)(cxt, prop); - } - } - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -}); -var require_limitItems2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -}); -var require_equal2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var equal = require_fast_deep_equal(); - equal.code = 'require("ajv/dist/runtime/equal").default'; - exports.default = equal; -}); -var require_uniqueItems2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var dataType_1 = require_dataType2(); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var equal_1 = require_equal2(); - var error2 = { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }; - var def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) - return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ i, j }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) - gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -}); -var require_const2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var equal_1 = require_equal2(); - var error2 = { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }; - var def = { - keyword: "const", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") { - cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - } else { - cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - } - }; - exports.default = def; -}); -var require_enum2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var equal_1 = require_equal2(); - var error2 = { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }; - var def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) - throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -}); -var require_validation2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var limitNumber_1 = require_limitNumber2(); - var multipleOf_1 = require_multipleOf2(); - var limitLength_1 = require_limitLength2(); - var pattern_1 = require_pattern2(); - var limitProperties_1 = require_limitProperties2(); - var required_1 = require_required2(); - var limitItems_1 = require_limitItems2(); - var uniqueItems_1 = require_uniqueItems2(); - var const_1 = require_const2(); - var enum_1 = require_enum2(); - var validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { keyword: "type", schemaType: ["string", "array"] }, - { keyword: "nullable", schemaType: "boolean" }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -}); -var require_additionalItems2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var error2 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: error2, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); - if (!it.allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -}); -var require_items2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var code_1 = require_code4(); - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "array", "boolean"], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) - return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) { - it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - } - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; -}); -var require_prefixItems2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var items_1 = require_items2(); - var def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -}); -var require_items20202 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var code_1 = require_code4(); - var additionalItems_1 = require_additionalItems2(); - var error2 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: error2, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - if (prefixItems) - (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; -}); -var require_contains2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var error2 = { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }; - var def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else { - min = 1; - } - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ min, max }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) - cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) { - validateItems(valid, () => gen.if(valid, () => gen.break())); - } else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) - gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) { - gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - } else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) - gen.assign(valid, true); - else - gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -}); -var require_dependencies2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var code_1 = require_code4(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - var def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") - continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) - return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) - continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) { - gen.if(hasProperty, () => { - for (const depProp of deps) { - (0, code_1.checkReportMissingProp)(cxt, depProp); - } - }); - } else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) - continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -}); -var require_propertyNames2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var error2 = { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }; - var def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: error2, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) - return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) - gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -}); -var require_additionalProperties2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code4(); - var codegen_1 = require_codegen2(); - var names_1 = require_names2(); - var util_1 = require_util2(); - var error2 = { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }; - var def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - if (!errsCount) - throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) - return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) - additionalPropertyCode(key); - else - gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) { - definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - } else { - definedProp = codegen_1.nil; - } - if (patProps.length) { - definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - } - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) - gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors3) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors3 === false) { - Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - } - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -}); -var require_properties2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var validate_1 = require_validate2(); - var code_1 = require_code4(); - var util_1 = require_util2(); - var additionalProperties_1 = require_additionalProperties2(); - var def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { - additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - } - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) { - it.definedProperties.add(prop); - } - if (it.opts.unevaluated && allProps.length && it.props !== true) { - it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - } - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) - return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) { - applyPropertySchema(prop); - } else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) - gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -}); -var require_patternProperties2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code4(); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var util_2 = require_util2(); - var def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { - return; - } - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) { - it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - } - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) - checkMatchingProperties(pat); - if (it.allErrors) { - validateProperties(pat); - } else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) { - if (new RegExp(pat).test(prop)) { - (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - } - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) { - cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - } - if (it.opts.unevaluated && props !== true) { - gen.assign((0, codegen_1._)`${props}[${key}]`, true); - } else if (!alwaysValid && !it.allErrors) { - gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - }); - }); - } - } - }; - exports.default = def; -}); -var require_not2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util2(); - var def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -}); -var require_anyOf2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code4(); - var def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: code_1.validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -}); -var require_oneOf2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var error2 = { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }; - var def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) - return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) { - gen.var(schValid, true); - } else { - schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - } - if (i > 0) { - gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - } - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) - cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -}); -var require_allOf2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util2(); - var def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - if (!Array.isArray(schema)) - throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -}); -var require_if2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var util_1 = require_util2(); - var error2 = { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }; - var def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: error2, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) { - (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); - } - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) - return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) { - gen.if(schValid, validateClause("then")); - } else { - gen.if((0, codegen_1.not)(schValid), validateClause("else")); - } - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) - gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else - cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); - } - exports.default = def; -}); -var require_thenElse2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util2(); - var def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) - (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; -}); -var require_applicator2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var additionalItems_1 = require_additionalItems2(); - var prefixItems_1 = require_prefixItems2(); - var items_1 = require_items2(); - var items2020_1 = require_items20202(); - var contains_1 = require_contains2(); - var dependencies_1 = require_dependencies2(); - var propertyNames_1 = require_propertyNames2(); - var additionalProperties_1 = require_additionalProperties2(); - var properties_1 = require_properties2(); - var patternProperties_1 = require_patternProperties2(); - var not_1 = require_not2(); - var anyOf_1 = require_anyOf2(); - var oneOf_1 = require_oneOf2(); - var allOf_1 = require_allOf2(); - var if_1 = require_if2(); - var thenElse_1 = require_thenElse2(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) - applicator.push(prefixItems_1.default, items2020_1.default); - else - applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -}); -var require_format3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }; - var def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: error2, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self: self2 } = it; - if (!opts.validateFormats) - return; - if ($data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self2.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) - return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self2.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) - return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) - cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self2.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { - return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; - } - return ["string", fmtDef, fmt]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) - throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } - } - } - }; - exports.default = def; -}); -var require_format4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var format_1 = require_format3(); - var format = [format_1.default]; - exports.default = format; -}); -var require_metadata2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -}); -var require_draft72 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var core_1 = require_core4(); - var validation_1 = require_validation2(); - var applicator_1 = require_applicator2(); - var format_1 = require_format4(); - var metadata_1 = require_metadata2(); - var draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -}); -var require_types2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError2) { - DiscrError2["Tag"] = "tag"; - DiscrError2["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -}); -var require_discriminator2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen2(); - var types_1 = require_types2(); - var compile_1 = require_compile2(); - var ref_error_1 = require_ref_error2(); - var util_1 = require_util2(); - var error2 = { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }; - var def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: error2, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) { - throw new Error("discriminator: requires discriminator option"); - } - const tagName = schema.propertyName; - if (typeof tagName != "string") - throw new Error("discriminator: requires propertyName"); - if (schema.mapping) - throw new Error("discriminator: mapping is not supported"); - if (!oneOf) - throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) - sch = sch.schema; - if (sch === void 0) - throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") { - throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - } - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) - throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required: required2 }) { - return Array.isArray(required2) && required2.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) { - addMapping(sch.const, i); - } else if (sch.enum) { - for (const tagValue of sch.enum) { - addMapping(tagValue, i); - } - } else { - throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) { - throw new Error(`discriminator: "${tagName}" values must be unique strings`); - } - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -}); -var require_json_schema_draft_072 = __commonJS((exports, module2) => { - module2.exports = { - $schema: "http://json-schema.org/draft-07/schema#", - $id: "http://json-schema.org/draft-07/schema#", - title: "Core schema meta-schema", - definitions: { - schemaArray: { - type: "array", - minItems: 1, - items: { $ref: "#" } - }, - nonNegativeInteger: { - type: "integer", - minimum: 0 - }, - nonNegativeIntegerDefault0: { - allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] - }, - simpleTypes: { - enum: ["array", "boolean", "integer", "null", "number", "object", "string"] - }, - stringArray: { - type: "array", - items: { type: "string" }, - uniqueItems: true, - default: [] - } - }, - type: ["object", "boolean"], - properties: { - $id: { - type: "string", - format: "uri-reference" - }, - $schema: { - type: "string", - format: "uri" - }, - $ref: { - type: "string", - format: "uri-reference" - }, - $comment: { - type: "string" - }, - title: { - type: "string" - }, - description: { - type: "string" - }, - default: true, - readOnly: { - type: "boolean", - default: false - }, - examples: { - type: "array", - items: true - }, - multipleOf: { - type: "number", - exclusiveMinimum: 0 - }, - maximum: { - type: "number" - }, - exclusiveMaximum: { - type: "number" - }, - minimum: { - type: "number" - }, - exclusiveMinimum: { - type: "number" - }, - maxLength: { $ref: "#/definitions/nonNegativeInteger" }, - minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - pattern: { - type: "string", - format: "regex" - }, - additionalItems: { $ref: "#" }, - items: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], - default: true - }, - maxItems: { $ref: "#/definitions/nonNegativeInteger" }, - minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - uniqueItems: { - type: "boolean", - default: false - }, - contains: { $ref: "#" }, - maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, - minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - required: { $ref: "#/definitions/stringArray" }, - additionalProperties: { $ref: "#" }, - definitions: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - properties: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - patternProperties: { - type: "object", - additionalProperties: { $ref: "#" }, - propertyNames: { format: "regex" }, - default: {} - }, - dependencies: { - type: "object", - additionalProperties: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] - } - }, - propertyNames: { $ref: "#" }, - const: true, - enum: { - type: "array", - items: true, - minItems: 1, - uniqueItems: true - }, - type: { - anyOf: [ - { $ref: "#/definitions/simpleTypes" }, - { - type: "array", - items: { $ref: "#/definitions/simpleTypes" }, - minItems: 1, - uniqueItems: true - } - ] - }, - format: { type: "string" }, - contentMediaType: { type: "string" }, - contentEncoding: { type: "string" }, - if: { $ref: "#" }, - then: { $ref: "#" }, - else: { $ref: "#" }, - allOf: { $ref: "#/definitions/schemaArray" }, - anyOf: { $ref: "#/definitions/schemaArray" }, - oneOf: { $ref: "#/definitions/schemaArray" }, - not: { $ref: "#" } - }, - default: true - }; -}); -var require_ajv2 = __commonJS((exports, module2) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - var core_1 = require_core3(); - var draft7_1 = require_draft72(); - var discriminator_1 = require_discriminator2(); - var draft7MetaSchema = require_json_schema_draft_072(); - var META_SUPPORT_DATA = ["/properties"]; - var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - class Ajv extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) - this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) - return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - } - exports.Ajv = Ajv; - module2.exports = exports = Ajv; - module2.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate2(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen2(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error2(); - Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { - return validation_error_1.default; - } }); - var ref_error_1 = require_ref_error2(); - Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { - return ref_error_1.default; - } }); -}); -var require_limit = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - var ajv_1 = require_ajv2(); - var codegen_1 = require_codegen2(); - var ops = codegen_1.operators; - var KWDs = { - formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } - }; - var error2 = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error: error2, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self: self2 } = it; - if (!opts.validateFormats) - return; - const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); - if (fCxt.$data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self2.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self2.formats[format]; - if (!fmtDef || fmtDef === true) - return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { - throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - } - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - var formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; -}); -var require_dist = __commonJS((exports, module2) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var formats_1 = require_formats(); - var limit_1 = require_limit(); - var codegen_1 = require_codegen2(); - var fullName = new codegen_1.Name("fullFormats"); - var fastName = new codegen_1.Name("fastFormats"); - var formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - const list = opts.formats || formats_1.formatNames; - addFormats(ajv, list, formats, exportName); - if (opts.keywords) - (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; - const f = formats[name]; - if (!f) - throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs22, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) - ajv.addFormat(f, fs22[f]); - } - module2.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; -}); -var DEFAULT_MAX_LISTENERS = 50; -function createAbortController(maxListeners = DEFAULT_MAX_LISTENERS) { - const controller = new AbortController(); - (0, import_events.setMaxListeners)(maxListeners, controller.signal); - return controller; -} -var freeGlobal = typeof global == "object" && global && global.Object === Object && global; -var _freeGlobal_default = freeGlobal; -var freeSelf = typeof self == "object" && self && self.Object === Object && self; -var root = _freeGlobal_default || freeSelf || Function("return this")(); -var _root_default = root; -var Symbol2 = _root_default.Symbol; -var _Symbol_default = Symbol2; -var objectProto = Object.prototype; -var hasOwnProperty = objectProto.hasOwnProperty; -var nativeObjectToString = objectProto.toString; -var symToStringTag = _Symbol_default ? _Symbol_default.toStringTag : void 0; -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { - value[symToStringTag] = void 0; - var unmasked = true; - } catch (e) { + if (!fs2.existsSync(cliPath)) { + return false; + } + const stat = fs2.statSync(cliPath); + if (!stat.isFile()) { + return false; + } + let fd = null; + try { + fd = fs2.openSync(cliPath, "r"); + const buffer = Buffer.alloc(200); + const bytesRead = fs2.readSync(fd, buffer, 0, buffer.length, 0); + const header = buffer.slice(0, bytesRead).toString("utf8"); + return header.startsWith("#!") && header.toLowerCase().includes("node"); + } finally { + if (fd !== null) { + try { + fs2.closeSync(fd); + } catch (e2) { + } + } + } + } catch (e2) { + return false; } - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; +} +function getMissingNodeError(cliPath, enhancedPath) { + if (!cliPathRequiresNode(cliPath)) { + return null; + } + const nodePath = findNodeExecutable(enhancedPath); + if (nodePath) { + return null; + } + return "Claude Code CLI requires Node.js, but Node was not found on PATH. Install Node.js or use the native Claude Code binary, then restart Obsidian."; +} +function getEnhancedPath(additionalPaths, cliPath) { + const extraPaths = getExtraBinaryPaths().filter((p2) => p2); + const currentPath = process.env.PATH || ""; + const segments = []; + if (additionalPaths) { + segments.push(...parsePathEntries(additionalPaths)); + } + let cliDirHasNode = false; + if (cliPath) { + try { + const cliDir = path2.dirname(cliPath); + const nodeInCliDir = path2.join(cliDir, NODE_EXECUTABLE); + if (fs2.existsSync(nodeInCliDir)) { + const stat = fs2.statSync(nodeInCliDir); + if (stat.isFile()) { + segments.push(cliDir); + cliDirHasNode = true; + } + } + } catch (e2) { + } + } + if (cliPath && cliPathRequiresNode(cliPath) && !cliDirHasNode) { + const nodeDir = findNodeDirectory(); + if (nodeDir) { + segments.push(nodeDir); + } + } + segments.push(...extraPaths); + if (currentPath) { + segments.push(...parsePathEntries(currentPath)); + } + const seen = /* @__PURE__ */ new Set(); + const unique = segments.filter((p2) => { + const normalized = isWindows ? p2.toLowerCase() : p2; + if (seen.has(normalized)) return false; + seen.add(normalized); + return true; + }); + return unique.join(PATH_SEPARATOR); +} +var CUSTOM_MODEL_ENV_KEYS = [ + "ANTHROPIC_MODEL", + "ANTHROPIC_DEFAULT_OPUS_MODEL", + "ANTHROPIC_DEFAULT_SONNET_MODEL", + "ANTHROPIC_DEFAULT_HAIKU_MODEL" +]; +function getModelTypeFromEnvKey(envKey) { + if (envKey === "ANTHROPIC_MODEL") return "model"; + const match = envKey.match(/ANTHROPIC_DEFAULT_(\w+)_MODEL/); + return match ? match[1].toLowerCase() : envKey; +} +function parseEnvironmentVariables(input) { + const result = {}; + for (const line of input.split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const normalized = trimmed.startsWith("export ") ? trimmed.slice(7) : trimmed; + const eqIndex = normalized.indexOf("="); + if (eqIndex > 0) { + const key = normalized.substring(0, eqIndex).trim(); + let value = normalized.substring(eqIndex + 1).trim(); + if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) { + value = value.slice(1, -1); + } + if (key) { + result[key] = value; + } } } return result; } -var _getRawTag_default = getRawTag; -var objectProto2 = Object.prototype; -var nativeObjectToString2 = objectProto2.toString; -function objectToString(value) { - return nativeObjectToString2.call(value); -} -var _objectToString_default = objectToString; -var nullTag = "[object Null]"; -var undefinedTag = "[object Undefined]"; -var symToStringTag2 = _Symbol_default ? _Symbol_default.toStringTag : void 0; -function baseGetTag(value) { - if (value == null) { - return value === void 0 ? undefinedTag : nullTag; - } - return symToStringTag2 && symToStringTag2 in Object(value) ? _getRawTag_default(value) : _objectToString_default(value); -} -var _baseGetTag_default = baseGetTag; -function isObject(value) { - var type = typeof value; - return value != null && (type == "object" || type == "function"); -} -var isObject_default = isObject; -var asyncTag = "[object AsyncFunction]"; -var funcTag = "[object Function]"; -var genTag = "[object GeneratorFunction]"; -var proxyTag = "[object Proxy]"; -function isFunction(value) { - if (!isObject_default(value)) { - return false; - } - var tag = _baseGetTag_default(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} -var isFunction_default = isFunction; -var coreJsData = _root_default["__core-js_shared__"]; -var _coreJsData_default = coreJsData; -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(_coreJsData_default && _coreJsData_default.keys && _coreJsData_default.keys.IE_PROTO || ""); - return uid ? "Symbol(src)_1." + uid : ""; -})(); -function isMasked(func) { - return !!maskSrcKey && maskSrcKey in func; -} -var _isMasked_default = isMasked; -var funcProto = Function.prototype; -var funcToString = funcProto.toString; -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) { - } - try { - return func + ""; - } catch (e) { +function getModelsFromEnvironment(envVars) { + const modelMap = /* @__PURE__ */ new Map(); + for (const envKey of CUSTOM_MODEL_ENV_KEYS) { + const type = getModelTypeFromEnvKey(envKey); + const modelValue = envVars[envKey]; + if (modelValue) { + const label = modelValue.includes("/") ? modelValue.split("/").pop() || modelValue : modelValue.replace(/-/g, " ").replace(/\b\w/g, (l3) => l3.toUpperCase()); + if (!modelMap.has(modelValue)) { + modelMap.set(modelValue, { types: [type], label }); + } else { + modelMap.get(modelValue).types.push(type); + } } } - return ""; -} -var _toSource_default = toSource; -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -var reIsHostCtor = /^\[object .+?Constructor\]$/; -var funcProto2 = Function.prototype; -var objectProto3 = Object.prototype; -var funcToString2 = funcProto2.toString; -var hasOwnProperty2 = objectProto3.hasOwnProperty; -var reIsNative = RegExp("^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); -function baseIsNative(value) { - if (!isObject_default(value) || _isMasked_default(value)) { - return false; + const models = []; + const typePriority = { "model": 4, "haiku": 3, "sonnet": 2, "opus": 1 }; + const sortedEntries = Array.from(modelMap.entries()).sort(([, aInfo], [, bInfo]) => { + const aPriority = Math.max(...aInfo.types.map((t2) => typePriority[t2] || 0)); + const bPriority = Math.max(...bInfo.types.map((t2) => typePriority[t2] || 0)); + return bPriority - aPriority; + }); + for (const [modelValue, info] of sortedEntries) { + const sortedTypes = info.types.sort( + (a, b3) => (typePriority[b3] || 0) - (typePriority[a] || 0) + ); + models.push({ + value: modelValue, + label: info.label, + description: `Custom model (${sortedTypes.join(", ")})` + }); } - var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor; - return pattern.test(_toSource_default(value)); + return models; } -var _baseIsNative_default = baseIsNative; -function getValue(object, key) { - return object == null ? void 0 : object[key]; +function getCurrentModelFromEnvironment(envVars) { + if (envVars.ANTHROPIC_MODEL) { + return envVars.ANTHROPIC_MODEL; + } + if (envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL) { + return envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL; + } + if (envVars.ANTHROPIC_DEFAULT_SONNET_MODEL) { + return envVars.ANTHROPIC_DEFAULT_SONNET_MODEL; + } + if (envVars.ANTHROPIC_DEFAULT_OPUS_MODEL) { + return envVars.ANTHROPIC_DEFAULT_OPUS_MODEL; + } + return null; } -var _getValue_default = getValue; -function getNative(object, key) { - var value = _getValue_default(object, key); - return _baseIsNative_default(value) ? value : void 0; +function getHostnameKey() { + return os2.hostname(); } -var _getNative_default = getNative; -var nativeCreate = _getNative_default(Object, "create"); -var _nativeCreate_default = nativeCreate; -function hashClear() { - this.__data__ = _nativeCreate_default ? _nativeCreate_default(null) : {}; - this.size = 0; +var MIN_CONTEXT_LIMIT = 1e3; +var MAX_CONTEXT_LIMIT = 1e7; +function getCustomModelIds(envVars) { + const modelIds = /* @__PURE__ */ new Set(); + for (const envKey of CUSTOM_MODEL_ENV_KEYS) { + const modelId = envVars[envKey]; + if (modelId) { + modelIds.add(modelId); + } + } + return modelIds; } -var _hashClear_default = hashClear; -function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; +function parseContextLimit(input) { + var _a3; + const trimmed = input.trim().toLowerCase().replace(/,/g, ""); + if (!trimmed) return null; + const match = trimmed.match(/^(\d+(?:\.\d+)?)\s*(k|m)?$/); + if (!match) return null; + const value = parseFloat(match[1]); + const suffix = match[2]; + if (isNaN(value) || value <= 0) return null; + const MULTIPLIERS = { k: 1e3, m: 1e6 }; + const multiplier = suffix ? (_a3 = MULTIPLIERS[suffix]) != null ? _a3 : 1 : 1; + const result = Math.round(value * multiplier); + if (result < MIN_CONTEXT_LIMIT || result > MAX_CONTEXT_LIMIT) return null; return result; } -var _hashDelete_default = hashDelete; -var HASH_UNDEFINED = "__lodash_hash_undefined__"; -var objectProto4 = Object.prototype; -var hasOwnProperty3 = objectProto4.hasOwnProperty; -function hashGet(key) { - var data = this.__data__; - if (_nativeCreate_default) { - var result = data[key]; - return result === HASH_UNDEFINED ? void 0 : result; +function formatContextLimit(tokens) { + if (tokens >= 1e6 && tokens % 1e6 === 0) { + return `${tokens / 1e6}m`; } - return hasOwnProperty3.call(data, key) ? data[key] : void 0; -} -var _hashGet_default = hashGet; -var objectProto5 = Object.prototype; -var hasOwnProperty4 = objectProto5.hasOwnProperty; -function hashHas(key) { - var data = this.__data__; - return _nativeCreate_default ? data[key] !== void 0 : hasOwnProperty4.call(data, key); -} -var _hashHas_default = hashHas; -var HASH_UNDEFINED2 = "__lodash_hash_undefined__"; -function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = _nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value; - return this; -} -var _hashSet_default = hashSet; -function Hash(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + if (tokens >= 1e3 && tokens % 1e3 === 0) { + return `${tokens / 1e3}k`; } + return tokens.toLocaleString(); } -Hash.prototype.clear = _hashClear_default; -Hash.prototype["delete"] = _hashDelete_default; -Hash.prototype.get = _hashGet_default; -Hash.prototype.has = _hashHas_default; -Hash.prototype.set = _hashSet_default; -var _Hash_default = Hash; -function listCacheClear() { - this.__data__ = []; - this.size = 0; + +// src/core/types/mcp.ts +function getMcpServerType(config2) { + if (config2.type === "sse") return "sse"; + if (config2.type === "http") return "http"; + if ("url" in config2) return "http"; + return "stdio"; } -var _listCacheClear_default = listCacheClear; -function eq(value, other) { - return value === other || value !== value && other !== other; +function isValidMcpServerConfig(obj) { + if (!obj || typeof obj !== "object") return false; + const config2 = obj; + if (config2.command && typeof config2.command === "string") return true; + if (config2.url && typeof config2.url === "string") return true; + return false; } -var eq_default = eq; -function assocIndexOf(array2, key) { - var length = array2.length; - while (length--) { - if (eq_default(array2[length][0], key)) { - return length; +var DEFAULT_MCP_SERVER = { + enabled: true, + contextSaving: true +}; + +// src/core/types/agent.ts +var AGENT_PERMISSION_MODES = ["default", "acceptEdits", "dontAsk", "bypassPermissions", "plan", "delegate"]; + +// src/core/agents/AgentStorage.ts +var KNOWN_AGENT_KEYS = /* @__PURE__ */ new Set([ + "name", + "description", + "tools", + "disallowedTools", + "model", + "skills", + "permissionMode", + "hooks" +]); +function parseAgentFile(content) { + const parsed = parseFrontmatter(content); + if (!parsed) return null; + const { frontmatter: fm, body } = parsed; + const name = fm.name; + const description = fm.description; + if (typeof name !== "string" || !name.trim()) return null; + if (typeof description !== "string" || !description.trim()) return null; + const tools = fm.tools; + const disallowedTools = fm.disallowedTools; + if (tools !== void 0 && !isStringOrArray(tools)) return null; + if (disallowedTools !== void 0 && !isStringOrArray(disallowedTools)) return null; + const model = typeof fm.model === "string" ? fm.model : void 0; + const extra = {}; + for (const key of Object.keys(fm)) { + if (!KNOWN_AGENT_KEYS.has(key)) { + extra[key] = fm[key]; } } - return -1; + const frontmatter = { + name, + description, + tools, + disallowedTools, + model, + skills: extractStringArray(fm, "skills"), + permissionMode: typeof fm.permissionMode === "string" ? fm.permissionMode : void 0, + hooks: isRecord(fm.hooks) ? fm.hooks : void 0, + extraFrontmatter: Object.keys(extra).length > 0 ? extra : void 0 + }; + return { frontmatter, body: body.trim() }; } -var _assocIndexOf_default = assocIndexOf; -var arrayProto = Array.prototype; -var splice = arrayProto.splice; -function listCacheDelete(key) { - var data = this.__data__, index = _assocIndexOf_default(data, key); - if (index < 0) { - return false; +function isStringOrArray(value) { + return typeof value === "string" || Array.isArray(value); +} +function parseToolsList(tools) { + return normalizeStringArray(tools); +} +function parsePermissionMode(mode) { + if (!mode) return void 0; + const trimmed = mode.trim(); + if (AGENT_PERMISSION_MODES.includes(trimmed)) { + return trimmed; } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); + return void 0; +} +var VALID_MODELS = ["sonnet", "opus", "haiku", "inherit"]; +function parseModel(model) { + if (!model) return "inherit"; + const normalized = model.toLowerCase().trim(); + if (VALID_MODELS.includes(normalized)) { + return normalized; } - --this.size; - return true; + return "inherit"; } -var _listCacheDelete_default = listCacheDelete; -function listCacheGet(key) { - var data = this.__data__, index = _assocIndexOf_default(data, key); - return index < 0 ? void 0 : data[index][1]; -} -var _listCacheGet_default = listCacheGet; -function listCacheHas(key) { - return _assocIndexOf_default(this.__data__, key) > -1; -} -var _listCacheHas_default = listCacheHas; -function listCacheSet(key, value) { - var data = this.__data__, index = _assocIndexOf_default(data, key); - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} -var _listCacheSet_default = listCacheSet; -function ListCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} -ListCache.prototype.clear = _listCacheClear_default; -ListCache.prototype["delete"] = _listCacheDelete_default; -ListCache.prototype.get = _listCacheGet_default; -ListCache.prototype.has = _listCacheHas_default; -ListCache.prototype.set = _listCacheSet_default; -var _ListCache_default = ListCache; -var Map2 = _getNative_default(_root_default, "Map"); -var _Map_default = Map2; -function mapCacheClear() { - this.size = 0; - this.__data__ = { - hash: new _Hash_default(), - map: new (_Map_default || _ListCache_default)(), - string: new _Hash_default() +function buildAgentFromFrontmatter(frontmatter, body, meta3) { + return { + id: meta3.id, + name: frontmatter.name, + description: frontmatter.description, + prompt: body, + tools: parseToolsList(frontmatter.tools), + disallowedTools: parseToolsList(frontmatter.disallowedTools), + model: parseModel(frontmatter.model), + source: meta3.source, + filePath: meta3.filePath, + pluginName: meta3.pluginName, + skills: frontmatter.skills, + permissionMode: parsePermissionMode(frontmatter.permissionMode), + hooks: frontmatter.hooks, + extraFrontmatter: frontmatter.extraFrontmatter }; } -var _mapCacheClear_default = mapCacheClear; -function isKeyable(value) { - var type = typeof value; - return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; + +// src/core/agents/AgentManager.ts +var GLOBAL_AGENTS_DIR = path3.join(os3.homedir(), ".claude", "agents"); +var VAULT_AGENTS_DIR = ".claude/agents"; +var PLUGIN_AGENTS_DIR = "agents"; +var FALLBACK_BUILTIN_AGENT_NAMES = ["Explore", "Plan", "Bash", "general-purpose"]; +var BUILTIN_AGENT_DESCRIPTIONS = { + "Explore": "Fast codebase exploration and search", + "Plan": "Implementation planning and architecture", + "Bash": "Command execution specialist", + "general-purpose": "Multi-step tasks and complex workflows" +}; +function makeBuiltinAgent(name) { + var _a3; + return { + id: name, + name: name.replace(/-/g, " ").replace(/\b\w/g, (l3) => l3.toUpperCase()), + description: (_a3 = BUILTIN_AGENT_DESCRIPTIONS[name]) != null ? _a3 : "", + prompt: "", + // Built-in — prompt managed by SDK + source: "builtin" + }; } -var _isKeyable_default = isKeyable; -function getMapData(map, key) { - var data = map.__data__; - return _isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; +function normalizePluginName(name) { + return name.toLowerCase().replace(/\s+/g, "-"); } -var _getMapData_default = getMapData; -function mapCacheDelete(key) { - var result = _getMapData_default(this, key)["delete"](key); - this.size -= result ? 1 : 0; - return result; -} -var _mapCacheDelete_default = mapCacheDelete; -function mapCacheGet(key) { - return _getMapData_default(this, key).get(key); -} -var _mapCacheGet_default = mapCacheGet; -function mapCacheHas(key) { - return _getMapData_default(this, key).has(key); -} -var _mapCacheHas_default = mapCacheHas; -function mapCacheSet(key, value) { - var data = _getMapData_default(this, key), size = data.size; - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} -var _mapCacheSet_default = mapCacheSet; -function MapCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); +var AgentManager = class { + constructor(vaultPath, pluginManager) { + this.agents = []; + this.builtinAgentNames = FALLBACK_BUILTIN_AGENT_NAMES; + this.vaultPath = vaultPath; + this.pluginManager = pluginManager; } -} -MapCache.prototype.clear = _mapCacheClear_default; -MapCache.prototype["delete"] = _mapCacheDelete_default; -MapCache.prototype.get = _mapCacheGet_default; -MapCache.prototype.has = _mapCacheHas_default; -MapCache.prototype.set = _mapCacheSet_default; -var _MapCache_default = MapCache; -var FUNC_ERROR_TEXT = "Expected a function"; -function memoize(func, resolver) { - if (typeof func != "function" || resolver != null && typeof resolver != "function") { - throw new TypeError(FUNC_ERROR_TEXT); + /** Built-in agents are those from init that are NOT loaded from files. */ + setBuiltinAgentNames(names) { + this.builtinAgentNames = names; + const fileAgentIds = new Set( + this.agents.filter((a) => a.source !== "builtin").map((a) => a.id) + ); + this.agents = [ + ...names.filter((n2) => !fileAgentIds.has(n2)).map(makeBuiltinAgent), + ...this.agents.filter((a) => a.source !== "builtin") + ]; } - var memoized = function() { - var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; - if (cache.has(key)) { - return cache.get(key); + async loadAgents() { + this.agents = []; + this.agents.push(...this.builtinAgentNames.map(makeBuiltinAgent)); + await this.loadPluginAgents(); + await this.loadVaultAgents(); + await this.loadGlobalAgents(); + } + getAvailableAgents() { + return [...this.agents]; + } + getAgentById(id) { + return this.agents.find((a) => a.id === id); + } + /** Used for @-mention filtering in the chat input. */ + searchAgents(query) { + const q = query.toLowerCase(); + return this.agents.filter( + (a) => a.name.toLowerCase().includes(q) || a.id.toLowerCase().includes(q) || a.description.toLowerCase().includes(q) + ); + } + async loadPluginAgents() { + for (const plugin of this.pluginManager.getPlugins()) { + if (!plugin.enabled) continue; + const agentsDir = path3.join(plugin.installPath, PLUGIN_AGENTS_DIR); + if (!fs3.existsSync(agentsDir)) continue; + for (const filePath of this.listMarkdownFiles(agentsDir)) { + const agent = await this.parsePluginAgentFromFile(filePath, plugin.name); + if (agent) this.agents.push(agent); + } + } + } + async loadVaultAgents() { + await this.loadAgentsFromDirectory(path3.join(this.vaultPath, VAULT_AGENTS_DIR), "vault"); + } + async loadGlobalAgents() { + await this.loadAgentsFromDirectory(GLOBAL_AGENTS_DIR, "global"); + } + async loadAgentsFromDirectory(dir, source) { + if (!fs3.existsSync(dir)) return; + for (const filePath of this.listMarkdownFiles(dir)) { + const agent = await this.parseAgentFromFile(filePath, source); + if (agent) this.agents.push(agent); + } + } + listMarkdownFiles(dir) { + const files = []; + try { + const entries = fs3.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + if (entry.isFile() && entry.name.endsWith(".md")) { + files.push(path3.join(dir, entry.name)); + } + } + } catch (e2) { + } + return files; + } + async parsePluginAgentFromFile(filePath, pluginName) { + try { + const content = fs3.readFileSync(filePath, "utf-8"); + const parsed = parseAgentFile(content); + if (!parsed) return null; + const { frontmatter, body } = parsed; + const normalizedPluginName = normalizePluginName(pluginName); + const id = `${normalizedPluginName}:${frontmatter.name}`; + if (this.agents.find((a) => a.id === id)) return null; + return buildAgentFromFrontmatter(frontmatter, body, { + id, + source: "plugin", + pluginName, + filePath + }); + } catch (e2) { + return null; + } + } + async parseAgentFromFile(filePath, source) { + try { + const content = fs3.readFileSync(filePath, "utf-8"); + const parsed = parseAgentFile(content); + if (!parsed) return null; + const { frontmatter, body } = parsed; + const id = frontmatter.name; + if (this.agents.find((a) => a.id === id)) return null; + return buildAgentFromFrontmatter(frontmatter, body, { + id, + source, + filePath + }); + } catch (e2) { + return null; + } + } +}; + +// src/utils/mcp.ts +function extractMcpMentions(text, validNames) { + const mentions = /* @__PURE__ */ new Set(); + const regex = /@([a-zA-Z0-9._-]+)(?!\/)/g; + let match; + while ((match = regex.exec(text)) !== null) { + const name = match[1]; + if (validNames.has(name)) { + mentions.add(name); + } + } + return mentions; +} +function transformMcpMentions(text, validNames) { + if (validNames.size === 0) return text; + const sortedNames = Array.from(validNames).sort((a, b3) => b3.length - a.length); + const escapedNames = sortedNames.map(escapeRegExp).join("|"); + const pattern = new RegExp( + `@(${escapedNames})(?! MCP)(?!/)(?![a-zA-Z0-9_-])(?!\\.[a-zA-Z0-9_-])`, + "g" + ); + return text.replace(pattern, "@$1 MCP"); +} +function escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function parseCommand(command, providedArgs) { + if (providedArgs && providedArgs.length > 0) { + return { cmd: command, args: providedArgs }; + } + const parts = splitCommandString(command); + if (parts.length === 0) { + return { cmd: "", args: [] }; + } + return { cmd: parts[0], args: parts.slice(1) }; +} +function splitCommandString(cmdStr) { + const parts = []; + let current = ""; + let inQuote = false; + let quoteChar = ""; + for (let i2 = 0; i2 < cmdStr.length; i2++) { + const char = cmdStr[i2]; + if ((char === '"' || char === "'") && !inQuote) { + inQuote = true; + quoteChar = char; + continue; + } + if (char === quoteChar && inQuote) { + inQuote = false; + quoteChar = ""; + continue; + } + if (/\s/.test(char) && !inQuote) { + if (current) { + parts.push(current); + current = ""; + } + continue; + } + current += char; + } + if (current) { + parts.push(current); + } + return parts; +} + +// src/core/mcp/McpServerManager.ts +var McpServerManager = class { + constructor(storage) { + this.servers = []; + this.storage = storage; + } + async loadServers() { + this.servers = await this.storage.load(); + } + getServers() { + return this.servers; + } + getEnabledCount() { + return this.servers.filter((s) => s.enabled).length; + } + /** + * Get servers to include in SDK options. + * + * A server is included if: + * - It is enabled AND + * - Either context-saving is disabled OR the server is @-mentioned + * + * @param mentionedNames Set of server names that were @-mentioned in the prompt + */ + getActiveServers(mentionedNames) { + const result = {}; + for (const server of this.servers) { + if (!server.enabled) continue; + if (server.contextSaving && !mentionedNames.has(server.name)) { + continue; + } + result[server.name] = server.config; } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; return result; - }; - memoized.cache = new (memoize.Cache || _MapCache_default)(); - return memoized; -} -memoize.Cache = _MapCache_default; -var memoize_default = memoize; -var CHUNK_SIZE = 2e3; -function writeToStderr(data) { - for (let i = 0; i < data.length; i += CHUNK_SIZE) { - process.stderr.write(data.substring(i, i + CHUNK_SIZE)); } -} -var parseDebugFilter = memoize_default((filterString) => { - if (!filterString || filterString.trim() === "") { - return null; + /** + * Get disabled MCP tools formatted for SDK disallowedTools option. + * + * Only returns disabled tools from servers that would be active (same filter as getActiveServers). + * + * @param mentionedNames Set of server names that were @-mentioned in the prompt + */ + getDisallowedMcpTools(mentionedNames) { + return this.collectDisallowedTools( + (s) => !s.contextSaving || mentionedNames.has(s.name) + ); } - const filters = filterString.split(",").map((f) => f.trim()).filter(Boolean); - if (filters.length === 0) { - return null; + /** + * Get all disabled MCP tools from ALL enabled servers (ignoring @-mentions). + * + * Used for persistent queries to pre-register all disabled tools upfront, + * so @-mentioning servers doesn't require cold start. + */ + getAllDisallowedMcpTools() { + return this.collectDisallowedTools().sort(); } - const hasExclusive = filters.some((f) => f.startsWith("!")); - const hasInclusive = filters.some((f) => !f.startsWith("!")); - if (hasExclusive && hasInclusive) { - return null; - } - const cleanFilters = filters.map((f) => f.replace(/^!/, "").toLowerCase()); - return { - include: hasExclusive ? [] : cleanFilters, - exclude: hasExclusive ? cleanFilters : [], - isExclusive: hasExclusive - }; -}); -function extractDebugCategories(message) { - const categories = []; - const mcpMatch = message.match(/^MCP server ["']([^"']+)["']/); - if (mcpMatch && mcpMatch[1]) { - categories.push("mcp"); - categories.push(mcpMatch[1].toLowerCase()); - } else { - const prefixMatch = message.match(/^([^:[]+):/); - if (prefixMatch && prefixMatch[1]) { - categories.push(prefixMatch[1].trim().toLowerCase()); + collectDisallowedTools(filter) { + const disallowed = /* @__PURE__ */ new Set(); + for (const server of this.servers) { + if (!server.enabled) continue; + if (filter && !filter(server)) continue; + if (!server.disabledTools || server.disabledTools.length === 0) continue; + for (const tool of server.disabledTools) { + const normalized = tool.trim(); + if (!normalized) continue; + disallowed.add(`mcp__${server.name}__${normalized}`); + } } + return Array.from(disallowed); } - const bracketMatch = message.match(/^\[([^\]]+)]/); - if (bracketMatch && bracketMatch[1]) { - categories.push(bracketMatch[1].trim().toLowerCase()); + hasServers() { + return this.servers.length > 0; } - if (message.toLowerCase().includes("statsig event:")) { - categories.push("statsig"); + getContextSavingServers() { + return this.servers.filter((s) => s.enabled && s.contextSaving); } - const secondaryMatch = message.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/); - if (secondaryMatch && secondaryMatch[1]) { - const secondary = secondaryMatch[1].trim().toLowerCase(); - if (secondary.length < 30 && !secondary.includes(" ")) { - categories.push(secondary); - } + getContextSavingNames() { + return new Set(this.getContextSavingServers().map((s) => s.name)); } - return Array.from(new Set(categories)); -} -function shouldShowDebugCategories(categories, filter) { - if (!filter) { - return true; + /** Only matches against enabled servers with context-saving mode. */ + extractMentions(text) { + return extractMcpMentions(text, this.getContextSavingNames()); } - if (categories.length === 0) { - return false; - } - if (filter.isExclusive) { - return !categories.some((cat) => filter.exclude.includes(cat)); - } else { - return categories.some((cat) => filter.include.includes(cat)); - } -} -function shouldShowDebugMessage(message, filter) { - if (!filter) { - return true; - } - const categories = extractDebugCategories(message); - return shouldShowDebugCategories(categories, filter); -} -function getClaudeConfigHomeDir() { - var _a; - return (_a = process.env.CLAUDE_CONFIG_DIR) != null ? _a : (0, import_path2.join)((0, import_os.homedir)(), ".claude"); -} -function isEnvTruthy(envVar) { - if (!envVar) - return false; - if (typeof envVar === "boolean") - return envVar; - const normalizedValue = envVar.toLowerCase().trim(); - return ["1", "true", "yes", "on"].includes(normalizedValue); -} -var bashMaxOutputLengthValidator = { - name: "BASH_MAX_OUTPUT_LENGTH", - default: 3e4, - validate: (value) => { - const MAX_OUTPUT_LENGTH = 15e4; - const DEFAULT_MAX_OUTPUT_LENGTH = 3e4; - if (!value) { - return { - effective: DEFAULT_MAX_OUTPUT_LENGTH, - status: "valid" - }; - } - const parsed = parseInt(value, 10); - if (isNaN(parsed) || parsed <= 0) { - return { - effective: DEFAULT_MAX_OUTPUT_LENGTH, - status: "invalid", - message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_LENGTH})` - }; - } - if (parsed > MAX_OUTPUT_LENGTH) { - return { - effective: MAX_OUTPUT_LENGTH, - status: "capped", - message: `Capped from ${parsed} to ${MAX_OUTPUT_LENGTH}` - }; - } - return { effective: parsed, status: "valid" }; - } -}; -var maxOutputTokensValidator = { - name: "CLAUDE_CODE_MAX_OUTPUT_TOKENS", - default: 32e3, - validate: (value) => { - const MAX_OUTPUT_TOKENS = 64e3; - const DEFAULT_MAX_OUTPUT_TOKENS = 32e3; - if (!value) { - return { effective: DEFAULT_MAX_OUTPUT_TOKENS, status: "valid" }; - } - const parsed = parseInt(value, 10); - if (isNaN(parsed) || parsed <= 0) { - return { - effective: DEFAULT_MAX_OUTPUT_TOKENS, - status: "invalid", - message: `Invalid value "${value}" (using default: ${DEFAULT_MAX_OUTPUT_TOKENS})` - }; - } - if (parsed > MAX_OUTPUT_TOKENS) { - return { - effective: MAX_OUTPUT_TOKENS, - status: "capped", - message: `Capped from ${parsed} to ${MAX_OUTPUT_TOKENS}` - }; - } - return { effective: parsed, status: "valid" }; - } -}; -function getInitialState() { - let resolvedCwd = ""; - if (typeof process !== "undefined" && typeof process.cwd === "function") { - resolvedCwd = (0, import_fs.realpathSync)((0, import_process.cwd)()); - } - return { - originalCwd: resolvedCwd, - totalCostUSD: 0, - totalAPIDuration: 0, - totalAPIDurationWithoutRetries: 0, - totalToolDuration: 0, - startTime: Date.now(), - lastInteractionTime: Date.now(), - totalLinesAdded: 0, - totalLinesRemoved: 0, - hasUnknownModelCost: false, - cwd: resolvedCwd, - modelUsage: {}, - mainLoopModelOverride: void 0, - initialMainLoopModel: null, - modelStrings: null, - isInteractive: false, - clientType: "cli", - sessionIngressToken: void 0, - oauthTokenFromFd: void 0, - apiKeyFromFd: void 0, - flagSettingsPath: void 0, - allowedSettingSources: [ - "userSettings", - "projectSettings", - "localSettings", - "flagSettings", - "policySettings" - ], - meter: null, - sessionCounter: null, - locCounter: null, - prCounter: null, - commitCounter: null, - costCounter: null, - tokenCounter: null, - codeEditToolDecisionCounter: null, - activeTimeCounter: null, - sessionId: (0, import_crypto.randomUUID)(), - loggerProvider: null, - eventLogger: null, - meterProvider: null, - tracerProvider: null, - agentColorMap: /* @__PURE__ */ new Map(), - agentColorIndex: 0, - envVarValidators: [bashMaxOutputLengthValidator, maxOutputTokensValidator], - lastAPIRequest: null, - inMemoryErrorLog: [], - inlinePlugins: [], - sessionBypassPermissionsMode: false, - sessionPersistenceDisabled: false, - hasExitedPlanMode: false, - needsPlanModeExitAttachment: false, - hasExitedDelegateMode: false, - needsDelegateModeExitAttachment: false, - lspRecommendationShownThisSession: false, - initJsonSchema: null, - registeredHooks: null, - planSlugCache: /* @__PURE__ */ new Map(), - teleportedSessionInfo: null, - invokedSkills: /* @__PURE__ */ new Map() - }; -} -var STATE = getInitialState(); -function getSessionId() { - return STATE.sessionId; -} -function createBufferedWriter({ - writeFn, - flushIntervalMs = 1e3, - maxBufferSize = 100, - immediateMode = false -}) { - let buffer = []; - let flushTimer = null; - function clearTimer() { - if (flushTimer) { - clearTimeout(flushTimer); - flushTimer = null; - } - } - function flush() { - if (buffer.length === 0) - return; - writeFn(buffer.join("")); - buffer = []; - clearTimer(); - } - function scheduleFlush() { - if (!flushTimer) { - flushTimer = setTimeout(flush, flushIntervalMs); - } - } - return { - write(content) { - if (immediateMode) { - writeFn(content); - return; - } - buffer.push(content); - scheduleFlush(); - if (buffer.length >= maxBufferSize) { - flush(); - } - }, - flush, - dispose() { - flush(); - } - }; -} -var cleanupFunctions = /* @__PURE__ */ new Set(); -function registerCleanup(cleanupFn) { - cleanupFunctions.add(cleanupFn); - return () => cleanupFunctions.delete(cleanupFn); -} -var isDebugMode = memoize_default(() => { - return isEnvTruthy(process.env.DEBUG) || isEnvTruthy(process.env.DEBUG_SDK) || process.argv.includes("--debug") || process.argv.includes("-d") || isDebugToStdErr() || process.argv.some((arg) => arg.startsWith("--debug=")); -}); -var getDebugFilter = memoize_default(() => { - const debugArg = process.argv.find((arg) => arg.startsWith("--debug=")); - if (!debugArg) { - return null; - } - const filterPattern = debugArg.substring("--debug=".length); - return parseDebugFilter(filterPattern); -}); -var isDebugToStdErr = memoize_default(() => { - return process.argv.includes("--debug-to-stderr") || process.argv.includes("-d2e"); -}); -function shouldLogDebugMessage(message) { - if (false) { - } - if (typeof process === "undefined" || typeof process.versions === "undefined" || typeof process.versions.node === "undefined") { - return false; - } - const filter = getDebugFilter(); - return shouldShowDebugMessage(message, filter); -} -var hasFormattedOutput = false; -var debugWriter = null; -function getDebugWriter() { - if (!debugWriter) { - debugWriter = createBufferedWriter({ - writeFn: (content) => { - const path12 = getDebugLogPath(); - if (!getFsImplementation().existsSync((0, import_path3.dirname)(path12))) { - getFsImplementation().mkdirSync((0, import_path3.dirname)(path12)); - } - getFsImplementation().appendFileSync(path12, content); - updateLatestDebugLogSymlink(); - }, - flushIntervalMs: 1e3, - maxBufferSize: 100, - immediateMode: isDebugMode() - }); - registerCleanup(async () => debugWriter == null ? void 0 : debugWriter.dispose()); - } - return debugWriter; -} -function logForDebugging(message, { level } = { - level: "debug" -}) { - if (!shouldLogDebugMessage(message)) { - return; - } - if (hasFormattedOutput && message.includes(` -`)) { - message = JSON.stringify(message); - } - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - const output = `${timestamp} [${level.toUpperCase()}] ${message.trim()} -`; - if (isDebugToStdErr()) { - writeToStderr(output); - return; - } - getDebugWriter().write(output); -} -function getDebugLogPath() { - var _a; - return (_a = process.env.CLAUDE_CODE_DEBUG_LOGS_DIR) != null ? _a : (0, import_path3.join)(getClaudeConfigHomeDir(), "debug", `${getSessionId()}.txt`); -} -var updateLatestDebugLogSymlink = memoize_default(() => { - if (process.argv[2] === "--ripgrep") { - return; - } - try { - const debugLogPath = getDebugLogPath(); - const debugLogsDir = (0, import_path3.dirname)(debugLogPath); - const latestSymlinkPath = (0, import_path3.join)(debugLogsDir, "latest"); - if (!getFsImplementation().existsSync(debugLogsDir)) { - getFsImplementation().mkdirSync(debugLogsDir); - } - if (getFsImplementation().existsSync(latestSymlinkPath)) { - try { - getFsImplementation().unlinkSync(latestSymlinkPath); - } catch (e) { - } - } - getFsImplementation().symlinkSync(debugLogPath, latestSymlinkPath); - } catch (e) { - } -}); -var SLOW_SYNC_THRESHOLD_MS = 5; -function withSlowLogging(operation, fn) { - const startTime = performance.now(); - try { - return fn(); - } finally { - const duration3 = performance.now() - startTime; - if (duration3 > SLOW_SYNC_THRESHOLD_MS) { - logForDebugging(`[SLOW OPERATION DETECTED] fs.${operation} (${duration3.toFixed(1)}ms)`); - } - } -} -var NodeFsOperations = { - cwd() { - return process.cwd(); - }, - existsSync(fsPath) { - return withSlowLogging("existsSync", () => fs.existsSync(fsPath)); - }, - async stat(fsPath) { - return (0, import_promises.stat)(fsPath); - }, - statSync(fsPath) { - return withSlowLogging("statSync", () => fs.statSync(fsPath)); - }, - lstatSync(fsPath) { - return withSlowLogging("lstatSync", () => fs.lstatSync(fsPath)); - }, - readFileSync(fsPath, options) { - return withSlowLogging("readFileSync", () => fs.readFileSync(fsPath, { encoding: options.encoding })); - }, - readFileBytesSync(fsPath) { - return withSlowLogging("readFileBytesSync", () => fs.readFileSync(fsPath)); - }, - readSync(fsPath, options) { - return withSlowLogging("readSync", () => { - let fd = void 0; - try { - fd = fs.openSync(fsPath, "r"); - const buffer = Buffer.alloc(options.length); - const bytesRead = fs.readSync(fd, buffer, 0, options.length, 0); - return { buffer, bytesRead }; - } finally { - if (fd) - fs.closeSync(fd); - } - }); - }, - writeFileSync(fsPath, data, options) { - return withSlowLogging("writeFileSync", () => { - var _a, _b; - const fileExists = fs.existsSync(fsPath); - if (!options.flush) { - const writeOptions = { - encoding: options.encoding - }; - if (!fileExists) { - writeOptions.mode = (_a = options.mode) != null ? _a : 384; - } else if (options.mode !== void 0) { - writeOptions.mode = options.mode; - } - fs.writeFileSync(fsPath, data, writeOptions); - return; - } - let fd; - try { - const mode = !fileExists ? (_b = options.mode) != null ? _b : 384 : options.mode; - fd = fs.openSync(fsPath, "w", mode); - fs.writeFileSync(fd, data, { encoding: options.encoding }); - fs.fsyncSync(fd); - } finally { - if (fd) { - fs.closeSync(fd); - } - } - }); - }, - appendFileSync(path12, data, options) { - return withSlowLogging("appendFileSync", () => { - var _a; - if (!fs.existsSync(path12)) { - const mode = (_a = options == null ? void 0 : options.mode) != null ? _a : 384; - const fd = fs.openSync(path12, "a", mode); - try { - fs.appendFileSync(fd, data); - } finally { - fs.closeSync(fd); - } - } else { - fs.appendFileSync(path12, data); - } - }); - }, - copyFileSync(src, dest) { - return withSlowLogging("copyFileSync", () => fs.copyFileSync(src, dest)); - }, - unlinkSync(path12) { - return withSlowLogging("unlinkSync", () => fs.unlinkSync(path12)); - }, - renameSync(oldPath, newPath) { - return withSlowLogging("renameSync", () => fs.renameSync(oldPath, newPath)); - }, - linkSync(target, path12) { - return withSlowLogging("linkSync", () => fs.linkSync(target, path12)); - }, - symlinkSync(target, path12) { - return withSlowLogging("symlinkSync", () => fs.symlinkSync(target, path12)); - }, - readlinkSync(path12) { - return withSlowLogging("readlinkSync", () => fs.readlinkSync(path12)); - }, - realpathSync(path12) { - return withSlowLogging("realpathSync", () => fs.realpathSync(path12)); - }, - mkdirSync(dirPath) { - return withSlowLogging("mkdirSync", () => { - if (!fs.existsSync(dirPath)) { - fs.mkdirSync(dirPath, { recursive: true, mode: 448 }); - } - }); - }, - readdirSync(dirPath) { - return withSlowLogging("readdirSync", () => fs.readdirSync(dirPath, { withFileTypes: true })); - }, - readdirStringSync(dirPath) { - return withSlowLogging("readdirStringSync", () => fs.readdirSync(dirPath)); - }, - isDirEmptySync(dirPath) { - return withSlowLogging("isDirEmptySync", () => { - const files = this.readdirSync(dirPath); - return files.length === 0; - }); - }, - rmdirSync(dirPath) { - return withSlowLogging("rmdirSync", () => fs.rmdirSync(dirPath)); - }, - rmSync(path12, options) { - return withSlowLogging("rmSync", () => fs.rmSync(path12, options)); - }, - createWriteStream(path12) { - return fs.createWriteStream(path12); - } -}; -var activeFs = NodeFsOperations; -function getFsImplementation() { - return activeFs; -} -var AbortError = class extends Error { -}; -function isRunningWithBun() { - return process.versions.bun !== void 0; -} -var debugFilePath = null; -var initialized = false; -function getOrCreateDebugFile() { - if (initialized) { - return debugFilePath; - } - initialized = true; - if (!process.env.DEBUG_CLAUDE_AGENT_SDK) { - return null; - } - const debugDir = (0, import_path4.join)(getClaudeConfigHomeDir(), "debug"); - debugFilePath = (0, import_path4.join)(debugDir, `sdk-${(0, import_crypto2.randomUUID)()}.txt`); - if (!(0, import_fs2.existsSync)(debugDir)) { - (0, import_fs2.mkdirSync)(debugDir, { recursive: true }); - } - process.stderr.write(`SDK debug logs: ${debugFilePath} -`); - return debugFilePath; -} -function logForSdkDebugging(message) { - const path12 = getOrCreateDebugFile(); - if (!path12) { - return; - } - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - const output = `${timestamp} ${message} -`; - (0, import_fs2.appendFileSync)(path12, output); -} -function mergeSandboxIntoExtraArgs(extraArgs, sandbox) { - const effectiveExtraArgs = { ...extraArgs }; - if (sandbox) { - let settingsObj = { sandbox }; - if (effectiveExtraArgs.settings) { - try { - const existingSettings = JSON.parse(effectiveExtraArgs.settings); - settingsObj = { ...existingSettings, sandbox }; - } catch (e) { - } - } - effectiveExtraArgs.settings = JSON.stringify(settingsObj); - } - return effectiveExtraArgs; -} -var ProcessTransport = class { - constructor(options) { - __publicField(this, "options"); - __publicField(this, "process"); - __publicField(this, "processStdin"); - __publicField(this, "processStdout"); - __publicField(this, "ready", false); - __publicField(this, "abortController"); - __publicField(this, "exitError"); - __publicField(this, "exitListeners", []); - __publicField(this, "processExitHandler"); - __publicField(this, "abortHandler"); - this.options = options; - this.abortController = options.abortController || createAbortController(); - this.initialize(); - } - getDefaultExecutable() { - return isRunningWithBun() ? "bun" : "node"; - } - spawnLocalProcess(spawnOptions) { - const { command, args, cwd: cwd2, env, signal } = spawnOptions; - const stderrMode = env.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr ? "pipe" : "ignore"; - const childProcess = (0, import_child_process.spawn)(command, args, { - cwd: cwd2, - stdio: ["pipe", "pipe", stderrMode], - signal, - env, - windowsHide: true - }); - if (env.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr) { - childProcess.stderr.on("data", (data) => { - const message = data.toString(); - logForSdkDebugging(message); - if (this.options.stderr) { - this.options.stderr(message); - } - }); - } - const mappedProcess = { - stdin: childProcess.stdin, - stdout: childProcess.stdout, - get killed() { - return childProcess.killed; - }, - get exitCode() { - return childProcess.exitCode; - }, - kill: childProcess.kill.bind(childProcess), - on: childProcess.on.bind(childProcess), - once: childProcess.once.bind(childProcess), - off: childProcess.off.bind(childProcess) - }; - return mappedProcess; - } - initialize() { - try { - const { - additionalDirectories = [], - betas, - cwd: cwd2, - executable = this.getDefaultExecutable(), - executableArgs = [], - extraArgs = {}, - pathToClaudeCodeExecutable, - env = { ...process.env }, - maxThinkingTokens, - maxTurns, - maxBudgetUsd, - model, - fallbackModel, - jsonSchema, - permissionMode, - allowDangerouslySkipPermissions, - permissionPromptToolName, - continueConversation, - resume, - settingSources, - allowedTools = [], - disallowedTools = [], - tools, - mcpServers, - strictMcpConfig, - canUseTool, - includePartialMessages, - plugins, - sandbox - } = this.options; - const args = [ - "--output-format", - "stream-json", - "--verbose", - "--input-format", - "stream-json" - ]; - if (maxThinkingTokens !== void 0) { - args.push("--max-thinking-tokens", maxThinkingTokens.toString()); - } - if (maxTurns) - args.push("--max-turns", maxTurns.toString()); - if (maxBudgetUsd !== void 0) { - args.push("--max-budget-usd", maxBudgetUsd.toString()); - } - if (model) - args.push("--model", model); - if (betas && betas.length > 0) { - args.push("--betas", betas.join(",")); - } - if (jsonSchema) { - args.push("--json-schema", JSON.stringify(jsonSchema)); - } - if (env.DEBUG_CLAUDE_AGENT_SDK) { - args.push("--debug-to-stderr"); - } - if (canUseTool) { - if (permissionPromptToolName) { - throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other."); - } - args.push("--permission-prompt-tool", "stdio"); - } else if (permissionPromptToolName) { - args.push("--permission-prompt-tool", permissionPromptToolName); - } - if (continueConversation) - args.push("--continue"); - if (resume) - args.push("--resume", resume); - if (allowedTools.length > 0) { - args.push("--allowedTools", allowedTools.join(",")); - } - if (disallowedTools.length > 0) { - args.push("--disallowedTools", disallowedTools.join(",")); - } - if (tools !== void 0) { - if (Array.isArray(tools)) { - if (tools.length === 0) { - args.push("--tools", ""); - } else { - args.push("--tools", tools.join(",")); - } - } else { - args.push("--tools", "default"); - } - } - if (mcpServers && Object.keys(mcpServers).length > 0) { - args.push("--mcp-config", JSON.stringify({ mcpServers })); - } - if (settingSources) { - args.push("--setting-sources", settingSources.join(",")); - } - if (strictMcpConfig) { - args.push("--strict-mcp-config"); - } - if (permissionMode) { - args.push("--permission-mode", permissionMode); - } - if (allowDangerouslySkipPermissions) { - args.push("--allow-dangerously-skip-permissions"); - } - if (fallbackModel) { - if (model && fallbackModel === model) { - throw new Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option."); - } - args.push("--fallback-model", fallbackModel); - } - if (includePartialMessages) { - args.push("--include-partial-messages"); - } - for (const dir of additionalDirectories) { - args.push("--add-dir", dir); - } - if (plugins && plugins.length > 0) { - for (const plugin of plugins) { - if (plugin.type === "local") { - args.push("--plugin-dir", plugin.path); - } else { - throw new Error(`Unsupported plugin type: ${plugin.type}`); - } - } - } - if (this.options.forkSession) { - args.push("--fork-session"); - } - if (this.options.resumeSessionAt) { - args.push("--resume-session-at", this.options.resumeSessionAt); - } - if (this.options.persistSession === false) { - args.push("--no-session-persistence"); - } - const effectiveExtraArgs = mergeSandboxIntoExtraArgs(extraArgs != null ? extraArgs : {}, sandbox); - for (const [flag, value] of Object.entries(effectiveExtraArgs)) { - if (value === null) { - args.push(`--${flag}`); - } else { - args.push(`--${flag}`, value); - } - } - if (!env.CLAUDE_CODE_ENTRYPOINT) { - env.CLAUDE_CODE_ENTRYPOINT = "sdk-ts"; - } - delete env.NODE_OPTIONS; - if (env.DEBUG_CLAUDE_AGENT_SDK) { - env.DEBUG = "1"; - } else { - delete env.DEBUG; - } - const isNative = isNativeBinary(pathToClaudeCodeExecutable); - const spawnCommand = isNative ? pathToClaudeCodeExecutable : executable; - const spawnArgs = isNative ? [...executableArgs, ...args] : [...executableArgs, pathToClaudeCodeExecutable, ...args]; - const spawnOptions = { - command: spawnCommand, - args: spawnArgs, - cwd: cwd2, - env, - signal: this.abortController.signal - }; - if (this.options.spawnClaudeCodeProcess) { - logForSdkDebugging(`Spawning Claude Code (custom): ${spawnCommand} ${spawnArgs.join(" ")}`); - this.process = this.options.spawnClaudeCodeProcess(spawnOptions); - } else { - const fs22 = getFsImplementation(); - if (!fs22.existsSync(pathToClaudeCodeExecutable)) { - const errorMessage = isNative ? `Claude Code native binary not found at ${pathToClaudeCodeExecutable}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.` : `Claude Code executable not found at ${pathToClaudeCodeExecutable}. Is options.pathToClaudeCodeExecutable set?`; - throw new ReferenceError(errorMessage); - } - logForSdkDebugging(`Spawning Claude Code: ${spawnCommand} ${spawnArgs.join(" ")}`); - this.process = this.spawnLocalProcess(spawnOptions); - } - this.processStdin = this.process.stdin; - this.processStdout = this.process.stdout; - const cleanup = () => { - if (this.process && !this.process.killed) { - this.process.kill("SIGTERM"); - } - }; - this.processExitHandler = cleanup; - this.abortHandler = cleanup; - process.on("exit", this.processExitHandler); - this.abortController.signal.addEventListener("abort", this.abortHandler); - this.process.on("error", (error2) => { - this.ready = false; - if (this.abortController.signal.aborted) { - this.exitError = new AbortError("Claude Code process aborted by user"); - } else { - this.exitError = new Error(`Failed to spawn Claude Code process: ${error2.message}`); - logForSdkDebugging(this.exitError.message); - } - }); - this.process.on("exit", (code, signal) => { - this.ready = false; - if (this.abortController.signal.aborted) { - this.exitError = new AbortError("Claude Code process aborted by user"); - } else { - const error2 = this.getProcessExitError(code, signal); - if (error2) { - this.exitError = error2; - logForSdkDebugging(error2.message); - } - } - }); - this.ready = true; - } catch (error2) { - this.ready = false; - throw error2; - } - } - getProcessExitError(code, signal) { - if (code !== 0 && code !== null) { - return new Error(`Claude Code process exited with code ${code}`); - } else if (signal) { - return new Error(`Claude Code process terminated by signal ${signal}`); - } - return; - } - write(data) { - var _a, _b; - if (this.abortController.signal.aborted) { - throw new AbortError("Operation aborted"); - } - if (!this.ready || !this.processStdin) { - throw new Error("ProcessTransport is not ready for writing"); - } - if (((_a = this.process) == null ? void 0 : _a.killed) || ((_b = this.process) == null ? void 0 : _b.exitCode) !== null) { - throw new Error("Cannot write to terminated process"); - } - if (this.exitError) { - throw new Error(`Cannot write to process that exited with error: ${this.exitError.message}`); - } - logForSdkDebugging(`[ProcessTransport] Writing to stdin: ${data.substring(0, 100)}`); - try { - const written = this.processStdin.write(data); - if (!written) { - logForSdkDebugging("[ProcessTransport] Write buffer full, data queued"); - } - } catch (error2) { - this.ready = false; - throw new Error(`Failed to write to process stdin: ${error2.message}`); - } - } - close() { - var _a; - if (this.processStdin) { - this.processStdin.end(); - this.processStdin = void 0; - } - if (this.abortHandler) { - this.abortController.signal.removeEventListener("abort", this.abortHandler); - this.abortHandler = void 0; - } - for (const { handler } of this.exitListeners) { - (_a = this.process) == null ? void 0 : _a.off("exit", handler); - } - this.exitListeners = []; - if (this.process && !this.process.killed) { - this.process.kill("SIGTERM"); - setTimeout(() => { - if (this.process && !this.process.killed) { - this.process.kill("SIGKILL"); - } - }, 5e3); - } - this.ready = false; - if (this.processExitHandler) { - process.off("exit", this.processExitHandler); - this.processExitHandler = void 0; - } - } - isReady() { - return this.ready; - } - async *readMessages() { - if (!this.processStdout) { - throw new Error("ProcessTransport output stream not available"); - } - const rl = (0, import_readline.createInterface)({ input: this.processStdout }); - try { - for await (const line of rl) { - if (line.trim()) { - const message = JSON.parse(line); - yield message; - } - } - await this.waitForExit(); - } catch (error2) { - throw error2; - } finally { - rl.close(); - } - } - endInput() { - if (this.processStdin) { - this.processStdin.end(); - } - } - getInputStream() { - return this.processStdin; - } - onExit(callback) { - if (!this.process) - return () => { - }; - const handler = (code, signal) => { - const error2 = this.getProcessExitError(code, signal); - callback(error2); - }; - this.process.on("exit", handler); - this.exitListeners.push({ callback, handler }); - return () => { - if (this.process) { - this.process.off("exit", handler); - } - const index = this.exitListeners.findIndex((l) => l.handler === handler); - if (index !== -1) { - this.exitListeners.splice(index, 1); - } - }; - } - async waitForExit() { - if (!this.process) { - if (this.exitError) { - throw this.exitError; - } - return; - } - if (this.process.exitCode !== null || this.process.killed) { - if (this.exitError) { - throw this.exitError; - } - return; - } - return new Promise((resolve7, reject) => { - const exitHandler = (code, signal) => { - if (this.abortController.signal.aborted) { - reject(new AbortError("Operation aborted")); - return; - } - const error2 = this.getProcessExitError(code, signal); - if (error2) { - reject(error2); - } else { - resolve7(); - } - }; - this.process.once("exit", exitHandler); - const errorHandler = (error2) => { - this.process.off("exit", exitHandler); - reject(error2); - }; - this.process.once("error", errorHandler); - this.process.once("exit", () => { - this.process.off("error", errorHandler); - }); - }); - } -}; -function isNativeBinary(executablePath) { - const jsExtensions = [".js", ".mjs", ".tsx", ".ts", ".jsx"]; - return !jsExtensions.some((ext) => executablePath.endsWith(ext)); -} -var Stream = class { - constructor(returned) { - __publicField(this, "returned"); - __publicField(this, "queue", []); - __publicField(this, "readResolve"); - __publicField(this, "readReject"); - __publicField(this, "isDone", false); - __publicField(this, "hasError"); - __publicField(this, "started", false); - this.returned = returned; - } - [Symbol.asyncIterator]() { - if (this.started) { - throw new Error("Stream can only be iterated once"); - } - this.started = true; - return this; - } - next() { - if (this.queue.length > 0) { - return Promise.resolve({ - done: false, - value: this.queue.shift() - }); - } - if (this.isDone) { - return Promise.resolve({ done: true, value: void 0 }); - } - if (this.hasError) { - return Promise.reject(this.hasError); - } - return new Promise((resolve7, reject) => { - this.readResolve = resolve7; - this.readReject = reject; - }); - } - enqueue(value) { - if (this.readResolve) { - const resolve7 = this.readResolve; - this.readResolve = void 0; - this.readReject = void 0; - resolve7({ done: false, value }); - } else { - this.queue.push(value); - } - } - done() { - this.isDone = true; - if (this.readResolve) { - const resolve7 = this.readResolve; - this.readResolve = void 0; - this.readReject = void 0; - resolve7({ done: true, value: void 0 }); - } - } - error(error2) { - this.hasError = error2; - if (this.readReject) { - const reject = this.readReject; - this.readResolve = void 0; - this.readReject = void 0; - reject(error2); - } - } - return() { - this.isDone = true; - if (this.returned) { - this.returned(); - } - return Promise.resolve({ done: true, value: void 0 }); - } -}; -var SdkControlServerTransport = class { - constructor(sendMcpMessage) { - __publicField(this, "sendMcpMessage"); - __publicField(this, "isClosed", false); - __publicField(this, "onclose"); - __publicField(this, "onerror"); - __publicField(this, "onmessage"); - this.sendMcpMessage = sendMcpMessage; - } - async start() { - } - async send(message) { - if (this.isClosed) { - throw new Error("Transport is closed"); - } - this.sendMcpMessage(message); - } - async close() { - var _a; - if (this.isClosed) { - return; - } - this.isClosed = true; - (_a = this.onclose) == null ? void 0 : _a.call(this); - } -}; -var Query = class { - constructor(transport, isSingleUserTurn, canUseTool, hooks, abortController, sdkMcpServers = /* @__PURE__ */ new Map(), jsonSchema, initConfig) { - __publicField(this, "transport"); - __publicField(this, "isSingleUserTurn"); - __publicField(this, "canUseTool"); - __publicField(this, "hooks"); - __publicField(this, "abortController"); - __publicField(this, "jsonSchema"); - __publicField(this, "initConfig"); - __publicField(this, "pendingControlResponses", /* @__PURE__ */ new Map()); - __publicField(this, "cleanupPerformed", false); - __publicField(this, "sdkMessages"); - __publicField(this, "inputStream", new Stream()); - __publicField(this, "initialization"); - __publicField(this, "cancelControllers", /* @__PURE__ */ new Map()); - __publicField(this, "hookCallbacks", /* @__PURE__ */ new Map()); - __publicField(this, "nextCallbackId", 0); - __publicField(this, "sdkMcpTransports", /* @__PURE__ */ new Map()); - __publicField(this, "sdkMcpServerInstances", /* @__PURE__ */ new Map()); - __publicField(this, "pendingMcpResponses", /* @__PURE__ */ new Map()); - __publicField(this, "firstResultReceivedResolve"); - __publicField(this, "firstResultReceived", false); - this.transport = transport; - this.isSingleUserTurn = isSingleUserTurn; - this.canUseTool = canUseTool; - this.hooks = hooks; - this.abortController = abortController; - this.jsonSchema = jsonSchema; - this.initConfig = initConfig; - for (const [name, server] of sdkMcpServers) { - this.connectSdkMcpServer(name, server); - } - this.sdkMessages = this.readSdkMessages(); - this.readMessages(); - this.initialization = this.initialize(); - this.initialization.catch(() => { - }); - } - hasBidirectionalNeeds() { - return this.sdkMcpTransports.size > 0 || this.hooks !== void 0 && Object.keys(this.hooks).length > 0 || this.canUseTool !== void 0; - } - setError(error2) { - this.inputStream.error(error2); - } - cleanup(error2) { - if (this.cleanupPerformed) - return; - this.cleanupPerformed = true; - try { - this.transport.close(); - this.pendingControlResponses.clear(); - this.pendingMcpResponses.clear(); - this.cancelControllers.clear(); - this.hookCallbacks.clear(); - for (const transport of this.sdkMcpTransports.values()) { - try { - transport.close(); - } catch (e) { - } - } - this.sdkMcpTransports.clear(); - if (error2) { - this.inputStream.error(error2); - } else { - this.inputStream.done(); - } - } catch (_error) { - } - } - next(...[value]) { - return this.sdkMessages.next(...[value]); - } - return(value) { - return this.sdkMessages.return(value); - } - throw(e) { - return this.sdkMessages.throw(e); - } - [Symbol.asyncIterator]() { - return this.sdkMessages; - } - [Symbol.asyncDispose]() { - return this.sdkMessages[Symbol.asyncDispose](); - } - async readMessages() { - try { - for await (const message of this.transport.readMessages()) { - if (message.type === "control_response") { - const handler = this.pendingControlResponses.get(message.response.request_id); - if (handler) { - handler(message.response); - } - continue; - } else if (message.type === "control_request") { - this.handleControlRequest(message); - continue; - } else if (message.type === "control_cancel_request") { - this.handleControlCancelRequest(message); - continue; - } else if (message.type === "keep_alive") { - continue; - } - if (message.type === "result") { - this.firstResultReceived = true; - if (this.firstResultReceivedResolve) { - this.firstResultReceivedResolve(); - } - if (this.isSingleUserTurn) { - logForDebugging(`[Query.readMessages] First result received for single-turn query, closing stdin`); - this.transport.endInput(); - } - } - this.inputStream.enqueue(message); - } - if (this.firstResultReceivedResolve) { - this.firstResultReceivedResolve(); - } - this.inputStream.done(); - this.cleanup(); - } catch (error2) { - if (this.firstResultReceivedResolve) { - this.firstResultReceivedResolve(); - } - this.inputStream.error(error2); - this.cleanup(error2); - } - } - async handleControlRequest(request) { - const controller = new AbortController(); - this.cancelControllers.set(request.request_id, controller); - try { - const response = await this.processControlRequest(request, controller.signal); - const controlResponse = { - type: "control_response", - response: { - subtype: "success", - request_id: request.request_id, - response - } - }; - await Promise.resolve(this.transport.write(JSON.stringify(controlResponse) + ` -`)); - } catch (error2) { - const controlErrorResponse = { - type: "control_response", - response: { - subtype: "error", - request_id: request.request_id, - error: error2.message || String(error2) - } - }; - await Promise.resolve(this.transport.write(JSON.stringify(controlErrorResponse) + ` -`)); - } finally { - this.cancelControllers.delete(request.request_id); - } - } - handleControlCancelRequest(request) { - const controller = this.cancelControllers.get(request.request_id); - if (controller) { - controller.abort(); - this.cancelControllers.delete(request.request_id); - } - } - async processControlRequest(request, signal) { - if (request.request.subtype === "can_use_tool") { - if (!this.canUseTool) { - throw new Error("canUseTool callback is not provided."); - } - const result = await this.canUseTool(request.request.tool_name, request.request.input, { - signal, - suggestions: request.request.permission_suggestions, - blockedPath: request.request.blocked_path, - decisionReason: request.request.decision_reason, - toolUseID: request.request.tool_use_id, - agentID: request.request.agent_id - }); - return { - ...result, - toolUseID: request.request.tool_use_id - }; - } else if (request.request.subtype === "hook_callback") { - const result = await this.handleHookCallbacks(request.request.callback_id, request.request.input, request.request.tool_use_id, signal); - return result; - } else if (request.request.subtype === "mcp_message") { - const mcpRequest = request.request; - const transport = this.sdkMcpTransports.get(mcpRequest.server_name); - if (!transport) { - throw new Error(`SDK MCP server not found: ${mcpRequest.server_name}`); - } - if ("method" in mcpRequest.message && "id" in mcpRequest.message && mcpRequest.message.id !== null) { - const response = await this.handleMcpControlRequest(mcpRequest.server_name, mcpRequest, transport); - return { mcp_response: response }; - } else { - if (transport.onmessage) { - transport.onmessage(mcpRequest.message); - } - return { mcp_response: { jsonrpc: "2.0", result: {}, id: 0 } }; - } - } - throw new Error("Unsupported control request subtype: " + request.request.subtype); - } - async *readSdkMessages() { - for await (const message of this.inputStream) { - yield message; - } - } - async initialize() { - var _a, _b, _c; - let hooks; - if (this.hooks) { - hooks = {}; - for (const [event, matchers] of Object.entries(this.hooks)) { - if (matchers.length > 0) { - hooks[event] = matchers.map((matcher) => { - const callbackIds = []; - for (const callback of matcher.hooks) { - const callbackId = `hook_${this.nextCallbackId++}`; - this.hookCallbacks.set(callbackId, callback); - callbackIds.push(callbackId); - } - return { - matcher: matcher.matcher, - hookCallbackIds: callbackIds, - timeout: matcher.timeout - }; - }); - } - } - } - const sdkMcpServers = this.sdkMcpTransports.size > 0 ? Array.from(this.sdkMcpTransports.keys()) : void 0; - const initRequest = { - subtype: "initialize", - hooks, - sdkMcpServers, - jsonSchema: this.jsonSchema, - systemPrompt: (_a = this.initConfig) == null ? void 0 : _a.systemPrompt, - appendSystemPrompt: (_b = this.initConfig) == null ? void 0 : _b.appendSystemPrompt, - agents: (_c = this.initConfig) == null ? void 0 : _c.agents - }; - const response = await this.request(initRequest); - return response.response; - } - async interrupt() { - await this.request({ - subtype: "interrupt" - }); - } - async setPermissionMode(mode) { - await this.request({ - subtype: "set_permission_mode", - mode - }); - } - async setModel(model) { - await this.request({ - subtype: "set_model", - model - }); - } - async setMaxThinkingTokens(maxThinkingTokens) { - await this.request({ - subtype: "set_max_thinking_tokens", - max_thinking_tokens: maxThinkingTokens - }); - } - async rewindFiles(userMessageId) { - await this.request({ - subtype: "rewind_files", - user_message_id: userMessageId - }); - } - async processPendingPermissionRequests(pendingPermissionRequests) { - for (const request of pendingPermissionRequests) { - if (request.request.subtype === "can_use_tool") { - this.handleControlRequest(request).catch(() => { - }); - } - } - } - request(request) { - const requestId = Math.random().toString(36).substring(2, 15); - const sdkRequest = { - request_id: requestId, - type: "control_request", - request - }; - return new Promise((resolve7, reject) => { - this.pendingControlResponses.set(requestId, (response) => { - if (response.subtype === "success") { - resolve7(response); - } else { - reject(new Error(response.error)); - if (response.pending_permission_requests) { - this.processPendingPermissionRequests(response.pending_permission_requests); - } - } - }); - Promise.resolve(this.transport.write(JSON.stringify(sdkRequest) + ` -`)); - }); - } - async supportedCommands() { - return (await this.initialization).commands; - } - async supportedModels() { - return (await this.initialization).models; - } - async mcpServerStatus() { - const response = await this.request({ - subtype: "mcp_status" - }); - const mcpStatusResponse = response.response; - return mcpStatusResponse.mcpServers; - } - async setMcpServers(servers) { - const sdkServers = {}; - const processServers = {}; - for (const [name, config2] of Object.entries(servers)) { - if (config2.type === "sdk" && "instance" in config2) { - sdkServers[name] = config2.instance; - } else { - processServers[name] = config2; - } - } - const currentSdkNames = new Set(this.sdkMcpServerInstances.keys()); - const newSdkNames = new Set(Object.keys(sdkServers)); - for (const name of currentSdkNames) { - if (!newSdkNames.has(name)) { - await this.disconnectSdkMcpServer(name); - } - } - for (const [name, server] of Object.entries(sdkServers)) { - if (!currentSdkNames.has(name)) { - this.connectSdkMcpServer(name, server); - } - } - const sdkServerConfigs = {}; - for (const name of Object.keys(sdkServers)) { - sdkServerConfigs[name] = { type: "sdk", name }; - } - const response = await this.request({ - subtype: "mcp_set_servers", - servers: { ...processServers, ...sdkServerConfigs } - }); - return response.response; - } - async accountInfo() { - return (await this.initialization).account; - } - async streamInput(stream) { - var _a; - logForDebugging(`[Query.streamInput] Starting to process input stream`); - try { - let messageCount = 0; - for await (const message of stream) { - messageCount++; - logForDebugging(`[Query.streamInput] Processing message ${messageCount}: ${message.type}`); - if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted) - break; - await Promise.resolve(this.transport.write(JSON.stringify(message) + ` -`)); - } - logForDebugging(`[Query.streamInput] Finished processing ${messageCount} messages from input stream`); - if (this.hasBidirectionalNeeds()) { - logForDebugging(`[Query.streamInput] Has bidirectional needs, waiting for first result`); - await this.waitForFirstResult(); - } - logForDebugging(`[Query] Calling transport.endInput() to close stdin to CLI process`); - this.transport.endInput(); - } catch (error2) { - if (!(error2 instanceof AbortError)) { - throw error2; - } - } - } - waitForFirstResult() { - if (this.firstResultReceived) { - logForDebugging(`[Query.waitForFirstResult] Result already received, returning immediately`); - return Promise.resolve(); - } - return new Promise((resolve7) => { - var _a, _b; - if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted) { - resolve7(); - return; - } - (_b = this.abortController) == null ? void 0 : _b.signal.addEventListener("abort", () => resolve7(), { - once: true - }); - this.firstResultReceivedResolve = resolve7; - }); - } - handleHookCallbacks(callbackId, input, toolUseID, abortSignal) { - const callback = this.hookCallbacks.get(callbackId); - if (!callback) { - throw new Error(`No hook callback found for ID: ${callbackId}`); - } - return callback(input, toolUseID, { - signal: abortSignal - }); - } - connectSdkMcpServer(name, server) { - const sdkTransport = new SdkControlServerTransport((message) => this.sendMcpServerMessageToCli(name, message)); - this.sdkMcpTransports.set(name, sdkTransport); - this.sdkMcpServerInstances.set(name, server); - server.connect(sdkTransport); - } - async disconnectSdkMcpServer(name) { - const transport = this.sdkMcpTransports.get(name); - if (transport) { - await transport.close(); - this.sdkMcpTransports.delete(name); - } - this.sdkMcpServerInstances.delete(name); - } - sendMcpServerMessageToCli(serverName, message) { - if ("id" in message && message.id !== null && message.id !== void 0) { - const key = `${serverName}:${message.id}`; - const pending = this.pendingMcpResponses.get(key); - if (pending) { - pending.resolve(message); - this.pendingMcpResponses.delete(key); - return; - } - } - const controlRequest = { - type: "control_request", - request_id: (0, import_crypto3.randomUUID)(), - request: { - subtype: "mcp_message", - server_name: serverName, - message - } - }; - this.transport.write(JSON.stringify(controlRequest) + ` -`); - } - handleMcpControlRequest(serverName, mcpRequest, transport) { - const messageId = "id" in mcpRequest.message ? mcpRequest.message.id : null; - const key = `${serverName}:${messageId}`; - return new Promise((resolve7, reject) => { - const cleanup = () => { - this.pendingMcpResponses.delete(key); - }; - const resolveAndCleanup = (response) => { - cleanup(); - resolve7(response); - }; - const rejectAndCleanup = (error2) => { - cleanup(); - reject(error2); - }; - this.pendingMcpResponses.set(key, { - resolve: resolveAndCleanup, - reject: rejectAndCleanup - }); - if (transport.onmessage) { - transport.onmessage(mcpRequest.message); - } else { - cleanup(); - reject(new Error("No message handler registered")); - return; - } - }); + /** + * Appends " MCP" after each valid @mention. Applied to API requests only, not shown in UI. + */ + transformMentions(text) { + return transformMcpMentions(text, this.getContextSavingNames()); } }; + +// node_modules/zod/v3/helpers/util.js var util; (function(util2) { util2.assertEqual = (_) => { @@ -13525,14 +14513,14 @@ var util; return util2.objectValues(filtered); }; util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; + return util2.objectKeys(obj).map(function(e2) { + return obj[e2]; }); }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { + for (const key in object3) { + if (Object.prototype.hasOwnProperty.call(object3, key)) { keys.push(key); } } @@ -13543,7 +14531,7 @@ var util; if (checker(item)) return item; } - return; + return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues2(array2, separator = " | ") { @@ -13563,6 +14551,7 @@ var objectUtil; return { ...first, ...second + // second overwrites first }; }; })(objectUtil || (objectUtil = {})); @@ -13589,8 +14578,8 @@ var ZodParsedType = util.arrayToEnum([ "set" ]); var getParsedType = (data) => { - const t = typeof data; - switch (t) { + const t2 = typeof data; + switch (t2) { case "undefined": return ZodParsedType.undefined; case "string": @@ -13629,6 +14618,8 @@ var getParsedType = (data) => { return ZodParsedType.unknown; } }; + +// node_modules/zod/v3/ZodError.js var ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", @@ -13674,8 +14665,8 @@ var ZodError = class _ZodError extends Error { return issue2.message; }; const fieldErrors = { _errors: [] }; - const processError = (error2) => { - for (const issue2 of error2.issues) { + const processError = (error48) => { + for (const issue2 of error48.issues) { if (issue2.code === "invalid_union") { issue2.unionErrors.map(processError); } else if (issue2.code === "invalid_return_type") { @@ -13686,10 +14677,10 @@ var ZodError = class _ZodError extends Error { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; + let i2 = 0; + while (i2 < issue2.path.length) { + const el = issue2.path[i2]; + const terminal = i2 === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { @@ -13697,7 +14688,7 @@ var ZodError = class _ZodError extends Error { curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; - i++; + i2++; } } } @@ -13720,7 +14711,7 @@ var ZodError = class _ZodError extends Error { return this.issues.length === 0; } flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = {}; + const fieldErrors = /* @__PURE__ */ Object.create(null); const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { @@ -13738,9 +14729,11 @@ var ZodError = class _ZodError extends Error { } }; ZodError.create = (issues) => { - const error2 = new ZodError(issues); - return error2; + const error48 = new ZodError(issues); + return error48; }; + +// node_modules/zod/v3/locales/en.js var errorMap = (issue2, _ctx) => { let message; switch (issue2.code) { @@ -13842,13 +14835,17 @@ var errorMap = (issue2, _ctx) => { return { message }; }; var en_default = errorMap; + +// node_modules/zod/v3/errors.js var overrideErrorMap = en_default; function getErrorMap() { return overrideErrorMap; } + +// node_modules/zod/v3/helpers/parseUtil.js var makeIssue = (params) => { - const { data, path: path12, errorMaps, issueData } = params; - const fullPath = [...path12, ...issueData.path || []]; + const { data, path: path10, errorMaps, issueData } = params; + const fullPath = [...path10, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath @@ -13862,8 +14859,8 @@ var makeIssue = (params) => { } let errorMessage = ""; const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + for (const map2 of maps) { + errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, @@ -13879,10 +14876,14 @@ function addIssueToContext(ctx, issueData) { path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, + // contextual error map is first priority ctx.schemaErrorMap, + // then schema-bound map if available overrideMap, + // then global override map overrideMap === en_default ? void 0 : en_default - ].filter((x) => !!x) + // then global default map + ].filter((x3) => !!x3) }); ctx.common.issues.push(issue2); } @@ -13945,21 +14946,25 @@ var INVALID = Object.freeze({ }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); -var isAborted = (x) => x.status === "aborted"; -var isDirty = (x) => x.status === "dirty"; -var isValid = (x) => x.status === "valid"; -var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; +var isAborted = (x3) => x3.status === "aborted"; +var isDirty = (x3) => x3.status === "dirty"; +var isValid = (x3) => x3.status === "valid"; +var isAsync = (x3) => typeof Promise !== "undefined" && x3 instanceof Promise; + +// node_modules/zod/v3/helpers/errorUtil.js var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message; })(errorUtil || (errorUtil = {})); + +// node_modules/zod/v3/types.js var ParseInputLazyPath = class { - constructor(parent, value, path12, key) { + constructor(parent, value, path10, key) { this._cachedPath = []; this.parent = parent; this.data = value; - this._path = path12; + this._path = path10; this._key = key; } get path() { @@ -13985,8 +14990,8 @@ var handleResult = (ctx, result) => { get error() { if (this._error) return this._error; - const error2 = new ZodError(ctx.common.issues); - this._error = error2; + const error48 = new ZodError(ctx.common.issues); + this._error = error48; return this._error; } }; @@ -14002,13 +15007,13 @@ function processCreateParams(params) { if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { - var _a, _b; + var _a3, _b; const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message != null ? message : ctx.defaultError }; } if (typeof ctx.data === "undefined") { - return { message: (_a = message != null ? message : required_error) != null ? _a : ctx.defaultError }; + return { message: (_a3 = message != null ? message : required_error) != null ? _a3 : ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; @@ -14064,11 +15069,11 @@ var ZodType = class { throw result.error; } safeParse(data, params) { - var _a; + var _a3; const ctx = { common: { issues: [], - async: (_a = params == null ? void 0 : params.async) != null ? _a : false, + async: (_a3 = params == null ? void 0 : params.async) != null ? _a3 : false, contextualErrorMap: params == null ? void 0 : params.errorMap }, path: (params == null ? void 0 : params.path) || [], @@ -14081,7 +15086,7 @@ var ZodType = class { return handleResult(ctx, result); } "~validate"(data) { - var _a, _b; + var _a3, _b; const ctx = { common: { issues: [], @@ -14102,7 +15107,7 @@ var ZodType = class { issues: ctx.common.issues }; } catch (err) { - if ((_b = (_a = err == null ? void 0 : err.message) == null ? void 0 : _a.toLowerCase()) == null ? void 0 : _b.includes("encountered")) { + if ((_b = (_a3 = err == null ? void 0 : err.message) == null ? void 0 : _a3.toLowerCase()) == null ? void 0 : _b.includes("encountered")) { this["~standard"].async = true; } ctx.common = { @@ -14350,15 +15355,15 @@ function isValidIP(ip, version2) { } return false; } -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) +function isValidJWT(jwt2, alg) { + if (!jwtRegex.test(jwt2)) return false; try { - const [header] = jwt.split("."); + const [header] = jwt2.split("."); if (!header) return false; - const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base642)); + const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base643)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT") @@ -14368,7 +15373,7 @@ function isValidJWT(jwt, alg) { if (alg && decoded.alg !== alg) return false; return true; - } catch (e) { + } catch (e2) { return false; } } @@ -14527,7 +15532,7 @@ var ZodString = class _ZodString2 extends ZodType { } else if (check2.kind === "url") { try { new URL(input.data); - } catch (e) { + } catch (e2) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", @@ -14739,7 +15744,7 @@ var ZodString = class _ZodString2 extends ZodType { return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); } datetime(options) { - var _a, _b; + var _a3, _b; if (typeof options === "string") { return this._addCheck({ kind: "datetime", @@ -14752,7 +15757,7 @@ var ZodString = class _ZodString2 extends ZodType { return this._addCheck({ kind: "datetime", precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision, - offset: (_a = options == null ? void 0 : options.offset) != null ? _a : false, + offset: (_a3 = options == null ? void 0 : options.offset) != null ? _a3 : false, local: (_b = options == null ? void 0 : options.local) != null ? _b : false, ...errorUtil.errToObj(options == null ? void 0 : options.message) }); @@ -14827,6 +15832,9 @@ var ZodString = class _ZodString2 extends ZodType { ...errorUtil.errToObj(message) }); } + /** + * Equivalent to `.min(1)` + */ nonempty(message) { return this.min(1, errorUtil.errToObj(message)); } @@ -14918,11 +15926,11 @@ var ZodString = class _ZodString2 extends ZodType { } }; ZodString.create = (params) => { - var _a; + var _a3; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params == null ? void 0 : params.coerce) != null ? _a : false, + coerce: (_a3 = params == null ? void 0 : params.coerce) != null ? _a3 : false, ...processCreateParams(params) }); }; @@ -15176,7 +16184,7 @@ var ZodBigInt = class _ZodBigInt extends ZodType { if (this._def.coerce) { try { input.data = BigInt(input.data); - } catch (e) { + } catch (e2) { return this._getInvalidInput(input); } } @@ -15331,11 +16339,11 @@ var ZodBigInt = class _ZodBigInt extends ZodType { } }; ZodBigInt.create = (params) => { - var _a; + var _a3; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params == null ? void 0 : params.coerce) != null ? _a : false, + coerce: (_a3 = params == null ? void 0 : params.coerce) != null ? _a3 : false, ...processCreateParams(params) }); }; @@ -15659,14 +16667,14 @@ var ZodArray = class _ZodArray extends ZodType { } } if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + return Promise.all([...ctx.data].map((item, i2) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + const result = [...ctx.data].map((item, i2) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); }); return ParseStatus.mergeArray(status, result); } @@ -15804,7 +16812,10 @@ var ZodObject = class _ZodObject extends ZodType { const value = ctx.data[key]; pairs.push({ key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), alwaysSet: key in ctx.data }); } @@ -15839,8 +16850,8 @@ var ZodObject = class _ZodObject extends ZodType { unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue2, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) == null ? void 0 : _b.call(_a, issue2, ctx).message) != null ? _c : ctx.defaultError; + var _a3, _b, _c, _d; + const defaultError = (_c = (_b = (_a3 = this._def).errorMap) == null ? void 0 : _b.call(_a3, issue2, ctx).message) != null ? _c : ctx.defaultError; if (issue2.code === "unrecognized_keys") return { message: (_d = errorUtil.errToObj(message).message) != null ? _d : defaultError @@ -15864,6 +16875,23 @@ var ZodObject = class _ZodObject extends ZodType { unknownKeys: "passthrough" }); } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; extend(augmentation) { return new _ZodObject({ ...this._def, @@ -15873,6 +16901,11 @@ var ZodObject = class _ZodObject extends ZodType { }) }); } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, @@ -15885,9 +16918,65 @@ var ZodObject = class _ZodObject extends ZodType { }); return merged; } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } setKey(key, schema) { return this.augment({ [key]: schema }); } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } catchall(index) { return new _ZodObject({ ...this._def, @@ -15918,6 +17007,9 @@ var ZodObject = class _ZodObject extends ZodType { shape: () => shape }); } + /** + * @deprecated + */ deepPartial() { return deepPartialify(this); } @@ -16153,6 +17245,14 @@ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { get optionsMap() { return this._def.optionsMap; } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type of options) { @@ -16176,17 +17276,17 @@ var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { }); } }; -function mergeValues(a, b) { +function mergeValues(a, b3) { const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { + const bType = getParsedType(b3); + if (a === b3) { return { valid: true, data: a }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); + const bKeys = util.objectKeys(b3); const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; + const newObj = { ...a, ...b3 }; for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); + const sharedValue = mergeValues(a[key], b3[key]); if (!sharedValue.valid) { return { valid: false }; } @@ -16194,13 +17294,13 @@ function mergeValues(a, b) { } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { + if (a.length !== b3.length) { return { valid: false }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; - const itemB = b[index]; + const itemB = b3[index]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; @@ -16208,7 +17308,7 @@ function mergeValues(a, b) { newArray.push(sharedValue.data); } return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b3) { return { valid: true, data: a }; } else { return { valid: false }; @@ -16304,7 +17404,7 @@ var ZodTuple = class _ZodTuple extends ZodType { if (!schema) return null; return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); + }).filter((x3) => !!x3); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); @@ -16503,7 +17603,7 @@ var ZodSet = class _ZodSet extends ZodType { } return { status: status.value, value: parsedSet }; } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { @@ -16553,25 +17653,25 @@ var ZodFunction = class _ZodFunction extends ZodType { }); return INVALID; } - function makeArgsIssue(args, error2) { + function makeArgsIssue(args, error48) { return makeIssue({ data: args, path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x3) => !!x3), issueData: { code: ZodIssueCode.invalid_arguments, - argumentsError: error2 + argumentsError: error48 } }); } - function makeReturnsIssue(returns, error2) { + function makeReturnsIssue(returns, error48) { return makeIssue({ data: returns, path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x3) => !!x3), issueData: { code: ZodIssueCode.invalid_return_type, - returnTypeError: error2 + returnTypeError: error48 } }); } @@ -16580,15 +17680,15 @@ var ZodFunction = class _ZodFunction extends ZodType { if (this._def.returns instanceof ZodPromise) { const me = this; return OK(async function(...args) { - const error2 = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error2.addIssue(makeArgsIssue(args, e)); - throw error2; + const error48 = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => { + error48.addIssue(makeArgsIssue(args, e2)); + throw error48; }); const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error2.addIssue(makeReturnsIssue(result, e)); - throw error2; + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => { + error48.addIssue(makeReturnsIssue(result, e2)); + throw error48; }); return parsedReturns; }); @@ -17161,10 +18261,10 @@ var ZodPipeline = class _ZodPipeline extends ZodType { } } } - static create(a, b) { + static create(a, b3) { return new _ZodPipeline({ in: a, - out: b, + out: b3, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } @@ -17195,43 +18295,43 @@ var late = { object: ZodObject.lazycreate }; var ZodFirstPartyTypeKind; -(function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; +(function(ZodFirstPartyTypeKind3) { + ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var stringType = ZodString.create; var numberType = ZodNumber.create; @@ -17267,38 +18367,327 @@ var optionalType = ZodOptional.create; var nullableType = ZodNullable.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; + +// node_modules/zod/v4/core/index.js +var core_exports2 = {}; +__export(core_exports2, { + $ZodAny: () => $ZodAny, + $ZodArray: () => $ZodArray, + $ZodAsyncError: () => $ZodAsyncError, + $ZodBase64: () => $ZodBase64, + $ZodBase64URL: () => $ZodBase64URL, + $ZodBigInt: () => $ZodBigInt, + $ZodBigIntFormat: () => $ZodBigIntFormat, + $ZodBoolean: () => $ZodBoolean, + $ZodCIDRv4: () => $ZodCIDRv4, + $ZodCIDRv6: () => $ZodCIDRv6, + $ZodCUID: () => $ZodCUID, + $ZodCUID2: () => $ZodCUID2, + $ZodCatch: () => $ZodCatch, + $ZodCheck: () => $ZodCheck, + $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, + $ZodCheckEndsWith: () => $ZodCheckEndsWith, + $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, + $ZodCheckIncludes: () => $ZodCheckIncludes, + $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, + $ZodCheckLessThan: () => $ZodCheckLessThan, + $ZodCheckLowerCase: () => $ZodCheckLowerCase, + $ZodCheckMaxLength: () => $ZodCheckMaxLength, + $ZodCheckMaxSize: () => $ZodCheckMaxSize, + $ZodCheckMimeType: () => $ZodCheckMimeType, + $ZodCheckMinLength: () => $ZodCheckMinLength, + $ZodCheckMinSize: () => $ZodCheckMinSize, + $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, + $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, + $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperty: () => $ZodCheckProperty, + $ZodCheckRegex: () => $ZodCheckRegex, + $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, + $ZodCheckStartsWith: () => $ZodCheckStartsWith, + $ZodCheckStringFormat: () => $ZodCheckStringFormat, + $ZodCheckUpperCase: () => $ZodCheckUpperCase, + $ZodCodec: () => $ZodCodec, + $ZodCustom: () => $ZodCustom, + $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodDate: () => $ZodDate, + $ZodDefault: () => $ZodDefault, + $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, + $ZodE164: () => $ZodE164, + $ZodEmail: () => $ZodEmail, + $ZodEmoji: () => $ZodEmoji, + $ZodEncodeError: () => $ZodEncodeError, + $ZodEnum: () => $ZodEnum, + $ZodError: () => $ZodError, + $ZodExactOptional: () => $ZodExactOptional, + $ZodFile: () => $ZodFile, + $ZodFunction: () => $ZodFunction, + $ZodGUID: () => $ZodGUID, + $ZodIPv4: () => $ZodIPv4, + $ZodIPv6: () => $ZodIPv6, + $ZodISODate: () => $ZodISODate, + $ZodISODateTime: () => $ZodISODateTime, + $ZodISODuration: () => $ZodISODuration, + $ZodISOTime: () => $ZodISOTime, + $ZodIntersection: () => $ZodIntersection, + $ZodJWT: () => $ZodJWT, + $ZodKSUID: () => $ZodKSUID, + $ZodLazy: () => $ZodLazy, + $ZodLiteral: () => $ZodLiteral, + $ZodMAC: () => $ZodMAC, + $ZodMap: () => $ZodMap, + $ZodNaN: () => $ZodNaN, + $ZodNanoID: () => $ZodNanoID, + $ZodNever: () => $ZodNever, + $ZodNonOptional: () => $ZodNonOptional, + $ZodNull: () => $ZodNull, + $ZodNullable: () => $ZodNullable, + $ZodNumber: () => $ZodNumber, + $ZodNumberFormat: () => $ZodNumberFormat, + $ZodObject: () => $ZodObject, + $ZodObjectJIT: () => $ZodObjectJIT, + $ZodOptional: () => $ZodOptional, + $ZodPipe: () => $ZodPipe, + $ZodPrefault: () => $ZodPrefault, + $ZodPromise: () => $ZodPromise, + $ZodReadonly: () => $ZodReadonly, + $ZodRealError: () => $ZodRealError, + $ZodRecord: () => $ZodRecord, + $ZodRegistry: () => $ZodRegistry, + $ZodSet: () => $ZodSet, + $ZodString: () => $ZodString, + $ZodStringFormat: () => $ZodStringFormat, + $ZodSuccess: () => $ZodSuccess, + $ZodSymbol: () => $ZodSymbol, + $ZodTemplateLiteral: () => $ZodTemplateLiteral, + $ZodTransform: () => $ZodTransform, + $ZodTuple: () => $ZodTuple, + $ZodType: () => $ZodType, + $ZodULID: () => $ZodULID, + $ZodURL: () => $ZodURL, + $ZodUUID: () => $ZodUUID, + $ZodUndefined: () => $ZodUndefined, + $ZodUnion: () => $ZodUnion, + $ZodUnknown: () => $ZodUnknown, + $ZodVoid: () => $ZodVoid, + $ZodXID: () => $ZodXID, + $ZodXor: () => $ZodXor, + $brand: () => $brand, + $constructor: () => $constructor, + $input: () => $input, + $output: () => $output, + Doc: () => Doc, + JSONSchema: () => json_schema_exports, + JSONSchemaGenerator: () => JSONSchemaGenerator, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + _any: () => _any, + _array: () => _array, + _base64: () => _base64, + _base64url: () => _base64url, + _bigint: () => _bigint, + _boolean: () => _boolean, + _catch: () => _catch, + _check: () => _check, + _cidrv4: () => _cidrv4, + _cidrv6: () => _cidrv6, + _coercedBigint: () => _coercedBigint, + _coercedBoolean: () => _coercedBoolean, + _coercedDate: () => _coercedDate, + _coercedNumber: () => _coercedNumber, + _coercedString: () => _coercedString, + _cuid: () => _cuid, + _cuid2: () => _cuid2, + _custom: () => _custom, + _date: () => _date, + _decode: () => _decode, + _decodeAsync: () => _decodeAsync, + _default: () => _default, + _discriminatedUnion: () => _discriminatedUnion, + _e164: () => _e164, + _email: () => _email, + _emoji: () => _emoji2, + _encode: () => _encode, + _encodeAsync: () => _encodeAsync, + _endsWith: () => _endsWith, + _enum: () => _enum, + _file: () => _file, + _float32: () => _float32, + _float64: () => _float64, + _gt: () => _gt, + _gte: () => _gte, + _guid: () => _guid, + _includes: () => _includes, + _int: () => _int, + _int32: () => _int32, + _int64: () => _int64, + _intersection: () => _intersection, + _ipv4: () => _ipv4, + _ipv6: () => _ipv6, + _isoDate: () => _isoDate, + _isoDateTime: () => _isoDateTime, + _isoDuration: () => _isoDuration, + _isoTime: () => _isoTime, + _jwt: () => _jwt, + _ksuid: () => _ksuid, + _lazy: () => _lazy, + _length: () => _length, + _literal: () => _literal, + _lowercase: () => _lowercase, + _lt: () => _lt, + _lte: () => _lte, + _mac: () => _mac, + _map: () => _map, + _max: () => _lte, + _maxLength: () => _maxLength, + _maxSize: () => _maxSize, + _mime: () => _mime, + _min: () => _gte, + _minLength: () => _minLength, + _minSize: () => _minSize, + _multipleOf: () => _multipleOf, + _nan: () => _nan, + _nanoid: () => _nanoid, + _nativeEnum: () => _nativeEnum, + _negative: () => _negative, + _never: () => _never, + _nonnegative: () => _nonnegative, + _nonoptional: () => _nonoptional, + _nonpositive: () => _nonpositive, + _normalize: () => _normalize, + _null: () => _null2, + _nullable: () => _nullable, + _number: () => _number, + _optional: () => _optional, + _overwrite: () => _overwrite, + _parse: () => _parse, + _parseAsync: () => _parseAsync, + _pipe: () => _pipe, + _positive: () => _positive, + _promise: () => _promise, + _property: () => _property, + _readonly: () => _readonly, + _record: () => _record, + _refine: () => _refine, + _regex: () => _regex, + _safeDecode: () => _safeDecode, + _safeDecodeAsync: () => _safeDecodeAsync, + _safeEncode: () => _safeEncode, + _safeEncodeAsync: () => _safeEncodeAsync, + _safeParse: () => _safeParse, + _safeParseAsync: () => _safeParseAsync, + _set: () => _set, + _size: () => _size, + _slugify: () => _slugify, + _startsWith: () => _startsWith, + _string: () => _string, + _stringFormat: () => _stringFormat, + _stringbool: () => _stringbool, + _success: () => _success, + _superRefine: () => _superRefine, + _symbol: () => _symbol, + _templateLiteral: () => _templateLiteral, + _toLowerCase: () => _toLowerCase, + _toUpperCase: () => _toUpperCase, + _transform: () => _transform, + _trim: () => _trim, + _tuple: () => _tuple, + _uint32: () => _uint32, + _uint64: () => _uint64, + _ulid: () => _ulid, + _undefined: () => _undefined2, + _union: () => _union, + _unknown: () => _unknown, + _uppercase: () => _uppercase, + _url: () => _url, + _uuid: () => _uuid, + _uuidv4: () => _uuidv4, + _uuidv6: () => _uuidv6, + _uuidv7: () => _uuidv7, + _void: () => _void, + _xid: () => _xid, + _xor: () => _xor, + clone: () => clone, + config: () => config, + createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod, + createToJSONSchemaMethod: () => createToJSONSchemaMethod, + decode: () => decode, + decodeAsync: () => decodeAsync, + describe: () => describe, + encode: () => encode, + encodeAsync: () => encodeAsync, + extractDefs: () => extractDefs, + finalize: () => finalize, + flattenError: () => flattenError, + formatError: () => formatError, + globalConfig: () => globalConfig, + globalRegistry: () => globalRegistry, + initializeContext: () => initializeContext, + isValidBase64: () => isValidBase64, + isValidBase64URL: () => isValidBase64URL, + isValidJWT: () => isValidJWT2, + locales: () => locales_exports, + meta: () => meta, + parse: () => parse, + parseAsync: () => parseAsync, + prettifyError: () => prettifyError, + process: () => process2, + regexes: () => regexes_exports, + registry: () => registry, + safeDecode: () => safeDecode, + safeDecodeAsync: () => safeDecodeAsync, + safeEncode: () => safeEncode, + safeEncodeAsync: () => safeEncodeAsync, + safeParse: () => safeParse, + safeParseAsync: () => safeParseAsync, + toDotPath: () => toDotPath, + toJSONSchema: () => toJSONSchema, + treeifyError: () => treeifyError, + util: () => util_exports, + version: () => version +}); + +// node_modules/zod/v4/core/core.js var NEVER = Object.freeze({ status: "aborted" }); +// @__NO_SIDE_EFFECTS__ function $constructor(name, initializer3, params) { - var _a; + var _a3; function init(inst, def) { - var _a3, _b; - var _a2; - Object.defineProperty(inst, "_zod", { - value: (_a3 = inst._zod) != null ? _a3 : {}, - enumerable: false - }); - (_b = (_a2 = inst._zod).traits) != null ? _b : _a2.traits = /* @__PURE__ */ new Set(); + if (!inst._zod) { + Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _, + traits: /* @__PURE__ */ new Set() + }, + enumerable: false + }); + } + if (inst._zod.traits.has(name)) { + return; + } inst._zod.traits.add(name); initializer3(inst, def); - for (const k in _.prototype) { - if (!(k in inst)) - Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); + const proto = _.prototype; + const keys = Object.keys(proto); + for (let i2 = 0; i2 < keys.length; i2++) { + const k = keys[i2]; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } } - inst._zod.constr = _; - inst._zod.def = def; } - const Parent = (_a = params == null ? void 0 : params.Parent) != null ? _a : Object; + const Parent = (_a3 = params == null ? void 0 : params.Parent) != null ? _a3 : Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name }); function _(def) { - var _a3; - var _a2; + var _a5; + var _a4; const inst = (params == null ? void 0 : params.Parent) ? new Definition() : this; init(inst, def); - (_a3 = (_a2 = inst._zod).deferred) != null ? _a3 : _a2.deferred = []; + (_a5 = (_a4 = inst._zod).deferred) != null ? _a5 : _a4.deferred = []; for (const fn of inst._zod.deferred) { fn(); } @@ -17307,77 +18696,99 @@ function $constructor(name, initializer3, params) { Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { - var _a2, _b; + var _a4, _b; if ((params == null ? void 0 : params.Parent) && inst instanceof params.Parent) return true; - return (_b = (_a2 = inst == null ? void 0 : inst._zod) == null ? void 0 : _a2.traits) == null ? void 0 : _b.has(name); + return (_b = (_a4 = inst == null ? void 0 : inst._zod) == null ? void 0 : _a4.traits) == null ? void 0 : _b.has(name); } }); Object.defineProperty(_, "name", { value: name }); return _; } +var $brand = /* @__PURE__ */ Symbol("zod_brand"); var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; +var $ZodEncodeError = class extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +}; var globalConfig = {}; function config(newConfig) { if (newConfig) Object.assign(globalConfig, newConfig); return globalConfig; } -var exports_util = {}; -__export2(exports_util, { - unwrapMessage: () => unwrapMessage, - stringifyPrimitive: () => stringifyPrimitive, - required: () => required, - randomString: () => randomString, - propertyKeyTypes: () => propertyKeyTypes, - promiseAllObject: () => promiseAllObject, - primitiveTypes: () => primitiveTypes, - prefixIssues: () => prefixIssues, - pick: () => pick, - partial: () => partial, - optionalKeys: () => optionalKeys, - omit: () => omit, - numKeys: () => numKeys, - nullish: () => nullish, - normalizeParams: () => normalizeParams, - merge: () => merge, - jsonStringifyReplacer: () => jsonStringifyReplacer, - joinValues: () => joinValues, - issue: () => issue, - isPlainObject: () => isPlainObject, - isObject: () => isObject2, - getSizableOrigin: () => getSizableOrigin, - getParsedType: () => getParsedType2, - getLengthableOrigin: () => getLengthableOrigin, - getEnumValues: () => getEnumValues, - getElementAtPath: () => getElementAtPath, - floatSafeRemainder: () => floatSafeRemainder2, - finalizeIssue: () => finalizeIssue, - extend: () => extend, - escapeRegex: () => escapeRegex, - esc: () => esc, - defineLazy: () => defineLazy, - createTransparentProxy: () => createTransparentProxy, - clone: () => clone, - cleanRegex: () => cleanRegex, - cleanEnum: () => cleanEnum, - captureStackTrace: () => captureStackTrace, - cached: () => cached, - assignProp: () => assignProp, - assertNotEqual: () => assertNotEqual, - assertNever: () => assertNever, - assertIs: () => assertIs, - assertEqual: () => assertEqual, - assert: () => assert, - allowsEval: () => allowsEval, - aborted: () => aborted, - NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + +// node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, Class: () => Class, - BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + base64ToUint8Array: () => base64ToUint8Array, + base64urlToUint8Array: () => base64urlToUint8Array, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + cloneDef: () => cloneDef, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder2, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType2, + getSizableOrigin: () => getSizableOrigin, + hexToUint8Array: () => hexToUint8Array, + isObject: () => isObject, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + mergeDefs: () => mergeDefs, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + objectClone: () => objectClone, + omit: () => omit, + optionalKeys: () => optionalKeys, + parsedType: () => parsedType, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + safeExtend: () => safeExtend, + shallowClone: () => shallowClone, + slugify: () => slugify, + stringifyPrimitive: () => stringifyPrimitive, + uint8ArrayToBase64: () => uint8ArrayToBase64, + uint8ArrayToBase64url: () => uint8ArrayToBase64url, + uint8ArrayToHex: () => uint8ArrayToHex, + unwrapMessage: () => unwrapMessage }); function assertEqual(val) { return val; @@ -17388,13 +18799,13 @@ function assertNotEqual(val) { function assertIs(_arg) { } function assertNever(_x) { - throw new Error(); + throw new Error("Unexpected value in exhaustive check"); } function assert(_) { } function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); + const numericValues = Object.values(entries).filter((v3) => typeof v3 === "number"); + const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v3]) => v3); return values; } function joinValues(array2, separator = "|") { @@ -17406,10 +18817,10 @@ function jsonStringifyReplacer(_, value) { return value; } function cached(getter) { - const set = false; + const set2 = false; return { get value() { - if (!set) { + if (!set2) { const value = getter(); Object.defineProperty(this, "value", { value }); return value; @@ -17428,31 +18839,45 @@ function cleanRegex(source) { } function floatSafeRemainder2(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; + const stepString = step.toString(); + let stepDecCount = (stepString.split(".")[1] || "").length; + if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { + const match = stepString.match(/\d?e-(\d?)/); + if (match == null ? void 0 : match[1]) { + stepDecCount = Number.parseInt(match[1]); + } + } const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / 10 ** decCount; } -function defineLazy(object, key, getter) { - const set = false; - Object.defineProperty(object, key, { +var EVALUATING = /* @__PURE__ */ Symbol("evaluating"); +function defineLazy(object3, key, getter) { + let value = void 0; + Object.defineProperty(object3, key, { get() { - if (!set) { - const value = getter(); - object[key] = value; - return value; + if (value === EVALUATING) { + return void 0; } - throw new Error("cached value already set"); + if (value === void 0) { + value = EVALUATING; + value = getter(); + } + return value; }, - set(v) { - Object.defineProperty(object, key, { - value: v + set(v3) { + Object.defineProperty(object3, key, { + value: v3 + // configurable: true, }); }, configurable: true }); } +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, @@ -17461,18 +18886,29 @@ function assignProp(target, prop, value) { configurable: true }); } -function getElementAtPath(obj, path12) { - if (!path12) +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path10) { + if (!path10) return obj; - return path12.reduce((acc, key) => acc == null ? void 0 : acc[key], obj); + return path10.reduce((acc, key) => acc == null ? void 0 : acc[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); const promises = keys.map((key) => promisesObj[key]); return Promise.all(promises).then((results) => { const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; + for (let i2 = 0; i2 < keys.length; i2++) { + resolvedObj[keys[i2]] = results[i2]; } return resolvedObj; }); @@ -17480,7 +18916,7 @@ function promiseAllObject(promisesObj) { function randomString(length = 10) { const chars = "abcdefghijklmnopqrstuvwxyz"; let str = ""; - for (let i = 0; i < length; i++) { + for (let i2 = 0; i2 < length; i2++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; @@ -17488,14 +18924,17 @@ function randomString(length = 10) { function esc(str) { return JSON.stringify(str); } -var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { +function slugify(input) { + return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, ""); +} +var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }; -function isObject2(data) { +function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } var allowsEval = cached(() => { - var _a; - if (typeof navigator !== "undefined" && ((_a = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a.includes("Cloudflare"))) { + var _a3; + if (typeof navigator !== "undefined" && ((_a3 = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a3.includes("Cloudflare"))) { return false; } try { @@ -17507,19 +18946,28 @@ var allowsEval = cached(() => { } }); function isPlainObject(o) { - if (isObject2(o) === false) + if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; + if (typeof ctor !== "function") + return true; const prot = ctor.prototype; - if (isObject2(prot) === false) + if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + return o; +} function numKeys(data) { let keyCount = 0; for (const key in data) { @@ -17530,8 +18978,8 @@ function numKeys(data) { return keyCount; } var getParsedType2 = (data) => { - const t = typeof data; - switch (t) { + const t2 = typeof data; + switch (t2) { case "undefined": return "undefined"; case "string": @@ -17570,7 +19018,7 @@ var getParsedType2 = (data) => { } return "object"; default: - throw new Error(`Unknown data type: ${t}`); + throw new Error(`Unknown data type: ${t2}`); } }; var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); @@ -17657,138 +19105,192 @@ var BIGINT_FORMAT_RANGES = { uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] }; function pick(schema, mask) { - const newShape = {}; const currDef = schema._zod.def; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); } - return clone(schema, { - ...schema._zod.def, - shape: newShape, + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, checks: [] }); + return clone(schema, def); } function omit(schema, mask) { - const newShape = { ...schema._zod.def.shape }; const currDef = schema._zod.def; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); } - return clone(schema, { - ...schema._zod.def, - shape: newShape, + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); + return newShape; + }, checks: [] }); + return clone(schema, def); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } - const def = { - ...schema._zod.def, + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + const existingShape = schema._zod.def.shape; + for (const key in shape) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); return _shape; - }, - checks: [] - }; + } + }); return clone(schema, def); } -function merge(a, b) { - return clone(a, { - ...a._zod.def, +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + } + }); + return clone(schema, def); +} +function merge(a, b3) { + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b3._zod.def.shape }; assignProp(this, "shape", _shape); return _shape; }, - catchall: b._zod.def.catchall, + get catchall() { + return b3._zod.def.catchall; + }, checks: [] + // delete existing checks }); + return clone(a, def); } function partial(Class2, schema, mask) { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".partial() cannot be used on object schemas containing refinements"); } - return clone(schema, { - ...schema._zod.def, - shape, + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + assignProp(this, "shape", shape); + return shape; + }, checks: [] }); + return clone(schema, def); } function required(Class2, schema, mask) { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); + assignProp(this, "shape", shape); + return shape; } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - return clone(schema, { - ...schema._zod.def, - shape, - checks: [] }); + return clone(schema, def); } -function aborted(x, startIndex = 0) { - var _a; - for (let i = startIndex; i < x.issues.length; i++) { - if (((_a = x.issues[i]) == null ? void 0 : _a.continue) !== true) +function aborted(x3, startIndex = 0) { + var _a3; + if (x3.aborted === true) + return true; + for (let i2 = startIndex; i2 < x3.issues.length; i2++) { + if (((_a3 = x3.issues[i2]) == null ? void 0 : _a3.continue) !== true) { return true; + } } return false; } -function prefixIssues(path12, issues) { +function prefixIssues(path10, issues) { return issues.map((iss) => { - var _a2; - var _a; - (_a2 = (_a = iss).path) != null ? _a2 : _a.path = []; - iss.path.unshift(path12); + var _a4; + var _a3; + (_a4 = (_a3 = iss).path) != null ? _a4 : _a3.path = []; + iss.path.unshift(path10); return iss; }); } @@ -17796,8 +19298,8 @@ function unwrapMessage(message) { return typeof message === "string" ? message : message == null ? void 0 : message.message; } function finalizeIssue(iss, ctx, config2) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; - const full = { ...iss, path: (_a = iss.path) != null ? _a : [] }; + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + const full = { ...iss, path: (_a3 = iss.path) != null ? _a3 : [] }; if (!iss.message) { const message = (_k = (_j = (_h = (_f = unwrapMessage((_d = (_c = (_b = iss.inst) == null ? void 0 : _b._zod.def) == null ? void 0 : _c.error) == null ? void 0 : _d.call(_c, iss))) != null ? _f : unwrapMessage((_e = ctx == null ? void 0 : ctx.error) == null ? void 0 : _e.call(ctx, iss))) != null ? _h : unwrapMessage((_g = config2.customError) == null ? void 0 : _g.call(config2, iss))) != null ? _j : unwrapMessage((_i = config2.localeError) == null ? void 0 : _i.call(config2, iss))) != null ? _k : "Invalid input"; full.message = message; @@ -17825,6 +19327,27 @@ function getLengthableOrigin(input) { return "string"; return "unknown"; } +function parsedType(data) { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t2; +} function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { @@ -17842,10 +19365,49 @@ function cleanEnum(obj) { return Number.isNaN(Number.parseInt(k, 10)); }).map((el) => el[1]); } +function base64ToUint8Array(base643) { + const binaryString = atob(base643); + const bytes = new Uint8Array(binaryString.length); + for (let i2 = 0; i2 < binaryString.length; i2++) { + bytes[i2] = binaryString.charCodeAt(i2); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i2 = 0; i2 < bytes.length; i2++) { + binaryString += String.fromCharCode(bytes[i2]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url3) { + const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - base643.length % 4) % 4); + return base64ToUint8Array(base643 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex3) { + const cleanHex = hex3.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i2 = 0; i2 < cleanHex.length; i2 += 2) { + bytes[i2 / 2] = Number.parseInt(cleanHex.slice(i2, i2 + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes).map((b3) => b3.toString(16).padStart(2, "0")).join(""); +} var Class = class { constructor(..._args) { } }; + +// node_modules/zod/v4/core/errors.js var initializer = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { @@ -17856,19 +19418,18 @@ var initializer = (inst, def) => { value: def, enumerable: false }); - Object.defineProperty(inst, "message", { - get() { - return JSON.stringify(def, jsonStringifyReplacer, 2); - }, - enumerable: true + inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false }); }; var $ZodError = $constructor("$ZodError", initializer); var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error2, mapper = (issue2) => issue2.message) { +function flattenError(error48, mapper = (issue2) => issue2.message) { const fieldErrors = {}; const formErrors = []; - for (const sub of error2.issues) { + for (const sub of error48.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); @@ -17878,13 +19439,10 @@ function flattenError(error2, mapper = (issue2) => issue2.message) { } return { formErrors, fieldErrors }; } -function formatError(error2, _mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; +function formatError(error48, mapper = (issue2) => issue2.message) { const fieldErrors = { _errors: [] }; - const processError = (error22) => { - for (const issue2 of error22.issues) { + const processError = (error49) => { + for (const issue2 of error49.issues) { if (issue2.code === "invalid_union" && issue2.errors.length) { issue2.errors.map((issues) => processError({ issues })); } else if (issue2.code === "invalid_key") { @@ -17895,10 +19453,10 @@ function formatError(error2, _mapper) { fieldErrors._errors.push(mapper(issue2)); } else { let curr = fieldErrors; - let i = 0; - while (i < issue2.path.length) { - const el = issue2.path[i]; - const terminal = i === issue2.path.length - 1; + let i2 = 0; + while (i2 < issue2.path.length) { + const el = issue2.path[i2]; + const terminal = i2 === issue2.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { @@ -17906,41 +19464,120 @@ function formatError(error2, _mapper) { curr[el]._errors.push(mapper(issue2)); } curr = curr[el]; - i++; + i2++; } } } }; - processError(error2); + processError(error48); return fieldErrors; } +function treeifyError(error48, mapper = (issue2) => issue2.message) { + const result = { errors: [] }; + const processError = (error49, path10 = []) => { + var _a4, _b2, _c, _d; + var _a3, _b; + for (const issue2 of error49.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues }, issue2.path)); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, issue2.path); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, issue2.path); + } else { + const fullpath = [...path10, ...issue2.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue2)); + continue; + } + let curr = result; + let i2 = 0; + while (i2 < fullpath.length) { + const el = fullpath[i2]; + const terminal = i2 === fullpath.length - 1; + if (typeof el === "string") { + (_a4 = curr.properties) != null ? _a4 : curr.properties = {}; + (_b2 = (_a3 = curr.properties)[el]) != null ? _b2 : _a3[el] = { errors: [] }; + curr = curr.properties[el]; + } else { + (_c = curr.items) != null ? _c : curr.items = []; + (_d = (_b = curr.items)[el]) != null ? _d : _b[el] = { errors: [] }; + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue2)); + } + i2++; + } + } + } + }; + processError(error48); + return result; +} +function toDotPath(_path) { + const segs = []; + const path10 = _path.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path10) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error48) { + var _a3; + const lines = []; + const issues = [...error48.issues].sort((a, b3) => { + var _a4, _b; + return ((_a4 = a.path) != null ? _a4 : []).length - ((_b = b3.path) != null ? _b : []).length; + }); + for (const issue2 of issues) { + lines.push(`\u2716 ${issue2.message}`); + if ((_a3 = issue2.path) == null ? void 0 : _a3.length) + lines.push(` \u2192 at ${toDotPath(issue2.path)}`); + } + return lines.join("\n"); +} + +// node_modules/zod/v4/core/parse.js var _parse = (_Err) => (schema, value, _ctx, _params) => { - var _a; + var _a3; const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) { throw new $ZodAsyncError(); } if (result.issues.length) { - const e = new ((_a = _params == null ? void 0 : _params.Err) != null ? _a : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params == null ? void 0 : _params.callee); - throw e; + const e2 = new ((_a3 = _params == null ? void 0 : _params.Err) != null ? _a3 : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e2, _params == null ? void 0 : _params.callee); + throw e2; } return result.value; }; +var parse = /* @__PURE__ */ _parse($ZodRealError); var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - var _a; + var _a3; const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { - const e = new ((_a = params == null ? void 0 : params.Err) != null ? _a : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params == null ? void 0 : params.callee); - throw e; + const e2 = new ((_a3 = params == null ? void 0 : params.Err) != null ? _a3 : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e2, params == null ? void 0 : params.callee); + throw e2; } return result.value; }; +var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); @@ -17964,6 +19601,105 @@ var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { } : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); +var _encode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parse(_Err)(schema, value, ctx); +}; +var encode = /* @__PURE__ */ _encode($ZodRealError); +var _decode = (_Err) => (schema, value, _ctx) => { + return _parse(_Err)(schema, value, _ctx); +}; +var decode = /* @__PURE__ */ _decode($ZodRealError); +var _encodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parseAsync(_Err)(schema, value, ctx); +}; +var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError); +var _decodeAsync = (_Err) => async (schema, value, _ctx) => { + return _parseAsync(_Err)(schema, value, _ctx); +}; +var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError); +var _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError); +var _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError); +var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError); +var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError); + +// node_modules/zod/v4/core/regexes.js +var regexes_exports = {}; +__export(regexes_exports, { + base64: () => base64, + base64url: () => base64url, + bigint: () => bigint, + boolean: () => boolean, + browserEmail: () => browserEmail, + cidrv4: () => cidrv4, + cidrv6: () => cidrv6, + cuid: () => cuid, + cuid2: () => cuid2, + date: () => date, + datetime: () => datetime, + domain: () => domain, + duration: () => duration, + e164: () => e164, + email: () => email, + emoji: () => emoji, + extendedDuration: () => extendedDuration, + guid: () => guid, + hex: () => hex, + hostname: () => hostname2, + html5Email: () => html5Email, + idnEmail: () => idnEmail, + integer: () => integer, + ipv4: () => ipv4, + ipv6: () => ipv6, + ksuid: () => ksuid, + lowercase: () => lowercase, + mac: () => mac, + md5_base64: () => md5_base64, + md5_base64url: () => md5_base64url, + md5_hex: () => md5_hex, + nanoid: () => nanoid, + null: () => _null, + number: () => number, + rfc5322Email: () => rfc5322Email, + sha1_base64: () => sha1_base64, + sha1_base64url: () => sha1_base64url, + sha1_hex: () => sha1_hex, + sha256_base64: () => sha256_base64, + sha256_base64url: () => sha256_base64url, + sha256_hex: () => sha256_hex, + sha384_base64: () => sha384_base64, + sha384_base64url: () => sha384_base64url, + sha384_hex: () => sha384_hex, + sha512_base64: () => sha512_base64, + sha512_base64url: () => sha512_base64url, + sha512_hex: () => sha512_hex, + string: () => string, + time: () => time, + ulid: () => ulid, + undefined: () => _undefined, + unicodeEmail: () => unicodeEmail, + uppercase: () => uppercase, + uuid: () => uuid, + uuid4: () => uuid4, + uuid6: () => uuid6, + uuid7: () => uuid7, + xid: () => xid +}); var cuid = /^[cC][^\s-]{8,}$/; var cuid2 = /^[0-9a-z]+$/; var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; @@ -17971,25 +19707,39 @@ var xid = /^[0-9a-vA-V]{20}$/; var ksuid = /^[A-Za-z0-9]{27}$/; var nanoid = /^[a-zA-Z0-9_-]{21}$/; var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; var uuid = (version2) => { if (!version2) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); }; +var uuid4 = /* @__PURE__ */ uuid(4); +var uuid6 = /* @__PURE__ */ uuid(6); +var uuid7 = /* @__PURE__ */ uuid(7); var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +var idnEmail = unicodeEmail; +var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; function emoji() { return new RegExp(_emoji, "u"); } var ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; +var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; +var mac = (delimiter) => { + const escapedDelim = escapeRegex(delimiter != null ? delimiter : ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; var cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; var base64url = /^[A-Za-z0-9_-]*$/; -var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -var e164 = /^\+(?:[0-9]){6,14}[0-9]$/; +var hostname2 = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +var e164 = /^\+[1-9]\d{6,14}$/; var dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); function timeSource(args) { @@ -18001,32 +19751,58 @@ function time(args) { return new RegExp(`^${timeSource(args)}$`); } function datetime(args) { - const time22 = timeSource({ precision: args.precision }); + const time4 = timeSource({ precision: args.precision }); const opts = ["Z"]; if (args.local) opts.push(""); if (args.offset) - opts.push(`([+-]\\d{2}:\\d{2})`); - const timeRegex2 = `${time22}(?:${opts.join("|")})`; + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const timeRegex2 = `${time4}(?:${opts.join("|")})`; return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); } var string = (params) => { - var _a, _b; - const regex = params ? `[\\s\\S]{${(_a = params == null ? void 0 : params.minimum) != null ? _a : 0},${(_b = params == null ? void 0 : params.maximum) != null ? _b : ""}}` : `[\\s\\S]*`; + var _a3, _b; + const regex = params ? `[\\s\\S]{${(_a3 = params == null ? void 0 : params.minimum) != null ? _a3 : 0},${(_b = params == null ? void 0 : params.maximum) != null ? _b : ""}}` : `[\\s\\S]*`; return new RegExp(`^${regex}$`); }; -var integer = /^\d+$/; -var number = /^-?\d+(?:\.\d+)?/i; -var boolean = /true|false/i; -var _null = /null/i; +var bigint = /^-?\d+n?$/; +var integer = /^-?\d+$/; +var number = /^-?\d+(?:\.\d+)?$/; +var boolean = /^(?:true|false)$/i; +var _null = /^null$/i; +var _undefined = /^undefined$/i; var lowercase = /^[^A-Z]*$/; var uppercase = /^[^a-z]*$/; +var hex = /^[0-9a-fA-F]*$/; +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +var md5_hex = /^[0-9a-fA-F]{32}$/; +var md5_base64 = /* @__PURE__ */ fixedBase64(22, "=="); +var md5_base64url = /* @__PURE__ */ fixedBase64url(22); +var sha1_hex = /^[0-9a-fA-F]{40}$/; +var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "="); +var sha1_base64url = /* @__PURE__ */ fixedBase64url(27); +var sha256_hex = /^[0-9a-fA-F]{64}$/; +var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "="); +var sha256_base64url = /* @__PURE__ */ fixedBase64url(43); +var sha384_hex = /^[0-9a-fA-F]{96}$/; +var sha384_base64 = /* @__PURE__ */ fixedBase64(64, ""); +var sha384_base64url = /* @__PURE__ */ fixedBase64url(64); +var sha512_hex = /^[0-9a-fA-F]{128}$/; +var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "=="); +var sha512_base64url = /* @__PURE__ */ fixedBase64url(86); + +// node_modules/zod/v4/core/checks.js var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { - var _a2, _b; - var _a; - (_a2 = inst._zod) != null ? _a2 : inst._zod = {}; + var _a4, _b; + var _a3; + (_a4 = inst._zod) != null ? _a4 : inst._zod = {}; inst._zod.def = def; - (_b = (_a = inst._zod).onattach) != null ? _b : _a.onattach = []; + (_b = (_a3 = inst._zod).onattach) != null ? _b : _a3.onattach = []; }); var numericOriginMap = { number: "number", @@ -18037,9 +19813,9 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { - var _a; + var _a3; const bag = inst2._zod.bag; - const curr = (_a = def.inclusive ? bag.maximum : bag.exclusiveMaximum) != null ? _a : Number.POSITIVE_INFINITY; + const curr = (_a3 = def.inclusive ? bag.maximum : bag.exclusiveMaximum) != null ? _a3 : Number.POSITIVE_INFINITY; if (def.value < curr) { if (def.inclusive) bag.maximum = def.value; @@ -18054,7 +19830,7 @@ var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, payload.issues.push({ origin, code: "too_big", - maximum: def.value, + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, @@ -18066,9 +19842,9 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.onattach.push((inst2) => { - var _a; + var _a3; const bag = inst2._zod.bag; - const curr = (_a = def.inclusive ? bag.minimum : bag.exclusiveMinimum) != null ? _a : Number.NEGATIVE_INFINITY; + const curr = (_a3 = def.inclusive ? bag.minimum : bag.exclusiveMinimum) != null ? _a3 : Number.NEGATIVE_INFINITY; if (def.value > curr) { if (def.inclusive) bag.minimum = def.value; @@ -18083,7 +19859,7 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", payload.issues.push({ origin, code: "too_small", - minimum: def.value, + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, @@ -18094,9 +19870,9 @@ var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { - var _a2; - var _a; - (_a2 = (_a = inst2._zod.bag).multipleOf) != null ? _a2 : _a.multipleOf = def.value; + var _a4; + var _a3; + (_a4 = (_a3 = inst2._zod.bag).multipleOf) != null ? _a4 : _a3.multipleOf = def.value; }); inst._zod.check = (payload) => { if (typeof payload.value !== typeof def.value) @@ -18115,10 +19891,10 @@ var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (i }; }); var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { - var _a; + var _a3; $ZodCheck.init(inst, def); def.format = def.format || "float64"; - const isInt = (_a = def.format) == null ? void 0 : _a.includes("int"); + const isInt = (_a3 = def.format) == null ? void 0 : _a3.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.onattach.push((inst2) => { @@ -18137,6 +19913,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" expected: origin, format: def.format, code: "invalid_type", + continue: false, input, inst }); @@ -18151,6 +19928,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" note: "Integers must be within the safe integer range.", inst, origin, + inclusive: true, continue: !def.abort }); } else { @@ -18161,6 +19939,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" note: "Integers must be within the safe integer range.", inst, origin, + inclusive: true, continue: !def.abort }); } @@ -18184,20 +19963,150 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat" input, code: "too_big", maximum, - inst + inclusive: true, + inst, + continue: !def.abort }); } }; }); -var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { +var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { $ZodCheck.init(inst, def); - inst._zod.when = (payload) => { + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { + var _a4; + var _a3; + $ZodCheck.init(inst, def); + (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }; + inst._zod.onattach.push((inst2) => { + var _a5; + const curr = (_a5 = inst2._zod.bag.maximum) != null ? _a5 : Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { + var _a4; + var _a3; + $ZodCheck.init(inst, def); + (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }; + inst._zod.onattach.push((inst2) => { + var _a5; + const curr = (_a5 = inst2._zod.bag.minimum) != null ? _a5 : Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a4; + var _a3; + $ZodCheck.init(inst, def); + (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: getSizableOrigin(input), + ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a4; + var _a3; + $ZodCheck.init(inst, def); + (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }; inst._zod.onattach.push((inst2) => { - var _a; - const curr = (_a = inst2._zod.bag.maximum) != null ? _a : Number.POSITIVE_INFINITY; + var _a5; + const curr = (_a5 = inst2._zod.bag.maximum) != null ? _a5 : Number.POSITIVE_INFINITY; if (def.maximum < curr) inst2._zod.bag.maximum = def.maximum; }); @@ -18219,14 +20128,16 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins }; }); var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a4; + var _a3; $ZodCheck.init(inst, def); - inst._zod.when = (payload) => { + (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }; inst._zod.onattach.push((inst2) => { - var _a; - const curr = (_a = inst2._zod.bag.minimum) != null ? _a : Number.NEGATIVE_INFINITY; + var _a5; + const curr = (_a5 = inst2._zod.bag.minimum) != null ? _a5 : Number.NEGATIVE_INFINITY; if (def.minimum > curr) inst2._zod.bag.minimum = def.minimum; }); @@ -18248,8 +20159,10 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins }; }); var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a4; + var _a3; $ZodCheck.init(inst, def); - inst._zod.when = (payload) => { + (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }; @@ -18278,20 +20191,20 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals" }; }); var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a2, _b2; - var _a, _b; + var _a4, _b2; + var _a3, _b; $ZodCheck.init(inst, def); inst._zod.onattach.push((inst2) => { - var _a3; + var _a5; const bag = inst2._zod.bag; bag.format = def.format; if (def.pattern) { - (_a3 = bag.patterns) != null ? _a3 : bag.patterns = /* @__PURE__ */ new Set(); + (_a5 = bag.patterns) != null ? _a5 : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(def.pattern); } }); if (def.pattern) - (_a2 = (_a = inst._zod).check) != null ? _a2 : _a.check = (payload) => { + (_a4 = (_a3 = inst._zod).check) != null ? _a4 : _a3.check = (payload) => { def.pattern.lastIndex = 0; if (def.pattern.test(payload.value)) return; @@ -18327,13 +20240,13 @@ var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) }; }); var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = lowercase; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = lowercase; $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = uppercase; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = uppercase; $ZodCheckStringFormat.init(inst, def); }); var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { @@ -18342,9 +20255,9 @@ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); def.pattern = pattern; inst._zod.onattach.push((inst2) => { - var _a; + var _a3; const bag = inst2._zod.bag; - (_a = bag.patterns) != null ? _a : bag.patterns = /* @__PURE__ */ new Set(); + (_a3 = bag.patterns) != null ? _a3 : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { @@ -18362,14 +20275,14 @@ var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, }; }); var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { - var _a; + var _a3; $ZodCheck.init(inst, def); const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - (_a = def.pattern) != null ? _a : def.pattern = pattern; + (_a3 = def.pattern) != null ? _a3 : def.pattern = pattern; inst._zod.onattach.push((inst2) => { - var _a2; + var _a4; const bag = inst2._zod.bag; - (_a2 = bag.patterns) != null ? _a2 : bag.patterns = /* @__PURE__ */ new Set(); + (_a4 = bag.patterns) != null ? _a4 : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { @@ -18387,14 +20300,14 @@ var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (i }; }); var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { - var _a; + var _a3; $ZodCheck.init(inst, def); const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - (_a = def.pattern) != null ? _a : def.pattern = pattern; + (_a3 = def.pattern) != null ? _a3 : def.pattern = pattern; inst._zod.onattach.push((inst2) => { - var _a2; + var _a4; const bag = inst2._zod.bag; - (_a2 = bag.patterns) != null ? _a2 : bag.patterns = /* @__PURE__ */ new Set(); + (_a4 = bag.patterns) != null ? _a4 : bag.patterns = /* @__PURE__ */ new Set(); bag.patterns.add(pattern); }); inst._zod.check = (payload) => { @@ -18411,12 +20324,51 @@ var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, }); }; }); +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues(property, result.issues)); + } +} +var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [] + }, {}); + if (result instanceof Promise) { + return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}); +var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort + }); + }; +}); var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { $ZodCheck.init(inst, def); inst._zod.check = (payload) => { payload.value = def.tx(payload.value); }; }); + +// node_modules/zod/v4/core/doc.js var Doc = class { constructor(args = []) { this.content = []; @@ -18436,37 +20388,39 @@ var Doc = class { return; } const content = arg; - const lines = content.split(` -`).filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + const lines = content.split("\n").filter((x3) => x3); + const minIndent = Math.min(...lines.map((x3) => x3.length - x3.trimStart().length)); + const dedented = lines.map((x3) => x3.slice(minIndent)).map((x3) => " ".repeat(this.indent * 2) + x3); for (const line of dedented) { this.content.push(line); } } compile() { - var _a; + var _a3; const F = Function; const args = this == null ? void 0 : this.args; - const content = (_a = this == null ? void 0 : this.content) != null ? _a : [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join(` -`)); + const content = (_a3 = this == null ? void 0 : this.content) != null ? _a3 : [``]; + const lines = [...content.map((x3) => ` ${x3}`)]; + return new F(...args, lines.join("\n")); } }; + +// node_modules/zod/v4/core/versions.js var version = { major: 4, - minor: 0, - patch: 0 + minor: 3, + patch: 5 }; + +// node_modules/zod/v4/core/schemas.js var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { - var _a2, _b, _c; - var _a; + var _a4, _b, _c; + var _a3; inst != null ? inst : inst = {}; inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; - const checks = [...(_a2 = inst._zod.def.checks) != null ? _a2 : []]; + const checks = [...(_a4 = inst._zod.def.checks) != null ? _a4 : []]; if (inst._zod.traits.has("$ZodCheck")) { checks.unshift(inst); } @@ -18476,7 +20430,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { } } if (checks.length === 0) { - (_b = (_a = inst._zod).deferred) != null ? _b : _a.deferred = []; + (_b = (_a3 = inst._zod).deferred) != null ? _b : _a3.deferred = []; (_c = inst._zod.deferred) == null ? void 0 : _c.push(() => { inst._zod.run = inst._zod.parse; }); @@ -18485,8 +20439,8 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { let isAborted2 = aborted(payload); let asyncResult; for (const ch of checks2) { - if (ch._zod.when) { - const shouldRun = ch._zod.when(payload); + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); if (!shouldRun) continue; } else if (isAborted2) { @@ -18521,7 +20475,32 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { } return payload; }; + const handleCanaryResult = (canary, payload, ctx) => { + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary2) => { + return handleCanaryResult(canary2, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) @@ -18531,32 +20510,32 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { return runChecks(result, checks, ctx); }; } - inst["~standard"] = { + defineLazy(inst, "~standard", () => ({ validate: (value) => { - var _a3; + var _a5; try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: (_a3 = r.error) == null ? void 0 : _a3.issues }; + const r2 = safeParse(inst, value); + return r2.success ? { value: r2.data } : { issues: (_a5 = r2.error) == null ? void 0 : _a5.issues }; } catch (_) { - return safeParseAsync(inst, value).then((r) => { - var _a4; - return r.success ? { value: r.data } : { issues: (_a4 = r.error) == null ? void 0 : _a4.issues }; + return safeParseAsync(inst, value).then((r2) => { + var _a6; + return r2.success ? { value: r2.data } : { issues: (_a6 = r2.error) == null ? void 0 : _a6.issues }; }); } }, vendor: "zod", version: 1 - }; + })); }); var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { - var _a, _b, _c; + var _a3, _b, _c; $ZodType.init(inst, def); - inst._zod.pattern = (_c = [...(_b = (_a = inst == null ? void 0 : inst._zod.bag) == null ? void 0 : _a.patterns) != null ? _b : []].pop()) != null ? _c : string(inst._zod.bag); + inst._zod.pattern = (_c = [...(_b = (_a3 = inst == null ? void 0 : inst._zod.bag) == null ? void 0 : _a3.patterns) != null ? _b : []].pop()) != null ? _c : string(inst._zod.bag); inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); - } catch (_2) { + } catch (_3) { } if (typeof payload.value === "string") return payload; @@ -18574,12 +20553,12 @@ var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, d $ZodString.init(inst, def); }); var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = guid; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = guid; $ZodStringFormat.init(inst, def); }); var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { - var _a, _b; + var _a3, _b; if (def.version) { const versionMap = { v1: 1, @@ -18591,34 +20570,33 @@ var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { v7: 7, v8: 8 }; - const v = versionMap[def.version]; - if (v === void 0) + const v3 = versionMap[def.version]; + if (v3 === void 0) throw new Error(`Invalid UUID version: "${def.version}"`); - (_a = def.pattern) != null ? _a : def.pattern = uuid(v); + (_a3 = def.pattern) != null ? _a3 : def.pattern = uuid(v3); } else (_b = def.pattern) != null ? _b : def.pattern = uuid(); $ZodStringFormat.init(inst, def); }); var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = email; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = email; $ZodStringFormat.init(inst, def); }); var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { try { - const orig = payload.value; - const url = new URL(orig); - const href = url.href; + const trimmed = payload.value.trim(); + const url2 = new URL(trimmed); if (def.hostname) { def.hostname.lastIndex = 0; - if (!def.hostname.test(url.hostname)) { + if (!def.hostname.test(url2.hostname)) { payload.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", - pattern: hostname.source, + pattern: def.hostname.source, input: payload.value, inst, continue: !def.abort @@ -18627,7 +20605,7 @@ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { } if (def.protocol) { def.protocol.lastIndex = 0; - if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { + if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { payload.issues.push({ code: "invalid_format", format: "url", @@ -18639,10 +20617,10 @@ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { }); } } - if (!orig.endsWith("/") && href.endsWith("/")) { - payload.value = href.slice(0, -1); + if (def.normalize) { + payload.value = url2.href; } else { - payload.value = href; + payload.value = trimmed; } return; } catch (_) { @@ -18657,81 +20635,75 @@ var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { }; }); var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = emoji(); + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = emoji(); $ZodStringFormat.init(inst, def); }); var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = nanoid; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = nanoid; $ZodStringFormat.init(inst, def); }); var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = cuid; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = cuid; $ZodStringFormat.init(inst, def); }); var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = cuid2; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = cuid2; $ZodStringFormat.init(inst, def); }); var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = ulid; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = ulid; $ZodStringFormat.init(inst, def); }); var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = xid; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = xid; $ZodStringFormat.init(inst, def); }); var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = ksuid; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = ksuid; $ZodStringFormat.init(inst, def); }); var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = datetime(def); + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = datetime(def); $ZodStringFormat.init(inst, def); }); var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = date; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = date; $ZodStringFormat.init(inst, def); }); var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = time(def); + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = time(def); $ZodStringFormat.init(inst, def); }); var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = duration; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = duration; $ZodStringFormat.init(inst, def); }); var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = ipv4; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = ipv4; $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = `ipv4`; - }); + inst._zod.bag.format = `ipv4`; }); var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = ipv6; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = ipv6; $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = `ipv6`; - }); + inst._zod.bag.format = `ipv6`; inst._zod.check = (payload) => { try { new URL(`http://[${payload.value}]`); - } catch (e) { + } catch (e2) { payload.issues.push({ code: "invalid_format", format: "ipv6", @@ -18742,18 +20714,27 @@ var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { } }; }); +var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => { + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = mac(def.delimiter); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}); var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = cidrv4; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = cidrv4; $ZodStringFormat.init(inst, def); }); var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = cidrv6; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = cidrv6; $ZodStringFormat.init(inst, def); inst._zod.check = (payload) => { - const [address, prefix] = payload.value.split("/"); + const parts = payload.value.split("/"); try { + if (parts.length !== 2) + throw new Error(); + const [address, prefix] = parts; if (!prefix) throw new Error(); const prefixNum = Number(prefix); @@ -18762,7 +20743,7 @@ var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { if (prefixNum < 0 || prefixNum > 128) throw new Error(); new URL(`http://[${address}]`); - } catch (e) { + } catch (e2) { payload.issues.push({ code: "invalid_format", format: "cidrv6", @@ -18781,17 +20762,15 @@ function isValidBase64(data) { try { atob(data); return true; - } catch (e) { + } catch (e2) { return false; } } var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = base64; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = base64; $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.contentEncoding = "base64"; - }); + inst._zod.bag.contentEncoding = "base64"; inst._zod.check = (payload) => { if (isValidBase64(payload.value)) return; @@ -18807,17 +20786,15 @@ var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { function isValidBase64URL(data) { if (!base64url.test(data)) return false; - const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); - const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "="); + const base643 = data.replace(/[-_]/g, (c3) => c3 === "-" ? "+" : "/"); + const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); return isValidBase64(padded); } var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = base64url; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = base64url; $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.contentEncoding = "base64url"; - }); + inst._zod.bag.contentEncoding = "base64url"; inst._zod.check = (payload) => { if (isValidBase64URL(payload.value)) return; @@ -18831,8 +20808,8 @@ var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => }; }); var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { - var _a; - (_a = def.pattern) != null ? _a : def.pattern = e164; + var _a3; + (_a3 = def.pattern) != null ? _a3 : def.pattern = e164; $ZodStringFormat.init(inst, def); }); function isValidJWT2(token, algorithm = null) { @@ -18851,7 +20828,7 @@ function isValidJWT2(token, algorithm = null) { if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false; return true; - } catch (e) { + } catch (e2) { return false; } } @@ -18869,10 +20846,24 @@ var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { }); }; }); +var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { - var _a; + var _a3; $ZodType.init(inst, def); - inst._zod.pattern = (_a = inst._zod.bag.pattern) != null ? _a : number; + inst._zod.pattern = (_a3 = inst._zod.bag.pattern) != null ? _a3 : number; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { @@ -18894,7 +20885,7 @@ var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { return payload; }; }); -var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { +var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); }); @@ -18919,6 +20910,64 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { return payload; }; }); +var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } catch (_) { + } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => { + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); +}); +var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = /* @__PURE__ */ new Set([void 0]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = _null; @@ -18936,6 +20985,10 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { return payload; }; }); +var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; @@ -18952,6 +21005,45 @@ var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { return payload; }; }); +var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } catch (_err) { + } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate ? { received: "Invalid Date" } : {}, + inst + }); + return payload; + }; +}); function handleArrayResult(result, final, index) { if (result.issues.length) { final.issues.push(...prefixIssues(index, result.issues)); @@ -18973,16 +21065,16 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { } payload.value = Array(input.length); const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; + for (let i2 = 0; i2 < input.length; i2++) { + const item = input[i2]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) { - proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); + proms.push(result.then((result2) => handleArrayResult(result2, payload, i2))); } else { - handleArrayResult(result, payload, i); + handleArrayResult(result, payload, i2); } } if (proms.length) { @@ -18991,63 +21083,142 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { return payload; }; }); -function handleObjectResult(result, final, key) { +function handlePropertyResult(result, final, key, input, isOptionalOut) { if (result.issues.length) { + if (isOptionalOut && !(key in input)) { + return; + } final.issues.push(...prefixIssues(key, result.issues)); } - final.value[key] = result.value; -} -function handleOptionalObjectResult(result, final, key, input) { - if (result.issues.length) { - if (input[key] === void 0) { - if (key in input) { - final.value[key] = void 0; - } else { - final.value[key] = result.value; - } - } else { - final.issues.push(...prefixIssues(key, result.issues)); - } - } else if (result.value === void 0) { - if (key in input) + if (result.value === void 0) { + if (key in input) { final.value[key] = void 0; + } } else { final.value[key] = result.value; } } +function normalizeDef(def) { + var _a3, _b, _c, _d; + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!((_d = (_c = (_b = (_a3 = def.shape) == null ? void 0 : _a3[k]) == null ? void 0 : _b._zod) == null ? void 0 : _c.traits) == null ? void 0 : _d.has("$ZodType"))) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t2 = _catchall.def.type; + const isOptionalOut = _catchall.optout === "optional"; + for (const key in input) { + if (keySet.has(key)) + continue; + if (t2 === "never") { + unrecognized.push(key); + continue; + } + const r2 = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r2 instanceof Promise) { + proms.push(r2.then((r5) => handlePropertyResult(r5, payload, key, input, isOptionalOut))); + } else { + handlePropertyResult(r2, payload, key, input, isOptionalOut); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); - const _normalized = cached(() => { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!(def.shape[k] instanceof $ZodType)) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!(desc == null ? void 0 : desc.get)) { + const sh = def.shape; + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh + }); + return newSh; } - } - const okeys = optionalKeys(def.shape); - return { - shape: def.shape, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys) - }; - }); + }); + } + const _normalized = cached(() => normalizeDef(def)); defineLazy(inst._zod, "propValues", () => { - var _a; + var _a3; const shape = def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { - (_a = propValues[key]) != null ? _a : propValues[key] = /* @__PURE__ */ new Set(); - for (const v of field.values) - propValues[key].add(v); + (_a3 = propValues[key]) != null ? _a3 : propValues[key] = /* @__PURE__ */ new Set(); + for (const v3 of field.values) + propValues[key].add(v3); } } return propValues; }); + const isObject2 = isObject; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value != null ? value : value = _normalized.value; + const input = payload.value; + if (!isObject2(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const isOptionalOut = el._zod.optout === "optional"; + const r2 = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r2 instanceof Promise) { + proms.push(r2.then((r5) => handlePropertyResult(r5, payload, key, input, isOptionalOut))); + } else { + handlePropertyResult(r2, payload, key, input, isOptionalOut); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => { + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def)); const generateFastpass = (shape) => { + var _a3; const doc = new Doc(["shape", "payload", "ctx"]); const normalized = _normalized.value; const parseStr = (key) => { @@ -19060,41 +21231,51 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { for (const key of normalized.keys) { ids[key] = `key_${counter++}`; } - doc.write(`const newResult = {}`); + doc.write(`const newResult = {};`); for (const key of normalized.keys) { - if (normalized.optionalKeys.has(key)) { - const id = ids[key]; - doc.write(`const ${id} = ${parseStr(key)};`); - const k = esc(key); + const id = ids[key]; + const k = esc(key); + const schema = shape[key]; + const isOptionalOut = ((_a3 = schema == null ? void 0 : schema._zod) == null ? void 0 : _a3.optout) === "optional"; + doc.write(`const ${id} = ${parseStr(key)};`); + if (isOptionalOut) { doc.write(` if (${id}.issues.length) { - if (input[${k}] === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - payload.issues = payload.issues.concat( - ${id}.issues.map((iss) => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}], - })) - ); + if (${k} in input) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; } - } else if (${id}.value === undefined) { - if (${k} in input) newResult[${k}] = undefined; } else { newResult[${k}] = ${id}.value; } - `); + + `); } else { - const id = ids[key]; - doc.write(`const ${id} = ${parseStr(key)};`); doc.write(` - if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ ...iss, - path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}] - })));`); - doc.write(`newResult[${esc(key)}] = ${id}.value`); + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); } } doc.write(`payload.value = newResult;`); @@ -19103,7 +21284,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { return (payload, ctx) => fn(shape, payload, ctx); }; let fastpass; - const isObject3 = isObject2; + const isObject2 = isObject; const jit = !globalConfig.jitless; const allowsEval2 = allowsEval; const fastEnabled = jit && allowsEval2.value; @@ -19112,7 +21293,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { inst._zod.parse = (payload, ctx) => { value != null ? value : value = _normalized.value; const input = payload.value; - if (!isObject3(input)) { + if (!isObject2(input)) { payload.issues.push({ expected: "object", code: "invalid_type", @@ -19121,61 +21302,15 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { }); return payload; } - const proms = []; if (jit && fastEnabled && (ctx == null ? void 0 : ctx.async) === false && ctx.jitless !== true) { if (!fastpass) fastpass = generateFastpass(def.shape); payload = fastpass(payload, ctx); - } else { - payload.value = {}; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; - if (r instanceof Promise) { - proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); - } else if (isOptional) { - handleOptionalObjectResult(r, payload, key, input); - } else { - handleObjectResult(r, payload, key); - } - } + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - const unrecognized = []; - const keySet = value.keySet; - const _catchall = catchall._zod; - const t = _catchall.def.type; - for (const key of Object.keys(input)) { - if (keySet.has(key)) - continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r2) => handleObjectResult(r2, payload, key))); - } else { - handleObjectResult(r, payload, key); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); + return superParse(payload, ctx); }; }); function handleUnionResults(results, final, inst, ctx) { @@ -19185,6 +21320,11 @@ function handleUnionResults(results, final, inst, ctx) { return final; } } + const nonaborted = results.filter((r2) => !aborted(r2)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } final.issues.push({ code: "invalid_union", input: final.value, @@ -19201,16 +21341,21 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { if (def.options.every((o) => o._zod.values)) { return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); } - return; + return void 0; }); defineLazy(inst._zod, "pattern", () => { if (def.options.every((o) => o._zod.pattern)) { const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + return new RegExp(`^(${patterns.map((p2) => cleanRegex(p2.source)).join("|")})$`); } - return; + return void 0; }); + const single = def.options.length === 1; + const first = def.options[0]._zod.run; inst._zod.parse = (payload, ctx) => { + if (single) { + return first(payload, ctx); + } let async = false; const results = []; for (const option of def.options) { @@ -19234,7 +21379,62 @@ var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { }); }; }); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r2) => r2.issues.length === 0); + if (successes.length === 1) { + final.value = successes[0].value; + return final; + } + if (successes.length === 0) { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + } else { + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false + }); + } + return final; +} +var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx) => { + if (single) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleExclusiveUnionResults(results2, payload, inst, ctx); + }); + }; +}); var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; $ZodUnion.init(inst, def); const _super = inst._zod.parse; defineLazy(inst._zod, "propValues", () => { @@ -19243,10 +21443,10 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio const pv = option._zod.propValues; if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { + for (const [k, v3] of Object.entries(pv)) { if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set(); - for (const val of v) { + for (const val of v3) { propValues[k].add(val); } } @@ -19254,24 +21454,25 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio return propValues; }); const disc = cached(() => { + var _a3; const opts = def.options; - const map = /* @__PURE__ */ new Map(); + const map2 = /* @__PURE__ */ new Map(); for (const o of opts) { - const values = o._zod.propValues[def.discriminator]; + const values = (_a3 = o._zod.propValues) == null ? void 0 : _a3[def.discriminator]; if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); + for (const v3 of values) { + if (map2.has(v3)) { + throw new Error(`Duplicate discriminator value "${String(v3)}"`); } - map.set(v, o); + map2.set(v3, o); } } - return map; + return map2; }); inst._zod.parse = (payload, ctx) => { const input = payload.value; - if (!isObject2(input)) { + if (!isObject(input)) { payload.issues.push({ code: "invalid_type", expected: "object", @@ -19291,6 +21492,7 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio code: "invalid_union", errors: [], note: "No matching discriminator", + discriminator: def.discriminator, input, path: [def.discriminator], inst @@ -19313,19 +21515,19 @@ var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, d return handleIntersectionResults(payload, left, right); }; }); -function mergeValues2(a, b) { - if (a === b) { +function mergeValues2(a, b3) { + if (a === b3) { return { valid: true, data: a }; } - if (a instanceof Date && b instanceof Date && +a === +b) { + if (a instanceof Date && b3 instanceof Date && +a === +b3) { return { valid: true, data: a }; } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); + if (isPlainObject(a) && isPlainObject(b3)) { + const bKeys = Object.keys(b3); const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; + const newObj = { ...a, ...b3 }; for (const key of sharedKeys) { - const sharedValue = mergeValues2(a[key], b[key]); + const sharedValue = mergeValues2(a[key], b3[key]); if (!sharedValue.valid) { return { valid: false, @@ -19336,14 +21538,14 @@ function mergeValues2(a, b) { } return { valid: true, data: newObj }; } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { + if (Array.isArray(a) && Array.isArray(b3)) { + if (a.length !== b3.length) { return { valid: false, mergeErrorPath: [] }; } const newArray = []; for (let index = 0; index < a.length; index++) { const itemA = a[index]; - const itemB = b[index]; + const itemB = b3[index]; const sharedValue = mergeValues2(itemA, itemB); if (!sharedValue.valid) { return { @@ -19358,11 +21560,34 @@ function mergeValues2(a, b) { return { valid: false, mergeErrorPath: [] }; } function handleIntersectionResults(result, left, right) { - if (left.issues.length) { - result.issues.push(...left.issues); + const unrecKeys = /* @__PURE__ */ new Map(); + let unrecIssue; + for (const iss of left.issues) { + if (iss.code === "unrecognized_keys") { + unrecIssue != null ? unrecIssue : unrecIssue = iss; + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).l = true; + } + } else { + result.issues.push(iss); + } } - if (right.issues.length) { - result.issues.push(...right.issues); + for (const iss of right.issues) { + if (iss.code === "unrecognized_keys") { + for (const k of iss.keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k).r = true; + } + } else { + result.issues.push(iss); + } + } + const bothKeys = [...unrecKeys].filter(([, f3]) => f3.l && f3.r).map(([k]) => k); + if (bothKeys.length && unrecIssue) { + result.issues.push({ ...unrecIssue, keys: bothKeys }); } if (aborted(result)) return result; @@ -19373,6 +21598,80 @@ function handleIntersectionResults(result, left, right) { result.value = merged.data; return result; } +var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" + }); + return payload; + } + payload.value = []; + const proms = []; + const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length }, + input, + inst, + origin: "array" + }); + return payload; + } + } + let i2 = -1; + for (const item of items) { + i2++; + if (i2 >= input.length) { + if (i2 >= optStart) + continue; + } + const result = item._zod.run({ + value: input[i2], + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload, i2))); + } else { + handleTupleResult(result, payload, i2); + } + } + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i2++; + const result = def.rest._zod.run({ + value: el, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload, i2))); + } else { + handleTupleResult(result, payload, i2); + } + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, ctx) => { @@ -19387,11 +21686,13 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { return payload; } const proms = []; - if (def.keyType._zod.values) { - const values = def.keyType._zod.values; + const values = def.keyType._zod.values; + if (values) { payload.value = {}; + const recordKeys = /* @__PURE__ */ new Set(); for (const key of values) { if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) { proms.push(result.then((result2) => { @@ -19410,7 +21711,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { } let unrecognized; for (const key in input) { - if (!values.has(key)) { + if (!recordKeys.has(key)) { unrecognized = unrecognized != null ? unrecognized : []; unrecognized.push(key); } @@ -19428,20 +21729,33 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { for (const key of Reflect.ownKeys(input)) { if (key === "__proto__") continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) { throw new Error("Async schemas not supported in object keys currently"); } + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length && keyResult.issues.some((iss) => iss.code === "invalid_type" && iss.expected === "number"); + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } if (keyResult.issues.length) { - payload.issues.push({ - origin: "record", - code: "invalid_key", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - payload.value[keyResult.value] = keyResult.value; + if (def.mode === "loose") { + payload.value[key] = input[key]; + } else { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + } continue; } const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); @@ -19466,14 +21780,109 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { return payload; }; }); +var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + })); + } else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleSetResult(result2, payload))); + } else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); - inst._zod.values = new Set(values); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; - if (inst._zod.values.has(input)) { + if (valuesSet.has(input)) { return payload; } payload.issues.push({ @@ -19487,11 +21896,15 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { }); var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); - inst._zod.values = new Set(def.values); - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`); + if (def.values.length === 0) { + throw new Error("Cannot create literal schema with no valid values"); + } + const values = new Set(def.values); + inst._zod.values = values; + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`); inst._zod.parse = (payload, _ctx) => { const input = payload.value; - if (inst._zod.values.has(input)) { + if (values.has(input)) { return payload; } payload.issues.push({ @@ -19503,11 +21916,29 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { return payload; }; }); -var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { +var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } const _out = def.transform(payload.value, payload); - if (_ctx.async) { + if (ctx.async) { const output = _out instanceof Promise ? _out : Promise.resolve(_out); return output.then((output2) => { payload.value = output2; @@ -19521,6 +21952,12 @@ var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => return payload; }; }); +function handleOptionalResult(result, input) { + if (result.issues.length && input === void 0) { + return { issues: [], value: void 0 }; + } + return result; +} var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); inst._zod.optin = "optional"; @@ -19534,7 +21971,10 @@ var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { }); inst._zod.parse = (payload, ctx) => { if (def.innerType._zod.optin === "optional") { - return def.innerType._zod.run(payload, ctx); + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) + return result.then((r2) => handleOptionalResult(r2, payload.value)); + return handleOptionalResult(result, payload.value); } if (payload.value === void 0) { return payload; @@ -19542,6 +21982,14 @@ var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { return def.innerType._zod.run(payload, ctx); }; }); +var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => { + $ZodOptional.init(inst, def); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern); + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); @@ -19564,6 +22012,9 @@ var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } if (payload.value === void 0) { payload.value = def.defaultValue; return payload; @@ -19586,6 +22037,9 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { inst._zod.optin = "optional"; defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } if (payload.value === void 0) { payload.value = def.defaultValue; } @@ -19595,8 +22049,8 @@ var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + const v3 = def.innerType._zod.values; + return v3 ? new Set([...v3].filter((x3) => x3 !== void 0)) : void 0; }); inst._zod.parse = (payload, ctx) => { const result = def.innerType._zod.run(payload, ctx); @@ -19617,12 +22071,32 @@ function handleNonOptionalResult(payload, inst) { } return payload; } +var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}); var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { $ZodType.init(inst, def); - inst._zod.optin = "optional"; + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); defineLazy(inst._zod, "values", () => def.innerType._zod.values); inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then((result2) => { @@ -19654,32 +22128,115 @@ var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { return payload; }; }); +var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type" + }); + return payload; + } + return payload; + }; +}); var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "values", () => def.in._zod.values); defineLazy(inst._zod, "optin", () => def.in._zod.optin); defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handlePipeResult(right2, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } const left = def.in._zod.run(payload, ctx); if (left instanceof Promise) { - return left.then((left2) => handlePipeResult(left2, def, ctx)); + return left.then((left2) => handlePipeResult(left2, def.out, ctx)); } - return handlePipeResult(left, def, ctx); + return handlePipeResult(left, def.out, ctx); }; }); -function handlePipeResult(left, def, ctx) { - if (aborted(left)) { +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + left.aborted = true; return left; } - return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handleCodecAResult(left2, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right2) => handleCodecAResult(right2, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); } var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { $ZodType.init(inst, def); defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "optin", () => { + var _a3, _b; + return (_b = (_a3 = def.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b.optin; + }); + defineLazy(inst._zod, "optout", () => { + var _a3, _b; + return (_b = (_a3 = def.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b.optout; + }); inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } const result = def.innerType._zod.run(payload, ctx); if (result instanceof Promise) { return result.then(handleReadonlyResult); @@ -19691,6 +22248,159 @@ function handleReadonlyResult(payload) { payload.value = Object.freeze(payload.value); return payload; } +var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + if (!part._zod.pattern) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (part === null || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex(`${part}`)); + } else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + var _a3; + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type" + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: (_a3 = def.format) != null ? _a3 : "template_literal", + pattern: inst._zod.pattern.source + }); + return payload; + } + return payload; + }; +}); +var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + inst._def = def; + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + return function(...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }; + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return async function(...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }; + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst + }); + return payload; + } + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: inst._def.output + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output + }); + }; + return inst; +}); +var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}); +var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "innerType", () => def.getter()); + defineLazy(inst._zod, "pattern", () => { + var _a3, _b; + return (_b = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b.pattern; + }); + defineLazy(inst._zod, "propValues", () => { + var _a3, _b; + return (_b = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b.propValues; + }); + defineLazy(inst._zod, "optin", () => { + var _a3, _b, _c; + return (_c = (_b = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b.optin) != null ? _c : void 0; + }); + defineLazy(inst._zod, "optout", () => { + var _a3, _b, _c; + return (_c = (_b = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b.optout) != null ? _c : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { $ZodCheck.init(inst, def); $ZodType.init(inst, def); @@ -19699,61 +22409,209 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { }; inst._zod.check = (payload) => { const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + const r2 = def.fn(input); + if (r2 instanceof Promise) { + return r2.then((r5) => handleRefineResult(r5, payload, input, inst)); } - handleRefineResult(r, payload, input, inst); + handleRefineResult(r2, payload, input, inst); return; }; }); function handleRefineResult(result, payload, input, inst) { - var _a; + var _a3; if (!result) { const _iss = { code: "custom", input, inst, - path: [...(_a = inst._zod.def.path) != null ? _a : []], + // incorporates params.error into issue reporting + path: [...(_a3 = inst._zod.def.path) != null ? _a3 : []], + // incorporates params.error into issue reporting continue: !inst._zod.def.abort + // params: inst._zod.def.params, }; if (inst._zod.def.params) _iss.params = inst._zod.def.params; payload.issues.push(issue(_iss)); } } -var parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; -}; + +// node_modules/zod/v4/locales/index.js +var locales_exports = {}; +__export(locales_exports, { + ar: () => ar_default, + az: () => az_default, + be: () => be_default, + bg: () => bg_default, + ca: () => ca_default, + cs: () => cs_default, + da: () => da_default, + de: () => de_default, + en: () => en_default2, + eo: () => eo_default, + es: () => es_default, + fa: () => fa_default, + fi: () => fi_default, + fr: () => fr_default, + frCA: () => fr_CA_default, + he: () => he_default, + hu: () => hu_default, + hy: () => hy_default, + id: () => id_default, + is: () => is_default, + it: () => it_default, + ja: () => ja_default, + ka: () => ka_default, + kh: () => kh_default, + km: () => km_default, + ko: () => ko_default, + lt: () => lt_default, + mk: () => mk_default, + ms: () => ms_default, + nl: () => nl_default, + no: () => no_default, + ota: () => ota_default, + pl: () => pl_default, + ps: () => ps_default, + pt: () => pt_default, + ru: () => ru_default, + sl: () => sl_default, + sv: () => sv_default, + ta: () => ta_default, + th: () => th_default, + tr: () => tr_default, + ua: () => ua_default, + uk: () => uk_default, + ur: () => ur_default, + uz: () => uz_default, + vi: () => vi_default, + yo: () => yo_default, + zhCN: () => zh_CN_default, + zhTW: () => zh_TW_default +}); + +// node_modules/zod/v4/locales/ar.js var error = () => { const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" } + string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } }; function getSizing(origin) { - var _a; - return (_a = Sizable[origin]) != null ? _a : null; + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; } - const Nouns = { + const FormatDictionary = { + regex: "\u0645\u062F\u062E\u0644", + email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", + url: "\u0631\u0627\u0628\u0637", + emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", + ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", + cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", + base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", + base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", + json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", + e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + jwt: "JWT", + template_literal: "\u0645\u062F\u062E\u0644" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_c = issue2.origin) != null ? _c : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0639\u0646\u0635\u0631"}`; + return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_e = issue2.origin) != null ? _e : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; + if (_issue.format === "ends_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; + } + case "not_multiple_of": + return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + case "invalid_union": + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + case "invalid_element": + return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + default: + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + } + }; +}; +function ar_default() { + return { + localeError: error() + }; +} + +// node_modules/zod/v4/locales/az.js +var error2 = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "element", verb: "olmal\u0131d\u0131r" }, + set: { unit: "element", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { regex: "input", email: "email address", url: "URL", @@ -19783,11 +22641,866 @@ var error = () => { jwt: "JWT", template_literal: "input" }; + const TypeDictionary = { + nan: "NaN" + }; return (issue2) => { - var _a, _b, _c, _d; + var _a3, _b, _c, _d, _e, _f; switch (issue2.code) { - case "invalid_type": - return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`; + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`; + } + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; + return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_c = issue2.origin) != null ? _c : "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "element"}`; + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_e = issue2.origin) != null ? _e : "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; + if (_issue.format === "ends_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; + if (_issue.format === "includes") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; + if (_issue.format === "regex") + return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; + return `Yanl\u0131\u015F ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; + case "unrecognized_keys": + return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; + case "invalid_union": + return "Yanl\u0131\u015F d\u0259y\u0259r"; + case "invalid_element": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; + default: + return `Yanl\u0131\u015F d\u0259y\u0259r`; + } + }; +}; +function az_default() { + return { + localeError: error2() + }; +} + +// node_modules/zod/v4/locales/be.js +function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +var error3 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0456\u043C\u0432\u0430\u043B", + few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", + many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u044B", + many: "\u0431\u0430\u0439\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0443\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0430\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0447\u0430\u0441", + duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", + base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", + json_string: "JSON \u0440\u0430\u0434\u043E\u043A", + e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + jwt: "JWT", + template_literal: "\u0443\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u043B\u0456\u043A", + array: "\u043C\u0430\u0441\u0456\u045E" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_c = issue2.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_d = issue2.origin) != null ? _d : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; + case "invalid_element": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; + default: + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; + } + }; +}; +function be_default() { + return { + localeError: error3() + }; +} + +// node_modules/zod/v4/locales/bg.js +var error4 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u043E\u0434", + email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0436\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437", + json_string: "JSON \u043D\u0438\u0437", + e164: "E.164 \u043D\u043E\u043C\u0435\u0440", + jwt: "JWT", + template_literal: "\u0432\u0445\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${(_c = issue2.origin) != null ? _c : "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`; + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${(_e = issue2.origin) != null ? _e : "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`; + let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D"; + if (_issue.format === "emoji") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "datetime") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "date") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + if (_issue.format === "time") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"; + if (_issue.format === "duration") + invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"; + return `${invalid_adj} ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"; + case "invalid_element": + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`; + } + }; +}; +function bg_default() { + return { + localeError: error4() + }; +} + +// node_modules/zod/v4/locales/ca.js +var error5 = () => { + const Sizable = { + string: { unit: "car\xE0cters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "entrada", + email: "adre\xE7a electr\xF2nica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adre\xE7a IPv4", + ipv6: "adre\xE7a IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`; + } + return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; + case "too_big": { + const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Massa gran: s'esperava que ${(_c = issue2.origin) != null ? _c : "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elements"}`; + return `Massa gran: s'esperava que ${(_e = issue2.origin) != null ? _e : "el valor"} fos ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; + return `Format inv\xE0lid per a ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Clau inv\xE0lida a ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE0lida"; + // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element inv\xE0lid a ${issue2.origin}`; + default: + return `Entrada inv\xE0lida`; + } + }; +}; +function ca_default() { + return { + localeError: error5() + }; +} + +// node_modules/zod/v4/locales/cs.js +var error6 = () => { + const Sizable = { + string: { unit: "znak\u016F", verb: "m\xEDt" }, + file: { unit: "bajt\u016F", verb: "m\xEDt" }, + array: { unit: "prvk\u016F", verb: "m\xEDt" }, + set: { unit: "prvk\u016F", verb: "m\xEDt" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "regul\xE1rn\xED v\xFDraz", + email: "e-mailov\xE1 adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a \u010Das ve form\xE1tu ISO", + date: "datum ve form\xE1tu ISO", + time: "\u010Das ve form\xE1tu ISO", + duration: "doba trv\xE1n\xED ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", + base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", + json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", + e164: "\u010D\xEDslo E.164", + jwt: "JWT", + template_literal: "vstup" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u010D\xEDslo", + string: "\u0159et\u011Bzec", + function: "funkce", + array: "pole" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`; + } + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_c = issue2.origin) != null ? _c : "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_e = issue2.origin) != null ? _e : "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_f = issue2.origin) != null ? _f : "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${(_g = sizing.unit) != null ? _g : "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_h = issue2.origin) != null ? _h : "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${(_i = FormatDictionary[_issue.format]) != null ? _i : issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; +}; +function cs_default() { + return { + localeError: error6() + }; +} + +// node_modules/zod/v4/locales/da.js +var error7 = () => { + const Sizable = { + string: { unit: "tegn", verb: "havde" }, + file: { unit: "bytes", verb: "havde" }, + array: { unit: "elementer", verb: "indeholdt" }, + set: { unit: "elementer", verb: "indeholdt" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "input", + email: "e-mailadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkesl\xE6t", + date: "ISO-dato", + time: "ISO-klokkesl\xE6t", + duration: "ISO-varighed", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodet streng", + base64url: "base64url-kodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + string: "streng", + number: "tal", + boolean: "boolean", + array: "liste", + object: "objekt", + set: "s\xE6t", + file: "fil" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`; + } + return `Ugyldigt input: forventede ${expected}, fik ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = (_c = TypeDictionary[issue2.origin]) != null ? _c : issue2.origin; + if (sizing) + return `For stor: forventede ${origin != null ? origin : "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementer"}`; + return `For stor: forventede ${origin != null ? origin : "value"} havde ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = (_e = TypeDictionary[issue2.origin]) != null ? _e : issue2.origin; + if (sizing) { + return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: skal starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: skal ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: skal indeholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8gle i ${issue2.origin}`; + case "invalid_union": + return "Ugyldigt input: matcher ingen af de tilladte typer"; + case "invalid_element": + return `Ugyldig v\xE6rdi i ${issue2.origin}`; + default: + return `Ugyldigt input`; + } + }; +}; +function da_default() { + return { + localeError: error7() + }; +} + +// node_modules/zod/v4/locales/de.js +var error8 = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe" + }; + const TypeDictionary = { + nan: "NaN", + number: "Zahl", + array: "Array" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`; + } + return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; + return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Zu gro\xDF: erwartet, dass ${(_c = issue2.origin) != null ? _c : "Wert"} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "Elemente"} hat`; + return `Zu gro\xDF: erwartet, dass ${(_e = issue2.origin) != null ? _e : "Wert"} ${adj}${issue2.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ung\xFCltig: ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; + case "invalid_union": + return "Ung\xFCltige Eingabe"; + case "invalid_element": + return `Ung\xFCltiger Wert in ${issue2.origin}`; + default: + return `Ung\xFCltige Eingabe`; + } + }; +}; +function de_default() { + return { + localeError: error8() + }; +} + +// node_modules/zod/v4/locales/en.js +var error9 = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN" + // All other type names omitted - they fall back to raw values via ?? operator + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + return `Invalid input: expected ${expected}, received ${received}`; + } case "invalid_value": if (issue2.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; @@ -19796,8 +23509,8 @@ var error = () => { const adj = issue2.inclusive ? "<=" : "<"; const sizing = getSizing(issue2.origin); if (sizing) - return `Too big: expected ${(_a = issue2.origin) != null ? _a : "value"} to have ${adj}${issue2.maximum.toString()} ${(_b = sizing.unit) != null ? _b : "elements"}`; - return `Too big: expected ${(_c = issue2.origin) != null ? _c : "value"} to be ${adj}${issue2.maximum.toString()}`; + return `Too big: expected ${(_c = issue2.origin) != null ? _c : "value"} to have ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elements"}`; + return `Too big: expected ${(_e = issue2.origin) != null ? _e : "value"} to be ${adj}${issue2.maximum.toString()}`; } case "too_small": { const adj = issue2.inclusive ? ">=" : ">"; @@ -19818,7 +23531,7 @@ var error = () => { return `Invalid string: must include "${_issue.includes}"`; if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${(_d = Nouns[_issue.format]) != null ? _d : issue2.format}`; + return `Invalid ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; } case "not_multiple_of": return `Invalid number: must be a multiple of ${issue2.divisor}`; @@ -19837,36 +23550,4602 @@ var error = () => { }; function en_default2() { return { - localeError: error() + localeError: error9() }; } + +// node_modules/zod/v4/locales/eo.js +var error10 = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emo\u011Dio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-da\u016Dro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombro", + array: "tabelo", + null: "senvalora" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`; + } + return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; + return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Tro granda: atendi\u011Dis ke ${(_c = issue2.origin) != null ? _c : "valoro"} havu ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementojn"}`; + return `Tro granda: atendi\u011Dis ke ${(_e = issue2.origin) != null ? _e : "valoro"} havu ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nevalida \u015Dlosilo en ${issue2.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue2.origin}`; + default: + return `Nevalida enigo`; + } + }; +}; +function eo_default() { + return { + localeError: error10() + }; +} + +// node_modules/zod/v4/locales/es.js +var error11 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "entrada", + email: "direcci\xF3n de correo electr\xF3nico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duraci\xF3n ISO", + ipv4: "direcci\xF3n IPv4", + ipv6: "direcci\xF3n IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + string: "texto", + number: "n\xFAmero", + boolean: "booleano", + array: "arreglo", + object: "objeto", + set: "conjunto", + file: "archivo", + date: "fecha", + bigint: "n\xFAmero grande", + symbol: "s\xEDmbolo", + undefined: "indefinido", + null: "nulo", + function: "funci\xF3n", + map: "mapa", + record: "registro", + tuple: "tupla", + enum: "enumeraci\xF3n", + union: "uni\xF3n", + literal: "literal", + promise: "promesa", + void: "vac\xEDo", + never: "nunca", + unknown: "desconocido", + any: "cualquiera" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f, _g, _h; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`; + } + return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const origin = (_c = TypeDictionary[issue2.origin]) != null ? _c : issue2.origin; + if (sizing) + return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} tuviera ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementos"}`; + return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} fuera ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const origin = (_e = TypeDictionary[issue2.origin]) != null ? _e : issue2.origin; + if (sizing) { + return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; + return `Inv\xE1lido ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Llave inv\xE1lida en ${(_g = TypeDictionary[issue2.origin]) != null ? _g : issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido en ${(_h = TypeDictionary[issue2.origin]) != null ? _h : issue2.origin}`; + default: + return `Entrada inv\xE1lida`; + } + }; +}; +function es_default() { + return { + localeError: error11() + }; +} + +// node_modules/zod/v4/locales/fa.js +var error12 = () => { + const Sizable = { + string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u06CC", + email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", + url: "URL", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", + time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + ipv4: "IPv4 \u0622\u062F\u0631\u0633", + ipv6: "IPv6 \u0622\u062F\u0631\u0633", + cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", + cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", + base64: "base64-encoded \u0631\u0634\u062A\u0647", + base64url: "base64url-encoded \u0631\u0634\u062A\u0647", + json_string: "JSON \u0631\u0634\u062A\u0647", + e164: "E.164 \u0639\u062F\u062F", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u06CC" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0622\u0631\u0627\u06CC\u0647" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; + } + return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_c = issue2.origin) != null ? _c : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_e = issue2.origin) != null ? _e : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; + } + if (_issue.format === "ends_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; + } + if (_issue.format === "includes") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; + } + if (_issue.format === "regex") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; + } + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + case "not_multiple_of": + return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; + case "invalid_union": + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + case "invalid_element": + return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; + default: + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + }; +}; +function fa_default() { + return { + localeError: error12() + }; +} + +// node_modules/zod/v4/locales/fi.js +var error13 = () => { + const Sizable = { + string: { unit: "merkki\xE4", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "s\xE4\xE4nn\xF6llinen lauseke", + email: "s\xE4hk\xF6postiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`; + } + return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; + return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${(_c = FormatDictionary[_issue.format]) != null ? _c : issue2.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen sy\xF6te`; + } + }; +}; +function fi_default() { + return { + localeError: error13() + }; +} + +// node_modules/zod/v4/locales/fr.js +var error14 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombre", + array: "tableau" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`; + } + return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : ${(_c = issue2.origin) != null ? _c : "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\xE9l\xE9ment(s)"}`; + return `Trop grand : ${(_e = issue2.origin) != null ? _e : "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; +}; +function fr_default() { + return { + localeError: error14() + }; +} + +// node_modules/zod/v4/locales/fr-CA.js +var error15 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "entr\xE9e", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`; + } + return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u2264" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : attendu que ${(_c = issue2.origin) != null ? _c : "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${(_d = issue2.origin) != null ? _d : "la valeur"} soit ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u2265" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; +}; +function fr_CA_default() { + return { + localeError: error15() + }; +} + +// node_modules/zod/v4/locales/he.js +var error16 = () => { + const TypeNames = { + string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" }, + number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" }, + boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" }, + bigint: { label: "BigInt", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" }, + array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" }, + object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" }, + null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" }, + undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" }, + symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" }, + function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" }, + map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" }, + set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" }, + file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" }, + promise: { label: "Promise", gender: "m" }, + NaN: { label: "NaN", gender: "m" }, + unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" }, + value: { label: "\u05E2\u05E8\u05DA", gender: "m" } + }; + const Sizable = { + string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" }, + file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }, + number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" } + // no unit + }; + const typeEntry = (t2) => t2 ? TypeNames[t2] : void 0; + const typeLabel = (t2) => { + const e2 = typeEntry(t2); + if (e2) + return e2.label; + return t2 != null ? t2 : TypeNames.unknown.label; + }; + const withDefinite = (t2) => `\u05D4${typeLabel(t2)}`; + const verbFor = (t2) => { + var _a3; + const e2 = typeEntry(t2); + const gender = (_a3 = e2 == null ? void 0 : e2.gender) != null ? _a3 : "m"; + return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"; + }; + const getSizing = (origin) => { + var _a3; + if (!origin) + return null; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + }; + const FormatDictionary = { + regex: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" }, + url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" }, + uuid: { label: "UUID", gender: "m" }, + nanoid: { label: "nanoid", gender: "m" }, + guid: { label: "GUID", gender: "m" }, + cuid: { label: "cuid", gender: "m" }, + cuid2: { label: "cuid2", gender: "m" }, + ulid: { label: "ULID", gender: "m" }, + xid: { label: "XID", gender: "m" }, + ksuid: { label: "KSUID", gender: "m" }, + datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" }, + date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" }, + time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" }, + duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" }, + ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" }, + ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" }, + cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" }, + cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" }, + base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" }, + base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" }, + json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" }, + e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" }, + jwt: { label: "JWT", gender: "m" }, + ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + includes: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" }, + uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" } + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q2, _r, _s, _t, _u; + switch (issue2.code) { + case "invalid_type": { + const expectedKey = issue2.expected; + const expected = (_a3 = TypeDictionary[expectedKey != null ? expectedKey : ""]) != null ? _a3 : typeLabel(expectedKey); + const receivedType = parsedType(issue2.input); + const received = (_d = (_c = TypeDictionary[receivedType]) != null ? _c : (_b = TypeNames[receivedType]) == null ? void 0 : _b.label) != null ? _d : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`; + } + case "invalid_value": { + if (issue2.values.length === 1) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`; + } + const stringified = issue2.values.map((v3) => stringifyPrimitive(v3)); + if (issue2.values.length === 2) { + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`; + } + const lastValue = stringified[stringified.length - 1]; + const restValues = stringified.slice(0, -1).join(", "); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`; + } + case "too_big": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite((_e = issue2.origin) != null ? _e : "value"); + if (issue2.origin === "string") { + return `${(_f = sizing == null ? void 0 : sizing.longLabel) != null ? _f : "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${(_g = sizing == null ? void 0 : sizing.unit) != null ? _g : ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + const comparison = issue2.inclusive ? `${issue2.maximum} ${(_h = sizing == null ? void 0 : sizing.unit) != null ? _h : ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${(_i = sizing == null ? void 0 : sizing.unit) != null ? _i : ""}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? "<=" : "<"; + const be = verbFor((_j = issue2.origin) != null ? _j : "value"); + if (sizing == null ? void 0 : sizing.unit) { + return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + } + return `${(_k = sizing == null ? void 0 : sizing.longLabel) != null ? _k : "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const sizing = getSizing(issue2.origin); + const subject = withDefinite((_l = issue2.origin) != null ? _l : "value"); + if (issue2.origin === "string") { + return `${(_m = sizing == null ? void 0 : sizing.shortLabel) != null ? _m : "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${(_n = sizing == null ? void 0 : sizing.unit) != null ? _n : ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim(); + } + if (issue2.origin === "number") { + const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`; + } + if (issue2.origin === "array" || issue2.origin === "set") { + const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA"; + if (issue2.minimum === 1 && issue2.inclusive) { + const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3"; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`; + } + const comparison = issue2.inclusive ? `${issue2.minimum} ${(_o = sizing == null ? void 0 : sizing.unit) != null ? _o : ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${(_p = sizing == null ? void 0 : sizing.unit) != null ? _p : ""}`; + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim(); + } + const adj = issue2.inclusive ? ">=" : ">"; + const be = verbFor((_q2 = issue2.origin) != null ? _q2 : "value"); + if (sizing == null ? void 0 : sizing.unit) { + return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `${(_r = sizing == null ? void 0 : sizing.shortLabel) != null ? _r : "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; + const nounEntry = FormatDictionary[_issue.format]; + const noun = (_s = nounEntry == null ? void 0 : nounEntry.label) != null ? _s : _issue.format; + const gender = (_t = nounEntry == null ? void 0 : nounEntry.gender) != null ? _t : "m"; + const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF"; + return `${noun} \u05DC\u05D0 ${adjective}`; + } + case "not_multiple_of": + return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; + case "unrecognized_keys": + return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": { + return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`; + } + case "invalid_union": + return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; + case "invalid_element": { + const place = withDefinite((_u = issue2.origin) != null ? _u : "array"); + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`; + } + default: + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; + } + }; +}; +function he_default() { + return { + localeError: error16() + }; +} + +// node_modules/zod/v4/locales/hu.js +var error17 = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "bemenet", + email: "email c\xEDm", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO id\u0151b\xE9lyeg", + date: "ISO d\xE1tum", + time: "ISO id\u0151", + duration: "ISO id\u0151intervallum", + ipv4: "IPv4 c\xEDm", + ipv6: "IPv6 c\xEDm", + cidrv4: "IPv4 tartom\xE1ny", + cidrv6: "IPv6 tartom\xE1ny", + base64: "base64-k\xF3dolt string", + base64url: "base64url-k\xF3dolt string", + json_string: "JSON string", + e164: "E.164 sz\xE1m", + jwt: "JWT", + template_literal: "bemenet" + }; + const TypeDictionary = { + nan: "NaN", + number: "sz\xE1m", + array: "t\xF6mb" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`; + } + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; + return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xFAl nagy: ${(_c = issue2.origin) != null ? _c : "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elem"}`; + return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${(_e = issue2.origin) != null ? _e : "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; + if (_issue.format === "ends_with") + return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; + if (_issue.format === "includes") + return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; + if (_issue.format === "regex") + return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; + return `\xC9rv\xE9nytelen ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; + case "invalid_union": + return "\xC9rv\xE9nytelen bemenet"; + case "invalid_element": + return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; + default: + return `\xC9rv\xE9nytelen bemenet`; + } + }; +}; +function hu_default() { + return { + localeError: error17() + }; +} + +// node_modules/zod/v4/locales/hy.js +function getArmenianPlural(count, one, many) { + return Math.abs(count) === 1 ? one : many; +} +function withDefiniteArticle(word) { + if (!word) + return ""; + const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"]; + const lastChar = word[word.length - 1]; + return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568"); +} +var error18 = () => { + const Sizable = { + string: { + unit: { + one: "\u0576\u0577\u0561\u0576", + many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + file: { + unit: { + one: "\u0562\u0561\u0575\u0569", + many: "\u0562\u0561\u0575\u0569\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + array: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + }, + set: { + unit: { + one: "\u057F\u0561\u0580\u0580", + many: "\u057F\u0561\u0580\u0580\u0565\u0580" + }, + verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C" + } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0574\u0578\u0582\u057F\u0584", + email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565", + url: "URL", + emoji: "\u0567\u0574\u0578\u057B\u056B", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574", + date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E", + time: "ISO \u056A\u0561\u0574", + duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576", + ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565", + ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565", + cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584", + base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572", + json_string: "JSON \u057F\u0578\u0572", + e164: "E.164 \u0570\u0561\u0574\u0561\u0580", + jwt: "JWT", + template_literal: "\u0574\u0578\u0582\u057F\u0584" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0569\u056B\u057E", + array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`; + return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle((_c = issue2.origin) != null ? _c : "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle((_d = issue2.origin) != null ? _d : "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many); + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`; + if (_issue.format === "ends_with") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`; + if (_issue.format === "includes") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`; + return `\u054D\u056D\u0561\u056C ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`; + } + case "not_multiple_of": + return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`; + case "unrecognized_keys": + return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + case "invalid_union": + return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"; + case "invalid_element": + return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`; + default: + return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`; + } + }; +}; +function hy_default() { + return { + localeError: error18() + }; +} + +// node_modules/zod/v4/locales/id.js +var error19 = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak valid: diharapkan ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: diharapkan ${(_c = issue2.origin) != null ? _c : "value"} memiliki ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elemen"}`; + return `Terlalu besar: diharapkan ${(_e = issue2.origin) != null ? _e : "value"} menjadi ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue2.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue2.origin}`; + default: + return `Input tidak valid`; + } + }; +}; +function id_default() { + return { + localeError: error19() + }; +} + +// node_modules/zod/v4/locales/is.js +var error20 = () => { + const Sizable = { + string: { unit: "stafi", verb: "a\xF0 hafa" }, + file: { unit: "b\xE6ti", verb: "a\xF0 hafa" }, + array: { unit: "hluti", verb: "a\xF0 hafa" }, + set: { unit: "hluti", verb: "a\xF0 hafa" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "gildi", + email: "netfang", + url: "vefsl\xF3\xF0", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dagsetning og t\xEDmi", + date: "ISO dagsetning", + time: "ISO t\xEDmi", + duration: "ISO t\xEDmalengd", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded strengur", + base64url: "base64url-encoded strengur", + json_string: "JSON strengur", + e164: "E.164 t\xF6lugildi", + jwt: "JWT", + template_literal: "gildi" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmer", + array: "fylki" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`; + } + return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`; + return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${(_c = issue2.origin) != null ? _c : "gildi"} hafi ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "hluti"}`; + return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${(_e = issue2.origin) != null ? _e : "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`; + if (_issue.format === "regex") + return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`; + return `Rangt ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`; + case "unrecognized_keys": + return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Rangur lykill \xED ${issue2.origin}`; + case "invalid_union": + return "Rangt gildi"; + case "invalid_element": + return `Rangt gildi \xED ${issue2.origin}`; + default: + return `Rangt gildi`; + } + }; +}; +function is_default() { + return { + localeError: error20() + }; +} + +// node_modules/zod/v4/locales/it.js +var error21 = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "numero", + array: "vettore" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`; + } + return `Input non valido: atteso ${expected}, ricevuto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Troppo grande: ${(_c = issue2.origin) != null ? _c : "valore"} deve avere ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementi"}`; + return `Troppo grande: ${(_e = issue2.origin) != null ? _e : "valore"} deve essere ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; + case "unrecognized_keys": + return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue2.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue2.origin}`; + default: + return `Input non valido`; + } + }; +}; +function it_default() { + return { + localeError: error21() + }; +} + +// node_modules/zod/v4/locales/ja.js +var error22 = () => { + const Sizable = { + string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, + file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, + array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u5165\u529B\u5024", + email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", + url: "URL", + emoji: "\u7D75\u6587\u5B57", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u6642", + date: "ISO\u65E5\u4ED8", + time: "ISO\u6642\u523B", + duration: "ISO\u671F\u9593", + ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", + ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + cidrv4: "IPv4\u7BC4\u56F2", + cidrv6: "IPv6\u7BC4\u56F2", + base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + json_string: "JSON\u6587\u5B57\u5217", + e164: "E.164\u756A\u53F7", + jwt: "JWT", + template_literal: "\u5165\u529B\u5024" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5024", + array: "\u914D\u5217" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; + return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "too_big": { + const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_c = issue2.origin) != null ? _c : "\u5024"}\u306F${issue2.maximum.toString()}${(_d = sizing.unit) != null ? _d : "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_e = issue2.origin) != null ? _e : "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "ends_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "includes") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "regex") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u7121\u52B9\u306A${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "unrecognized_keys": + return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; + case "invalid_union": + return "\u7121\u52B9\u306A\u5165\u529B"; + case "invalid_element": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; + default: + return `\u7121\u52B9\u306A\u5165\u529B`; + } + }; +}; +function ja_default() { + return { + localeError: error22() + }; +} + +// node_modules/zod/v4/locales/ka.js +var error23 = () => { + const Sizable = { + string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }, + set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0", + email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + url: "URL", + emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD", + date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8", + time: "\u10D3\u10E0\u10DD", + duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0", + ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8", + cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8", + base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8", + jwt: "JWT", + template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8", + string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8", + boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8", + function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0", + array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${(_c = issue2.origin) != null ? _c : "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${(_d = issue2.origin) != null ? _d : "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`; + } + if (_issue.format === "ends_with") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`; + if (_issue.format === "includes") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`; + if (_issue.format === "regex") + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`; + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`; + } + case "not_multiple_of": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`; + case "unrecognized_keys": + return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`; + case "invalid_union": + return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"; + case "invalid_element": + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`; + default: + return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`; + } + }; +}; +function ka_default() { + return { + localeError: error23() + }; +} + +// node_modules/zod/v4/locales/km.js +var error24 = () => { + const Sizable = { + string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", + email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", + url: "URL", + emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", + date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", + time: "\u1798\u17C9\u17C4\u1784 ISO", + duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", + ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", + base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", + json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", + e164: "\u179B\u17C1\u1781 E.164", + jwt: "JWT", + template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u179B\u17C1\u1781", + array: "\u17A2\u17B6\u179A\u17C1 (Array)", + null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; + return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_c = issue2.origin) != null ? _c : "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u1792\u17B6\u178F\u17BB"}`; + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_e = issue2.origin) != null ? _e : "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; + return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + case "invalid_union": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + case "invalid_element": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + default: + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + } + }; +}; +function km_default() { + return { + localeError: error24() + }; +} + +// node_modules/zod/v4/locales/kh.js +function kh_default() { + return km_default(); +} + +// node_modules/zod/v4/locales/ko.js +var error25 = () => { + const Sizable = { + string: { unit: "\uBB38\uC790", verb: "to have" }, + file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, + array: { unit: "\uAC1C", verb: "to have" }, + set: { unit: "\uAC1C", verb: "to have" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\uC785\uB825", + email: "\uC774\uBA54\uC77C \uC8FC\uC18C", + url: "URL", + emoji: "\uC774\uBAA8\uC9C0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", + date: "ISO \uB0A0\uC9DC", + time: "ISO \uC2DC\uAC04", + duration: "ISO \uAE30\uAC04", + ipv4: "IPv4 \uC8FC\uC18C", + ipv6: "IPv6 \uC8FC\uC18C", + cidrv4: "IPv4 \uBC94\uC704", + cidrv6: "IPv6 \uBC94\uC704", + base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + json_string: "JSON \uBB38\uC790\uC5F4", + e164: "E.164 \uBC88\uD638", + jwt: "JWT", + template_literal: "\uC785\uB825" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "too_big": { + const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; + const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = (_c = sizing == null ? void 0 : sizing.unit) != null ? _c : "\uC694\uC18C"; + if (sizing) + return `${(_d = issue2.origin) != null ? _d : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; + return `${(_e = issue2.origin) != null ? _e : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; + const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = (_f = sizing == null ? void 0 : sizing.unit) != null ? _f : "\uC694\uC18C"; + if (sizing) { + return `${(_g = issue2.origin) != null ? _g : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${(_h = issue2.origin) != null ? _h : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; + } + if (_issue.format === "ends_with") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "includes") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "regex") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C ${(_i = FormatDictionary[_issue.format]) != null ? _i : issue2.format}`; + } + case "not_multiple_of": + return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "unrecognized_keys": + return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; + case "invalid_union": + return `\uC798\uBABB\uB41C \uC785\uB825`; + case "invalid_element": + return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; + default: + return `\uC798\uBABB\uB41C \uC785\uB825`; + } + }; +}; +function ko_default() { + return { + localeError: error25() + }; +} + +// node_modules/zod/v4/locales/lt.js +var capitalizeFirstCharacter = (text) => { + return text.charAt(0).toUpperCase() + text.slice(1); +}; +function getUnitTypeFromNumber(number5) { + const abs = Math.abs(number5); + const last = abs % 10; + const last2 = abs % 100; + if (last2 >= 11 && last2 <= 19 || last === 0) + return "many"; + if (last === 1) + return "one"; + return "few"; +} +var error26 = () => { + const Sizable = { + string: { + unit: { + one: "simbolis", + few: "simboliai", + many: "simboli\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip", + notInclusive: "turi b\u016Bti trumpesn\u0117 kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip", + notInclusive: "turi b\u016Bti ilgesn\u0117 kaip" + } + } + }, + file: { + unit: { + one: "baitas", + few: "baitai", + many: "bait\u0173" + }, + verb: { + smaller: { + inclusive: "turi b\u016Bti ne didesnis kaip", + notInclusive: "turi b\u016Bti ma\u017Eesnis kaip" + }, + bigger: { + inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip", + notInclusive: "turi b\u016Bti didesnis kaip" + } + } + }, + array: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + }, + set: { + unit: { + one: "element\u0105", + few: "elementus", + many: "element\u0173" + }, + verb: { + smaller: { + inclusive: "turi tur\u0117ti ne daugiau kaip", + notInclusive: "turi tur\u0117ti ma\u017Eiau kaip" + }, + bigger: { + inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip", + notInclusive: "turi tur\u0117ti daugiau kaip" + } + } + } + }; + function getSizing(origin, unitType, inclusive, targetShouldBe) { + var _a3; + const result = (_a3 = Sizable[origin]) != null ? _a3 : null; + if (result === null) + return result; + return { + unit: result.unit[unitType], + verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"] + }; + } + const FormatDictionary = { + regex: "\u012Fvestis", + email: "el. pa\u0161to adresas", + url: "URL", + emoji: "jaustukas", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO data ir laikas", + date: "ISO data", + time: "ISO laikas", + duration: "ISO trukm\u0117", + ipv4: "IPv4 adresas", + ipv6: "IPv6 adresas", + cidrv4: "IPv4 tinklo prefiksas (CIDR)", + cidrv6: "IPv6 tinklo prefiksas (CIDR)", + base64: "base64 u\u017Ekoduota eilut\u0117", + base64url: "base64url u\u017Ekoduota eilut\u0117", + json_string: "JSON eilut\u0117", + e164: "E.164 numeris", + jwt: "JWT", + template_literal: "\u012Fvestis" + }; + const TypeDictionary = { + nan: "NaN", + number: "skai\u010Dius", + bigint: "sveikasis skai\u010Dius", + string: "eilut\u0117", + boolean: "login\u0117 reik\u0161m\u0117", + undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117", + function: "funkcija", + symbol: "simbolis", + array: "masyvas", + object: "objektas", + null: "nulin\u0117 reik\u0161m\u0117" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`; + } + return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`; + return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`; + case "too_big": { + const origin = (_c = TypeDictionary[issue2.origin]) != null ? _c : issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), (_d = issue2.inclusive) != null ? _d : false, "smaller"); + if (sizing == null ? void 0 : sizing.verb) + return `${capitalizeFirstCharacter((_e = origin != null ? origin : issue2.origin) != null ? _e : "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${(_f = sizing.unit) != null ? _f : "element\u0173"}`; + const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip"; + return `${capitalizeFirstCharacter((_g = origin != null ? origin : issue2.origin) != null ? _g : "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing == null ? void 0 : sizing.unit}`; + } + case "too_small": { + const origin = (_h = TypeDictionary[issue2.origin]) != null ? _h : issue2.origin; + const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), (_i = issue2.inclusive) != null ? _i : false, "bigger"); + if (sizing == null ? void 0 : sizing.verb) + return `${capitalizeFirstCharacter((_j = origin != null ? origin : issue2.origin) != null ? _j : "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${(_k = sizing.unit) != null ? _k : "element\u0173"}`; + const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip"; + return `${capitalizeFirstCharacter((_l = origin != null ? origin : issue2.origin) != null ? _l : "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing == null ? void 0 : sizing.unit}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`; + if (_issue.format === "regex") + return `Eilut\u0117 privalo atitikti ${_issue.pattern}`; + return `Neteisingas ${(_m = FormatDictionary[_issue.format]) != null ? _m : issue2.format}`; + } + case "not_multiple_of": + return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`; + case "unrecognized_keys": + return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Rastas klaidingas raktas"; + case "invalid_union": + return "Klaidinga \u012Fvestis"; + case "invalid_element": { + const origin = (_n = TypeDictionary[issue2.origin]) != null ? _n : issue2.origin; + return `${capitalizeFirstCharacter((_o = origin != null ? origin : issue2.origin) != null ? _o : "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`; + } + default: + return "Klaidinga \u012Fvestis"; + } + }; +}; +function lt_default() { + return { + localeError: error26() + }; +} + +// node_modules/zod/v4/locales/mk.js +var error27 = () => { + const Sizable = { + string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0432\u043D\u0435\u0441", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", + url: "URL", + emoji: "\u0435\u043C\u043E\u045F\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0443\u043C", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", + cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", + base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + json_string: "JSON \u043D\u0438\u0437\u0430", + e164: "E.164 \u0431\u0440\u043E\u0458", + jwt: "JWT", + template_literal: "\u0432\u043D\u0435\u0441" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0431\u0440\u043E\u0458", + array: "\u043D\u0438\u0437\u0430" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_c = issue2.origin) != null ? _c : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_e = issue2.origin) != null ? _e : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; + return `Invalid ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; + case "invalid_union": + return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; + case "invalid_element": + return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; + default: + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; + } + }; +}; +function mk_default() { + return { + localeError: error27() + }; +} + +// node_modules/zod/v4/locales/ms.js +var error28 = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "nombor" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`; + } + return `Input tidak sah: dijangka ${expected}, diterima ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: dijangka ${(_c = issue2.origin) != null ? _c : "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elemen"}`; + return `Terlalu besar: dijangka ${(_e = issue2.origin) != null ? _e : "nilai"} adalah ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue2.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue2.origin}`; + default: + return `Input tidak sah`; + } + }; +}; +function ms_default() { + return { + localeError: error28() + }; +} + +// node_modules/zod/v4/locales/nl.js +var error29 = () => { + const Sizable = { + string: { unit: "tekens", verb: "heeft" }, + file: { unit: "bytes", verb: "heeft" }, + array: { unit: "elementen", verb: "heeft" }, + set: { unit: "elementen", verb: "heeft" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer" + }; + const TypeDictionary = { + nan: "NaN", + number: "getal" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`; + } + return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; + return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot"; + if (sizing) + return `Te ${longName}: verwacht dat ${(_c = issue2.origin) != null ? _c : "waarde"} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementen"} ${sizing.verb}`; + return `Te ${longName}: verwacht dat ${(_e = issue2.origin) != null ? _e : "waarde"} ${adj}${issue2.maximum.toString()} is`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein"; + if (sizing) { + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue2.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue2.origin}`; + default: + return `Ongeldige invoer`; + } + }; +}; +function nl_default() { + return { + localeError: error29() + }; +} + +// node_modules/zod/v4/locales/no.js +var error30 = () => { + const Sizable = { + string: { unit: "tegn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "elementer", verb: "\xE5 inneholde" }, + set: { unit: "elementer", verb: "\xE5 inneholde" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "tall", + array: "liste" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`; + } + return `Ugyldig input: forventet ${expected}, fikk ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventet ${(_c = issue2.origin) != null ? _c : "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementer"}`; + return `For stor(t): forventet ${(_e = issue2.origin) != null ? _e : "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +function no_default() { + return { + localeError: error30() + }; +} + +// node_modules/zod/v4/locales/ota.js +var error31 = () => { + const Sizable = { + string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "giren", + email: "epostag\xE2h", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO heng\xE2m\u0131", + date: "ISO tarihi", + time: "ISO zaman\u0131", + duration: "ISO m\xFCddeti", + ipv4: "IPv4 ni\u015F\xE2n\u0131", + ipv6: "IPv6 ni\u015F\xE2n\u0131", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-\u015Fifreli metin", + base64url: "base64url-\u015Fifreli metin", + json_string: "JSON metin", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "giren" + }; + const TypeDictionary = { + nan: "NaN", + number: "numara", + array: "saf", + null: "gayb" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; + return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Fazla b\xFCy\xFCk: ${(_c = issue2.origin) != null ? _c : "value"}, ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elements"} sahip olmal\u0131yd\u0131.`; + return `Fazla b\xFCy\xFCk: ${(_e = issue2.origin) != null ? _e : "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; + } + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; + if (_issue.format === "ends_with") + return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; + if (_issue.format === "regex") + return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; + return `F\xE2sit ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; + case "invalid_union": + return "Giren tan\u0131namad\u0131."; + case "invalid_element": + return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; + default: + return `K\u0131ymet tan\u0131namad\u0131.`; + } + }; +}; +function ota_default() { + return { + localeError: error31() + }; +} + +// node_modules/zod/v4/locales/ps.js +var error32 = () => { + const Sizable = { + string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, + array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0648\u0631\u0648\u062F\u064A", + email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", + date: "\u0646\u06D0\u067C\u0647", + time: "\u0648\u062E\u062A", + duration: "\u0645\u0648\u062F\u0647", + ipv4: "\u062F IPv4 \u067E\u062A\u0647", + ipv6: "\u062F IPv6 \u067E\u062A\u0647", + cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", + cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", + base64: "base64-encoded \u0645\u062A\u0646", + base64url: "base64url-encoded \u0645\u062A\u0646", + json_string: "JSON \u0645\u062A\u0646", + e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u064A" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0639\u062F\u062F", + array: "\u0627\u0631\u06D0" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + } + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; + } + return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_c = issue2.origin) != null ? _c : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_e = issue2.origin) != null ? _e : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; + } + if (_issue.format === "ends_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; + } + if (_issue.format === "includes") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; + } + if (_issue.format === "regex") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; + } + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; + } + case "not_multiple_of": + return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; + case "unrecognized_keys": + return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + case "invalid_union": + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + case "invalid_element": + return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + default: + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + } + }; +}; +function ps_default() { + return { + localeError: error32() + }; +} + +// node_modules/zod/v4/locales/pl.js +var error33 = () => { + const Sizable = { + string: { unit: "znak\xF3w", verb: "mie\u0107" }, + file: { unit: "bajt\xF3w", verb: "mie\u0107" }, + array: { unit: "element\xF3w", verb: "mie\u0107" }, + set: { unit: "element\xF3w", verb: "mie\u0107" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "wyra\u017Cenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", + base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", + json_string: "ci\u0105g znak\xF3w w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wej\u015Bcie" + }; + const TypeDictionary = { + nan: "NaN", + number: "liczba", + array: "tablica" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`; + } + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; + return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${(_c = issue2.origin) != null ? _c : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "element\xF3w"}`; + } + return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${(_e = issue2.origin) != null ? _e : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${(_f = issue2.origin) != null ? _f : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${(_g = sizing.unit) != null ? _g : "element\xF3w"}`; + } + return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${(_h = issue2.origin) != null ? _h : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; + return `Nieprawid\u0142ow(y/a/e) ${(_i = FormatDictionary[_issue.format]) != null ? _i : issue2.format}`; + } + case "not_multiple_of": + return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nieprawid\u0142owy klucz w ${issue2.origin}`; + case "invalid_union": + return "Nieprawid\u0142owe dane wej\u015Bciowe"; + case "invalid_element": + return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; + default: + return `Nieprawid\u0142owe dane wej\u015Bciowe`; + } + }; +}; +function pl_default() { + return { + localeError: error33() + }; +} + +// node_modules/zod/v4/locales/pt.js +var error34 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "padr\xE3o", + email: "endere\xE7o de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "dura\xE7\xE3o ISO", + ipv4: "endere\xE7o IPv4", + ipv6: "endere\xE7o IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\xFAmero", + null: "nulo" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`; + } + return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Muito grande: esperado que ${(_c = issue2.origin) != null ? _c : "valor"} tivesse ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementos"}`; + return `Muito grande: esperado que ${(_e = issue2.origin) != null ? _e : "valor"} fosse ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chave inv\xE1lida em ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido em ${issue2.origin}`; + default: + return `Campo inv\xE1lido`; + } + }; +}; +function pt_default() { + return { + localeError: error34() + }; +} + +// node_modules/zod/v4/locales/ru.js +function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +var error35 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0438\u043C\u0432\u043E\u043B", + few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", + many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u0430", + many: "\u0431\u0430\u0439\u0442" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0432\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u044F", + duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", + base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", + json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0432\u043E\u0434" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0441\u0438\u0432" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_c = issue2.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_d = issue2.origin) != null ? _d : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; + case "invalid_element": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; + } + }; +}; +function ru_default() { + return { + localeError: error35() + }; +} + +// node_modules/zod/v4/locales/sl.js +var error36 = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "vnos", + email: "e-po\u0161tni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in \u010Das", + date: "ISO datum", + time: "ISO \u010Das", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 \u0161tevilka", + jwt: "JWT", + template_literal: "vnos" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0161tevilo", + array: "tabela" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`; + } + return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; + return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Preveliko: pri\u010Dakovano, da bo ${(_c = issue2.origin) != null ? _c : "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "elementov"}`; + return `Preveliko: pri\u010Dakovano, da bo ${(_e = issue2.origin) != null ? _e : "vrednost"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neveljaven klju\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue2.origin}`; + default: + return "Neveljaven vnos"; + } + }; +}; +function sl_default() { + return { + localeError: error36() + }; +} + +// node_modules/zod/v4/locales/sv.js +var error37 = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att inneh\xE5lla" }, + set: { unit: "objekt", verb: "att inneh\xE5lla" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "regulj\xE4rt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad str\xE4ng", + base64url: "base64url-kodad str\xE4ng", + json_string: "JSON-str\xE4ng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal" + }; + const TypeDictionary = { + nan: "NaN", + number: "antal", + array: "lista" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`; + } + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; + return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r stor(t): f\xF6rv\xE4ntade ${(_c = issue2.origin) != null ? _c : "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "element"}`; + } + return `F\xF6r stor(t): f\xF6rv\xE4ntat ${(_e = issue2.origin) != null ? _e : "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_f = issue2.origin) != null ? _f : "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_g = issue2.origin) != null ? _g : "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; + return `Ogiltig(t) ${(_h = FormatDictionary[_issue.format]) != null ? _h : issue2.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${(_i = issue2.origin) != null ? _i : "v\xE4rdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt v\xE4rde i ${(_j = issue2.origin) != null ? _j : "v\xE4rdet"}`; + default: + return `Ogiltig input`; + } + }; +}; +function sv_default() { + return { + localeError: error37() + }; +} + +// node_modules/zod/v4/locales/ta.js +var error38 = () => { + const Sizable = { + string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", + email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", + time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", + ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", + e164: "E.164 \u0B8E\u0BA3\u0BCD", + jwt: "JWT", + template_literal: "input" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0B8E\u0BA3\u0BCD", + array: "\u0B85\u0BA3\u0BBF", + null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_c = issue2.origin) != null ? _c : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_e = issue2.origin) != null ? _e : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "ends_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "includes") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "regex") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + case "unrecognized_keys": + return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; + case "invalid_union": + return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; + case "invalid_element": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; + default: + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; + } + }; +}; +function ta_default() { + return { + localeError: error38() + }; +} + +// node_modules/zod/v4/locales/th.js +var error39 = () => { + const Sizable = { + string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", + email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", + url: "URL", + emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", + time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", + ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", + cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", + base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", + base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", + json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", + e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", + template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02", + array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)", + null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_c = issue2.origin) != null ? _c : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_e = issue2.origin) != null ? _e : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; + if (_issue.format === "regex") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; + case "unrecognized_keys": + return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + case "invalid_union": + return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; + case "invalid_element": + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + default: + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; + } + }; +}; +function th_default() { + return { + localeError: error39() + }; +} + +// node_modules/zod/v4/locales/tr.js +var error40 = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmal\u0131" }, + file: { unit: "bayt", verb: "olmal\u0131" }, + array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO s\xFCre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aral\u0131\u011F\u0131", + cidrv6: "IPv6 aral\u0131\u011F\u0131", + base64: "base64 ile \u015Fifrelenmi\u015F metin", + base64url: "base64url ile \u015Fifrelenmi\u015F metin", + json_string: "JSON dizesi", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "\u015Eablon dizesi" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`; + } + return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; + return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok b\xFCy\xFCk: beklenen ${(_c = issue2.origin) != null ? _c : "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\xF6\u011Fe"}`; + return `\xC7ok b\xFCy\xFCk: beklenen ${(_e = issue2.origin) != null ? _e : "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; + if (_issue.format === "ends_with") + return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; + if (_issue.format === "regex") + return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; + return `Ge\xE7ersiz ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; + case "invalid_union": + return "Ge\xE7ersiz de\u011Fer"; + case "invalid_element": + return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; + default: + return `Ge\xE7ersiz de\u011Fer`; + } + }; +}; +function tr_default() { + return { + localeError: error40() + }; +} + +// node_modules/zod/v4/locales/uk.js +var error41 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", + date: "\u0434\u0430\u0442\u0430 ISO", + time: "\u0447\u0430\u0441 ISO", + duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", + ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", + ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", + cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", + base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", + base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", + json_string: "\u0440\u044F\u0434\u043E\u043A JSON", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0447\u0438\u0441\u043B\u043E", + array: "\u043C\u0430\u0441\u0438\u0432" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_c = issue2.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_e = issue2.origin) != null ? _e : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; + case "invalid_element": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; + default: + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; + } + }; +}; +function uk_default() { + return { + localeError: error41() + }; +} + +// node_modules/zod/v4/locales/ua.js +function ua_default() { + return uk_default(); +} + +// node_modules/zod/v4/locales/ur.js +var error42 = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, + file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, + array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0627\u0646 \u067E\u0679", + email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", + uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", + nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", + guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", + ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", + xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", + ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", + date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", + time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", + duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", + ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", + ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", + cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", + base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", + e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", + template_literal: "\u0627\u0646 \u067E\u0679" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u0646\u0645\u0628\u0631", + array: "\u0622\u0631\u06D2", + null: "\u0646\u0644" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_c = issue2.origin) != null ? _c : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_e = issue2.origin) != null ? _e : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + } + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + } + if (_issue.format === "ends_with") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "includes") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "regex") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + return `\u063A\u0644\u0637 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + case "unrecognized_keys": + return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; + case "invalid_union": + return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; + case "invalid_element": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; + default: + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; + } + }; +}; +function ur_default() { + return { + localeError: error42() + }; +} + +// node_modules/zod/v4/locales/uz.js +var error43 = () => { + const Sizable = { + string: { unit: "belgi", verb: "bo\u2018lishi kerak" }, + file: { unit: "bayt", verb: "bo\u2018lishi kerak" }, + array: { unit: "element", verb: "bo\u2018lishi kerak" }, + set: { unit: "element", verb: "bo\u2018lishi kerak" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "kirish", + email: "elektron pochta manzili", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO sana va vaqti", + date: "ISO sana", + time: "ISO vaqt", + duration: "ISO davomiylik", + ipv4: "IPv4 manzil", + ipv6: "IPv6 manzil", + mac: "MAC manzil", + cidrv4: "IPv4 diapazon", + cidrv6: "IPv6 diapazon", + base64: "base64 kodlangan satr", + base64url: "base64url kodlangan satr", + json_string: "JSON satr", + e164: "E.164 raqam", + jwt: "JWT", + template_literal: "kirish" + }; + const TypeDictionary = { + nan: "NaN", + number: "raqam", + array: "massiv" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`; + } + return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`; + return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Juda katta: kutilgan ${(_c = issue2.origin) != null ? _c : "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`; + return `Juda katta: kutilgan ${(_d = issue2.origin) != null ? _d : "qiymat"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`; + } + return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`; + if (_issue.format === "ends_with") + return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`; + if (_issue.format === "includes") + return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`; + if (_issue.format === "regex") + return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`; + return `Noto\u2018g\u2018ri ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`; + } + case "not_multiple_of": + return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`; + case "unrecognized_keys": + return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`; + case "invalid_union": + return "Noto\u2018g\u2018ri kirish"; + case "invalid_element": + return `${issue2.origin} da noto\u2018g\u2018ri qiymat`; + default: + return `Noto\u2018g\u2018ri kirish`; + } + }; +}; +function uz_default() { + return { + localeError: error43() + }; +} + +// node_modules/zod/v4/locales/vi.js +var error44 = () => { + const Sizable = { + string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, + file: { unit: "byte", verb: "c\xF3" }, + array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u0111\u1EA7u v\xE0o", + email: "\u0111\u1ECBa ch\u1EC9 email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ng\xE0y gi\u1EDD ISO", + date: "ng\xE0y ISO", + time: "gi\u1EDD ISO", + duration: "kho\u1EA3ng th\u1EDDi gian ISO", + ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", + ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + cidrv4: "d\u1EA3i IPv4", + cidrv6: "d\u1EA3i IPv6", + base64: "chu\u1ED7i m\xE3 h\xF3a base64", + base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", + json_string: "chu\u1ED7i JSON", + e164: "s\u1ED1 E.164", + jwt: "JWT", + template_literal: "\u0111\u1EA7u v\xE0o" + }; + const TypeDictionary = { + nan: "NaN", + number: "s\u1ED1", + array: "m\u1EA3ng" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; + return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_c = issue2.origin) != null ? _c : "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "ph\u1EA7n t\u1EED"}`; + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_e = issue2.origin) != null ? _e : "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; + return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; + } + case "not_multiple_of": + return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; + case "unrecognized_keys": + return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + case "invalid_union": + return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; + case "invalid_element": + return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + default: + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; + } + }; +}; +function vi_default() { + return { + localeError: error44() + }; +} + +// node_modules/zod/v4/locales/zh-CN.js +var error45 = () => { + const Sizable = { + string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, + file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, + array: { unit: "\u9879", verb: "\u5305\u542B" }, + set: { unit: "\u9879", verb: "\u5305\u542B" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u8F93\u5165", + email: "\u7535\u5B50\u90AE\u4EF6", + url: "URL", + emoji: "\u8868\u60C5\u7B26\u53F7", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u671F\u65F6\u95F4", + date: "ISO\u65E5\u671F", + time: "ISO\u65F6\u95F4", + duration: "ISO\u65F6\u957F", + ipv4: "IPv4\u5730\u5740", + ipv6: "IPv6\u5730\u5740", + cidrv4: "IPv4\u7F51\u6BB5", + cidrv6: "IPv6\u7F51\u6BB5", + base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", + base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", + json_string: "JSON\u5B57\u7B26\u4E32", + e164: "E.164\u53F7\u7801", + jwt: "JWT", + template_literal: "\u8F93\u5165" + }; + const TypeDictionary = { + nan: "NaN", + number: "\u6570\u5B57", + array: "\u6570\u7EC4", + null: "\u7A7A\u503C(null)" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; + return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_c = issue2.origin) != null ? _c : "\u503C"} ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u4E2A\u5143\u7D20"}`; + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_e = issue2.origin) != null ? _e : "\u503C"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; + if (_issue.format === "ends_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; + if (_issue.format === "includes") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; + return `\u65E0\u6548${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; + case "unrecognized_keys": + return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; + case "invalid_union": + return "\u65E0\u6548\u8F93\u5165"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; + default: + return `\u65E0\u6548\u8F93\u5165`; + } + }; +}; +function zh_CN_default() { + return { + localeError: error45() + }; +} + +// node_modules/zod/v4/locales/zh-TW.js +var error46 = () => { + const Sizable = { + string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, + file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, + array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u8F38\u5165", + email: "\u90F5\u4EF6\u5730\u5740", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u65E5\u671F\u6642\u9593", + date: "ISO \u65E5\u671F", + time: "ISO \u6642\u9593", + duration: "ISO \u671F\u9593", + ipv4: "IPv4 \u4F4D\u5740", + ipv6: "IPv6 \u4F4D\u5740", + cidrv4: "IPv4 \u7BC4\u570D", + cidrv6: "IPv6 \u7BC4\u570D", + base64: "base64 \u7DE8\u78BC\u5B57\u4E32", + base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", + json_string: "JSON \u5B57\u4E32", + e164: "E.164 \u6578\u503C", + jwt: "JWT", + template_literal: "\u8F38\u5165" + }; + const TypeDictionary = { + nan: "NaN" + }; + return (issue2) => { + var _a3, _b, _c, _d, _e, _f; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; + return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_c = issue2.origin) != null ? _c : "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${(_d = sizing.unit) != null ? _d : "\u500B\u5143\u7D20"}`; + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_e = issue2.origin) != null ? _e : "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; + } + if (_issue.format === "ends_with") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; + if (_issue.format === "includes") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; + return `\u7121\u6548\u7684 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; + case "unrecognized_keys": + return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; + case "invalid_union": + return "\u7121\u6548\u7684\u8F38\u5165\u503C"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; + default: + return `\u7121\u6548\u7684\u8F38\u5165\u503C`; + } + }; +}; +function zh_TW_default() { + return { + localeError: error46() + }; +} + +// node_modules/zod/v4/locales/yo.js +var error47 = () => { + const Sizable = { + string: { unit: "\xE0mi", verb: "n\xED" }, + file: { unit: "bytes", verb: "n\xED" }, + array: { unit: "nkan", verb: "n\xED" }, + set: { unit: "nkan", verb: "n\xED" } + }; + function getSizing(origin) { + var _a3; + return (_a3 = Sizable[origin]) != null ? _a3 : null; + } + const FormatDictionary = { + regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9", + email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\xE0k\xF3k\xF2 ISO", + date: "\u1ECDj\u1ECD\u0301 ISO", + time: "\xE0k\xF3k\xF2 ISO", + duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO", + ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4", + ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6", + cidrv4: "\xE0gb\xE8gb\xE8 IPv4", + cidrv6: "\xE0gb\xE8gb\xE8 IPv6", + base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64", + base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url", + json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON", + e164: "n\u1ECD\u0301mb\xE0 E.164", + jwt: "JWT", + template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9" + }; + const TypeDictionary = { + nan: "NaN", + number: "n\u1ECD\u0301mb\xE0", + array: "akop\u1ECD" + }; + return (issue2) => { + var _a3, _b, _c, _d; + switch (issue2.code) { + case "invalid_type": { + const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected; + const receivedType = parsedType(issue2.input); + const received = (_b = TypeDictionary[receivedType]) != null ? _b : receivedType; + if (/^[A-Z]/.test(issue2.expected)) { + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`; + } + case "invalid_value": + if (issue2.values.length === 1) + return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`; + return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${(_c = issue2.origin) != null ? _c : "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`; + return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`; + return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`; + return `A\u1E63\xEC\u1E63e: ${(_d = FormatDictionary[_issue.format]) != null ? _d : issue2.format}`; + } + case "not_multiple_of": + return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`; + case "unrecognized_keys": + return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + case "invalid_union": + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + case "invalid_element": + return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`; + default: + return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"; + } + }; +}; +function yo_default() { + return { + localeError: error47() + }; +} + +// node_modules/zod/v4/core/registries.js +var _a; +var $output = /* @__PURE__ */ Symbol("ZodOutput"); +var $input = /* @__PURE__ */ Symbol("ZodInput"); var $ZodRegistry = class { constructor() { this._map = /* @__PURE__ */ new WeakMap(); this._idmap = /* @__PURE__ */ new Map(); } add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - if (this._idmap.has(meta.id)) { - throw new Error(`ID ${meta.id} already exists in the registry`); - } - this._idmap.set(meta.id, schema); + const meta3 = _meta[0]; + this._map.set(schema, meta3); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.set(meta3.id, schema); } return this; } + clear() { + this._map = /* @__PURE__ */ new WeakMap(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } remove(schema) { + const meta3 = this._map.get(schema); + if (meta3 && typeof meta3 === "object" && "id" in meta3) { + this._idmap.delete(meta3.id); + } this._map.delete(schema); return this; } get(schema) { - var _a; - const p = schema._zod.parent; - if (p) { - const pm = { ...(_a = this.get(p)) != null ? _a : {} }; + var _a3; + const p2 = schema._zod.parent; + if (p2) { + const pm = { ...(_a3 = this.get(p2)) != null ? _a3 : {} }; delete pm.id; - return { ...pm, ...this._map.get(schema) }; + const f3 = { ...pm, ...this._map.get(schema) }; + return Object.keys(f3).length ? f3 : void 0; } return this._map.get(schema); } @@ -19877,13 +28156,27 @@ var $ZodRegistry = class { function registry() { return new $ZodRegistry(); } -var globalRegistry = /* @__PURE__ */ registry(); +var _a2; +(_a2 = (_a = globalThis).__zod_globalRegistry) != null ? _a2 : _a.__zod_globalRegistry = registry(); +var globalRegistry = globalThis.__zod_globalRegistry; + +// node_modules/zod/v4/core/api.js +// @__NO_SIDE_EFFECTS__ function _string(Class2, params) { return new Class2({ type: "string", ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class2, params) { + return new Class2({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _email(Class2, params) { return new Class2({ type: "string", @@ -19893,6 +28186,7 @@ function _email(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _guid(Class2, params) { return new Class2({ type: "string", @@ -19902,6 +28196,7 @@ function _guid(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _uuid(Class2, params) { return new Class2({ type: "string", @@ -19911,6 +28206,7 @@ function _uuid(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _uuidv4(Class2, params) { return new Class2({ type: "string", @@ -19921,6 +28217,7 @@ function _uuidv4(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _uuidv6(Class2, params) { return new Class2({ type: "string", @@ -19931,6 +28228,7 @@ function _uuidv6(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _uuidv7(Class2, params) { return new Class2({ type: "string", @@ -19941,6 +28239,7 @@ function _uuidv7(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _url(Class2, params) { return new Class2({ type: "string", @@ -19950,6 +28249,7 @@ function _url(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _emoji2(Class2, params) { return new Class2({ type: "string", @@ -19959,6 +28259,7 @@ function _emoji2(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _nanoid(Class2, params) { return new Class2({ type: "string", @@ -19968,6 +28269,7 @@ function _nanoid(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _cuid(Class2, params) { return new Class2({ type: "string", @@ -19977,6 +28279,7 @@ function _cuid(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _cuid2(Class2, params) { return new Class2({ type: "string", @@ -19986,6 +28289,7 @@ function _cuid2(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _ulid(Class2, params) { return new Class2({ type: "string", @@ -19995,6 +28299,7 @@ function _ulid(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _xid(Class2, params) { return new Class2({ type: "string", @@ -20004,6 +28309,7 @@ function _xid(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _ksuid(Class2, params) { return new Class2({ type: "string", @@ -20013,6 +28319,7 @@ function _ksuid(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _ipv4(Class2, params) { return new Class2({ type: "string", @@ -20022,6 +28329,7 @@ function _ipv4(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _ipv6(Class2, params) { return new Class2({ type: "string", @@ -20031,6 +28339,17 @@ function _ipv6(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _mac(Class2, params) { + return new Class2({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _cidrv4(Class2, params) { return new Class2({ type: "string", @@ -20040,6 +28359,7 @@ function _cidrv4(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _cidrv6(Class2, params) { return new Class2({ type: "string", @@ -20049,6 +28369,7 @@ function _cidrv6(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _base64(Class2, params) { return new Class2({ type: "string", @@ -20058,6 +28379,7 @@ function _base64(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _base64url(Class2, params) { return new Class2({ type: "string", @@ -20067,6 +28389,7 @@ function _base64url(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _e164(Class2, params) { return new Class2({ type: "string", @@ -20076,6 +28399,7 @@ function _e164(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _jwt(Class2, params) { return new Class2({ type: "string", @@ -20085,6 +28409,14 @@ function _jwt(Class2, params) { ...normalizeParams(params) }); } +var TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6 +}; +// @__NO_SIDE_EFFECTS__ function _isoDateTime(Class2, params) { return new Class2({ type: "string", @@ -20096,6 +28428,7 @@ function _isoDateTime(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _isoDate(Class2, params) { return new Class2({ type: "string", @@ -20104,6 +28437,7 @@ function _isoDate(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _isoTime(Class2, params) { return new Class2({ type: "string", @@ -20113,6 +28447,7 @@ function _isoTime(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _isoDuration(Class2, params) { return new Class2({ type: "string", @@ -20121,6 +28456,7 @@ function _isoDuration(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _number(Class2, params) { return new Class2({ type: "number", @@ -20128,6 +28464,16 @@ function _number(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class2, params) { + return new Class2({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _int(Class2, params) { return new Class2({ type: "number", @@ -20137,29 +28483,166 @@ function _int(Class2, params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _float32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _boolean(Class2, params) { return new Class2({ type: "boolean", ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class2, params) { + return new Class2({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class2, params) { + return new Class2({ + type: "bigint", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class2, params) { + return new Class2({ + type: "bigint", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class2, params) { + return new Class2({ + type: "symbol", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _undefined2(Class2, params) { + return new Class2({ + type: "undefined", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _null2(Class2, params) { return new Class2({ type: "null", ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _any(Class2) { + return new Class2({ + type: "any" + }); +} +// @__NO_SIDE_EFFECTS__ function _unknown(Class2) { return new Class2({ type: "unknown" }); } +// @__NO_SIDE_EFFECTS__ function _never(Class2, params) { return new Class2({ type: "never", ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _void(Class2, params) { + return new Class2({ + type: "void", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class2, params) { + return new Class2({ + type: "date", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class2, params) { + return new Class2({ + type: "date", + coerce: true, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class2, params) { + return new Class2({ + type: "nan", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _lt(value, params) { return new $ZodCheckLessThan({ check: "less_than", @@ -20168,6 +28651,7 @@ function _lt(value, params) { inclusive: false }); } +// @__NO_SIDE_EFFECTS__ function _lte(value, params) { return new $ZodCheckLessThan({ check: "less_than", @@ -20176,6 +28660,7 @@ function _lte(value, params) { inclusive: true }); } +// @__NO_SIDE_EFFECTS__ function _gt(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", @@ -20184,6 +28669,7 @@ function _gt(value, params) { inclusive: false }); } +// @__NO_SIDE_EFFECTS__ function _gte(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", @@ -20192,6 +28678,23 @@ function _gte(value, params) { inclusive: true }); } +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return /* @__PURE__ */ _gt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return /* @__PURE__ */ _lt(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return /* @__PURE__ */ _lte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return /* @__PURE__ */ _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ function _multipleOf(value, params) { return new $ZodCheckMultipleOf({ check: "multiple_of", @@ -20199,6 +28702,31 @@ function _multipleOf(value, params) { value }); } +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size + }); +} +// @__NO_SIDE_EFFECTS__ function _maxLength(maximum, params) { const ch = new $ZodCheckMaxLength({ check: "max_length", @@ -20207,6 +28735,7 @@ function _maxLength(maximum, params) { }); return ch; } +// @__NO_SIDE_EFFECTS__ function _minLength(minimum, params) { return new $ZodCheckMinLength({ check: "min_length", @@ -20214,6 +28743,7 @@ function _minLength(minimum, params) { minimum }); } +// @__NO_SIDE_EFFECTS__ function _length(length, params) { return new $ZodCheckLengthEquals({ check: "length_equals", @@ -20221,6 +28751,7 @@ function _length(length, params) { length }); } +// @__NO_SIDE_EFFECTS__ function _regex(pattern, params) { return new $ZodCheckRegex({ check: "string_format", @@ -20229,6 +28760,7 @@ function _regex(pattern, params) { pattern }); } +// @__NO_SIDE_EFFECTS__ function _lowercase(params) { return new $ZodCheckLowerCase({ check: "string_format", @@ -20236,6 +28768,7 @@ function _lowercase(params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _uppercase(params) { return new $ZodCheckUpperCase({ check: "string_format", @@ -20243,6 +28776,7 @@ function _uppercase(params) { ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ function _includes(includes, params) { return new $ZodCheckIncludes({ check: "string_format", @@ -20251,6 +28785,7 @@ function _includes(includes, params) { includes }); } +// @__NO_SIDE_EFFECTS__ function _startsWith(prefix, params) { return new $ZodCheckStartsWith({ check: "string_format", @@ -20259,6 +28794,7 @@ function _startsWith(prefix, params) { prefix }); } +// @__NO_SIDE_EFFECTS__ function _endsWith(suffix, params) { return new $ZodCheckEndsWith({ check: "string_format", @@ -20267,35 +28803,260 @@ function _endsWith(suffix, params) { suffix }); } +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ function _overwrite(tx) { return new $ZodCheckOverwrite({ check: "overwrite", tx }); } +// @__NO_SIDE_EFFECTS__ function _normalize(form) { - return _overwrite((input) => input.normalize(form)); + return /* @__PURE__ */ _overwrite((input) => input.normalize(form)); } +// @__NO_SIDE_EFFECTS__ function _trim() { - return _overwrite((input) => input.trim()); + return /* @__PURE__ */ _overwrite((input) => input.trim()); } +// @__NO_SIDE_EFFECTS__ function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); + return /* @__PURE__ */ _overwrite((input) => input.toLowerCase()); } +// @__NO_SIDE_EFFECTS__ function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); + return /* @__PURE__ */ _overwrite((input) => input.toUpperCase()); } +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return /* @__PURE__ */ _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ function _array(Class2, element, params) { return new Class2({ type: "array", element, + // get element() { + // return element; + // }, ...normalizeParams(params) }); } +// @__NO_SIDE_EFFECTS__ +function _union(Class2, options, params) { + return new Class2({ + type: "union", + options, + ...normalizeParams(params) + }); +} +function _xor(Class2, options, params) { + return new Class2({ + type: "union", + options, + inclusive: false, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class2, discriminator, options, params) { + return new Class2({ + type: "union", + options, + discriminator, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class2, left, right) { + return new Class2({ + type: "intersection", + left, + right + }); +} +// @__NO_SIDE_EFFECTS__ +function _tuple(Class2, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class2({ + type: "tuple", + items, + rest, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class2, keyType, valueType, params) { + return new Class2({ + type: "record", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class2, keyType, valueType, params) { + return new Class2({ + type: "map", + keyType, + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class2, valueType, params) { + return new Class2({ + type: "set", + valueType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class2, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v3) => [v3, v3])) : values; + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _nativeEnum(Class2, entries, params) { + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class2, value, params) { + return new Class2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class2, params) { + return new Class2({ + type: "file", + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class2, fn) { + return new Class2({ + type: "transform", + transform: fn + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class2, innerType) { + return new Class2({ + type: "optional", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class2, innerType) { + return new Class2({ + type: "nullable", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class2, innerType, defaultValue) { + return new Class2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + } + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class2, innerType, params) { + return new Class2({ + type: "nonoptional", + innerType, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class2, innerType) { + return new Class2({ + type: "success", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class2, innerType, catchValue) { + return new Class2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class2, in_, out) { + return new Class2({ + type: "pipe", + in: in_, + out + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class2, innerType) { + return new Class2({ + type: "readonly", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class2, parts, params) { + return new Class2({ + type: "template_literal", + parts, + ...normalizeParams(params) + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class2, getter) { + return new Class2({ + type: "lazy", + getter + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class2, innerType) { + return new Class2({ + type: "promise", + innerType + }); +} +// @__NO_SIDE_EFFECTS__ function _custom(Class2, fn, _params) { - var _a; + var _a3; const norm = normalizeParams(_params); - (_a = norm.abort) != null ? _a : norm.abort = true; + (_a3 = norm.abort) != null ? _a3 : norm.abort = true; const schema = new Class2({ type: "custom", check: "custom", @@ -20304,6 +29065,7 @@ function _custom(Class2, fn, _params) { }); return schema; } +// @__NO_SIDE_EFFECTS__ function _refine(Class2, fn, _params) { const schema = new Class2({ type: "custom", @@ -20313,65 +29075,1596 @@ function _refine(Class2, fn, _params) { }); return schema; } -var exports_iso2 = {}; -__export2(exports_iso2, { - time: () => time2, - duration: () => duration2, - datetime: () => datetime2, +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn) { + const ch = /* @__PURE__ */ _check((payload) => { + payload.addIssue = (issue2) => { + var _a3, _b, _c, _d; + if (typeof issue2 === "string") { + payload.issues.push(issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + (_a3 = _issue.code) != null ? _a3 : _issue.code = "custom"; + (_b = _issue.input) != null ? _b : _issue.input = payload.value; + (_c = _issue.inst) != null ? _c : _issue.inst = ch; + (_d = _issue.continue) != null ? _d : _issue.continue = !ch._zod.def.abort; + payload.issues.push(issue(_issue)); + } + }; + return fn(payload.value, payload); + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params) + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + var _a3; + const existing = (_a3 = globalRegistry.get(inst)) != null ? _a3 : {}; + globalRegistry.add(inst, { ...existing, description }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + var _a3; + const existing = (_a3 = globalRegistry.get(inst)) != null ? _a3 : {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + } + ]; + ch._zod.check = () => { + }; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + var _a3, _b, _c, _d, _e; + const params = normalizeParams(_params); + let truthyArray = (_a3 = params.truthy) != null ? _a3 : ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = (_b = params.falsy) != null ? _b : ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v3) => typeof v3 === "string" ? v3.toLowerCase() : v3); + falsyArray = falsyArray.map((v3) => typeof v3 === "string" ? v3.toLowerCase() : v3); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = (_c = Classes.Codec) != null ? _c : $ZodCodec; + const _Boolean = (_d = Classes.Boolean) != null ? _d : $ZodBoolean; + const _String = (_e = Classes.String) != null ? _e : $ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec2 = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } else if (falsySet.has(data)) { + return false; + } else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec2, + continue: false + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } else { + return falsyArray[0] || "false"; + } + }), + error: params.error + }); + return codec2; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class2, format, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def = { + ...normalizeParams(_params), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class2(def); + return inst; +} + +// node_modules/zod/v4/core/to-json-schema.js +function initializeContext(params) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i; + let target = (_a3 = params == null ? void 0 : params.target) != null ? _a3 : "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: (_b = params.processors) != null ? _b : {}, + metadataRegistry: (_c = params == null ? void 0 : params.metadata) != null ? _c : globalRegistry, + target, + unrepresentable: (_d = params == null ? void 0 : params.unrepresentable) != null ? _d : "throw", + override: (_e = params == null ? void 0 : params.override) != null ? _e : (() => { + }), + io: (_f = params == null ? void 0 : params.io) != null ? _f : "output", + counter: 0, + seen: /* @__PURE__ */ new Map(), + cycles: (_g = params == null ? void 0 : params.cycles) != null ? _g : "ref", + reused: (_h = params == null ? void 0 : params.reused) != null ? _h : "inline", + external: (_i = params == null ? void 0 : params.external) != null ? _i : void 0 + }; +} +function process2(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a4, _b, _c; + var _a3; + const def = schema._zod.def; + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + ctx.seen.set(schema, result); + const overrideSchema = (_b = (_a4 = schema._zod).toJSONSchema) == null ? void 0 : _b.call(_a4); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + if (!result.ref) + result.ref = parent; + process2(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + const meta3 = ctx.metadataRegistry.get(schema); + if (meta3) + Object.assign(result.schema, meta3); + if (ctx.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (ctx.io === "input" && result.schema._prefault) + (_c = (_a3 = result.schema).default) != null ? _c : _a3.default = result.schema._prefault; + delete result.schema._prefault; + const _result = ctx.seen.get(schema); + return _result.schema; +} +function extractDefs(ctx, schema) { + var _a3, _b, _c, _d; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const idToSchema = /* @__PURE__ */ new Map(); + for (const entry of ctx.seen.entries()) { + const id = (_a3 = ctx.metadataRegistry.get(entry[0])) == null ? void 0 : _a3.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + const makeURI = (entry) => { + var _a4, _b2, _c2, _d2, _e; + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = (_a4 = ctx.external.registry.get(entry[0])) == null ? void 0 : _a4.id; + const uriGenerator = (_b2 = ctx.external.uri) != null ? _b2 : ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id = (_d2 = (_c2 = entry[1].defId) != null ? _c2 : entry[1].schema.id) != null ? _d2 : `schema${ctx.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = (_e = entry[1].schema.id) != null ? _e : `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema2 = seen.schema; + for (const key in schema2) { + delete schema2[key]; + } + schema2.$ref = ref; + }; + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${(_b = seen.cycle) == null ? void 0 : _b.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (ctx.external) { + const ext = (_c = ctx.external.registry.get(entry[0])) == null ? void 0 : _c.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = (_d = ctx.metadataRegistry.get(entry[0])) == null ? void 0 : _d.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + continue; + } + } + } +} +function finalize(ctx, schema) { + var _a3, _b, _c, _d, _e; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const flattenRef = (zodSchema) => { + var _a4, _b2, _c2; + const seen = ctx.seen.get(zodSchema); + if (seen.ref === null) + return; + const schema2 = (_a4 = seen.def) != null ? _a4 : seen.schema; + const _cached = { ...schema2 }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema2.allOf = (_b2 = schema2.allOf) != null ? _b2 : []; + schema2.allOf.push(refSchema); + } else { + Object.assign(schema2, refSchema); + } + Object.assign(schema2, _cached); + const isParentRef = zodSchema._zod.parent === ref; + if (isParentRef) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema2[key]; + } + } + } + if (refSchema.$ref) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) { + delete schema2[key]; + } + } + } + } + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen == null ? void 0 : parentSeen.schema.$ref) { + schema2.$ref = parentSeen.schema.$ref; + if (parentSeen.def) { + for (const key in schema2) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema2[key]; + } + } + } + } + } + ctx.override({ + zodSchema, + jsonSchema: schema2, + path: (_c2 = seen.path) != null ? _c2 : [] + }); + }; + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } else if (ctx.target === "openapi-3.0") { + } else { + } + if ((_a3 = ctx.external) == null ? void 0 : _a3.uri) { + const id = (_b = ctx.external.registry.get(schema)) == null ? void 0 : _b.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + Object.assign(result, (_c = root.def) != null ? _c : root.schema); + const defs = (_e = (_d = ctx.external) == null ? void 0 : _d.defs) != null ? _e : {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + if (ctx.external) { + } else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors) + } + }, + enumerable: false, + writable: false + }); + return finalized; + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx != null ? _ctx : { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +var createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + process2(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params != null ? params : {}; + const ctx = initializeContext({ ...libraryOptions != null ? libraryOptions : {}, target, io, processors }); + process2(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + +// node_modules/zod/v4/core/json-schema-processors.js +var formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set +}; +var stringProcessor = (schema, ctx, _json, _params) => { + var _a3; + const json2 = _json; + json2.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") + json2.minLength = minimum; + if (typeof maximum === "number") + json2.maxLength = maximum; + if (format) { + json2.format = (_a3 = formatMap[format]) != null ? _a3 : format; + if (json2.format === "") + delete json2.format; + if (format === "time") { + delete json2.format; + } + } + if (contentEncoding) + json2.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json2.pattern = regexes[0].source; + else if (regexes.length > 1) { + json2.allOf = [ + ...regexes.map((regex) => ({ + ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } +}; +var numberProcessor = (schema, ctx, _json, _params) => { + const json2 = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json2.type = "integer"; + else + json2.type = "number"; + if (typeof exclusiveMinimum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.minimum = exclusiveMinimum; + json2.exclusiveMinimum = true; + } else { + json2.exclusiveMinimum = exclusiveMinimum; + } + } + if (typeof minimum === "number") { + json2.minimum = minimum; + if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { + if (exclusiveMinimum >= minimum) + delete json2.minimum; + else + delete json2.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.maximum = exclusiveMaximum; + json2.exclusiveMaximum = true; + } else { + json2.exclusiveMaximum = exclusiveMaximum; + } + } + if (typeof maximum === "number") { + json2.maximum = maximum; + if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { + if (exclusiveMaximum <= maximum) + delete json2.maximum; + else + delete json2.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json2.multipleOf = multipleOf; +}; +var booleanProcessor = (_schema, _ctx, json2, _params) => { + json2.type = "boolean"; +}; +var bigintProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } +}; +var symbolProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } +}; +var nullProcessor = (_schema, ctx, json2, _params) => { + if (ctx.target === "openapi-3.0") { + json2.type = "string"; + json2.nullable = true; + json2.enum = [null]; + } else { + json2.type = "null"; + } +}; +var undefinedProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } +}; +var voidProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } +}; +var neverProcessor = (_schema, _ctx, json2, _params) => { + json2.not = {}; +}; +var anyProcessor = (_schema, _ctx, _json, _params) => { +}; +var unknownProcessor = (_schema, _ctx, _json, _params) => { +}; +var dateProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } +}; +var enumProcessor = (schema, _ctx, json2, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + if (values.every((v3) => typeof v3 === "number")) + json2.type = "number"; + if (values.every((v3) => typeof v3 === "string")) + json2.type = "string"; + json2.enum = values; +}; +var literalProcessor = (schema, ctx, json2, _params) => { + const def = schema._zod.def; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (ctx.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json2.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json2.enum = [val]; + } else { + json2.const = val; + } + } else { + if (vals.every((v3) => typeof v3 === "number")) + json2.type = "number"; + if (vals.every((v3) => typeof v3 === "string")) + json2.type = "string"; + if (vals.every((v3) => typeof v3 === "boolean")) + json2.type = "boolean"; + if (vals.every((v3) => v3 === null)) + json2.type = "null"; + json2.enum = vals; + } +}; +var nanProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } +}; +var templateLiteralProcessor = (schema, _ctx, json2, _params) => { + const _json = json2; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +var fileProcessor = (schema, _ctx, json2, _params) => { + const _json = json2; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== void 0) + file2.minLength = minimum; + if (maximum !== void 0) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(_json, file2); + } else { + Object.assign(_json, file2); + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); + } + } else { + Object.assign(_json, file2); + } +}; +var successProcessor = (_schema, _ctx, json2, _params) => { + json2.type = "boolean"; +}; +var customProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } +}; +var functionProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Function types cannot be represented in JSON Schema"); + } +}; +var transformProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } +}; +var mapProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } +}; +var setProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } +}; +var arrayProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + json2.type = "array"; + json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] }); +}; +var objectProcessor = (schema, ctx, _json, params) => { + var _a3; + const json2 = _json; + const def = schema._zod.def; + json2.type = "object"; + json2.properties = {}; + const shape = def.shape; + for (const key in shape) { + json2.properties[key] = process2(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v3 = def.shape[key]._zod; + if (ctx.io === "input") { + return v3.optin === void 0; + } else { + return v3.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json2.required = Array.from(requiredKeys); + } + if (((_a3 = def.catchall) == null ? void 0 : _a3._zod.def.type) === "never") { + json2.additionalProperties = false; + } else if (!def.catchall) { + if (ctx.io === "output") + json2.additionalProperties = false; + } else if (def.catchall) { + json2.additionalProperties = process2(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } +}; +var unionProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + const isExclusive = def.inclusive === false; + const options = def.options.map((x3, i2) => process2(x3, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i2] + })); + if (isExclusive) { + json2.oneOf = options; + } else { + json2.anyOf = options; + } +}; +var intersectionProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + const a = process2(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b3 = process2(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b3) ? b3.allOf : [b3] + ]; + json2.allOf = allOf; +}; +var tupleProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def = schema._zod.def; + json2.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x3, i2) => process2(x3, ctx, { + ...params, + path: [...params.path, prefixPath, i2] + })); + const rest = def.rest ? process2(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []] + }) : null; + if (ctx.target === "draft-2020-12") { + json2.prefixItems = prefixItems; + if (rest) { + json2.items = rest; + } + } else if (ctx.target === "openapi-3.0") { + json2.items = { + anyOf: prefixItems + }; + if (rest) { + json2.items.anyOf.push(rest); + } + json2.minItems = prefixItems.length; + if (!rest) { + json2.maxItems = prefixItems.length; + } + } else { + json2.items = prefixItems; + if (rest) { + json2.additionalItems = rest; + } + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; +}; +var recordProcessor = (schema, ctx, _json, params) => { + const json2 = _json; + const def = schema._zod.def; + json2.type = "object"; + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag == null ? void 0 : keyBag.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + const valueSchema = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"] + }); + json2.patternProperties = {}; + for (const pattern of patterns) { + json2.patternProperties[pattern.source] = valueSchema; + } + } else { + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json2.propertyNames = process2(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"] + }); + } + json2.additionalProperties = process2(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + const keyValues = keyType._zod.values; + if (keyValues) { + const validKeyValues = [...keyValues].filter((v3) => typeof v3 === "string" || typeof v3 === "number"); + if (validKeyValues.length > 0) { + json2.required = validKeyValues; + } + } +}; +var nullableProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + const inner = process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json2.nullable = true; + } else { + json2.anyOf = [inner, { type: "null" }]; + } +}; +var nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var defaultProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json2.default = JSON.parse(JSON.stringify(def.defaultValue)); +}; +var prefaultProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io === "input") + json2._prefault = JSON.parse(JSON.stringify(def.defaultValue)); +}; +var catchProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch (e2) { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json2.default = catchValue; +}; +var pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var readonlyProcessor = (schema, ctx, json2, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json2.readOnly = true; +}; +var promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + process2(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +var lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + process2(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +var allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + const registry2 = input; + const ctx2 = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + for (const entry of registry2._idmap.entries()) { + const [_, schema] = entry; + process2(schema, ctx2); + } + const schemas = {}; + const external = { + registry: registry2, + uri: params == null ? void 0 : params.uri, + defs + }; + ctx2.external = external; + for (const entry of registry2._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx2, schema); + schemas[key] = finalize(ctx2, schema); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const ctx = initializeContext({ ...params, processors: allProcessors }); + process2(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + +// node_modules/zod/v4/core/json-schema-generator.js +var JSONSchemaGenerator = class { + /** @deprecated Access via ctx instead */ + get metadataRegistry() { + return this.ctx.metadataRegistry; + } + /** @deprecated Access via ctx instead */ + get target() { + return this.ctx.target; + } + /** @deprecated Access via ctx instead */ + get unrepresentable() { + return this.ctx.unrepresentable; + } + /** @deprecated Access via ctx instead */ + get override() { + return this.ctx.override; + } + /** @deprecated Access via ctx instead */ + get io() { + return this.ctx.io; + } + /** @deprecated Access via ctx instead */ + get counter() { + return this.ctx.counter; + } + set counter(value) { + this.ctx.counter = value; + } + /** @deprecated Access via ctx instead */ + get seen() { + return this.ctx.seen; + } + constructor(params) { + var _a3; + let normalizedTarget = (_a3 = params == null ? void 0 : params.target) != null ? _a3 : "draft-2020-12"; + if (normalizedTarget === "draft-4") + normalizedTarget = "draft-04"; + if (normalizedTarget === "draft-7") + normalizedTarget = "draft-07"; + this.ctx = initializeContext({ + processors: allProcessors, + target: normalizedTarget, + ...(params == null ? void 0 : params.metadata) && { metadata: params.metadata }, + ...(params == null ? void 0 : params.unrepresentable) && { unrepresentable: params.unrepresentable }, + ...(params == null ? void 0 : params.override) && { override: params.override }, + ...(params == null ? void 0 : params.io) && { io: params.io } + }); + } + /** + * Process a schema to prepare it for JSON Schema generation. + * This must be called before emit(). + */ + process(schema, _params = { path: [], schemaPath: [] }) { + return process2(schema, this.ctx, _params); + } + /** + * Emit the final JSON Schema after processing. + * Must call process() first. + */ + emit(schema, _params) { + if (_params) { + if (_params.cycles) + this.ctx.cycles = _params.cycles; + if (_params.reused) + this.ctx.reused = _params.reused; + if (_params.external) + this.ctx.external = _params.external; + } + extractDefs(this.ctx, schema); + const result = finalize(this.ctx, schema); + const { "~standard": _, ...plainResult } = result; + return plainResult; + } +}; + +// node_modules/zod/v4/core/json-schema.js +var json_schema_exports = {}; + +// node_modules/zod/v4/mini/schemas.js +var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => { + if (!inst._zod) + throw new Error("Uninitialized schema in ZodMiniType."); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); + inst.check = (...checks) => { + var _a3; + return inst.clone({ + ...def, + checks: [ + ...(_a3 = def.checks) != null ? _a3 : [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + }, { parent: true }); + }; + inst.with = inst.check; + inst.clone = (_def, params) => clone(inst, _def, params); + inst.brand = () => inst; + inst.register = ((reg, meta3) => { + reg.add(inst, meta3); + return inst; + }); + inst.apply = (fn) => fn(inst); +}); +var ZodMiniString = /* @__PURE__ */ $constructor("ZodMiniString", (inst, def) => { + $ZodString.init(inst, def); + ZodMiniType.init(inst, def); +}); +var ZodMiniStringFormat = /* @__PURE__ */ $constructor("ZodMiniStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + ZodMiniString.init(inst, def); +}); +var ZodMiniNumber = /* @__PURE__ */ $constructor("ZodMiniNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodMiniType.init(inst, def); +}); +var ZodMiniBoolean = /* @__PURE__ */ $constructor("ZodMiniBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodMiniType.init(inst, def); +}); +var ZodMiniBigInt = /* @__PURE__ */ $constructor("ZodMiniBigInt", (inst, def) => { + $ZodBigInt.init(inst, def); + ZodMiniType.init(inst, def); +}); +var ZodMiniDate = /* @__PURE__ */ $constructor("ZodMiniDate", (inst, def) => { + $ZodDate.init(inst, def); + ZodMiniType.init(inst, def); +}); + +// node_modules/zod/v4/mini/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodMiniISODate: () => ZodMiniISODate, + ZodMiniISODateTime: () => ZodMiniISODateTime, + ZodMiniISODuration: () => ZodMiniISODuration, + ZodMiniISOTime: () => ZodMiniISOTime, date: () => date2, - ZodISOTime: () => ZodISOTime, - ZodISODuration: () => ZodISODuration, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +var ZodMiniISODateTime = /* @__PURE__ */ $constructor("ZodMiniISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodMiniStringFormat.init(inst, def); +}); +// @__NO_SIDE_EFFECTS__ +function datetime2(params) { + return _isoDateTime(ZodMiniISODateTime, params); +} +var ZodMiniISODate = /* @__PURE__ */ $constructor("ZodMiniISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodMiniStringFormat.init(inst, def); +}); +// @__NO_SIDE_EFFECTS__ +function date2(params) { + return _isoDate(ZodMiniISODate, params); +} +var ZodMiniISOTime = /* @__PURE__ */ $constructor("ZodMiniISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodMiniStringFormat.init(inst, def); +}); +// @__NO_SIDE_EFFECTS__ +function time2(params) { + return _isoTime(ZodMiniISOTime, params); +} +var ZodMiniISODuration = /* @__PURE__ */ $constructor("ZodMiniISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodMiniStringFormat.init(inst, def); +}); +// @__NO_SIDE_EFFECTS__ +function duration2(params) { + return _isoDuration(ZodMiniISODuration, params); +} + +// node_modules/zod/v4/mini/coerce.js +var coerce_exports = {}; +__export(coerce_exports, { + bigint: () => bigint2, + boolean: () => boolean2, + date: () => date3, + number: () => number2, + string: () => string2 +}); +// @__NO_SIDE_EFFECTS__ +function string2(params) { + return _coercedString(ZodMiniString, params); +} +// @__NO_SIDE_EFFECTS__ +function number2(params) { + return _coercedNumber(ZodMiniNumber, params); +} +// @__NO_SIDE_EFFECTS__ +function boolean2(params) { + return _coercedBoolean(ZodMiniBoolean, params); +} +// @__NO_SIDE_EFFECTS__ +function bigint2(params) { + return _coercedBigint(ZodMiniBigInt, params); +} +// @__NO_SIDE_EFFECTS__ +function date3(params) { + return _coercedDate(ZodMiniDate, params); +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js +function isZ4Schema(s) { + const schema = s; + return !!schema._zod; +} +function safeParse2(schema, data) { + if (isZ4Schema(schema)) { + const result2 = safeParse(schema, data); + return result2; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; +} +function getObjectShape(schema) { + var _a3, _b; + if (!schema) + return void 0; + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = (_b = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def) == null ? void 0 : _b.shape; + } else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return void 0; + if (typeof rawShape === "function") { + try { + return rawShape(); + } catch (e2) { + return void 0; + } + } + return rawShape; +} +function getLiteralValue(schema) { + var _a3; + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def2 = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def; + if (def2) { + if (def2.value !== void 0) + return def2.value; + if (Array.isArray(def2.values) && def2.values.length > 0) { + return def2.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== void 0) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + const directValue = schema.value; + if (directValue !== void 0) + return directValue; + return void 0; +} + +// node_modules/zod/v4/classic/schemas.js +var schemas_exports3 = {}; +__export(schemas_exports3, { + ZodAny: () => ZodAny2, + ZodArray: () => ZodArray2, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt2, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean2, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch2, + ZodCodec: () => ZodCodec, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate2, + ZodDefault: () => ZodDefault2, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum2, + ZodExactOptional: () => ZodExactOptional, + ZodFile: () => ZodFile, + ZodFunction: () => ZodFunction2, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodIntersection: () => ZodIntersection2, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy2, + ZodLiteral: () => ZodLiteral2, + ZodMAC: () => ZodMAC, + ZodMap: () => ZodMap2, + ZodNaN: () => ZodNaN2, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever2, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull2, + ZodNullable: () => ZodNullable2, + ZodNumber: () => ZodNumber2, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject2, + ZodOptional: () => ZodOptional2, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise2, + ZodReadonly: () => ZodReadonly2, + ZodRecord: () => ZodRecord2, + ZodSet: () => ZodSet2, + ZodString: () => ZodString2, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol2, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple2, + ZodType: () => ZodType2, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined2, + ZodUnion: () => ZodUnion2, + ZodUnknown: () => ZodUnknown2, + ZodVoid: () => ZodVoid2, + ZodXID: () => ZodXID, + ZodXor: () => ZodXor, + _ZodString: () => _ZodString, + _default: () => _default2, + _function: () => _function, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint3, + boolean: () => boolean3, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + codec: () => codec, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date5, + describe: () => describe2, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + enum: () => _enum2, + exactOptional: () => exactOptional, + file: () => file, + float32: () => float32, + float64: () => float64, + function: () => _function, + guid: () => guid2, + hash: () => hash, + hex: () => hex2, + hostname: () => hostname3, + httpUrl: () => httpUrl, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + ipv4: () => ipv42, + ipv6: () => ipv62, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + literal: () => literal, + looseObject: () => looseObject, + looseRecord: () => looseRecord, + mac: () => mac2, + map: () => map, + meta: () => meta2, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + never: () => never, + nonoptional: () => nonoptional, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number3, + object: () => object2, + optional: () => optional, + partialRecord: () => partialRecord, + pipe: () => pipe, + prefault: () => prefault, + preprocess: () => preprocess, + promise: () => promise, + readonly: () => readonly, + record: () => record, + refine: () => refine, + set: () => set, + strictObject: () => strictObject, + string: () => string3, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + transform: () => transform, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + url: () => url, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + xor: () => xor +}); + +// node_modules/zod/v4/classic/checks.js +var checks_exports2 = {}; +__export(checks_exports2, { + endsWith: () => _endsWith, + gt: () => _gt, + gte: () => _gte, + includes: () => _includes, + length: () => _length, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + negative: () => _negative, + nonnegative: () => _nonnegative, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + overwrite: () => _overwrite, + positive: () => _positive, + property: () => _property, + regex: () => _regex, + size: () => _size, + slugify: () => _slugify, + startsWith: () => _startsWith, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + trim: () => _trim, + uppercase: () => _uppercase +}); + +// node_modules/zod/v4/classic/iso.js +var iso_exports2 = {}; +__export(iso_exports2, { + ZodISODate: () => ZodISODate, ZodISODateTime: () => ZodISODateTime, - ZodISODate: () => ZodISODate + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date4, + datetime: () => datetime3, + duration: () => duration3, + time: () => time3 }); var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { $ZodISODateTime.init(inst, def); ZodStringFormat.init(inst, def); }); -function datetime2(params) { +function datetime3(params) { return _isoDateTime(ZodISODateTime, params); } var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { $ZodISODate.init(inst, def); ZodStringFormat.init(inst, def); }); -function date2(params) { +function date4(params) { return _isoDate(ZodISODate, params); } var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { $ZodISOTime.init(inst, def); ZodStringFormat.init(inst, def); }); -function time2(params) { +function time3(params) { return _isoTime(ZodISOTime, params); } var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { $ZodISODuration.init(inst, def); ZodStringFormat.init(inst, def); }); -function duration2(params) { +function duration3(params) { return _isoDuration(ZodISODuration, params); } + +// node_modules/zod/v4/classic/errors.js var initializer2 = (inst, issues) => { $ZodError.init(inst, issues); inst.name = "ZodError"; Object.defineProperties(inst, { format: { value: (mapper) => formatError(inst, mapper) + // enumerable: false, }, flatten: { value: (mapper) => flattenError(inst, mapper) + // enumerable: false, }, addIssue: { - value: (issue2) => inst.issues.push(issue2) + value: (issue2) => { + inst.issues.push(issue2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, }, addIssues: { - value: (issues2) => inst.issues.push(...issues2) + value: (issues2) => { + inst.issues.push(...issues2); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + } + // enumerable: false, }, isEmpty: { get() { return inst.issues.length === 0; } + // enumerable: false, } }); }; @@ -20379,39 +30672,70 @@ var ZodError2 = $constructor("ZodError", initializer2); var ZodRealError = $constructor("ZodError", initializer2, { Parent: Error }); -var parse4 = /* @__PURE__ */ _parse(ZodRealError); + +// node_modules/zod/v4/classic/parse.js +var parse2 = /* @__PURE__ */ _parse(ZodRealError); var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError); -var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError); +var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); +var encode2 = /* @__PURE__ */ _encode(ZodRealError); +var decode2 = /* @__PURE__ */ _decode(ZodRealError); +var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError); +var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError); +var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError); +var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError); +var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + +// node_modules/zod/v4/classic/schemas.js var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { $ZodType.init(inst, def); + Object.assign(inst["~standard"], { + jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output") + } + }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); inst.def = def; + inst.type = def.type; Object.defineProperty(inst, "_def", { value: def }); - inst.check = (...checks3) => { - var _a; - return inst.clone({ - ...def, + inst.check = (...checks) => { + var _a3; + return inst.clone(util_exports.mergeDefs(def, { checks: [ - ...(_a = def.checks) != null ? _a : [], - ...checks3.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ...(_a3 = def.checks) != null ? _a3 : [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) ] + }), { + parent: true }); }; + inst.with = inst.check; inst.clone = (def2, params) => clone(inst, def2, params); inst.brand = () => inst; - inst.register = (reg, meta) => { - reg.add(inst, meta); + inst.register = ((reg, meta3) => { + reg.add(inst, meta3); return inst; - }; - inst.parse = (data, params) => parse4(inst, data, params, { callee: inst.parse }); + }); + inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); inst.safeParse = (data, params) => safeParse3(inst, data, params); inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync3(inst, data, params); + inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); inst.spa = inst.safeParseAsync; + inst.encode = (data, params) => encode2(inst, data, params); + inst.decode = (data, params) => decode2(inst, data, params); + inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params); + inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params); + inst.safeEncode = (data, params) => safeEncode2(inst, data, params); + inst.safeDecode = (data, params) => safeDecode2(inst, data, params); + inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params); + inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params); inst.refine = (check2, params) => inst.check(refine(check2, params)); inst.superRefine = (refinement) => inst.check(superRefine(refinement)); inst.overwrite = (fn) => inst.check(_overwrite(fn)); inst.optional = () => optional(inst); + inst.exactOptional = () => exactOptional(inst); inst.nullable = () => nullable(inst); inst.nullish = () => optional(nullable(inst)); inst.nonoptional = (params) => nonoptional(inst, params); @@ -20419,9 +30743,9 @@ var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { inst.or = (arg) => union([inst, arg]); inst.and = (arg) => intersection(inst, arg); inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def2) => _default(inst, def2); + inst.default = (def2) => _default2(inst, def2); inst.prefault = (def2) => prefault(inst, def2); - inst.catch = (params) => _catch(inst, params); + inst.catch = (params) => _catch2(inst, params); inst.pipe = (target) => pipe(inst, target); inst.readonly = () => readonly(inst); inst.describe = (description) => { @@ -20431,8 +30755,8 @@ var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { }; Object.defineProperty(inst, "description", { get() { - var _a; - return (_a = globalRegistry.get(inst)) == null ? void 0 : _a.description; + var _a3; + return (_a3 = globalRegistry.get(inst)) == null ? void 0 : _a3.description; }, configurable: true }); @@ -20446,14 +30770,16 @@ var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { }; inst.isOptional = () => inst.safeParse(void 0).success; inst.isNullable = () => inst.safeParse(null).success; + inst.apply = (fn) => fn(inst); return inst; }); var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - var _a, _b, _c; + var _a3, _b, _c; $ZodString.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params); const bag = inst._zod.bag; - inst.format = (_a = bag.format) != null ? _a : null; + inst.format = (_a3 = bag.format) != null ? _a3 : null; inst.minLength = (_b = bag.minimum) != null ? _b : null; inst.maxLength = (_c = bag.maximum) != null ? _c : null; inst.regex = (...args) => inst.check(_regex(...args)); @@ -20470,6 +30796,7 @@ var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { inst.normalize = (...args) => inst.check(_normalize(...args)); inst.toLowerCase = () => inst.check(_toLowerCase()); inst.toUpperCase = () => inst.check(_toUpperCase()); + inst.slugify = () => inst.check(_slugify()); }); var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { $ZodString.init(inst, def); @@ -20497,12 +30824,12 @@ var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); + inst.datetime = (params) => inst.check(datetime3(params)); + inst.date = (params) => inst.check(date4(params)); + inst.time = (params) => inst.check(time3(params)); + inst.duration = (params) => inst.check(duration3(params)); }); -function string2(params) { +function string3(params) { return _string(ZodString2, params); } var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { @@ -20513,82 +30840,185 @@ var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { $ZodEmail.init(inst, def); ZodStringFormat.init(inst, def); }); +function email2(params) { + return _email(ZodEmail, params); +} var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { $ZodGUID.init(inst, def); ZodStringFormat.init(inst, def); }); +function guid2(params) { + return _guid(ZodGUID, params); +} var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { $ZodUUID.init(inst, def); ZodStringFormat.init(inst, def); }); +function uuid2(params) { + return _uuid(ZodUUID, params); +} +function uuidv4(params) { + return _uuidv4(ZodUUID, params); +} +function uuidv6(params) { + return _uuidv6(ZodUUID, params); +} +function uuidv7(params) { + return _uuidv7(ZodUUID, params); +} var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { $ZodURL.init(inst, def); ZodStringFormat.init(inst, def); }); +function url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return _url(ZodURL, { + protocol: /^https?$/, + hostname: regexes_exports.domain, + ...util_exports.normalizeParams(params) + }); +} var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { $ZodEmoji.init(inst, def); ZodStringFormat.init(inst, def); }); +function emoji2(params) { + return _emoji2(ZodEmoji, params); +} var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { $ZodNanoID.init(inst, def); ZodStringFormat.init(inst, def); }); +function nanoid2(params) { + return _nanoid(ZodNanoID, params); +} var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { $ZodCUID.init(inst, def); ZodStringFormat.init(inst, def); }); +function cuid3(params) { + return _cuid(ZodCUID, params); +} var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { $ZodCUID2.init(inst, def); ZodStringFormat.init(inst, def); }); +function cuid22(params) { + return _cuid2(ZodCUID2, params); +} var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { $ZodULID.init(inst, def); ZodStringFormat.init(inst, def); }); +function ulid2(params) { + return _ulid(ZodULID, params); +} var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { $ZodXID.init(inst, def); ZodStringFormat.init(inst, def); }); +function xid2(params) { + return _xid(ZodXID, params); +} var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { $ZodKSUID.init(inst, def); ZodStringFormat.init(inst, def); }); +function ksuid2(params) { + return _ksuid(ZodKSUID, params); +} var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { $ZodIPv4.init(inst, def); ZodStringFormat.init(inst, def); }); +function ipv42(params) { + return _ipv4(ZodIPv4, params); +} +var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => { + $ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function mac2(params) { + return _mac(ZodMAC, params); +} var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { $ZodIPv6.init(inst, def); ZodStringFormat.init(inst, def); }); +function ipv62(params) { + return _ipv6(ZodIPv6, params); +} var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { $ZodCIDRv4.init(inst, def); ZodStringFormat.init(inst, def); }); +function cidrv42(params) { + return _cidrv4(ZodCIDRv4, params); +} var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { $ZodCIDRv6.init(inst, def); ZodStringFormat.init(inst, def); }); +function cidrv62(params) { + return _cidrv6(ZodCIDRv6, params); +} var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { $ZodBase64.init(inst, def); ZodStringFormat.init(inst, def); }); +function base642(params) { + return _base64(ZodBase64, params); +} var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { $ZodBase64URL.init(inst, def); ZodStringFormat.init(inst, def); }); +function base64url2(params) { + return _base64url(ZodBase64URL, params); +} var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { $ZodE164.init(inst, def); ZodStringFormat.init(inst, def); }); +function e1642(params) { + return _e164(ZodE164, params); +} var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { $ZodJWT.init(inst, def); ZodStringFormat.init(inst, def); }); +function jwt(params) { + return _jwt(ZodJWT, params); +} +var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function stringFormat(format, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function hostname3(_params) { + return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params); +} +function hex2(_params) { + return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params); +} +function hash(alg, params) { + var _a3; + const enc = (_a3 = params == null ? void 0 : params.enc) != null ? _a3 : "hex"; + const format = `${alg}_${enc}`; + const regex = regexes_exports[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return _stringFormat(ZodCustomStringFormat, format, regex, params); +} var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; + var _a3, _b, _c, _d, _e, _f, _g, _h, _i; $ZodNumber.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params); inst.gt = (value, params) => inst.check(_gt(value, params)); inst.gte = (value, params) => inst.check(_gte(value, params)); inst.min = (value, params) => inst.check(_gte(value, params)); @@ -20605,13 +31035,13 @@ var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { inst.step = (value, params) => inst.check(_multipleOf(value, params)); inst.finite = () => inst; const bag = inst._zod.bag; - inst.minValue = (_c = Math.max((_a = bag.minimum) != null ? _a : Number.NEGATIVE_INFINITY, (_b = bag.exclusiveMinimum) != null ? _b : Number.NEGATIVE_INFINITY)) != null ? _c : null; + inst.minValue = (_c = Math.max((_a3 = bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY, (_b = bag.exclusiveMinimum) != null ? _b : Number.NEGATIVE_INFINITY)) != null ? _c : null; inst.maxValue = (_f = Math.min((_d = bag.maximum) != null ? _d : Number.POSITIVE_INFINITY, (_e = bag.exclusiveMaximum) != null ? _e : Number.POSITIVE_INFINITY)) != null ? _f : null; inst.isInt = ((_g = bag.format) != null ? _g : "").includes("int") || Number.isSafeInteger((_h = bag.multipleOf) != null ? _h : 0.5); inst.isFinite = true; inst.format = (_i = bag.format) != null ? _i : null; }); -function number2(params) { +function number3(params) { return _number(ZodNumber2, params); } var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { @@ -20621,23 +31051,98 @@ var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def function int(params) { return _int(ZodNumberFormat, params); } +function float32(params) { + return _float32(ZodNumberFormat, params); +} +function float64(params) { + return _float64(ZodNumberFormat, params); +} +function int32(params) { + return _int32(ZodNumberFormat, params); +} +function uint32(params) { + return _uint32(ZodNumberFormat, params); +} var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params); }); -function boolean2(params) { +function boolean3(params) { return _boolean(ZodBoolean2, params); } +var ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { + var _a3, _b, _c; + $ZodBigInt.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = (_a3 = bag.minimum) != null ? _a3 : null; + inst.maxValue = (_b = bag.maximum) != null ? _b : null; + inst.format = (_c = bag.format) != null ? _c : null; +}); +function bigint3(params) { + return _bigint(ZodBigInt2, params); +} +var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat.init(inst, def); + ZodBigInt2.init(inst, def); +}); +function int64(params) { + return _int64(ZodBigIntFormat, params); +} +function uint64(params) { + return _uint64(ZodBigIntFormat, params); +} +var ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { + $ZodSymbol.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params); +}); +function symbol(params) { + return _symbol(ZodSymbol2, params); +} +var ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { + $ZodUndefined.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params); +}); +function _undefined3(params) { + return _undefined2(ZodUndefined2, params); +} var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { $ZodNull.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params); }); function _null3(params) { return _null2(ZodNull2, params); } +var ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params); +}); +function any() { + return _any(ZodAny2); +} var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params); }); function unknown() { return _unknown(ZodUnknown2); @@ -20645,13 +31150,36 @@ function unknown() { var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { $ZodNever.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params); }); function never(params) { return _never(ZodNever2, params); } +var ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { + $ZodVoid.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params); +}); +function _void2(params) { + return _void(ZodVoid2, params); +} +var ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { + $ZodDate.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + const c3 = inst._zod.bag; + inst.minDate = c3.minimum ? new Date(c3.minimum) : null; + inst.maxDate = c3.maximum ? new Date(c3.maximum) : null; +}); +function date5(params) { + return _date(ZodDate2, params); +} var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { $ZodArray.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params); inst.element = def.element; inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); inst.nonempty = (params) => inst.check(_minLength(1, params)); @@ -20662,57 +31190,84 @@ var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { function array(element, params) { return _array(ZodArray2, element, params); } +function keyof(schema) { + const shape = schema._zod.def.shape; + return _enum2(Object.keys(shape)); +} var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { - $ZodObject.init(inst, def); + $ZodObjectJIT.init(inst, def); ZodType2.init(inst, def); - exports_util.defineLazy(inst, "shape", () => def.shape); - inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)); + inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params); + util_exports.defineLazy(inst, "shape", () => { + return def.shape; + }); + inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); inst.extend = (incoming) => { - return exports_util.extend(inst, incoming); + return util_exports.extend(inst, incoming); }; - inst.merge = (other) => exports_util.merge(inst, other); - inst.pick = (mask) => exports_util.pick(inst, mask); - inst.omit = (mask) => exports_util.omit(inst, mask); - inst.partial = (...args) => exports_util.partial(ZodOptional2, inst, args[0]); - inst.required = (...args) => exports_util.required(ZodNonOptional, inst, args[0]); + inst.safeExtend = (incoming) => { + return util_exports.safeExtend(inst, incoming); + }; + inst.merge = (other) => util_exports.merge(inst, other); + inst.pick = (mask) => util_exports.pick(inst, mask); + inst.omit = (mask) => util_exports.omit(inst, mask); + inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]); + inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); }); function object2(shape, params) { const def = { type: "object", - get shape() { - exports_util.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - ...exports_util.normalizeParams(params) + shape: shape != null ? shape : {}, + ...util_exports.normalizeParams(params) }; return new ZodObject2(def); } +function strictObject(shape, params) { + return new ZodObject2({ + type: "object", + shape, + catchall: never(), + ...util_exports.normalizeParams(params) + }); +} function looseObject(shape, params) { return new ZodObject2({ type: "object", - get shape() { - exports_util.assignProp(this, "shape", { ...shape }); - return this.shape; - }, + shape, catchall: unknown(), - ...exports_util.normalizeParams(params) + ...util_exports.normalizeParams(params) }); } var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { $ZodUnion.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); inst.options = def.options; }); function union(options, params) { return new ZodUnion2({ type: "union", options, - ...exports_util.normalizeParams(params) + ...util_exports.normalizeParams(params) + }); +} +var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => { + ZodUnion2.init(inst, def); + $ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params); + inst.options = def.options; +}); +function xor(options, params) { + return new ZodXor({ + type: "union", + options, + inclusive: false, + ...util_exports.normalizeParams(params) }); } var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { @@ -20724,12 +31279,13 @@ function discriminatedUnion(discriminator, options, params) { type: "union", options, discriminator, - ...exports_util.normalizeParams(params) + ...util_exports.normalizeParams(params) }); } var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { $ZodIntersection.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params); }); function intersection(left, right) { return new ZodIntersection2({ @@ -20738,9 +31294,30 @@ function intersection(left, right) { right }); } +var ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); +}); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple2({ + type: "tuple", + items, + rest, + ...util_exports.normalizeParams(params) + }); +} var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params); inst.keyType = def.keyType; inst.valueType = def.valueType; }); @@ -20749,12 +31326,67 @@ function record(keyType, valueType, params) { type: "record", keyType, valueType, - ...exports_util.normalizeParams(params) + ...util_exports.normalizeParams(params) + }); +} +function partialRecord(keyType, valueType, params) { + const k = clone(keyType); + k._zod.values = void 0; + return new ZodRecord2({ + type: "record", + keyType: k, + valueType, + ...util_exports.normalizeParams(params) + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord2({ + type: "record", + keyType, + valueType, + mode: "loose", + ...util_exports.normalizeParams(params) + }); +} +var ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + $ZodMap.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); +}); +function map(keyType, valueType, params) { + return new ZodMap2({ + type: "map", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +var ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + $ZodSet.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); +}); +function set(valueType, params) { + return new ZodSet2({ + type: "set", + valueType, + ...util_exports.normalizeParams(params) }); } var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params); inst.enum = def.entries; inst.options = Object.values(def.entries); const keys = new Set(Object.keys(def.entries)); @@ -20769,7 +31401,7 @@ var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { return new ZodEnum2({ ...def, checks: [], - ...exports_util.normalizeParams(params), + ...util_exports.normalizeParams(params), entries: newEntries }); }; @@ -20784,22 +31416,30 @@ var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { return new ZodEnum2({ ...def, checks: [], - ...exports_util.normalizeParams(params), + ...util_exports.normalizeParams(params), entries: newEntries }); }; }); -function _enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; +function _enum2(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v3) => [v3, v3])) : values; return new ZodEnum2({ type: "enum", entries, - ...exports_util.normalizeParams(params) + ...util_exports.normalizeParams(params) + }); +} +function nativeEnum(entries, params) { + return new ZodEnum2({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) }); } var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params); inst.values = new Set(def.values); Object.defineProperty(inst, "value", { get() { @@ -20814,26 +31454,40 @@ function literal(value, params) { return new ZodLiteral2({ type: "literal", values: Array.isArray(value) ? value : [value], - ...exports_util.normalizeParams(params) + ...util_exports.normalizeParams(params) }); } +var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { + $ZodFile.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params); + inst.min = (size, params) => inst.check(_minSize(size, params)); + inst.max = (size, params) => inst.check(_maxSize(size, params)); + inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); +}); +function file(params) { + return _file(ZodFile, params); +} var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { $ZodTransform.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params); inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } payload.addIssue = (issue2) => { - var _a, _b, _c, _d; + var _a3, _b, _c; if (typeof issue2 === "string") { - payload.issues.push(exports_util.issue(issue2, payload.value, def)); + payload.issues.push(util_exports.issue(issue2, payload.value, def)); } else { const _issue = issue2; if (_issue.fatal) _issue.continue = false; - (_a = _issue.code) != null ? _a : _issue.code = "custom"; + (_a3 = _issue.code) != null ? _a3 : _issue.code = "custom"; (_b = _issue.input) != null ? _b : _issue.input = payload.value; (_c = _issue.inst) != null ? _c : _issue.inst = inst; - (_d = _issue.continue) != null ? _d : _issue.continue = true; - payload.issues.push(exports_util.issue(_issue)); + payload.issues.push(util_exports.issue(_issue)); } }; const output = def.transform(payload.value, payload); @@ -20856,6 +31510,7 @@ function transform(fn) { var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function optional(innerType) { @@ -20864,9 +31519,22 @@ function optional(innerType) { innerType }); } +var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType + }); +} var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function nullable(innerType) { @@ -20875,24 +31543,29 @@ function nullable(innerType) { innerType }); } +function nullish2(innerType) { + return optional(nullable(innerType)); +} var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { $ZodDefault.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeDefault = inst.unwrap; }); -function _default(innerType, defaultValue) { +function _default2(innerType, defaultValue) { return new ZodDefault2({ type: "default", innerType, get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { $ZodPrefault.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function prefault(innerType, defaultValue) { @@ -20900,38 +31573,61 @@ function prefault(innerType, defaultValue) { type: "prefault", innerType, get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; + return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue); } }); } var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { $ZodNonOptional.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; }); function nonoptional(innerType, params) { return new ZodNonOptional({ type: "nonoptional", innerType, - ...exports_util.normalizeParams(params) + ...util_exports.normalizeParams(params) + }); +} +var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { + $ZodSuccess.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType }); } var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { $ZodCatch.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params); inst.unwrap = () => inst._zod.def.innerType; inst.removeCatch = inst.unwrap; }); -function _catch(innerType, catchValue) { +function _catch2(innerType, catchValue) { return new ZodCatch2({ type: "catch", innerType, catchValue: typeof catchValue === "function" ? catchValue : () => catchValue }); } +var ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { + $ZodNaN.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params); +}); +function nan(params) { + return _nan(ZodNaN2, params); +} var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { $ZodPipe.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params); inst.in = def.in; inst.out = def.out; }); @@ -20940,11 +31636,27 @@ function pipe(in_, out) { type: "pipe", in: in_, out + // ...util.normalizeParams(params), + }); +} +var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + $ZodCodec.init(inst, def); +}); +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out, + transform: params.decode, + reverseTransform: params.encode }); } var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { $ZodReadonly.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; }); function readonly(innerType) { return new ZodReadonly2({ @@ -20952,14 +31664,64 @@ function readonly(innerType) { innerType }); } +var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params); +}); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util_exports.normalizeParams(params) + }); +} +var ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy2({ + type: "lazy", + getter + }); +} +var ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { + $ZodPromise.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function promise(innerType) { + return new ZodPromise2({ + type: "promise", + innerType + }); +} +var ZodFunction2 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => { + $ZodFunction.init(inst, def); + ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params); +}); +function _function(params) { + var _a3, _b; + return new ZodFunction2({ + type: "function", + input: Array.isArray(params == null ? void 0 : params.input) ? tuple(params == null ? void 0 : params.input) : (_a3 = params == null ? void 0 : params.input) != null ? _a3 : array(unknown()), + output: (_b = params == null ? void 0 : params.output) != null ? _b : unknown() + }); +} var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { $ZodCustom.init(inst, def); ZodType2.init(inst, def); + inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params); }); -function check(fn, params) { +function check(fn) { const ch = new $ZodCheck({ - check: "custom", - ...exports_util.normalizeParams(params) + check: "custom" + // ...util.normalizeParams(params), }); ch._zod.check = fn; return ch; @@ -20970,84 +31732,195 @@ function custom(fn, _params) { function refine(fn, _params = {}) { return _refine(ZodCustom, fn, _params); } -function superRefine(fn, params) { - const ch = check((payload) => { - payload.addIssue = (issue2) => { - var _a, _b, _c, _d; - if (typeof issue2 === "string") { - payload.issues.push(exports_util.issue(issue2, payload.value, ch._zod.def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - (_a = _issue.code) != null ? _a : _issue.code = "custom"; - (_b = _issue.input) != null ? _b : _issue.input = payload.value; - (_c = _issue.inst) != null ? _c : _issue.inst = ch; - (_d = _issue.continue) != null ? _d : _issue.continue = !ch._zod.def.abort; - payload.issues.push(exports_util.issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; +function superRefine(fn) { + return _superRefine(fn); +} +var describe2 = describe; +var meta2 = meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util_exports.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + inst._zod.check = (payload) => { + var _a3; + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(_a3 = inst._zod.def.path) != null ? _a3 : []] + }); + } + }; + return inst; +} +var stringbool = (...args) => _stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean2, + String: ZodString2 +}, ...args); +function json(params) { + const jsonSchema = lazy(() => { + return union([string3(params), number3(), boolean3(), _null3(), array(jsonSchema), record(string3(), jsonSchema)]); + }); + return jsonSchema; } function preprocess(fn, schema) { return pipe(transform(fn), schema); } + +// node_modules/zod/v4/classic/compat.js +var ZodIssueCode2 = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom" +}; +var ZodFirstPartyTypeKind2; +/* @__PURE__ */ (function(ZodFirstPartyTypeKind3) { +})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); + +// node_modules/zod/v4/classic/from-json-schema.js +var z = { + ...schemas_exports3, + ...checks_exports2, + iso: iso_exports2 +}; + +// node_modules/zod/v4/classic/coerce.js +var coerce_exports2 = {}; +__export(coerce_exports2, { + bigint: () => bigint4, + boolean: () => boolean4, + date: () => date6, + number: () => number4, + string: () => string4 +}); +function string4(params) { + return _coercedString(ZodString2, params); +} +function number4(params) { + return _coercedNumber(ZodNumber2, params); +} +function boolean4(params) { + return _coercedBoolean(ZodBoolean2, params); +} +function bigint4(params) { + return _coercedBigint(ZodBigInt2, params); +} +function date6(params) { + return _coercedDate(ZodDate2, params); +} + +// node_modules/zod/v4/classic/external.js config(en_default2()); + +// node_modules/@modelcontextprotocol/sdk/dist/esm/types.js +var LATEST_PROTOCOL_VERSION = "2025-11-25"; +var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"]; var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; var JSONRPC_VERSION = "2.0"; -var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function")); -var ProgressTokenSchema = union([string2(), number2().int()]); -var CursorSchema = string2(); +var AssertObjectSchema = custom((v3) => v3 !== null && (typeof v3 === "object" || typeof v3 === "function")); +var ProgressTokenSchema = union([string3(), number3().int()]); +var CursorSchema = string3(); var TaskCreationParamsSchema = looseObject({ - ttl: union([number2(), _null3()]).optional(), - pollInterval: number2().optional() + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: union([number3(), _null3()]).optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: number3().optional() }); -var RelatedTaskMetadataSchema = looseObject({ - taskId: string2() +var TaskMetadataSchema = object2({ + ttl: number3().optional() +}); +var RelatedTaskMetadataSchema = object2({ + taskId: string3() }); var RequestMetaSchema = looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() }); -var BaseRequestParamsSchema = looseObject({ - task: TaskCreationParamsSchema.optional(), +var BaseRequestParamsSchema = object2({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ _meta: RequestMetaSchema.optional() }); -var RequestSchema = object2({ - method: string2(), - params: BaseRequestParamsSchema.optional() +var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() }); -var NotificationsParamsSchema = looseObject({ - _meta: object2({ - [RELATED_TASK_META_KEY]: optional(RelatedTaskMetadataSchema) - }).passthrough().optional() +var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +var RequestSchema = object2({ + method: string3(), + params: BaseRequestParamsSchema.loose().optional() +}); +var NotificationsParamsSchema = object2({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() }); var NotificationSchema = object2({ - method: string2(), - params: NotificationsParamsSchema.optional() + method: string3(), + params: NotificationsParamsSchema.loose().optional() }); var ResultSchema = looseObject({ - _meta: looseObject({ - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() - }).optional() + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() }); -var RequestIdSchema = union([string2(), number2().int()]); +var RequestIdSchema = union([string3(), number3().int()]); var JSONRPCRequestSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, ...RequestSchema.shape }).strict(); +var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; var JSONRPCNotificationSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), ...NotificationSchema.shape }).strict(); -var JSONRPCResponseSchema = object2({ +var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +var JSONRPCResultResponseSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), id: RequestIdSchema, result: ResultSchema }).strict(); +var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; var ErrorCode; (function(ErrorCode2) { ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; @@ -21059,46 +31932,121 @@ var ErrorCode; ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; })(ErrorCode || (ErrorCode = {})); -var JSONRPCErrorSchema = object2({ +var JSONRPCErrorResponseSchema = object2({ jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, + id: RequestIdSchema.optional(), error: object2({ - code: number2().int(), - message: string2(), - data: optional(unknown()) + /** + * The error type that occurred. + */ + code: number3().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string3(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: unknown().optional() }) }).strict(); -var JSONRPCMessageSchema = union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]); +var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +var JSONRPCMessageSchema = union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); var EmptyResultSchema = ResultSchema.strict(); var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema, - reason: string2().optional() + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: string3().optional() }); var CancelledNotificationSchema = NotificationSchema.extend({ method: literal("notifications/cancelled"), params: CancelledNotificationParamsSchema }); var IconSchema = object2({ - src: string2(), - mimeType: string2().optional(), - sizes: array(string2()).optional() + /** + * URL or data URI for the icon. + */ + src: string3(), + /** + * Optional MIME type for the icon. + */ + mimeType: string3().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: array(string3()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: _enum2(["light", "dark"]).optional() }); var IconsSchema = object2({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ icons: array(IconSchema).optional() }); var BaseMetadataSchema = object2({ - name: string2(), - title: string2().optional() + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: string3(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: string3().optional() }); var ImplementationSchema = BaseMetadataSchema.extend({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, - version: string2(), - websiteUrl: string2().optional() + version: string3(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: string3().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: string3().optional() }); var FormElicitationCapabilitySchema = intersection(object2({ - applyDefaults: boolean2().optional() -}), record(string2(), unknown())); + applyDefaults: boolean3().optional() +}), record(string3(), unknown())); var ElicitationCapabilitySchema = preprocess((value) => { if (value && typeof value === "object" && !Array.isArray(value)) { if (Object.keys(value).length === 0) { @@ -21109,42 +32057,97 @@ var ElicitationCapabilitySchema = preprocess((value) => { }, intersection(object2({ form: FormElicitationCapabilitySchema.optional(), url: AssertObjectSchema.optional() -}), record(string2(), unknown()).optional())); -var ClientTasksCapabilitySchema = object2({ - list: optional(object2({}).passthrough()), - cancel: optional(object2({}).passthrough()), - requests: optional(object2({ - sampling: optional(object2({ - createMessage: optional(object2({}).passthrough()) - }).passthrough()), - elicitation: optional(object2({ - create: optional(object2({}).passthrough()) - }).passthrough()) - }).passthrough()) -}).passthrough(); -var ServerTasksCapabilitySchema = object2({ - list: optional(object2({}).passthrough()), - cancel: optional(object2({}).passthrough()), - requests: optional(object2({ - tools: optional(object2({ - call: optional(object2({}).passthrough()) - }).passthrough()) - }).passthrough()) -}).passthrough(); +}), record(string3(), unknown()).optional())); +var ClientTasksCapabilitySchema = looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for sampling requests. + */ + sampling: looseObject({ + createMessage: AssertObjectSchema.optional() + }).optional(), + /** + * Task support for elicitation requests. + */ + elicitation: looseObject({ + create: AssertObjectSchema.optional() + }).optional() + }).optional() +}); +var ServerTasksCapabilitySchema = looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for tool requests. + */ + tools: looseObject({ + call: AssertObjectSchema.optional() + }).optional() + }).optional() +}); var ClientCapabilitiesSchema = object2({ - experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: record(string3(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ sampling: object2({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ tools: AssertObjectSchema.optional() }).optional(), + /** + * Present if the client supports eliciting user input. + */ elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ roots: object2({ - listChanged: boolean2().optional() + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: boolean3().optional() }).optional(), - tasks: optional(ClientTasksCapabilitySchema) + /** + * Present if the client supports task creation. + */ + tasks: ClientTasksCapabilitySchema.optional() }); var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: string2(), + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string3(), capabilities: ClientCapabilitiesSchema, clientInfo: ImplementationSchema }); @@ -21153,41 +32156,97 @@ var InitializeRequestSchema = RequestSchema.extend({ params: InitializeRequestParamsSchema }); var ServerCapabilitiesSchema = object2({ - experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: record(string3(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ completions: AssertObjectSchema.optional(), - prompts: optional(object2({ - listChanged: optional(boolean2()) - })), + /** + * Present if the server offers any prompt templates. + */ + prompts: object2({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: boolean3().optional() + }).optional(), + /** + * Present if the server offers any resources to read. + */ resources: object2({ - subscribe: boolean2().optional(), - listChanged: boolean2().optional() + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: boolean3().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: boolean3().optional() }).optional(), + /** + * Present if the server offers any tools to call. + */ tools: object2({ - listChanged: boolean2().optional() + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: boolean3().optional() }).optional(), - tasks: optional(ServerTasksCapabilitySchema) -}).passthrough(); + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional() +}); var InitializeResultSchema = ResultSchema.extend({ - protocolVersion: string2(), + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string3(), capabilities: ServerCapabilitiesSchema, serverInfo: ImplementationSchema, - instructions: string2().optional() + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: string3().optional() }); var InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized") + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() }); +var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; var PingRequestSchema = RequestSchema.extend({ - method: literal("ping") + method: literal("ping"), + params: BaseRequestParamsSchema.optional() }); var ProgressSchema = object2({ - progress: number2(), - total: optional(number2()), - message: optional(string2()) + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: number3(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: optional(number3()), + /** + * An optional message describing the current progress. + */ + message: optional(string3()) }); var ProgressNotificationParamsSchema = object2({ ...NotificationsParamsSchema.shape, ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ progressToken: ProgressTokenSchema }); var ProgressNotificationSchema = NotificationSchema.extend({ @@ -21195,22 +32254,44 @@ var ProgressNotificationSchema = NotificationSchema.extend({ params: ProgressNotificationParamsSchema }); var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ cursor: CursorSchema.optional() }); var PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); var PaginatedResultSchema = ResultSchema.extend({ - nextCursor: optional(CursorSchema) + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() }); +var TaskStatusSchema = _enum2(["working", "input_required", "completed", "failed", "cancelled"]); var TaskSchema = object2({ - taskId: string2(), - status: _enum(["working", "input_required", "completed", "failed", "cancelled"]), - ttl: union([number2(), _null3()]), - createdAt: string2(), - lastUpdatedAt: string2(), - pollInterval: optional(number2()), - statusMessage: optional(string2()) + taskId: string3(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: union([number3(), _null3()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string3(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string3(), + pollInterval: optional(number3()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: optional(string3()) }); var CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema @@ -21223,16 +32304,17 @@ var TaskStatusNotificationSchema = NotificationSchema.extend({ var GetTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/get"), params: BaseRequestParamsSchema.extend({ - taskId: string2() + taskId: string3() }) }); var GetTaskResultSchema = ResultSchema.merge(TaskSchema); var GetTaskPayloadRequestSchema = RequestSchema.extend({ method: literal("tasks/result"), params: BaseRequestParamsSchema.extend({ - taskId: string2() + taskId: string3() }) }); +var GetTaskPayloadResultSchema = ResultSchema.loose(); var ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); @@ -21242,50 +32324,112 @@ var ListTasksResultSchema = PaginatedResultSchema.extend({ var CancelTaskRequestSchema = RequestSchema.extend({ method: literal("tasks/cancel"), params: BaseRequestParamsSchema.extend({ - taskId: string2() + taskId: string3() }) }); var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); var ResourceContentsSchema = object2({ - uri: string2(), - mimeType: optional(string2()), - _meta: record(string2(), unknown()).optional() + /** + * The URI of this resource. + */ + uri: string3(), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string3()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() }); var TextResourceContentsSchema = ResourceContentsSchema.extend({ - text: string2() + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string3() }); -var Base64Schema = string2().refine((val) => { +var Base64Schema = string3().refine((val) => { try { atob(val); return true; - } catch (_a) { + } catch (e2) { return false; } }, { message: "Invalid Base64 string" }); var BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ blob: Base64Schema }); +var RoleSchema = _enum2(["user", "assistant"]); var AnnotationsSchema = object2({ - audience: array(_enum(["user", "assistant"])).optional(), - priority: number2().min(0).max(1).optional(), - lastModified: exports_iso2.datetime({ offset: true }).optional() + /** + * Intended audience(s) for the resource. + */ + audience: array(RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: number3().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: iso_exports2.datetime({ offset: true }).optional() }); var ResourceSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, - uri: string2(), - description: optional(string2()), - mimeType: optional(string2()), + /** + * The URI of this resource. + */ + uri: string3(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string3()), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string3()), + /** + * Optional annotations for the client. + */ annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: optional(looseObject({})) }); var ResourceTemplateSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, - uriTemplate: string2(), - description: optional(string2()), - mimeType: optional(string2()), + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: string3(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string3()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: optional(string3()), + /** + * Optional annotations for the client. + */ annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: optional(looseObject({})) }); var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ @@ -21301,7 +32445,12 @@ var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: array(ResourceTemplateSchema) }); var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ - uri: string2() + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string3() }); var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; var ReadResourceRequestSchema = RequestSchema.extend({ @@ -21312,7 +32461,8 @@ var ReadResourceResultSchema = ResultSchema.extend({ contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); var ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed") + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() }); var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; var SubscribeRequestSchema = RequestSchema.extend({ @@ -21325,22 +32475,44 @@ var UnsubscribeRequestSchema = RequestSchema.extend({ params: UnsubscribeRequestParamsSchema }); var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - uri: string2() + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: string3() }); var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ method: literal("notifications/resources/updated"), params: ResourceUpdatedNotificationParamsSchema }); var PromptArgumentSchema = object2({ - name: string2(), - description: optional(string2()), - required: optional(boolean2()) + /** + * The name of the argument. + */ + name: string3(), + /** + * A human-readable description of the argument. + */ + description: optional(string3()), + /** + * Whether this argument must be provided. + */ + required: optional(boolean3()) }); var PromptSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, - description: optional(string2()), + /** + * An optional description of what this prompt provides + */ + description: optional(string3()), + /** + * A list of arguments to use for templating the prompt. + */ arguments: optional(array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ _meta: optional(looseObject({})) }); var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ @@ -21350,8 +32522,14 @@ var ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: array(PromptSchema) }); var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: string2(), - arguments: record(string2(), string2()).optional() + /** + * The name of the prompt or prompt template. + */ + name: string3(), + /** + * Arguments to use for templating the prompt. + */ + arguments: record(string3(), string3()).optional() }); var GetPromptRequestSchema = RequestSchema.extend({ method: literal("prompts/get"), @@ -21359,36 +32537,95 @@ var GetPromptRequestSchema = RequestSchema.extend({ }); var TextContentSchema = object2({ type: literal("text"), - text: string2(), + /** + * The text content of the message. + */ + text: string3(), + /** + * Optional annotations for the client. + */ annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() }); var ImageContentSchema = object2({ type: literal("image"), + /** + * The base64-encoded image data. + */ data: Base64Schema, - mimeType: string2(), + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string3(), + /** + * Optional annotations for the client. + */ annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() }); var AudioContentSchema = object2({ type: literal("audio"), + /** + * The base64-encoded audio data. + */ data: Base64Schema, - mimeType: string2(), + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string3(), + /** + * Optional annotations for the client. + */ annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() }); var ToolUseContentSchema = object2({ type: literal("tool_use"), - name: string2(), - id: string2(), - input: object2({}).passthrough(), - _meta: optional(object2({}).passthrough()) -}).passthrough(); + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: string3(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: string3(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: record(string3(), unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() +}); var EmbeddedResourceSchema = object2({ type: literal("resource"), resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ annotations: AnnotationsSchema.optional(), - _meta: record(string2(), unknown()).optional() + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() }); var ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") @@ -21401,43 +32638,109 @@ var ContentBlockSchema = union([ EmbeddedResourceSchema ]); var PromptMessageSchema = object2({ - role: _enum(["user", "assistant"]), + role: RoleSchema, content: ContentBlockSchema }); var GetPromptResultSchema = ResultSchema.extend({ - description: optional(string2()), + /** + * An optional description for the prompt. + */ + description: string3().optional(), messages: array(PromptMessageSchema) }); var PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed") + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() }); var ToolAnnotationsSchema = object2({ - title: string2().optional(), - readOnlyHint: boolean2().optional(), - destructiveHint: boolean2().optional(), - idempotentHint: boolean2().optional(), - openWorldHint: boolean2().optional() + /** + * A human-readable title for the tool. + */ + title: string3().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: boolean3().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: boolean3().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: boolean3().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: boolean3().optional() }); var ToolExecutionSchema = object2({ - taskSupport: _enum(["required", "optional", "forbidden"]).optional() + /** + * Indicates the tool's preference for task-augmented execution. + * - "required": Clients MUST invoke the tool as a task + * - "optional": Clients MAY invoke the tool as a task or normal request + * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to "forbidden". + */ + taskSupport: _enum2(["required", "optional", "forbidden"]).optional() }); var ToolSchema = object2({ ...BaseMetadataSchema.shape, ...IconsSchema.shape, - description: string2().optional(), + /** + * A human-readable description of the tool. + */ + description: string3().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ inputSchema: object2({ type: literal("object"), - properties: record(string2(), AssertObjectSchema).optional(), - required: array(string2()).optional() + properties: record(string3(), AssertObjectSchema).optional(), + required: array(string3()).optional() }).catchall(unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ outputSchema: object2({ type: literal("object"), - properties: record(string2(), AssertObjectSchema).optional(), - required: array(string2()).optional() + properties: record(string3(), AssertObjectSchema).optional(), + required: array(string3()).optional() }).catchall(unknown()).optional(), - annotations: optional(ToolAnnotationsSchema), - execution: optional(ToolExecutionSchema), - _meta: record(string2(), unknown()).optional() + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() }); var ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") @@ -21446,26 +32749,81 @@ var ListToolsResultSchema = PaginatedResultSchema.extend({ tools: array(ToolSchema) }); var CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ content: array(ContentBlockSchema).default([]), - structuredContent: record(string2(), unknown()).optional(), - isError: optional(boolean2()) + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: record(string3(), unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: boolean3().optional() }); var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); -var CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: string2(), - arguments: optional(record(string2(), unknown())) +var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: string3(), + /** + * Arguments to pass to the tool. + */ + arguments: record(string3(), unknown()).optional() }); var CallToolRequestSchema = RequestSchema.extend({ method: literal("tools/call"), params: CallToolRequestParamsSchema }); var ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed") + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() }); -var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); +var ListChangedOptionsBaseSchema = object2({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: boolean3().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: number3().int().nonnegative().default(300) +}); +var LoggingLevelSchema = _enum2(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ level: LoggingLevelSchema }); var SetLevelRequestSchema = RequestSchema.extend({ @@ -21473,8 +32831,17 @@ var SetLevelRequestSchema = RequestSchema.extend({ params: SetLevelRequestParamsSchema }); var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ level: LoggingLevelSchema, - logger: string2().optional(), + /** + * An optional name of the logger issuing this message. + */ + logger: string3().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ data: unknown() }); var LoggingMessageNotificationSchema = NotificationSchema.extend({ @@ -21482,25 +32849,50 @@ var LoggingMessageNotificationSchema = NotificationSchema.extend({ params: LoggingMessageNotificationParamsSchema }); var ModelHintSchema = object2({ - name: string2().optional() + /** + * A hint for a model name. + */ + name: string3().optional() }); var ModelPreferencesSchema = object2({ - hints: optional(array(ModelHintSchema)), - costPriority: optional(number2().min(0).max(1)), - speedPriority: optional(number2().min(0).max(1)), - intelligencePriority: optional(number2().min(0).max(1)) + /** + * Optional hints to use for model selection. + */ + hints: array(ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: number3().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: number3().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: number3().min(0).max(1).optional() }); var ToolChoiceSchema = object2({ - mode: optional(_enum(["auto", "required", "none"])) + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: _enum2(["auto", "required", "none"]).optional() }); var ToolResultContentSchema = object2({ type: literal("tool_result"), - toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + toolUseId: string3().describe("The unique identifier for the corresponding tool call."), content: array(ContentBlockSchema).default([]), - structuredContent: object2({}).passthrough().optional(), - isError: optional(boolean2()), - _meta: optional(object2({}).passthrough()) -}).passthrough(); + structuredContent: object2({}).loose().optional(), + isError: boolean3().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() +}); var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ TextContentSchema, @@ -21510,130 +32902,222 @@ var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ ToolResultContentSchema ]); var SamplingMessageSchema = object2({ - role: _enum(["user", "assistant"]), + role: RoleSchema, content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), - _meta: optional(object2({}).passthrough()) -}).passthrough(); -var CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() +}); +var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ messages: array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: string2().optional(), - includeContext: _enum(["none", "thisServer", "allServers"]).optional(), - temperature: number2().optional(), - maxTokens: number2().int(), - stopSequences: array(string2()).optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: string3().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: _enum2(["none", "thisServer", "allServers"]).optional(), + temperature: number3().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number3().int(), + stopSequences: array(string3()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ metadata: AssertObjectSchema.optional(), - tools: optional(array(ToolSchema)), - toolChoice: optional(ToolChoiceSchema) + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: array(ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: ToolChoiceSchema.optional() }); var CreateMessageRequestSchema = RequestSchema.extend({ method: literal("sampling/createMessage"), params: CreateMessageRequestParamsSchema }); var CreateMessageResultSchema = ResultSchema.extend({ - model: string2(), - stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())), - role: _enum(["user", "assistant"]), + /** + * The name of the model that generated the message. + */ + model: string3(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string3())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ content: SamplingContentSchema }); var CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: string2(), - stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), - role: _enum(["user", "assistant"]), + /** + * The name of the model that generated the message. + */ + model: string3(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string3())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) }); var BooleanSchemaSchema = object2({ type: literal("boolean"), - title: string2().optional(), - description: string2().optional(), - default: boolean2().optional() + title: string3().optional(), + description: string3().optional(), + default: boolean3().optional() }); var StringSchemaSchema = object2({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), - minLength: number2().optional(), - maxLength: number2().optional(), - format: _enum(["email", "uri", "date", "date-time"]).optional(), - default: string2().optional() + title: string3().optional(), + description: string3().optional(), + minLength: number3().optional(), + maxLength: number3().optional(), + format: _enum2(["email", "uri", "date", "date-time"]).optional(), + default: string3().optional() }); var NumberSchemaSchema = object2({ - type: _enum(["number", "integer"]), - title: string2().optional(), - description: string2().optional(), - minimum: number2().optional(), - maximum: number2().optional(), - default: number2().optional() + type: _enum2(["number", "integer"]), + title: string3().optional(), + description: string3().optional(), + minimum: number3().optional(), + maximum: number3().optional(), + default: number3().optional() }); var UntitledSingleSelectEnumSchemaSchema = object2({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - default: string2().optional() + title: string3().optional(), + description: string3().optional(), + enum: array(string3()), + default: string3().optional() }); var TitledSingleSelectEnumSchemaSchema = object2({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), + title: string3().optional(), + description: string3().optional(), oneOf: array(object2({ - const: string2(), - title: string2() + const: string3(), + title: string3() })), - default: string2().optional() + default: string3().optional() }); var LegacyTitledEnumSchemaSchema = object2({ type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - enumNames: array(string2()).optional(), - default: string2().optional() + title: string3().optional(), + description: string3().optional(), + enum: array(string3()), + enumNames: array(string3()).optional(), + default: string3().optional() }); var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); var UntitledMultiSelectEnumSchemaSchema = object2({ type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), + title: string3().optional(), + description: string3().optional(), + minItems: number3().optional(), + maxItems: number3().optional(), items: object2({ type: literal("string"), - enum: array(string2()) + enum: array(string3()) }), - default: array(string2()).optional() + default: array(string3()).optional() }); var TitledMultiSelectEnumSchemaSchema = object2({ type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), + title: string3().optional(), + description: string3().optional(), + minItems: number3().optional(), + maxItems: number3().optional(), items: object2({ anyOf: array(object2({ - const: string2(), - title: string2() + const: string3(), + title: string3() })) }), - default: array(string2()).optional() + default: array(string3()).optional() }); var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); -var ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ +var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ mode: literal("form").optional(), - message: string2(), + /** + * The message to present to the user describing what information is being requested. + */ + message: string3(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ requestedSchema: object2({ type: literal("object"), - properties: record(string2(), PrimitiveSchemaDefinitionSchema), - required: array(string2()).optional() + properties: record(string3(), PrimitiveSchemaDefinitionSchema), + required: array(string3()).optional() }) }); -var ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({ +var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ mode: literal("url"), - message: string2(), - elicitationId: string2(), - url: string2().url() + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string3(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string3(), + /** + * The URL that the user should navigate to. + */ + url: string3().url() }); var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); var ElicitRequestSchema = RequestSchema.extend({ @@ -21641,32 +33125,65 @@ var ElicitRequestSchema = RequestSchema.extend({ params: ElicitRequestParamsSchema }); var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - elicitationId: string2() + /** + * The ID of the elicitation that completed. + */ + elicitationId: string3() }); var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ method: literal("notifications/elicitation/complete"), params: ElicitationCompleteNotificationParamsSchema }); var ElicitResultSchema = ResultSchema.extend({ - action: _enum(["accept", "decline", "cancel"]), - content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: _enum2(["accept", "decline", "cancel"]), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: preprocess((val) => val === null ? void 0 : val, record(string3(), union([string3(), number3(), boolean3(), array(string3())])).optional()) }); var ResourceTemplateReferenceSchema = object2({ type: literal("ref/resource"), - uri: string2() + /** + * The URI or URI template of the resource. + */ + uri: string3() }); var PromptReferenceSchema = object2({ type: literal("ref/prompt"), - name: string2() + /** + * The name of the prompt or prompt template + */ + name: string3() }); var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ argument: object2({ - name: string2(), - value: string2() + /** + * The name of the argument + */ + name: string3(), + /** + * The value of the argument to use for completion matching. + */ + value: string3() }), context: object2({ - arguments: record(string2(), string2()).optional() + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: record(string3(), string3()).optional() }).optional() }); var CompleteRequestSchema = RequestSchema.extend({ @@ -21675,24 +33192,45 @@ var CompleteRequestSchema = RequestSchema.extend({ }); var CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: array(string2()).max(100), - total: optional(number2().int()), - hasMore: optional(boolean2()) + /** + * An array of completion values. Must not exceed 100 items. + */ + values: array(string3()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: optional(number3().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: optional(boolean3()) }) }); var RootSchema = object2({ - uri: string2().startsWith("file://"), - name: string2().optional(), - _meta: record(string2(), unknown()).optional() + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: string3().startsWith("file://"), + /** + * An optional name for the root. + */ + name: string3().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string3(), unknown()).optional() }); var ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list") + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() }); var ListRootsResultSchema = ResultSchema.extend({ roots: array(RootSchema) }); var RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed") + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() }); var ClientRequestSchema = union([ PingRequestSchema, @@ -21710,7 +33248,8 @@ var ClientRequestSchema = union([ ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema + ListTasksRequestSchema, + CancelTaskRequestSchema ]); var ClientNotificationSchema = union([ CancelledNotificationSchema, @@ -21736,7 +33275,8 @@ var ServerRequestSchema = union([ ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema + ListTasksRequestSchema, + CancelTaskRequestSchema ]); var ServerNotificationSchema = union([ CancelledNotificationSchema, @@ -21764,2927 +33304,4656 @@ var ServerResultSchema = union([ ListTasksResultSchema, CreateTaskResultSchema ]); +var McpError = class _McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = "McpError"; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + return new _McpError(code, message, data); + } +}; +var UrlElicitationRequiredError = class extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations + }); + } + get elicitations() { + var _a3, _b; + return (_b = (_a3 = this.data) == null ? void 0 : _a3.elicitations) != null ? _b : []; + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js +function isTerminal(status) { + return status === "completed" || status === "failed" || status === "cancelled"; +} + +// node_modules/zod-to-json-schema/dist/esm/parsers/string.js var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); -var import_ajv = __toESM2(require_ajv(), 1); -var import_ajv_formats = __toESM2(require_dist(), 1); -var McpZodTypeKind; -(function(McpZodTypeKind2) { - McpZodTypeKind2["Completable"] = "McpCompletable"; -})(McpZodTypeKind || (McpZodTypeKind = {})); -function query({ - prompt, - options -}) { - const { systemPrompt, settingSources, sandbox, ...rest } = options != null ? options : {}; - let customSystemPrompt; - let appendSystemPrompt; - if (systemPrompt === void 0) { - customSystemPrompt = ""; - } else if (typeof systemPrompt === "string") { - customSystemPrompt = systemPrompt; - } else if (systemPrompt.type === "preset") { - appendSystemPrompt = systemPrompt.append; - } - let pathToClaudeCodeExecutable = rest.pathToClaudeCodeExecutable; - if (!pathToClaudeCodeExecutable) { - const filename = (0, import_url.fileURLToPath)(import_meta.url); - const dirname22 = (0, import_path.join)(filename, ".."); - pathToClaudeCodeExecutable = (0, import_path.join)(dirname22, "cli.js"); - } - process.env.CLAUDE_AGENT_SDK_VERSION = "0.1.76"; - const { - abortController = createAbortController(), - additionalDirectories = [], - agents, - allowedTools = [], - betas, - canUseTool, - continue: continueConversation, - cwd: cwd2, - disallowedTools = [], - tools, - env, - executable = isRunningWithBun() ? "bun" : "node", - executableArgs = [], - extraArgs = {}, - fallbackModel, - enableFileCheckpointing, - forkSession, - hooks, - includePartialMessages, - persistSession, - maxThinkingTokens, - maxTurns, - maxBudgetUsd, - mcpServers, - model, - outputFormat, - permissionMode = "default", - allowDangerouslySkipPermissions = false, - permissionPromptToolName, - plugins, - resume, - resumeSessionAt, - stderr, - strictMcpConfig - } = rest; - const jsonSchema = (outputFormat == null ? void 0 : outputFormat.type) === "json_schema" ? outputFormat.schema : void 0; - let processEnv = env; - if (!processEnv) { - processEnv = { ...process.env }; - } - if (!processEnv.CLAUDE_CODE_ENTRYPOINT) { - processEnv.CLAUDE_CODE_ENTRYPOINT = "sdk-ts"; - } - if (enableFileCheckpointing) { - processEnv.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING = "true"; - } - if (!pathToClaudeCodeExecutable) { - throw new Error("pathToClaudeCodeExecutable is required"); - } - const allMcpServers = {}; - const sdkMcpServers = /* @__PURE__ */ new Map(); - if (mcpServers) { - for (const [name, config2] of Object.entries(mcpServers)) { - if (config2.type === "sdk" && "instance" in config2) { - sdkMcpServers.set(name, config2.instance); - allMcpServers[name] = { - type: "sdk", - name - }; - } else { - allMcpServers[name] = config2; - } - } - } - const isSingleUserTurn = typeof prompt === "string"; - const transport = new ProcessTransport({ - abortController, - additionalDirectories, - betas, - cwd: cwd2, - executable, - executableArgs, - extraArgs, - pathToClaudeCodeExecutable, - env: processEnv, - forkSession, - stderr, - maxThinkingTokens, - maxTurns, - maxBudgetUsd, - model, - fallbackModel, - jsonSchema, - permissionMode, - allowDangerouslySkipPermissions, - permissionPromptToolName, - continueConversation, - resume, - resumeSessionAt, - settingSources: settingSources != null ? settingSources : [], - allowedTools, - disallowedTools, - tools, - mcpServers: allMcpServers, - strictMcpConfig, - canUseTool: !!canUseTool, - hooks: !!hooks, - includePartialMessages, - persistSession, - plugins, - sandbox, - spawnClaudeCodeProcess: rest.spawnClaudeCodeProcess - }); - const initConfig = { - systemPrompt: customSystemPrompt, - appendSystemPrompt, - agents - }; - const queryInstance = new Query(transport, isSingleUserTurn, canUseTool, hooks, abortController, sdkMcpServers, jsonSchema, initConfig); - if (typeof prompt === "string") { - transport.write(JSON.stringify({ - type: "user", - session_id: "", - message: { - role: "user", - content: [{ type: "text", text: prompt }] - }, - parent_tool_use_id: null - }) + ` -`); - } else { - queryInstance.streamInput(prompt); - } - return queryInstance; -} -// src/core/agent/ClaudianService.ts -var fs6 = __toESM(require("fs")); -var os2 = __toESM(require("os")); -var path7 = __toESM(require("path")); - -// src/utils/context.ts -var CURRENT_NOTE_PREFIX_REGEX = /^\n[\s\S]*?<\/current_note>\n\n/; -function formatCurrentNote(notePath) { - return ` -${notePath} -`; -} -function prependCurrentNote(prompt, notePath) { - return `${formatCurrentNote(notePath)} - -${prompt}`; -} -function stripCurrentNotePrefix(prompt) { - return prompt.replace(CURRENT_NOTE_PREFIX_REGEX, ""); -} -function formatContextFilesLine(files) { - return ` -${files.join(", ")} -`; -} - -// === CONTEXT FILE OPTIMIZATION: File summarization === -async function prependContextFiles(prompt, files, vaultPath = "") { - if (!files || files.length === 0) { - return prompt; +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js +function getMethodLiteral(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape == null ? void 0 : shape.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); } - - const fs = require("fs"); - const path = require("path"); - const FILE_SIZE_THRESHOLD = 10000; // 10KB - - const processedFiles = []; - - for (const filePath of files) { - try { - // Resolve absolute path - const absolutePath = path.isAbsolute(filePath) - ? filePath - : path.join(vaultPath || process.cwd(), filePath); - - // Check file size - const stats = fs.statSync(absolutePath); - - if (stats.size > FILE_SIZE_THRESHOLD) { - // Large file: Generate summary - const summary = await generateFileSummary(absolutePath); - processedFiles.push(summary); - } else { - // Small file: Load full content - const content = fs.readFileSync(absolutePath, "utf-8"); - processedFiles.push(`📄 **${filePath}** - -${content}`); - } - } catch (error) { - // Fallback: Just list the file path - console.error(`[Context File] Failed to process ${filePath}:`, error.message); - processedFiles.push(`📄 **${filePath}** _(Use Read tool to view)_`); - } - } - - return ` -${processedFiles.join("\n\n---\n\n")} - - -${prompt}`; -} - -// Helper: Generate file summary -async function generateFileSummary(filePath) { - const fs = require("fs"); - const path = require("path"); - - const content = fs.readFileSync(filePath, "utf-8"); - const fileName = path.basename(filePath); - - // Extract YAML frontmatter - const frontmatter = extractYAMLFrontmatter(content); - - // Extract markdown headings - const headings = extractMarkdownHeadings(content); - - // Extract first paragraph (skip frontmatter) - // Normalize line endings first - const normalized = content.replace(/\r\n/g, "\n"); - const textContent = normalized.replace(/^---\n[\s\S]*?\n---\n/, ""); - const firstPara = textContent.trim().split("\n\n")[0] || ""; - const preview = firstPara.slice(0, 300); - - // Format summary - const parts = []; - parts.push(`📄 **${fileName}** _(Summary - ${(content.length / 1024).toFixed(1)}KB)_`); - parts.push(""); - - if (frontmatter.type || frontmatter.tags || frontmatter.created) { - parts.push("**Metadata:**"); - if (frontmatter.type) parts.push(`- Type: ${frontmatter.type}`); - if (frontmatter.tags && frontmatter.tags.length > 0) { - parts.push(`- Tags: ${frontmatter.tags.join(", ")}`); - } - if (frontmatter.created) parts.push(`- Created: ${frontmatter.created}`); - parts.push(""); - } - - if (headings.length > 0) { - parts.push(`**Structure:** ${headings.slice(0, 5).join(" > ")}`); - if (headings.length > 5) parts.push(`_(+${headings.length - 5} more sections)_`); - parts.push(""); - } - - if (preview) { - parts.push("**Preview:**"); - parts.push(preview + (firstPara.length > 300 ? "..." : "")); - parts.push(""); - } - - parts.push(`_📖 Use Read tool to view full content: \`${filePath}\`_`); - - return parts.join("\n"); -} - -// Helper: Extract YAML frontmatter -function extractYAMLFrontmatter(content) { - // Normalize line endings to \n - const normalized = content.replace(/\r\n/g, "\n"); - const frontmatterMatch = normalized.match(/^---\n([\s\S]*?)\n---/); - if (!frontmatterMatch) return {}; - - const yaml = frontmatterMatch[1]; - const result = {}; - - // Simple YAML parsing (key: value) - const lines = yaml.split("\n"); - for (const line of lines) { - const match = line.match(/^(\w+):\s*(.+)$/); - if (match) { - const [, key, value] = match; - - // Handle arrays - if (value.startsWith("[") && value.endsWith("]")) { - result[key] = value - .slice(1, -1) - .split(",") - .map(v => v.trim().replace(/^["']|["']$/g, "")); - } else { - result[key] = value.replace(/^["']|["']$/g, ""); - } - } - } - - return result; -} - -// Helper: Extract markdown headings -function extractMarkdownHeadings(content) { - const headings = []; - // Normalize line endings - const lines = content.replace(/\r\n/g, "\n").split("\n"); - - for (const line of lines) { - const match = line.match(/^#{1,6}\s+(.+)$/); - if (match) { - headings.push(match[1].trim()); - } - } - - return headings; -} - -// src/utils/env.ts -var path = __toESM(require("path")); -var isWindows = process.platform === "win32"; -var PATH_SEPARATOR = isWindows ? ";" : ":"; -function getHomeDir() { - return process.env.HOME || process.env.USERPROFILE || ""; -} -function getExtraBinaryPaths() { - const home = getHomeDir(); - if (isWindows) { - const paths = []; - const localAppData = process.env.LOCALAPPDATA; - const appData = process.env.APPDATA; - const programFiles = process.env.ProgramFiles || "C:\\Program Files"; - const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"; - if (appData) { - paths.push(path.join(appData, "npm")); - paths.push(path.join(appData, "nvm")); - } - if (localAppData) { - paths.push(path.join(localAppData, "Programs", "node")); - } - paths.push(path.join(programFiles, "nodejs")); - paths.push(path.join(programFilesX86, "nodejs")); - paths.push(path.join(programFiles, "Docker", "Docker", "resources", "bin")); - if (home) { - paths.push(path.join(home, ".local", "bin")); - } - return paths; - } else { - const paths = [ - "/usr/local/bin", - "/opt/homebrew/bin", - // macOS ARM Homebrew - "/usr/bin", - "/bin" - ]; - if (home) { - paths.push(path.join(home, ".local", "bin")); - paths.push(path.join(home, ".docker", "bin")); - const nvmBin = process.env.NVM_BIN; - if (nvmBin) { - paths.push(nvmBin); - } - } - return paths; - } -} -function getEnhancedPath(additionalPaths) { - const extraPaths = getExtraBinaryPaths().filter((p) => p); - const currentPath = process.env.PATH || ""; - const segments = []; - if (additionalPaths) { - segments.push(...additionalPaths.split(PATH_SEPARATOR).filter((p) => p)); - } - segments.push(...extraPaths); - if (currentPath) { - segments.push(...currentPath.split(PATH_SEPARATOR).filter((p) => p)); - } - const seen = /* @__PURE__ */ new Set(); - const unique = segments.filter((p) => { - const normalized = isWindows ? p.toLowerCase() : p; - if (seen.has(normalized)) return false; - seen.add(normalized); - return true; - }); - return unique.join(PATH_SEPARATOR); -} -function parseEnvironmentVariables(input) { - const result = {}; - for (const line of input.split(/\r?\n/)) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - const eqIndex = trimmed.indexOf("="); - if (eqIndex > 0) { - const key = trimmed.substring(0, eqIndex).trim(); - let value = trimmed.substring(eqIndex + 1).trim(); - if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) { - value = value.slice(1, -1); - } - if (key) { - result[key] = value; - } - } - } - return result; -} -function getModelsFromEnvironment(envVars) { - const modelMap = /* @__PURE__ */ new Map(); - const modelEnvEntries = [ - { type: "model", envKey: "ANTHROPIC_MODEL" }, - { type: "opus", envKey: "ANTHROPIC_DEFAULT_OPUS_MODEL" }, - { type: "sonnet", envKey: "ANTHROPIC_DEFAULT_SONNET_MODEL" }, - { type: "haiku", envKey: "ANTHROPIC_DEFAULT_HAIKU_MODEL" } - ]; - for (const { type, envKey } of modelEnvEntries) { - const modelValue = envVars[envKey]; - if (modelValue) { - const label = modelValue.includes("/") ? modelValue.split("/").pop() || modelValue : modelValue.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase()); - if (!modelMap.has(modelValue)) { - modelMap.set(modelValue, { types: [type], label }); - } else { - modelMap.get(modelValue).types.push(type); - } - } - } - const models = []; - const typePriority = { "model": 4, "haiku": 3, "sonnet": 2, "opus": 1 }; - const sortedEntries = Array.from(modelMap.entries()).sort(([, aInfo], [, bInfo]) => { - const aPriority = Math.max(...aInfo.types.map((t) => typePriority[t] || 0)); - const bPriority = Math.max(...bInfo.types.map((t) => typePriority[t] || 0)); - return bPriority - aPriority; - }); - for (const [modelValue, info] of sortedEntries) { - const sortedTypes = info.types.sort( - (a, b) => (typePriority[b] || 0) - (typePriority[a] || 0) - ); - models.push({ - value: modelValue, - label: info.label, - description: `Custom model (${sortedTypes.join(", ")})` - }); - } - return models; -} -function getCurrentModelFromEnvironment(envVars) { - if (envVars.ANTHROPIC_MODEL) { - return envVars.ANTHROPIC_MODEL; - } - if (envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL) { - return envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL; - } - if (envVars.ANTHROPIC_DEFAULT_SONNET_MODEL) { - return envVars.ANTHROPIC_DEFAULT_SONNET_MODEL; - } - if (envVars.ANTHROPIC_DEFAULT_OPUS_MODEL) { - return envVars.ANTHROPIC_DEFAULT_OPUS_MODEL; - } - return null; -} - -// src/utils/path.ts -var fs2 = __toESM(require("fs")); -var os = __toESM(require("os")); -var path2 = __toESM(require("path")); -function getVaultPath(app) { - const adapter = app.vault.adapter; - if ("basePath" in adapter) { - return adapter.basePath; - } - return null; -} -function getEnvValue(key) { - const hasKey = (name) => Object.prototype.hasOwnProperty.call(process.env, name); - if (hasKey(key)) { - return process.env[key]; - } - if (process.platform !== "win32") { - return void 0; - } - const upper = key.toUpperCase(); - if (hasKey(upper)) { - return process.env[upper]; - } - const lower = key.toLowerCase(); - if (hasKey(lower)) { - return process.env[lower]; - } - const matchKey = Object.keys(process.env).find((name) => name.toLowerCase() === key.toLowerCase()); - return matchKey ? process.env[matchKey] : void 0; -} -function expandEnvironmentVariables(value) { - if (!value.includes("%") && !value.includes("$") && !value.includes("!")) { - return value; - } - const isWindows2 = process.platform === "win32"; - let expanded = value; - expanded = expanded.replace(/%([A-Za-z_][A-Za-z0-9_]*(?:\([A-Za-z0-9_]+\))?[A-Za-z0-9_]*)%/g, (match, name) => { - const envValue = getEnvValue(name); - return envValue !== void 0 ? envValue : match; - }); - if (isWindows2) { - expanded = expanded.replace(/!([A-Za-z_][A-Za-z0-9_]*)!/g, (match, name) => { - const envValue = getEnvValue(name); - return envValue !== void 0 ? envValue : match; - }); - expanded = expanded.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (match, name) => { - const envValue = getEnvValue(name); - return envValue !== void 0 ? envValue : match; - }); - } - expanded = expanded.replace(/\$([A-Za-z_][A-Za-z0-9_]*)|\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name1, name2) => { - const key = name1 != null ? name1 : name2; - if (!key) return match; - const envValue = getEnvValue(key); - return envValue !== void 0 ? envValue : match; - }); - return expanded; -} -function expandHomePath(p) { - const expanded = expandEnvironmentVariables(p); - if (expanded === "~") { - return os.homedir(); - } - if (expanded.startsWith("~/")) { - return path2.join(os.homedir(), expanded.slice(2)); - } - if (expanded.startsWith("~\\")) { - return path2.join(os.homedir(), expanded.slice(2)); - } - return expanded; -} -function getNpmGlobalPrefix() { - if (process.env.npm_config_prefix) { - return process.env.npm_config_prefix; - } - if (process.platform === "win32") { - const appDataNpm = process.env.APPDATA ? path2.join(process.env.APPDATA, "npm") : null; - if (appDataNpm && fs2.existsSync(appDataNpm)) { - return appDataNpm; - } - } - return null; -} -function getNpmCliJsPaths() { - const homeDir = os.homedir(); - const isWindows2 = process.platform === "win32"; - const cliJsPaths = []; - if (isWindows2) { - cliJsPaths.push( - path2.join(homeDir, "AppData", "Roaming", "npm", "node_modules", "@anthropic-ai", "claude-code", "cli.js") - ); - const npmPrefix = getNpmGlobalPrefix(); - if (npmPrefix) { - cliJsPaths.push( - path2.join(npmPrefix, "node_modules", "@anthropic-ai", "claude-code", "cli.js") - ); - } - const programFiles = process.env.ProgramFiles || "C:\\Program Files"; - const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)"; - cliJsPaths.push( - path2.join(programFiles, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js"), - path2.join(programFilesX86, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js") - ); - cliJsPaths.push( - path2.join("D:", "Program Files", "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js") - ); - } else { - cliJsPaths.push( - path2.join(homeDir, ".npm-global", "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js"), - "/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js", - "/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js" - ); - if (process.env.npm_config_prefix) { - cliJsPaths.push( - path2.join(process.env.npm_config_prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js") - ); - } - } - return cliJsPaths; -} -function findClaudeCLIPath() { - const homeDir = os.homedir(); - const isWindows2 = process.platform === "win32"; - if (isWindows2) { - const exePaths = [ - path2.join(homeDir, ".claude", "local", "claude.exe"), - path2.join(homeDir, "AppData", "Local", "Claude", "claude.exe"), - path2.join(process.env.ProgramFiles || "C:\\Program Files", "Claude", "claude.exe"), - path2.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Claude", "claude.exe"), - path2.join(homeDir, ".local", "bin", "claude.exe"), - path2.join(homeDir, ".bun", "bin", "claude.exe"), - ]; - for (const p of exePaths) { - if (fs2.existsSync(p)) { - return p; - } - } - const cliJsPaths = getNpmCliJsPaths(); - for (const p of cliJsPaths) { - if (fs2.existsSync(p)) { - return p; - } - } - const cmdPaths = [ - path2.join(homeDir, "AppData", "Roaming", "npm", "claude.cmd") - ]; - for (const p of cmdPaths) { - if (fs2.existsSync(p)) { - return p; - } - } - return null; - } - const commonPaths = [ - // Native binary paths (preferred) - path2.join(homeDir, ".claude", "local", "claude"), - path2.join(homeDir, ".local", "bin", "claude"), - path2.join(homeDir, ".bun", "bin", "claude"), - "/usr/local/bin/claude", - "/opt/homebrew/bin/claude", - path2.join(homeDir, "bin", "claude"), - // npm global bin symlinks (created by npm install -g) - path2.join(homeDir, ".npm-global", "bin", "claude") - ]; - const npmPrefix = getNpmGlobalPrefix(); - if (npmPrefix) { - commonPaths.push(path2.join(npmPrefix, "bin", "claude")); - } - for (const p of commonPaths) { - if (fs2.existsSync(p)) { - return p; - } - } - if (!isWindows2) { - const cliJsPaths = getNpmCliJsPaths(); - for (const p of cliJsPaths) { - if (fs2.existsSync(p)) { - return p; - } - } - } - return null; -} -function resolveRealPath(p) { - var _a; - const realpathFn = (_a = fs2.realpathSync.native) != null ? _a : fs2.realpathSync; - try { - return realpathFn(p); - } catch (e) { - const absolute = path2.resolve(p); - let current = absolute; - const suffix = []; - while (true) { - try { - if (fs2.existsSync(current)) { - const resolvedExisting = realpathFn(current); - return suffix.length > 0 ? path2.join(resolvedExisting, ...suffix.reverse()) : resolvedExisting; - } - } catch (e2) { - } - const parent = path2.dirname(current); - if (parent === current) { - return absolute; - } - suffix.push(path2.basename(current)); - current = parent; - } - } -} -function translateMsysPath(value) { - var _a; - if (process.platform !== "win32") { - return value; - } - const msysMatch = value.match(/^\/([a-zA-Z])(\/.*)?$/); - if (msysMatch) { - const driveLetter = msysMatch[1].toUpperCase(); - const restOfPath = (_a = msysMatch[2]) != null ? _a : ""; - return `${driveLetter}:${restOfPath.replace(/\//g, "\\")}`; + const value = getLiteralValue(methodSchema); + if (typeof value !== "string") { + throw new Error("Schema method literal must be a string"); } return value; } -function normalizePathBeforeResolution(p) { - const expanded = expandHomePath(p); - return translateMsysPath(expanded); +function parseWithCompat(schema, data) { + const result = safeParse2(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; } -function normalizeWindowsPathPrefix(value) { - if (process.platform !== "win32") { - return value; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js +var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +var Protocol = class { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = /* @__PURE__ */ new Map(); + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + this._notificationHandlers = /* @__PURE__ */ new Map(); + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers = /* @__PURE__ */ new Map(); + this._timeoutInfo = /* @__PURE__ */ new Map(); + this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + this._taskProgressTokens = /* @__PURE__ */ new Map(); + this._requestResolvers = /* @__PURE__ */ new Map(); + this.setNotificationHandler(CancelledNotificationSchema, (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler(ProgressNotificationSchema, (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler( + PingRequestSchema, + // Automatic pong by default. + (_request) => ({}) + ); + this._taskStore = _options == null ? void 0 : _options.taskStore; + this._taskMessageQueue = _options == null ? void 0 : _options.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return { + ...task + }; + }); + this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + var _a3; + const taskId = request.params.taskId; + if (this._taskMessageQueue) { + let queuedMessage; + while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { + if (queuedMessage.type === "response" || queuedMessage.type === "error") { + const message = queuedMessage.message; + const requestId = message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + this._requestResolvers.delete(requestId); + if (queuedMessage.type === "response") { + resolver(message); + } else { + const errorMessage = message; + const error48 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); + resolver(error48); + } + } else { + const messageType = queuedMessage.type === "response" ? "Response" : "Error"; + this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); + } + continue; + } + await ((_a3 = this._transport) == null ? void 0 : _a3.send(queuedMessage.message, { relatedRequestId: extra.requestId })); + } + } + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + if (!isTerminal(task.status)) { + await this._waitForTaskUpdate(taskId, extra.signal); + return await handleTaskResult(); + } + if (isTerminal(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId); + return { + ...result, + _meta: { + ...result._meta, + [RELATED_TASK_META_KEY]: { + taskId + } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { + var _a3; + try { + const { tasks, nextCursor } = await this._taskStore.listTasks((_a3 = request.params) == null ? void 0 : _a3.cursor, extra.sessionId); + return { + tasks, + nextCursor, + _meta: {} + }; + } catch (error48) { + throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error48 instanceof Error ? error48.message : String(error48)}`); + } + }); + this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { + try { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + } + await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); + this._clearTaskQueue(request.params.taskId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) { + throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + } + return { + _meta: {}, + ...cancelledTask + }; + } catch (error48) { + if (error48 instanceof McpError) { + throw error48; + } + throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error48 instanceof Error ? error48.message : String(error48)}`); + } + }); + } } - const normalized = translateMsysPath(value); - if (normalized.startsWith("\\\\?\\UNC\\")) { - return `\\\\${normalized.slice("\\\\?\\UNC\\".length)}`; + async _oncancel(notification) { + if (!notification.params.requestId) { + return; + } + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller == null ? void 0 : controller.abort(notification.params.reason); } - if (normalized.startsWith("\\\\?\\")) { - return normalized.slice("\\\\?\\".length); + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); } - return normalized; -} -function normalizePathForFilesystem(value) { - if (!value || typeof value !== "string") { - return ""; + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; } - const expanded = normalizePathBeforeResolution(value); - let normalized = expanded; - try { - normalized = process.platform === "win32" ? path2.win32.normalize(expanded) : path2.normalize(expanded); - } catch (e) { - normalized = expanded; + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } } - return normalizeWindowsPathPrefix(normalized); -} -function normalizePathForComparison(value) { - if (!value || typeof value !== "string") { - return ""; + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + var _a3, _b, _c; + this._transport = transport; + const _onclose = (_a3 = this.transport) == null ? void 0 : _a3.onclose; + this._transport.onclose = () => { + _onclose == null ? void 0 : _onclose(); + this._onclose(); + }; + const _onerror = (_b = this.transport) == null ? void 0 : _b.onerror; + this._transport.onerror = (error48) => { + _onerror == null ? void 0 : _onerror(error48); + this._onerror(error48); + }; + const _onmessage = (_c = this._transport) == null ? void 0 : _c.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage == null ? void 0 : _onmessage(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._onresponse(message); + } else if (isJSONRPCRequest(message)) { + this._onrequest(message, extra); + } else if (isJSONRPCNotification(message)) { + this._onnotification(message); + } else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); } - const expanded = normalizePathBeforeResolution(value); - let normalized = expanded; - try { - normalized = process.platform === "win32" ? path2.win32.normalize(expanded) : path2.normalize(expanded); - } catch (e) { - normalized = expanded; + _onclose() { + var _a3; + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + const error48 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + (_a3 = this.onclose) == null ? void 0 : _a3.call(this); + for (const handler of responseHandlers.values()) { + handler(error48); + } } - normalized = normalizeWindowsPathPrefix(normalized); - normalized = normalized.replace(/\\/g, "/").replace(/\/+$/, ""); - return process.platform === "win32" ? normalized.toLowerCase() : normalized; -} -function isPathWithinVault(candidatePath, vaultPath) { - const vaultReal = normalizePathForComparison(resolveRealPath(vaultPath)); - const normalizedPath = normalizePathBeforeResolution(candidatePath); - const absCandidate = path2.isAbsolute(normalizedPath) ? normalizedPath : path2.resolve(vaultPath, normalizedPath); - const resolvedCandidate = normalizePathForComparison(resolveRealPath(absCandidate)); - return resolvedCandidate === vaultReal || resolvedCandidate.startsWith(vaultReal + "/"); -} -function getPathAccessType(candidatePath, allowedContextPaths, allowedExportPaths, vaultPath) { - if (!candidatePath) return "none"; - const vaultReal = normalizePathForComparison(resolveRealPath(vaultPath)); - const normalizedCandidate = normalizePathBeforeResolution(candidatePath); - const absCandidate = path2.isAbsolute(normalizedCandidate) ? normalizedCandidate : path2.resolve(vaultPath, normalizedCandidate); - const resolvedCandidate = normalizePathForComparison(resolveRealPath(absCandidate)); - if (resolvedCandidate === vaultReal || resolvedCandidate.startsWith(vaultReal + "/")) { - return "vault"; + _onerror(error48) { + var _a3; + (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error48); } - const claudeDir = normalizePathForComparison(resolveRealPath(path2.join(os.homedir(), ".claude"))); - if (resolvedCandidate === claudeDir || resolvedCandidate.startsWith(claudeDir + "/")) { - return "vault"; + _onnotification(notification) { + var _a3; + const handler = (_a3 = this._notificationHandlers.get(notification.method)) != null ? _a3 : this.fallbackNotificationHandler; + if (handler === void 0) { + return; + } + Promise.resolve().then(() => handler(notification)).catch((error48) => this._onerror(new Error(`Uncaught error in notification handler: ${error48}`))); } - const roots = /* @__PURE__ */ new Map(); - const addRoot = (rawPath, kind) => { - var _a; - const trimmed = rawPath.trim(); - if (!trimmed) return; - const normalized = normalizePathBeforeResolution(trimmed); - const resolved = normalizePathForComparison(resolveRealPath(normalized)); - const existing = (_a = roots.get(resolved)) != null ? _a : { context: false, export: false }; - existing[kind] = true; - roots.set(resolved, existing); - }; - for (const contextPath of allowedContextPaths != null ? allowedContextPaths : []) { - addRoot(contextPath, "context"); + _onrequest(request, extra) { + var _a3, _b, _c, _d, _e; + const handler = (_a3 = this._requestHandlers.get(request.method)) != null ? _a3 : this.fallbackRequestHandler; + const capturedTransport = this._transport; + const relatedTaskId = (_d = (_c = (_b = request.params) == null ? void 0 : _b._meta) == null ? void 0 : _c[RELATED_TASK_META_KEY]) == null ? void 0 : _d.taskId; + if (handler === void 0) { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: "Method not found" + } + }; + if (relatedTaskId && this._taskMessageQueue) { + this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport == null ? void 0 : capturedTransport.sessionId).catch((error48) => this._onerror(new Error(`Failed to enqueue error response: ${error48}`))); + } else { + capturedTransport == null ? void 0 : capturedTransport.send(errorResponse).catch((error48) => this._onerror(new Error(`Failed to send an error response: ${error48}`))); + } + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport == null ? void 0 : capturedTransport.sessionId) : void 0; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport == null ? void 0 : capturedTransport.sessionId, + _meta: (_e = request.params) == null ? void 0 : _e._meta, + sendNotification: async (notification) => { + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) { + notificationOptions.relatedTask = { taskId: relatedTaskId }; + } + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r2, resultSchema, options) => { + var _a4, _b2; + const requestOptions = { ...options, relatedRequestId: request.id }; + if (relatedTaskId && !requestOptions.relatedTask) { + requestOptions.relatedTask = { taskId: relatedTaskId }; + } + const effectiveTaskId = (_b2 = (_a4 = requestOptions.relatedTask) == null ? void 0 : _a4.taskId) != null ? _b2 : relatedTaskId; + if (effectiveTaskId && taskStore) { + await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); + } + return await this.request(r2, resultSchema, requestOptions); + }, + authInfo: extra == null ? void 0 : extra.authInfo, + requestId: request.id, + requestInfo: extra == null ? void 0 : extra.requestInfo, + taskId: relatedTaskId, + taskStore, + taskRequestedTtl: taskCreationParams == null ? void 0 : taskCreationParams.ttl, + closeSSEStream: extra == null ? void 0 : extra.closeSSEStream, + closeStandaloneSSEStream: extra == null ? void 0 : extra.closeStandaloneSSEStream + }; + Promise.resolve().then(() => { + if (taskCreationParams) { + this.assertTaskHandlerCapability(request.method); + } + }).then(() => handler(request, fullExtra)).then(async (result) => { + if (abortController.signal.aborted) { + return; + } + const response = { + result, + jsonrpc: "2.0", + id: request.id + }; + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "response", + message: response, + timestamp: Date.now() + }, capturedTransport == null ? void 0 : capturedTransport.sessionId); + } else { + await (capturedTransport == null ? void 0 : capturedTransport.send(response)); + } + }, async (error48) => { + var _a4; + if (abortController.signal.aborted) { + return; + } + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: Number.isSafeInteger(error48["code"]) ? error48["code"] : ErrorCode.InternalError, + message: (_a4 = error48.message) != null ? _a4 : "Internal error", + ...error48["data"] !== void 0 && { data: error48["data"] } + } + }; + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport == null ? void 0 : capturedTransport.sessionId); + } else { + await (capturedTransport == null ? void 0 : capturedTransport.send(errorResponse)); + } + }).catch((error48) => this._onerror(new Error(`Failed to send response: ${error48}`))).finally(() => { + this._requestHandlerAbortControllers.delete(request.id); + }); } - for (const exportPath of allowedExportPaths != null ? allowedExportPaths : []) { - addRoot(exportPath, "export"); + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } catch (error48) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error48); + return; + } + } + handler(params); } - let bestRoot = null; - let bestFlags = null; - for (const [root2, flags] of roots) { - if (resolvedCandidate === root2 || resolvedCandidate.startsWith(root2 + "/")) { - if (!bestRoot || root2.length > bestRoot.length) { - bestRoot = root2; - bestFlags = flags; + _onresponse(response) { + const messageId = Number(response.id); + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if (isJSONRPCResultResponse(response)) { + resolver(response); + } else { + const error48 = new McpError(response.error.code, response.error.message, response.error.data); + resolver(error48); + } + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + let isTaskResponse = false; + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { + const result = response.result; + if (result.task && typeof result.task === "object") { + const task = result.task; + if (typeof task.taskId === "string") { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) { + this._progressHandlers.delete(messageId); + } + if (isJSONRPCResultResponse(response)) { + handler(response); + } else { + const error48 = McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error48); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + var _a3; + await ((_a3 = this._transport) == null ? void 0 : _a3.close()); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + async *requestStream(request, resultSchema, options) { + var _a3, _b, _c, _d; + const { task } = options != null ? options : {}; + if (!task) { + try { + const result = await this.request(request, resultSchema, options); + yield { type: "result", result }; + } catch (error48) { + yield { + type: "error", + error: error48 instanceof McpError ? error48 : new McpError(ErrorCode.InternalError, String(error48)) + }; + } + return; + } + let taskId; + try { + const createResult = await this.request(request, CreateTaskResultSchema, options); + if (createResult.task) { + taskId = createResult.task.taskId; + yield { type: "taskCreated", task: createResult.task }; + } else { + throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); + } + while (true) { + const task2 = await this.getTask({ taskId }, options); + yield { type: "taskStatus", task: task2 }; + if (isTerminal(task2.status)) { + if (task2.status === "completed") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + } else if (task2.status === "failed") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) + }; + } else if (task2.status === "cancelled") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + } + return; + } + if (task2.status === "input_required") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + return; + } + const pollInterval = (_c = (_b = task2.pollInterval) != null ? _b : (_a3 = this._options) == null ? void 0 : _a3.defaultTaskPollInterval) != null ? _c : 1e3; + await new Promise((resolve4) => setTimeout(resolve4, pollInterval)); + (_d = options == null ? void 0 : options.signal) == null ? void 0 : _d.throwIfAborted(); + } + } catch (error48) { + yield { + type: "error", + error: error48 instanceof McpError ? error48 : new McpError(ErrorCode.InternalError, String(error48)) + }; + } + } + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options != null ? options : {}; + return new Promise((resolve4, reject) => { + var _a3, _b, _c, _d, _e, _f, _g; + const earlyReject = (error48) => { + reject(error48); + }; + if (!this._transport) { + earlyReject(new Error("Not connected")); + return; + } + if (((_a3 = this._options) == null ? void 0 : _a3.enforceStrictCapabilities) === true) { + try { + this.assertCapabilityForMethod(request.method); + if (task) { + this.assertTaskCapability(request.method); + } + } catch (e2) { + earlyReject(e2); + return; + } + } + (_b = options == null ? void 0 : options.signal) == null ? void 0 : _b.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options == null ? void 0 : options.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...((_c = request.params) == null ? void 0 : _c._meta) || {}, + progressToken: messageId + } + }; + } + if (task) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task + }; + } + if (relatedTask) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...((_d = jsonrpcRequest.params) == null ? void 0 : _d._meta) || {}, + [RELATED_TASK_META_KEY]: relatedTask + } + }; + } + const cancel = (reason) => { + var _a4; + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + (_a4 = this._transport) == null ? void 0 : _a4.send({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error49) => this._onerror(new Error(`Failed to send cancellation: ${error49}`))); + const error48 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); + reject(error48); + }; + this._responseHandlers.set(messageId, (response) => { + var _a4; + if ((_a4 = options == null ? void 0 : options.signal) == null ? void 0 : _a4.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = safeParse2(resultSchema, response.result); + if (!parseResult.success) { + reject(parseResult.error); + } else { + resolve4(parseResult.data); + } + } catch (error48) { + reject(error48); + } + }); + (_e = options == null ? void 0 : options.signal) == null ? void 0 : _e.addEventListener("abort", () => { + var _a4; + cancel((_a4 = options == null ? void 0 : options.signal) == null ? void 0 : _a4.reason); + }); + const timeout = (_f = options == null ? void 0 : options.timeout) != null ? _f : DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options == null ? void 0 : options.maxTotalTimeout, timeoutHandler, (_g = options == null ? void 0 : options.resetTimeoutOnProgress) != null ? _g : false); + const relatedTaskId = relatedTask == null ? void 0 : relatedTask.taskId; + if (relatedTaskId) { + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) { + handler(response); + } else { + this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); + } + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: "request", + message: jsonrpcRequest, + timestamp: Date.now() + }).catch((error48) => { + this._cleanupTimeout(messageId); + reject(error48); + }); + } else { + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error48) => { + this._cleanupTimeout(messageId); + reject(error48); + }); + } + }); + } + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + async getTask(params, options) { + return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options); + } + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + async getTaskResult(params, resultSchema, options) { + return this.request({ method: "tasks/result", params }, resultSchema, options); + } + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + async listTasks(params, options) { + return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options); + } + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + async cancelTask(params, options) { + return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + var _a3, _b, _c, _d, _e; + if (!this._transport) { + throw new Error("Not connected"); + } + this.assertNotificationCapability(notification.method); + const relatedTaskId = (_a3 = options == null ? void 0 : options.relatedTask) == null ? void 0 : _a3.taskId; + if (relatedTaskId) { + const jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0", + params: { + ...notification.params, + _meta: { + ...((_b = notification.params) == null ? void 0 : _b._meta) || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: "notification", + message: jsonrpcNotification2, + timestamp: Date.now() + }); + return; + } + const debouncedMethods = (_d = (_c = this._options) == null ? void 0 : _c.debouncedNotificationMethods) != null ? _d : []; + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options == null ? void 0 : options.relatedRequestId) && !(options == null ? void 0 : options.relatedTask); + if (canDebounce) { + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + var _a4, _b2; + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) { + return; + } + let jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0" + }; + if (options == null ? void 0 : options.relatedTask) { + jsonrpcNotification2 = { + ...jsonrpcNotification2, + params: { + ...jsonrpcNotification2.params, + _meta: { + ...((_a4 = jsonrpcNotification2.params) == null ? void 0 : _a4._meta) || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + (_b2 = this._transport) == null ? void 0 : _b2.send(jsonrpcNotification2, options).catch((error48) => this._onerror(error48)); + }); + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: "2.0" + }; + if (options == null ? void 0 : options.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...((_e = jsonrpcNotification.params) == null ? void 0 : _e._meta) || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, (notification) => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== void 0) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + async _enqueueTaskMessage(taskId, message, sessionId) { + var _a3; + if (!this._taskStore || !this._taskMessageQueue) { + throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); + } + const maxQueueSize = (_a3 = this._options) == null ? void 0 : _a3.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); + } + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) { + if (message.type === "request" && isJSONRPCRequest(message.message)) { + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); + this._requestResolvers.delete(requestId); + } else { + this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } } } } - if (!bestRoot || !bestFlags) return "none"; - if (bestFlags.context && bestFlags.export) return "readwrite"; - if (bestFlags.context) return "context"; - if (bestFlags.export) return "export"; - return "none"; -} - -// src/utils/session.ts -var SESSION_ERROR_PATTERNS = [ - "session expired", - "session not found", - "invalid session", - "session invalid", - "process exited with code" -]; -var SESSION_ERROR_COMPOUND_PATTERNS = [ - { includes: ["session", "expired"] }, - { includes: ["resume", "failed"] }, - { includes: ["resume", "error"] } -]; -function isSessionExpiredError(error2) { - const msg = error2 instanceof Error ? error2.message.toLowerCase() : ""; - for (const pattern of SESSION_ERROR_PATTERNS) { - if (msg.includes(pattern)) { - return true; + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + async _waitForTaskUpdate(taskId, signal) { + var _a3, _b, _c; + let interval = (_b = (_a3 = this._options) == null ? void 0 : _a3.defaultTaskPollInterval) != null ? _b : 1e3; + try { + const task = await ((_c = this._taskStore) == null ? void 0 : _c.getTask(taskId)); + if (task == null ? void 0 : task.pollInterval) { + interval = task.pollInterval; + } + } catch (e2) { } + return new Promise((resolve4, reject) => { + if (signal.aborted) { + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + return; + } + const timeoutId = setTimeout(resolve4, interval); + signal.addEventListener("abort", () => { + clearTimeout(timeoutId); + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + }, { once: true }); + }); } - for (const { includes } of SESSION_ERROR_COMPOUND_PATTERNS) { - if (includes.every((part) => msg.includes(part))) { - return true; + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) { + throw new Error("No task store configured"); } + return { + createTask: async (taskParams) => { + if (!request) { + throw new Error("No request provided"); + } + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: task + }); + await this.notification(notification); + if (isTerminal(task.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + getTaskResult: (taskId) => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: updatedTask + }); + await this.notification(notification); + if (isTerminal(updatedTask.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + listTasks: (cursor) => { + return taskStore.listTasks(cursor, sessionId); + } + }; } - return false; +}; +function isPlainObject2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); } -function formatToolCallForContext(toolCall, maxResultLength = 800) { - var _a; - const status = (_a = toolCall.status) != null ? _a : "completed"; - const base = `[Tool ${toolCall.name} status=${status}]`; - const hasResult = typeof toolCall.result === "string" && toolCall.result.trim().length > 0; - if (!hasResult) { - return base; - } - const result = truncateToolResult(toolCall.result, maxResultLength); - return `${base} result: ${result}`; -} -function truncateToolResult(result, maxLength = 300) { - if (result.length > maxLength) { - return `${result.slice(0, maxLength)}... (truncated)`; +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) + continue; + const baseValue = result[k]; + if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } else { + result[k] = addValue; + } } return result; } -function formatContextLine(message) { - if (!message.currentNote) { + +// node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js +var import_ajv = __toESM(require_ajv(), 1); +var import_ajv_formats = __toESM(require_dist(), 1); +function createDefaultAjvInstance() { + const ajv = new import_ajv.default({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = import_ajv_formats.default; + addFormats(ajv); + return ajv; +} +var AjvJsonSchemaValidator = class { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv != null ? ajv : createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + var _a3; + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? (_a3 = this._ajv.getSchema(schema.$id)) != null ? _a3 : this._ajv.compile(schema) : this._ajv.compile(schema); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: void 0 + }; + } else { + return { + valid: false, + data: void 0, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js +var ExperimentalClientTasks = class { + constructor(_client) { + this._client = _client; + } + /** + * Calls a tool and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to tool execution, allowing you to + * observe intermediate task status updates for long-running tool calls. + * Automatically validates structured output if the tool has an outputSchema. + * + * @example + * ```typescript + * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} }); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Tool execution started:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Tool status:', message.task.status); + * break; + * case 'result': + * console.log('Tool result:', message.result); + * break; + * case 'error': + * console.error('Tool error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - Tool call parameters (name and arguments) + * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema) + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + async *callToolStream(params, resultSchema = CallToolResultSchema, options) { + var _a3; + const clientInternal = this._client; + const optionsWithTask = { + ...options, + // We check if the tool is known to be a task during auto-configuration, but assume + // the caller knows what they're doing if they pass this explicitly + task: (_a3 = options == null ? void 0 : options.task) != null ? _a3 : clientInternal.isToolTask(params.name) ? {} : void 0 + }; + const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask); + const validator = clientInternal.getToolOutputValidator(params.name); + for await (const message of stream) { + if (message.type === "result" && validator) { + const result = message.result; + if (!result.structuredContent && !result.isError) { + yield { + type: "error", + error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`) + }; + return; + } + if (result.structuredContent) { + try { + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + yield { + type: "error", + error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`) + }; + return; + } + } catch (error48) { + if (error48 instanceof McpError) { + yield { type: "error", error: error48 }; + return; + } + yield { + type: "error", + error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error48 instanceof Error ? error48.message : String(error48)}`) + }; + return; + } + } + } + yield message; + } + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._client.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + return this._client.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + return this._client.listTasks(cursor ? { cursor } : void 0, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + return this._client.cancelTask({ taskId }, options); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._client.requestStream(request, resultSchema, options); + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js +function assertToolsCallTaskCapability(requests, method, entityName) { + var _a3; + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case "tools/call": + if (!((_a3 = requests.tools) == null ? void 0 : _a3.call)) { + throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); + } + break; + default: + break; + } +} +function assertClientRequestTaskCapability(requests, method, entityName) { + var _a3, _b; + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case "sampling/createMessage": + if (!((_a3 = requests.sampling) == null ? void 0 : _a3.createMessage)) { + throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); + } + break; + case "elicitation/create": + if (!((_b = requests.elicitation) == null ? void 0 : _b.create)) { + throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); + } + break; + default: + break; + } +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== "object") + return; + if (schema.type === "object" && schema.properties && typeof schema.properties === "object") { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) { + obj[key] = propSchema.default; + } + if (obj[key] !== void 0) { + applyElicitationDefaults(propSchema, obj[key]); + } + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) { + if (typeof sub !== "boolean") { + applyElicitationDefaults(sub, data); + } + } + } + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) { + if (typeof sub !== "boolean") { + applyElicitationDefaults(sub, data); + } + } + } +} +function getSupportedElicitationModes(capabilities) { + if (!capabilities) { + return { supportsFormMode: false, supportsUrlMode: false }; + } + const hasFormCapability = capabilities.form !== void 0; + const hasUrlCapability = capabilities.url !== void 0; + const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability; + const supportsUrlMode = hasUrlCapability; + return { supportsFormMode, supportsUrlMode }; +} +var Client = class extends Protocol { + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + var _a3, _b; + super(options); + this._clientInfo = _clientInfo; + this._cachedToolOutputValidators = /* @__PURE__ */ new Map(); + this._cachedKnownTaskTools = /* @__PURE__ */ new Set(); + this._cachedRequiredTaskTools = /* @__PURE__ */ new Set(); + this._listChangedDebounceTimers = /* @__PURE__ */ new Map(); + this._capabilities = (_a3 = options == null ? void 0 : options.capabilities) != null ? _a3 : {}; + this._jsonSchemaValidator = (_b = options == null ? void 0 : options.jsonSchemaValidator) != null ? _b : new AjvJsonSchemaValidator(); + if (options == null ? void 0 : options.listChanged) { + this._pendingListChangedConfig = options.listChanged; + } + } + /** + * Set up handlers for list changed notifications based on config and server capabilities. + * This should only be called after initialization when server capabilities are known. + * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability. + * @internal + */ + _setupListChangedHandlers(config2) { + var _a3, _b, _c, _d, _e, _f; + if (config2.tools && ((_b = (_a3 = this._serverCapabilities) == null ? void 0 : _a3.tools) == null ? void 0 : _b.listChanged)) { + this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config2.tools, async () => { + const result = await this.listTools(); + return result.tools; + }); + } + if (config2.prompts && ((_d = (_c = this._serverCapabilities) == null ? void 0 : _c.prompts) == null ? void 0 : _d.listChanged)) { + this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config2.prompts, async () => { + const result = await this.listPrompts(); + return result.prompts; + }); + } + if (config2.resources && ((_f = (_e = this._serverCapabilities) == null ? void 0 : _e.resources) == null ? void 0 : _f.listChanged)) { + this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config2.resources, async () => { + const result = await this.listResources(); + return result.resources; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalClientTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error("Cannot register capabilities after connecting to transport"); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema, handler) { + var _a3, _b, _c; + const shape = getObjectShape(requestSchema); + const methodSchema = shape == null ? void 0 : shape.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); + } + let methodValue; + if (isZ4Schema(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def; + methodValue = (_b = v4Def == null ? void 0 : v4Def.value) != null ? _b : v4Schema.value; + } else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = (_c = legacyDef == null ? void 0 : legacyDef.value) != null ? _c : v3Schema.value; + } + if (typeof methodValue !== "string") { + throw new Error("Schema method literal must be a string"); + } + const method = methodValue; + if (method === "elicitation/create") { + const wrappedHandler = async (request, extra) => { + var _a4, _b2, _c2; + const validatedRequest = safeParse2(ElicitRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + params.mode = (_a4 = params.mode) != null ? _a4 : "form"; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === "form" && !supportsFormMode) { + throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests"); + } + if (params.mode === "url" && !supportsUrlMode) { + throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests"); + } + const result = await Promise.resolve(handler(request, extra)); + if (params.task) { + const taskValidationResult = safeParse2(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + const validationResult = safeParse2(ElicitResultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); + } + const validatedResult = validationResult.data; + const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0; + if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) { + if ((_c2 = (_b2 = this._capabilities.elicitation) == null ? void 0 : _b2.form) == null ? void 0 : _c2.applyDefaults) { + try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } catch (e2) { + } + } + } + return validatedResult; + }; + return super.setRequestHandler(requestSchema, wrappedHandler); + } + if (method === "sampling/createMessage") { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse2(CreateMessageRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + if (params.task) { + const taskValidationResult = safeParse2(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + const hasTools = params.tools || params.toolChoice; + const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema; + const validationResult = safeParse2(resultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`); + } + return validationResult.data; + }; + return super.setRequestHandler(requestSchema, wrappedHandler); + } + return super.setRequestHandler(requestSchema, handler); + } + assertCapability(capability, method) { + var _a3; + if (!((_a3 = this._serverCapabilities) == null ? void 0 : _a3[capability])) { + throw new Error(`Server does not support ${capability} (required for ${method})`); + } + } + async connect(transport, options) { + await super.connect(transport); + if (transport.sessionId !== void 0) { + return; + } + try { + const result = await this.request({ + method: "initialize", + params: { + protocolVersion: LATEST_PROTOCOL_VERSION, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, InitializeResultSchema, options); + if (result === void 0) { + throw new Error(`Server sent invalid initialize result: ${result}`); + } + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + } + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + if (transport.setProtocolVersion) { + transport.setProtocolVersion(result.protocolVersion); + } + this._instructions = result.instructions; + await this.notification({ + method: "notifications/initialized" + }); + if (this._pendingListChangedConfig) { + this._setupListChangedHandlers(this._pendingListChangedConfig); + this._pendingListChangedConfig = void 0; + } + } catch (error48) { + void this.close(); + throw error48; + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + assertCapabilityForMethod(method) { + var _a3, _b, _c, _d, _e; + switch (method) { + case "logging/setLevel": + if (!((_a3 = this._serverCapabilities) == null ? void 0 : _a3.logging)) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case "prompts/get": + case "prompts/list": + if (!((_b = this._serverCapabilities) == null ? void 0 : _b.prompts)) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + case "resources/subscribe": + case "resources/unsubscribe": + if (!((_c = this._serverCapabilities) == null ? void 0 : _c.resources)) { + throw new Error(`Server does not support resources (required for ${method})`); + } + if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) { + throw new Error(`Server does not support resource subscriptions (required for ${method})`); + } + break; + case "tools/call": + case "tools/list": + if (!((_d = this._serverCapabilities) == null ? void 0 : _d.tools)) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case "completion/complete": + if (!((_e = this._serverCapabilities) == null ? void 0 : _e.completions)) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case "initialize": + break; + case "ping": + break; + } + } + assertNotificationCapability(method) { + var _a3; + switch (method) { + case "notifications/roots/list_changed": + if (!((_a3 = this._capabilities.roots) == null ? void 0 : _a3.listChanged)) { + throw new Error(`Client does not support roots list changed notifications (required for ${method})`); + } + break; + case "notifications/initialized": + break; + case "notifications/cancelled": + break; + case "notifications/progress": + break; + } + } + assertRequestHandlerCapability(method) { + if (!this._capabilities) { + return; + } + switch (method) { + case "sampling/createMessage": + if (!this._capabilities.sampling) { + throw new Error(`Client does not support sampling capability (required for ${method})`); + } + break; + case "elicitation/create": + if (!this._capabilities.elicitation) { + throw new Error(`Client does not support elicitation capability (required for ${method})`); + } + break; + case "roots/list": + if (!this._capabilities.roots) { + throw new Error(`Client does not support roots capability (required for ${method})`); + } + break; + case "tasks/get": + case "tasks/list": + case "tasks/result": + case "tasks/cancel": + if (!this._capabilities.tasks) { + throw new Error(`Client does not support tasks capability (required for ${method})`); + } + break; + case "ping": + break; + } + } + assertTaskCapability(method) { + var _a3, _b; + assertToolsCallTaskCapability((_b = (_a3 = this._serverCapabilities) == null ? void 0 : _a3.tasks) == null ? void 0 : _b.requests, method, "Server"); + } + assertTaskHandlerCapability(method) { + var _a3; + if (!this._capabilities) { + return; + } + assertClientRequestTaskCapability((_a3 = this._capabilities.tasks) == null ? void 0 : _a3.requests, method, "Client"); + } + async ping(options) { + return this.request({ method: "ping" }, EmptyResultSchema, options); + } + async complete(params, options) { + return this.request({ method: "completion/complete", params }, CompleteResultSchema, options); + } + async setLoggingLevel(level, options) { + return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options); + } + async getPrompt(params, options) { + return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options); + } + async listPrompts(params, options) { + return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options); + } + async listResources(params, options) { + return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options); + } + async listResourceTemplates(params, options) { + return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options); + } + async readResource(params, options) { + return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options); + } + async subscribeResource(params, options) { + return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options); + } + async unsubscribeResource(params, options) { + return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options); + } + /** + * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema. + * + * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead. + */ + async callTool(params, resultSchema = CallToolResultSchema, options) { + if (this.isToolTaskRequired(params.name)) { + throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`); + } + const result = await this.request({ method: "tools/call", params }, resultSchema, options); + const validator = this.getToolOutputValidator(params.name); + if (validator) { + if (!result.structuredContent && !result.isError) { + throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + } + if (result.structuredContent) { + try { + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } + } catch (error48) { + if (error48 instanceof McpError) { + throw error48; + } + throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error48 instanceof Error ? error48.message : String(error48)}`); + } + } + } + return result; + } + isToolTask(toolName) { + var _a3, _b, _c, _d; + if (!((_d = (_c = (_b = (_a3 = this._serverCapabilities) == null ? void 0 : _a3.tasks) == null ? void 0 : _b.requests) == null ? void 0 : _c.tools) == null ? void 0 : _d.call)) { + return false; + } + return this._cachedKnownTaskTools.has(toolName); + } + /** + * Check if a tool requires task-based execution. + * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'. + */ + isToolTaskRequired(toolName) { + return this._cachedRequiredTaskTools.has(toolName); + } + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + cacheToolMetadata(tools) { + var _a3; + this._cachedToolOutputValidators.clear(); + this._cachedKnownTaskTools.clear(); + this._cachedRequiredTaskTools.clear(); + for (const tool of tools) { + if (tool.outputSchema) { + const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); + this._cachedToolOutputValidators.set(tool.name, toolValidator); + } + const taskSupport = (_a3 = tool.execution) == null ? void 0 : _a3.taskSupport; + if (taskSupport === "required" || taskSupport === "optional") { + this._cachedKnownTaskTools.add(tool.name); + } + if (taskSupport === "required") { + this._cachedRequiredTaskTools.add(tool.name); + } + } + } + /** + * Get cached validator for a tool + */ + getToolOutputValidator(toolName) { + return this._cachedToolOutputValidators.get(toolName); + } + async listTools(params, options) { + const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options); + this.cacheToolMetadata(result.tools); + return result; + } + /** + * Set up a single list changed handler. + * @internal + */ + _setupListChangedHandler(listType, notificationSchema, options, fetcher) { + const parseResult = ListChangedOptionsBaseSchema.safeParse(options); + if (!parseResult.success) { + throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`); + } + if (typeof options.onChanged !== "function") { + throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`); + } + const { autoRefresh, debounceMs } = parseResult.data; + const { onChanged } = options; + const refresh = async () => { + if (!autoRefresh) { + onChanged(null, null); + return; + } + try { + const items = await fetcher(); + onChanged(null, items); + } catch (e2) { + const error48 = e2 instanceof Error ? e2 : new Error(String(e2)); + onChanged(error48, null); + } + }; + const handler = () => { + if (debounceMs) { + const existingTimer = this._listChangedDebounceTimers.get(listType); + if (existingTimer) { + clearTimeout(existingTimer); + } + const timer = setTimeout(refresh, debounceMs); + this._listChangedDebounceTimers.set(listType, timer); + } else { + refresh(); + } + }; + this.setNotificationHandler(notificationSchema, handler); + } + async sendRootsListChanged() { + return this.notification({ method: "notifications/roots/list_changed" }); + } +}; + +// node_modules/eventsource-parser/dist/index.js +var ParseError = class extends Error { + constructor(message, options) { + super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; + } +}; +function noop(_arg) { +} +function createParser(callbacks) { + if (typeof callbacks == "function") + throw new TypeError( + "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" + ); + const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; + let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; + function feed(newChunk) { + const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); + for (const line of complete) + parseLine(line); + incompleteLine = incomplete, isFirstChunk = false; + } + function parseLine(line) { + if (line === "") { + dispatchEvent(); + return; + } + if (line.startsWith(":")) { + onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); + return; + } + const fieldSeparatorIndex = line.indexOf(":"); + if (fieldSeparatorIndex !== -1) { + const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); + processField(field, value, line); + return; + } + processField(line, "", line); + } + function processField(field, value, line) { + switch (field) { + case "event": + eventType = value; + break; + case "data": + data = `${data}${value} +`; + break; + case "id": + id = value.includes("\0") ? void 0 : value; + break; + case "retry": + /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( + new ParseError(`Invalid \`retry\` value: "${value}"`, { + type: "invalid-retry", + value, + line + }) + ); + break; + default: + onError( + new ParseError( + `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, + { type: "unknown-field", field, value, line } + ) + ); + break; + } + } + function dispatchEvent() { + data.length > 0 && onEvent({ + id, + event: eventType || void 0, + // If the data buffer's last character is a U+000A LINE FEED (LF) character, + // then remove the last character from the data buffer. + data: data.endsWith(` +`) ? data.slice(0, -1) : data + }), id = void 0, data = "", eventType = ""; + } + function reset(options = {}) { + incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = ""; + } + return { feed, reset }; +} +function splitLines(chunk) { + const lines = []; + let incompleteLine = "", searchIndex = 0; + for (; searchIndex < chunk.length; ) { + const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` +`, searchIndex); + let lineEnd = -1; + if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) { + incompleteLine = chunk.slice(searchIndex); + break; + } else { + const line = chunk.slice(searchIndex, lineEnd); + lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === ` +` && searchIndex++; + } + } + return [lines, incompleteLine]; +} + +// node_modules/eventsource/dist/index.js +var ErrorEvent = class extends Event { + /** + * Constructs a new `ErrorEvent` instance. This is typically not called directly, + * but rather emitted by the `EventSource` object when an error occurs. + * + * @param type - The type of the event (should be "error") + * @param errorEventInitDict - Optional properties to include in the error event + */ + constructor(type, errorEventInitDict) { + var _a3, _b; + super(type), this.code = (_a3 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a3 : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0; + } + /** + * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Node.js when you `console.log` an instance of this class. + * + * @param _depth - The current depth + * @param options - The options passed to `util.inspect` + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @returns A string representation of the error + */ + [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) { + return inspect(inspectableError(this), options); + } + /** + * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance, + * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, + * we explicitly include the properties in the `inspect` method. + * + * This is automatically called by Deno when you `console.log` an instance of this class. + * + * @param inspect - The inspect function to use (prevents having to import it from `util`) + * @param options - The options passed to `Deno.inspect` + * @returns A string representation of the error + */ + [/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) { + return inspect(inspectableError(this), options); + } +}; +function syntaxError(message) { + const DomException = globalThis.DOMException; + return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message); +} +function flattenError2(err) { + return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError2).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError2(err.cause)}` : err.message : `${err}`; +} +function inspectableError(err) { + return { + type: err.type, + message: err.message, + code: err.code, + defaultPrevented: err.defaultPrevented, + cancelable: err.cancelable, + timeStamp: err.timeStamp + }; +} +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); +var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); +var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); +var _readyState; +var _url2; +var _redirectUrl; +var _withCredentials; +var _fetch; +var _reconnectInterval; +var _reconnectTimer; +var _lastEventId; +var _controller; +var _parser; +var _onError; +var _onMessage; +var _onOpen; +var _EventSource_instances; +var connect_fn; +var _onFetchResponse; +var _onFetchError; +var getRequestOptions_fn; +var _onEvent; +var _onRetryChange; +var failConnection_fn; +var scheduleReconnect_fn; +var _reconnect; +var EventSource = class extends EventTarget { + constructor(url2, eventSourceInitDict) { + var _a3, _b; + super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url2), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => { + var _a22; + __privateGet(this, _parser).reset(); + const { body, redirected, status, headers } = response; + if (status === 204) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close(); + return; + } + if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status); + return; + } + if (!(headers.get("content-type") || "").startsWith("text/event-stream")) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status); + return; + } + if (__privateGet(this, _readyState) === this.CLOSED) + return; + __privateSet(this, _readyState, this.OPEN); + const openEvent = new Event("open"); + if ((_a22 = __privateGet(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) { + __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close(); + return; + } + const decoder = new TextDecoder(), reader = body.getReader(); + let open = true; + do { + const { done, value } = await reader.read(); + value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = false, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this)); + } while (open); + }), __privateAdd(this, _onFetchError, (err) => { + __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err)); + }), __privateAdd(this, _onEvent, (event) => { + typeof event.id == "string" && __privateSet(this, _lastEventId, event.id); + const messageEvent = new MessageEvent(event.event || "message", { + data: event.data, + origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url2).origin, + lastEventId: event.id || "" + }); + __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent); + }), __privateAdd(this, _onRetryChange, (value) => { + __privateSet(this, _reconnectInterval, value); + }), __privateAdd(this, _reconnect, () => { + __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this); + }); + try { + if (url2 instanceof URL) + __privateSet(this, _url2, url2); + else if (typeof url2 == "string") + __privateSet(this, _url2, new URL(url2, getBaseURL())); + else + throw new Error("Invalid URL"); + } catch (e2) { + throw syntaxError("An invalid or illegal string was specified"); + } + __privateSet(this, _parser, createParser({ + onEvent: __privateGet(this, _onEvent), + onRetry: __privateGet(this, _onRetryChange) + })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a3 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a3 : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this); + } + /** + * Returns the state of this EventSource object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + * + * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface, + * defined in the TypeScript `dom` library. + * + * @public + */ + get readyState() { + return __privateGet(this, _readyState); + } + /** + * Returns the URL providing the event stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + * + * @public + */ + get url() { + return __privateGet(this, _url2).href; + } + /** + * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials() { + return __privateGet(this, _withCredentials); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror() { + return __privateGet(this, _onError); + } + set onerror(value) { + __privateSet(this, _onError, value); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage() { + return __privateGet(this, _onMessage); + } + set onmessage(value) { + __privateSet(this, _onMessage, value); + } + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen() { + return __privateGet(this, _onOpen); + } + set onopen(value) { + __privateSet(this, _onOpen, value); + } + addEventListener(type, listener, options) { + const listen = listener; + super.addEventListener(type, listen, options); + } + removeEventListener(type, listener, options) { + const listen = listener; + super.removeEventListener(type, listen, options); + } + /** + * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + * + * @public + */ + close() { + __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0)); + } +}; +_readyState = /* @__PURE__ */ new WeakMap(), _url2 = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /** +* Connect to the given URL and start receiving events +* +* @internal +*/ +connect_fn = function() { + __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url2), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError)); +}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /** +* Get request options for the `fetch()` request +* +* @returns The request options +* @internal +*/ +getRequestOptions_fn = function() { + var _a3; + const init = { + // [spec] Let `corsAttributeState` be `Anonymous`… + // [spec] …will have their mode set to "cors"… + mode: "cors", + redirect: "follow", + headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 }, + cache: "no-store", + signal: (_a3 = __privateGet(this, _controller)) == null ? void 0 : _a3.signal + }; + return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init; +}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /** +* Handles the process referred to in the EventSource specification as "failing a connection". +* +* @param error - The error causing the connection to fail +* @param code - The HTTP status code, if available +* @internal +*/ +failConnection_fn = function(message, code) { + var _a3; + __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED); + const errorEvent = new ErrorEvent("error", { code, message }); + (_a3 = __privateGet(this, _onError)) == null || _a3.call(this, errorEvent), this.dispatchEvent(errorEvent); +}, /** +* Schedules a reconnection attempt against the EventSource endpoint. +* +* @param message - The error causing the connection to fail +* @param code - The HTTP status code, if available +* @internal +*/ +scheduleReconnect_fn = function(message, code) { + var _a3; + if (__privateGet(this, _readyState) === this.CLOSED) + return; + __privateSet(this, _readyState, this.CONNECTING); + const errorEvent = new ErrorEvent("error", { code, message }); + (_a3 = __privateGet(this, _onError)) == null || _a3.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval))); +}, _reconnect = /* @__PURE__ */ new WeakMap(), /** +* ReadyState representing an EventSource currently trying to connect +* +* @public +*/ +EventSource.CONNECTING = 0, /** +* ReadyState representing an EventSource connection that is open (eg connected) +* +* @public +*/ +EventSource.OPEN = 1, /** +* ReadyState representing an EventSource connection that is closed (eg disconnected) +* +* @public +*/ +EventSource.CLOSED = 2; +function getBaseURL() { + const doc = "document" in globalThis ? globalThis.document : void 0; + return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0; +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js +function normalizeHeaders(headers) { + if (!headers) + return {}; + if (headers instanceof Headers) { + return Object.fromEntries(headers.entries()); + } + if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } + return { ...headers }; +} +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) { + return baseFetch; + } + return async (url2, init) => { + const mergedInit = { + ...baseInit, + ...init, + // Headers need special handling - merge instead of replace + headers: (init == null ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers + }; + return baseFetch(url2, mergedInit); + }; +} + +// node_modules/pkce-challenge/dist/index.browser.js +var crypto; +crypto = globalThis.crypto; +async function getRandomValues(size) { + return (await crypto).getRandomValues(new Uint8Array(size)); +} +async function random(size) { + const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"; + const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length; + let result = ""; + while (result.length < size) { + const randomBytes = await getRandomValues(size - result.length); + for (const randomByte of randomBytes) { + if (randomByte < evenDistCutoff) { + result += mask[randomByte % mask.length]; + } + } + } + return result; +} +async function generateVerifier(length) { + return await random(length); +} +async function generateChallenge(code_verifier) { + const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier)); + return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, ""); +} +async function pkceChallenge(length) { + if (!length) + length = 43; + if (length < 43 || length > 128) { + throw `Expected a length between 43 and 128. Received ${length}.`; + } + const verifier = await generateVerifier(length); + const challenge = await generateChallenge(verifier); + return { + code_verifier: verifier, + code_challenge: challenge + }; +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js +var SafeUrlSchema = url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode2.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url2) => { + const u = new URL(url2); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +var OAuthProtectedResourceMetadataSchema = looseObject({ + resource: string3().url(), + authorization_servers: array(SafeUrlSchema).optional(), + jwks_uri: string3().url().optional(), + scopes_supported: array(string3()).optional(), + bearer_methods_supported: array(string3()).optional(), + resource_signing_alg_values_supported: array(string3()).optional(), + resource_name: string3().optional(), + resource_documentation: string3().optional(), + resource_policy_uri: string3().url().optional(), + resource_tos_uri: string3().url().optional(), + tls_client_certificate_bound_access_tokens: boolean3().optional(), + authorization_details_types_supported: array(string3()).optional(), + dpop_signing_alg_values_supported: array(string3()).optional(), + dpop_bound_access_tokens_required: boolean3().optional() +}); +var OAuthMetadataSchema = looseObject({ + issuer: string3(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string3()).optional(), + response_types_supported: array(string3()), + response_modes_supported: array(string3()).optional(), + grant_types_supported: array(string3()).optional(), + token_endpoint_auth_methods_supported: array(string3()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string3()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: array(string3()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: array(string3()).optional(), + introspection_endpoint: string3().optional(), + introspection_endpoint_auth_methods_supported: array(string3()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: array(string3()).optional(), + code_challenge_methods_supported: array(string3()).optional(), + client_id_metadata_document_supported: boolean3().optional() +}); +var OpenIdProviderMetadataSchema = looseObject({ + issuer: string3(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: array(string3()).optional(), + response_types_supported: array(string3()), + response_modes_supported: array(string3()).optional(), + grant_types_supported: array(string3()).optional(), + acr_values_supported: array(string3()).optional(), + subject_types_supported: array(string3()), + id_token_signing_alg_values_supported: array(string3()), + id_token_encryption_alg_values_supported: array(string3()).optional(), + id_token_encryption_enc_values_supported: array(string3()).optional(), + userinfo_signing_alg_values_supported: array(string3()).optional(), + userinfo_encryption_alg_values_supported: array(string3()).optional(), + userinfo_encryption_enc_values_supported: array(string3()).optional(), + request_object_signing_alg_values_supported: array(string3()).optional(), + request_object_encryption_alg_values_supported: array(string3()).optional(), + request_object_encryption_enc_values_supported: array(string3()).optional(), + token_endpoint_auth_methods_supported: array(string3()).optional(), + token_endpoint_auth_signing_alg_values_supported: array(string3()).optional(), + display_values_supported: array(string3()).optional(), + claim_types_supported: array(string3()).optional(), + claims_supported: array(string3()).optional(), + service_documentation: string3().optional(), + claims_locales_supported: array(string3()).optional(), + ui_locales_supported: array(string3()).optional(), + claims_parameter_supported: boolean3().optional(), + request_parameter_supported: boolean3().optional(), + request_uri_parameter_supported: boolean3().optional(), + require_request_uri_registration: boolean3().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: boolean3().optional() +}); +var OpenIdProviderDiscoveryMetadataSchema = object2({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ + code_challenge_methods_supported: true + }).shape +}); +var OAuthTokensSchema = object2({ + access_token: string3(), + id_token: string3().optional(), + // Optional for OAuth 2.1, but necessary in OpenID Connect + token_type: string3(), + expires_in: coerce_exports2.number().optional(), + scope: string3().optional(), + refresh_token: string3().optional() +}).strip(); +var OAuthErrorResponseSchema = object2({ + error: string3(), + error_description: string3().optional(), + error_uri: string3().optional() +}); +var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +var OAuthClientMetadataSchema = object2({ + redirect_uris: array(SafeUrlSchema), + token_endpoint_auth_method: string3().optional(), + grant_types: array(string3()).optional(), + response_types: array(string3()).optional(), + client_name: string3().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: string3().optional(), + contacts: array(string3()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: string3().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: string3().optional(), + software_version: string3().optional(), + software_statement: string3().optional() +}).strip(); +var OAuthClientInformationSchema = object2({ + client_id: string3(), + client_secret: string3().optional(), + client_id_issued_at: number3().optional(), + client_secret_expires_at: number3().optional() +}).strip(); +var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +var OAuthClientRegistrationErrorSchema = object2({ + error: string3(), + error_description: string3().optional() +}).strip(); +var OAuthTokenRevocationRequestSchema = object2({ + token: string3(), + token_type_hint: string3().optional() +}).strip(); + +// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js +function resourceUrlFromServerUrl(url2) { + const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href); + resourceURL.hash = ""; + return resourceURL; +} +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) { + return false; + } + if (requested.pathname.length < configured.pathname.length) { + return false; + } + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js +var OAuthError = class extends Error { + constructor(message, errorUri) { + super(message); + this.errorUri = errorUri; + this.name = this.constructor.name; + } + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject() { + const response = { + error: this.errorCode, + error_description: this.message + }; + if (this.errorUri) { + response.error_uri = this.errorUri; + } + return response; + } + get errorCode() { + return this.constructor.errorCode; + } +}; +var InvalidRequestError = class extends OAuthError { +}; +InvalidRequestError.errorCode = "invalid_request"; +var InvalidClientError = class extends OAuthError { +}; +InvalidClientError.errorCode = "invalid_client"; +var InvalidGrantError = class extends OAuthError { +}; +InvalidGrantError.errorCode = "invalid_grant"; +var UnauthorizedClientError = class extends OAuthError { +}; +UnauthorizedClientError.errorCode = "unauthorized_client"; +var UnsupportedGrantTypeError = class extends OAuthError { +}; +UnsupportedGrantTypeError.errorCode = "unsupported_grant_type"; +var InvalidScopeError = class extends OAuthError { +}; +InvalidScopeError.errorCode = "invalid_scope"; +var AccessDeniedError = class extends OAuthError { +}; +AccessDeniedError.errorCode = "access_denied"; +var ServerError = class extends OAuthError { +}; +ServerError.errorCode = "server_error"; +var TemporarilyUnavailableError = class extends OAuthError { +}; +TemporarilyUnavailableError.errorCode = "temporarily_unavailable"; +var UnsupportedResponseTypeError = class extends OAuthError { +}; +UnsupportedResponseTypeError.errorCode = "unsupported_response_type"; +var UnsupportedTokenTypeError = class extends OAuthError { +}; +UnsupportedTokenTypeError.errorCode = "unsupported_token_type"; +var InvalidTokenError = class extends OAuthError { +}; +InvalidTokenError.errorCode = "invalid_token"; +var MethodNotAllowedError = class extends OAuthError { +}; +MethodNotAllowedError.errorCode = "method_not_allowed"; +var TooManyRequestsError = class extends OAuthError { +}; +TooManyRequestsError.errorCode = "too_many_requests"; +var InvalidClientMetadataError = class extends OAuthError { +}; +InvalidClientMetadataError.errorCode = "invalid_client_metadata"; +var InsufficientScopeError = class extends OAuthError { +}; +InsufficientScopeError.errorCode = "insufficient_scope"; +var InvalidTargetError = class extends OAuthError { +}; +InvalidTargetError.errorCode = "invalid_target"; +var OAUTH_ERRORS = { + [InvalidRequestError.errorCode]: InvalidRequestError, + [InvalidClientError.errorCode]: InvalidClientError, + [InvalidGrantError.errorCode]: InvalidGrantError, + [UnauthorizedClientError.errorCode]: UnauthorizedClientError, + [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, + [InvalidScopeError.errorCode]: InvalidScopeError, + [AccessDeniedError.errorCode]: AccessDeniedError, + [ServerError.errorCode]: ServerError, + [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, + [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, + [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, + [InvalidTokenError.errorCode]: InvalidTokenError, + [MethodNotAllowedError.errorCode]: MethodNotAllowedError, + [TooManyRequestsError.errorCode]: TooManyRequestsError, + [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, + [InsufficientScopeError.errorCode]: InsufficientScopeError, + [InvalidTargetError.errorCode]: InvalidTargetError +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js +var UnauthorizedError = class extends Error { + constructor(message) { + super(message != null ? message : "Unauthorized"); + } +}; +function isClientAuthMethod(method) { + return ["client_secret_basic", "client_secret_post", "none"].includes(method); +} +var AUTHORIZATION_CODE_RESPONSE_TYPE = "code"; +var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256"; +function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== void 0; + if (supportedMethods.length === 0) { + return hasClientSecret ? "client_secret_post" : "none"; + } + if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { + return clientInformation.token_endpoint_auth_method; + } + if (hasClientSecret && supportedMethods.includes("client_secret_basic")) { + return "client_secret_basic"; + } + if (hasClientSecret && supportedMethods.includes("client_secret_post")) { + return "client_secret_post"; + } + if (supportedMethods.includes("none")) { + return "none"; + } + return hasClientSecret ? "client_secret_post" : "none"; +} +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case "client_secret_basic": + applyBasicAuth(client_id, client_secret, headers); + return; + case "client_secret_post": + applyPostAuth(client_id, client_secret, params); + return; + case "none": + applyPublicAuth(client_id, params); + return; + default: + throw new Error(`Unsupported client authentication method: ${method}`); + } +} +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) { + throw new Error("client_secret_basic authentication requires a client_secret"); + } + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set("Authorization", `Basic ${credentials}`); +} +function applyPostAuth(clientId, clientSecret, params) { + params.set("client_id", clientId); + if (clientSecret) { + params.set("client_secret", clientSecret); + } +} +function applyPublicAuth(clientId, params) { + params.set("client_id", clientId); +} +async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : void 0; + const body = input instanceof Response ? await input.text() : input; + try { + const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); + const { error: error48, error_description, error_uri } = result; + const errorClass = OAUTH_ERRORS[error48] || ServerError; + return new errorClass(error_description || "", error_uri); + } catch (error48) { + const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error48}. Raw body: ${body}`; + return new ServerError(errorMessage); + } +} +async function auth(provider, options) { + var _a3, _b; + try { + return await authInternal(provider, options); + } catch (error48) { + if (error48 instanceof InvalidClientError || error48 instanceof UnauthorizedClientError) { + await ((_a3 = provider.invalidateCredentials) == null ? void 0 : _a3.call(provider, "all")); + return await authInternal(provider, options); + } else if (error48 instanceof InvalidGrantError) { + await ((_b = provider.invalidateCredentials) == null ? void 0 : _b.call(provider, "tokens")); + return await authInternal(provider, options); + } + throw error48; + } +} +async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { + var _a3, _b; + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { + authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } + } catch (e2) { + } + if (!authorizationServerUrl) { + authorizationServerUrl = new URL("/", serverUrl); + } + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { + fetchFn + }); + let clientInformation = await Promise.resolve(provider.clientInformation()); + if (!clientInformation) { + if (authorizationCode !== void 0) { + throw new Error("Existing OAuth client information is required when exchanging an authorization code"); + } + const supportsUrlBasedClientId = (metadata == null ? void 0 : metadata.client_id_metadata_document_supported) === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { + throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + } + const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; + if (shouldUseUrlBasedClientId) { + clientInformation = { + client_id: clientMetadataUrl + }; + await ((_a3 = provider.saveClientInformation) == null ? void 0 : _a3.call(provider, clientInformation)); + } else { + if (!provider.saveClientInformation) { + throw new Error("OAuth client information must be saveable for dynamic registration"); + } + const fullInformation = await registerClient(authorizationServerUrl, { + metadata, + clientMetadata: provider.clientMetadata, + fetchFn + }); + await provider.saveClientInformation(fullInformation); + clientInformation = fullInformation; + } + } + const nonInteractiveFlow = !provider.redirectUrl; + if (authorizationCode !== void 0 || nonInteractiveFlow) { + const tokens2 = await fetchToken(provider, authorizationServerUrl, { + metadata, + resource, + authorizationCode, + fetchFn + }); + await provider.saveTokens(tokens2); + return "AUTHORIZED"; + } + const tokens = await provider.tokens(); + if (tokens == null ? void 0 : tokens.refresh_token) { + try { + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens(newTokens); + return "AUTHORIZED"; + } catch (error48) { + if (!(error48 instanceof OAuthError) || error48 instanceof ServerError) { + } else { + throw error48; + } + } + } + const state = provider.state ? await provider.state() : void 0; + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: scope || ((_b = resourceMetadata == null ? void 0 : resourceMetadata.scopes_supported) == null ? void 0 : _b.join(" ")) || provider.clientMetadata.scope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return "REDIRECT"; +} +function isHttpsUrl(value) { + if (!value) + return false; + try { + const url2 = new URL(value); + return url2.protocol === "https:" && url2.pathname !== "/"; + } catch (e2) { + return false; + } +} +async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = resourceUrlFromServerUrl(serverUrl); + if (provider.validateResourceURL) { + return await provider.validateResourceURL(defaultResource, resourceMetadata == null ? void 0 : resourceMetadata.resource); + } + if (!resourceMetadata) { + return void 0; + } + if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + } + return new URL(resourceMetadata.resource); +} +function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get("WWW-Authenticate"); + if (!authenticateHeader) { + return {}; + } + const [type, scheme] = authenticateHeader.split(" "); + if (type.toLowerCase() !== "bearer" || !scheme) { + return {}; + } + const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0; + let resourceMetadataUrl; + if (resourceMetadataMatch) { + try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } catch (e2) { + } + } + const scope = extractFieldFromWwwAuth(res, "scope") || void 0; + const error48 = extractFieldFromWwwAuth(res, "error") || void 0; + return { + resourceMetadataUrl, + scope, + error: error48 + }; +} +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get("WWW-Authenticate"); + if (!wwwAuthHeader) { return null; } - return formatCurrentNote(message.currentNote); -} -// === HISTORY OPTIMIZATION: Token-based message window === -function buildContextFromHistory(messages, tokenBudget = 4e3) { - var _a, _b, _c; - - if (!messages || messages.length === 0) { - return ""; + const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) { + return match[1] || match[2]; } - - // Helper: Estimate tokens for a message (rough approximation: 1 token ≈ 4 characters) - function estimateMessageTokens(message2) { - var _a2; - let chars = 0; - - // Content - if (message2.content) { - chars += message2.content.length; - } - - // Tool calls - if ((_a2 = message2.toolCalls) == null ? void 0 : _a2.length) { - for (const tc of message2.toolCalls) { - chars += (tc.name || "").length; - chars += JSON.stringify(tc.args || {}).length; - chars += (tc.result || "").length; + return null; +} +async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + var _a3, _b; + const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, { + protocolVersion: opts == null ? void 0 : opts.protocolVersion, + metadataUrl: opts == null ? void 0 : opts.resourceMetadataUrl + }); + if (!response || response.status === 404) { + await ((_a3 = response == null ? void 0 : response.body) == null ? void 0 : _a3.cancel()); + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + await ((_b = response.body) == null ? void 0 : _b.cancel()); + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) { + try { + return await fetchFn(url2, { headers }); + } catch (error48) { + if (error48 instanceof TypeError) { + if (headers) { + return fetchWithCorsRetry(url2, void 0, fetchFn); + } else { + return void 0; } } - - return Math.ceil(chars / 4); + throw error48; } - - const selectedMessages = []; - let currentTokens = 0; - - // Always include the first message (initial context) - if (messages.length > 0) { - selectedMessages.push(messages[0]); - currentTokens += estimateMessageTokens(messages[0]); +} +function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) { + if (pathname.endsWith("/")) { + pathname = pathname.slice(0, -1); } - - // Add recent messages from newest to oldest, respecting budget - let skipped = 0; - for (let i = messages.length - 1; i >= 1; i--) { - const msg = messages[i]; - const msgTokens = estimateMessageTokens(msg); - - if (currentTokens + msgTokens > tokenBudget) { - // Budget exceeded, mark remaining as skipped - skipped = i; - break; - } - - selectedMessages.splice(1, 0, msg); // Insert after first message - currentTokens += msgTokens; + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) { + const headers = { + "MCP-Protocol-Version": protocolVersion + }; + return await fetchWithCorsRetry(url2, headers, fetchFn); +} +function shouldAttemptFallback(response, pathname) { + return !response || response.status >= 400 && response.status < 500 && pathname !== "/"; +} +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + var _a3, _b; + const issuer = new URL(serverUrl); + const protocolVersion = (_a3 = opts == null ? void 0 : opts.protocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION; + let url2; + if (opts == null ? void 0 : opts.metadataUrl) { + url2 = new URL(opts.metadataUrl); + } else { + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url2 = new URL(wellKnownPath, (_b = opts == null ? void 0 : opts.metadataServerUrl) != null ? _b : issuer); + url2.search = issuer.search; } - - // Format messages - const parts = []; - - // Add skipped indicator - if (skipped > 0) { - parts.push(`[${skipped} earlier messages omitted]`); + let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn); + if (!(opts == null ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) { + const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); + response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); } - - // Format selected messages - for (const message of selectedMessages) { - if (message.role !== "user" && message.role !== "assistant") { + return response; +} +function buildDiscoveryUrls(authorizationServerUrl) { + const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url2.pathname !== "/"; + const urlsToTry = []; + if (!hasPath) { + urlsToTry.push({ + url: new URL("/.well-known/oauth-authorization-server", url2.origin), + type: "oauth" + }); + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration`, url2.origin), + type: "oidc" + }); + return urlsToTry; + } + let pathname = url2.pathname; + if (pathname.endsWith("/")) { + pathname = pathname.slice(0, -1); + } + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin), + type: "oauth" + }); + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin), + type: "oidc" + }); + urlsToTry.push({ + url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin), + type: "oidc" + }); + return urlsToTry; +} +async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) { + var _a3; + const headers = { + "MCP-Protocol-Version": protocolVersion, + Accept: "application/json" + }; + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) { continue; } - - if (message.role === "assistant") { - const hasContent = message.content && message.content.trim().length > 0; - const hasToolResult = (_a = message.toolCalls) == null ? void 0 : _a.some( - (tc) => tc.result && tc.result.trim().length > 0 - ); - if (!hasContent && !hasToolResult) { + if (!response.ok) { + await ((_a3 = response.body) == null ? void 0 : _a3.cancel()); + if (response.status >= 400 && response.status < 500) { continue; } + throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`); } - - const role = message.role === "user" ? "User" : "Assistant"; - const lines = []; - const content = (_b = message.content) == null ? void 0 : _b.trim(); - const contextLine = formatContextLine(message); - const userPayload = contextLine ? content ? `${contextLine} - -${content}` : contextLine : content; - lines.push(userPayload ? `${role}: ${userPayload}` : `${role}:`); - - if (message.role === "assistant" && ((_c = message.toolCalls) == null ? void 0 : _c.length)) { - const toolLines = message.toolCalls.map((tc) => formatToolCallForContext(tc)).filter(Boolean); - if (toolLines.length > 0) { - lines.push(...toolLines); - } - } - - parts.push(lines.join("\n")); - } - - return parts.join("\n\n"); -} -function getLastUserMessage(messages) { - for (let i = messages.length - 1; i >= 0; i--) { - if (messages[i].role === "user") { - return messages[i]; + if (type === "oauth") { + return OAuthMetadataSchema.parse(await response.json()); + } else { + return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); } } return void 0; } - -// src/core/hooks/DiffTrackingHooks.ts -var fs3 = __toESM(require("fs")); -var path3 = __toESM(require("path")); - -// src/core/tools/toolNames.ts -var TOOL_AGENT_OUTPUT = "AgentOutputTool"; -var TOOL_ASK_USER_QUESTION = "AskUserQuestion"; -var TOOL_BASH = "Bash"; -var TOOL_BASH_OUTPUT = "BashOutput"; -var TOOL_EDIT = "Edit"; -var TOOL_GLOB = "Glob"; -var TOOL_GREP = "Grep"; -var TOOL_KILL_SHELL = "KillShell"; -var TOOL_LS = "LS"; -var TOOL_LIST_MCP_RESOURCES = "ListMcpResources"; -var TOOL_MCP = "Mcp"; -var TOOL_NOTEBOOK_EDIT = "NotebookEdit"; -var TOOL_READ = "Read"; -var TOOL_READ_MCP_RESOURCE = "ReadMcpResource"; -var TOOL_SKILL = "Skill"; -var TOOL_TASK = "Task"; -var TOOL_TODO_WRITE = "TodoWrite"; -var TOOL_WEB_FETCH = "WebFetch"; -var TOOL_WEB_SEARCH = "WebSearch"; -var TOOL_WRITE = "Write"; -var TOOL_ENTER_PLAN_MODE = "EnterPlanMode"; -var TOOL_EXIT_PLAN_MODE = "ExitPlanMode"; -var PLAN_MODE_TOOLS = [TOOL_ENTER_PLAN_MODE, TOOL_EXIT_PLAN_MODE]; -function isPlanModeTool(toolName) { - return PLAN_MODE_TOOLS.includes(toolName); +async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { + throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + } + if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { + throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } + } else { + authorizationUrl = new URL("/authorize", authorizationServerUrl); + } + const challenge = await pkceChallenge(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set("client_id", clientInformation.client_id); + authorizationUrl.searchParams.set("code_challenge", codeChallenge); + authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl)); + if (state) { + authorizationUrl.searchParams.set("state", state); + } + if (scope) { + authorizationUrl.searchParams.set("scope", scope); + } + if (scope == null ? void 0 : scope.includes("offline_access")) { + authorizationUrl.searchParams.append("prompt", "consent"); + } + if (resource) { + authorizationUrl.searchParams.set("resource", resource.href); + } + return { authorizationUrl, codeVerifier }; } -var EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT, TOOL_NOTEBOOK_EDIT]; -var WRITE_EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT]; -var FILE_TOOLS = [ - TOOL_READ, - TOOL_WRITE, - TOOL_EDIT, - TOOL_GLOB, - TOOL_GREP, - TOOL_LS, - TOOL_NOTEBOOK_EDIT, - TOOL_BASH -]; -var READ_ONLY_TOOLS = [ - TOOL_READ, - TOOL_GREP, - TOOL_GLOB, - TOOL_LS, - TOOL_WEB_SEARCH, - TOOL_WEB_FETCH -]; -function isEditTool(toolName) { - return EDIT_TOOLS.includes(toolName); +function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) { + return new URLSearchParams({ + grant_type: "authorization_code", + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); } -function isWriteEditTool(toolName) { - return WRITE_EDIT_TOOLS.includes(toolName); +async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) { + var _a3; + const tokenUrl = (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl); + const headers = new Headers({ + "Content-Type": "application/x-www-form-urlencoded", + Accept: "application/json" + }); + if (resource) { + tokenRequestParams.set("resource", resource.href); + } + if (addClientAuthentication) { + await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata); + } else if (clientInformation) { + const supportedMethods = (_a3 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a3 : []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams); + } + const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, { + method: "POST", + headers, + body: tokenRequestParams + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthTokensSchema.parse(await response.json()); } -function isFileTool(toolName) { - return FILE_TOOLS.includes(toolName); +async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + const tokenRequestParams = new URLSearchParams({ + grant_type: "refresh_token", + refresh_token: refreshToken + }); + const tokens = await executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation, + addClientAuthentication, + resource, + fetchFn + }); + return { refresh_token: refreshToken, ...tokens }; } -function isReadOnlyTool(toolName) { - return READ_ONLY_TOOLS.includes(toolName); +async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) { + const scope = provider.clientMetadata.scope; + let tokenRequestParams; + if (provider.prepareTokenRequest) { + tokenRequestParams = await provider.prepareTokenRequest(scope); + } + if (!tokenRequestParams) { + if (!authorizationCode) { + throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required"); + } + if (!provider.redirectUrl) { + throw new Error("redirectUrl is required for authorization_code flow"); + } + const codeVerifier = await provider.codeVerifier(); + tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl); + } + const clientInformation = await provider.clientInformation(); + return executeTokenRequest(authorizationServerUrl, { + metadata, + tokenRequestParams, + clientInformation: clientInformation != null ? clientInformation : void 0, + addClientAuthentication: provider.addClientAuthentication, + resource, + fetchFn + }); +} +async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) { + throw new Error("Incompatible auth server: does not support dynamic client registration"); + } + registrationUrl = new URL(metadata.registration_endpoint); + } else { + registrationUrl = new URL("/register", authorizationServerUrl); + } + const response = await (fetchFn != null ? fetchFn : fetch)(registrationUrl, { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + body: JSON.stringify(clientMetadata) + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthClientInformationFullSchema.parse(await response.json()); } -// src/core/hooks/DiffTrackingHooks.ts -var MAX_DIFF_SIZE = 100 * 1024; -function createFileHashPreHook(vaultPath, originalContents) { - return { - matcher: "Write|Edit|NotebookEdit", - hooks: [ - async (hookInput, toolUseId, _options) => { - const input = hookInput; - if (input.tool_name === TOOL_WRITE || input.tool_name === TOOL_EDIT) { - const rawPath = input.tool_input.file_path; - const filePath = typeof rawPath === "string" && rawPath ? rawPath : void 0; - if (filePath && vaultPath && toolUseId) { - const normalizedPath = normalizePathForFilesystem(filePath); - const fullPath = path3.isAbsolute(normalizedPath) ? normalizedPath : path3.join(vaultPath, normalizedPath); - try { - if (fs3.existsSync(fullPath)) { - const stats = fs3.statSync(fullPath); - if (stats.size <= MAX_DIFF_SIZE) { - const content = fs3.readFileSync(fullPath, "utf-8"); - originalContents.set(toolUseId, { filePath, content }); - } else { - originalContents.set(toolUseId, { filePath, content: null, skippedReason: "too_large" }); - } - } else { - originalContents.set(toolUseId, { filePath, content: "" }); - } - } catch (error2) { - console.warn("Failed to capture original file contents:", fullPath, error2); - originalContents.set(toolUseId, { filePath, content: null, skippedReason: "unavailable" }); - } - } - } - return { continue: true }; - } - ] - }; -} -function createFileHashPostHook(vaultPath, originalContents, pendingDiffData, postCallback) { - return { - matcher: "Write|Edit|NotebookEdit", - hooks: [ - async (hookInput, toolUseId, _options) => { - var _a, _b, _c; - const input = hookInput; - const isError = (_b = (_a = input.tool_result) == null ? void 0 : _a.is_error) != null ? _b : false; - if ((input.tool_name === TOOL_WRITE || input.tool_name === TOOL_EDIT) && toolUseId) { - const originalEntry = originalContents.get(toolUseId); - const rawPath = input.tool_input.file_path; - const filePath = typeof rawPath === "string" && rawPath ? rawPath : originalEntry == null ? void 0 : originalEntry.filePath; - if (!isError && filePath && vaultPath) { - const normalizedPath = normalizePathForFilesystem(filePath); - const fullPath = path3.isAbsolute(normalizedPath) ? normalizedPath : path3.join(vaultPath, normalizedPath); - let diffData; - if ((originalEntry == null ? void 0 : originalEntry.content) === null) { - diffData = { filePath, skippedReason: (_c = originalEntry.skippedReason) != null ? _c : "unavailable" }; - } else { - try { - if (fs3.existsSync(fullPath)) { - const stats = fs3.statSync(fullPath); - if (stats.size <= MAX_DIFF_SIZE) { - const newContent = fs3.readFileSync(fullPath, "utf-8"); - if (originalEntry && originalEntry.content !== void 0) { - diffData = { - filePath, - originalContent: originalEntry.content, - newContent - }; - } else { - diffData = { filePath, skippedReason: "unavailable" }; - } - } else { - diffData = { filePath, skippedReason: "too_large" }; - } - } else { - diffData = { filePath, skippedReason: "unavailable" }; - } - } catch (error2) { - console.warn("Failed to capture updated file contents:", fullPath, error2); - diffData = { filePath, skippedReason: "unavailable" }; - } - } - if (diffData) { - pendingDiffData.set(toolUseId, diffData); - } - } - originalContents.delete(toolUseId); - } - await (postCallback == null ? void 0 : postCallback.trackEditedFile(input.tool_name, input.tool_input, isError)); - return { continue: true }; - } - ] - }; -} - -// src/core/security/BashPathValidator.ts -var path4 = __toESM(require("path")); -function tokenizeBashCommand(command) { - var _a; - const tokens = []; - const tokenRegex = /(['"`])(.*?)\1|[^\s]+/g; - let match; - while ((match = tokenRegex.exec(command)) !== null) { - const token = (_a = match[2]) != null ? _a : match[0]; - const cleaned = token.trim(); - if (!cleaned) continue; - tokens.push(cleaned); +// node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js +var SseError = class extends Error { + constructor(code, message, event) { + super(`SSE error: ${message}`); + this.code = code; + this.event = event; } - return tokens; -} -function splitBashTokensIntoSegments(tokens) { - const separators = /* @__PURE__ */ new Set(["&&", "||", ";", "|"]); - const segments = []; - let current = []; - for (const token of tokens) { - if (separators.has(token)) { - if (current.length > 0) { - segments.push(current); - current = []; - } - continue; +}; +var SSEClientTransport = class { + constructor(url2, opts) { + this._url = url2; + this._resourceMetadataUrl = void 0; + this._scope = void 0; + this._eventSourceInit = opts == null ? void 0 : opts.eventSourceInit; + this._requestInit = opts == null ? void 0 : opts.requestInit; + this._authProvider = opts == null ? void 0 : opts.authProvider; + this._fetch = opts == null ? void 0 : opts.fetch; + this._fetchWithInit = createFetchWithInit(opts == null ? void 0 : opts.fetch, opts == null ? void 0 : opts.requestInit); + } + async _authThenStart() { + var _a3; + if (!this._authProvider) { + throw new UnauthorizedError("No auth provider"); } - current.push(token); - } - if (current.length > 0) { - segments.push(current); - } - return segments; -} -function getBashSegmentCommandName(segment) { - const wrappers = /* @__PURE__ */ new Set(["command", "env", "sudo"]); - let cmdIndex = 0; - while (cmdIndex < segment.length && wrappers.has(segment[cmdIndex])) { - cmdIndex += 1; - } - const rawCmd = segment[cmdIndex] || ""; - const cmdName = path4.basename(rawCmd); - return { cmdName, cmdIndex }; -} -function isBashOutputRedirectOperator(token) { - return token === ">" || token === ">>" || token === "1>" || token === "1>>" || token === "2>" || token === "2>>" || token === "&>" || token === "&>>" || token === ">|"; -} -function isBashInputRedirectOperator(token) { - return token === "<" || token === "<<" || token === "0<" || token === "0<<"; -} -function isBashOutputOptionExpectingValue(token) { - return token === "-o" || token === "--output" || token === "--out" || token === "--outfile" || token === "--output-file"; -} -function cleanPathToken(raw) { - let token = raw.trim(); - if (!token) return null; - if (token.startsWith('"') && token.endsWith('"') || token.startsWith("'") && token.endsWith("'") || token.startsWith("`") && token.endsWith("`")) { - token = token.slice(1, -1).trim(); - } - while (token.startsWith("(") || token.startsWith("[") || token.startsWith("{")) { - token = token.slice(1).trim(); - } - while (token.endsWith(")") || token.endsWith("]") || token.endsWith("}") || token.endsWith(";") || token.endsWith(",")) { - token = token.slice(0, -1).trim(); - } - if (!token) return null; - if (token === "." || token === "/" || token === "\\") return null; - return token; -} -function isPathLikeToken(token) { - const cleaned = token.trim(); - if (!cleaned) return false; - if (cleaned === "." || cleaned === "/" || cleaned === "\\" || cleaned === "--") return false; - const isWindows2 = process.platform === "win32"; - return ( - // Home directory paths (Unix and Windows style) - cleaned === "~" || cleaned.startsWith("~/") || isWindows2 && cleaned.startsWith("~\\") || // Relative paths - cleaned.startsWith("./") || cleaned.startsWith("../") || cleaned === ".." || isWindows2 && (cleaned.startsWith(".\\") || cleaned.startsWith("..\\")) || // Absolute paths (Unix) - cleaned.startsWith("/") || // Absolute paths (Windows drive letters) - isWindows2 && /^[A-Za-z]:[\\/]/.test(cleaned) || // Absolute paths (Windows UNC) - isWindows2 && (cleaned.startsWith("\\\\") || cleaned.startsWith("//")) || // Contains path separators - cleaned.includes("/") || isWindows2 && cleaned.includes("\\") - ); -} -function checkBashPathAccess(candidate, access, context) { - const cleaned = cleanPathToken(candidate); - if (!cleaned) return null; - const accessType = context.getPathAccessType(cleaned); - if (accessType === "vault" || accessType === "readwrite") { - return null; - } - if (accessType === "context") { - return access === "read" ? null : { type: "context_path_write", path: cleaned }; - } - if (accessType === "export") { - return access === "write" ? null : { type: "export_path_read", path: cleaned }; - } - return { type: "outside_vault", path: cleaned }; -} -function findBashPathViolationInSegment(segment, context) { - if (segment.length === 0) return null; - const { cmdName, cmdIndex } = getBashSegmentCommandName(segment); - const destinationCommands = /* @__PURE__ */ new Set(["cp", "mv", "rsync"]); - let destinationTokenIndex = null; - if (destinationCommands.has(cmdName)) { - const pathArgIndices = []; - let seenDoubleDash = false; - for (let i = cmdIndex + 1; i < segment.length; i += 1) { - const token = segment[i]; - if (!seenDoubleDash && token === "--") { - seenDoubleDash = true; - continue; - } - if (!seenDoubleDash && token.startsWith("-")) { - continue; - } - if (isPathLikeToken(token)) { - pathArgIndices.push(i); - } - } - if (pathArgIndices.length > 0) { - destinationTokenIndex = pathArgIndices[pathArgIndices.length - 1]; - } - } - let expectWriteNext = false; - for (let i = 0; i < segment.length; i += 1) { - const token = segment[i]; - if (isBashOutputRedirectOperator(token)) { - expectWriteNext = true; - continue; - } - if (isBashInputRedirectOperator(token)) { - expectWriteNext = false; - continue; - } - if (isBashOutputOptionExpectingValue(token)) { - expectWriteNext = true; - continue; - } - const embeddedOutputRedirect = token.match(/^(?:&>>|&>|\d*>>|\d*>\||\d*>|>>|>\||>)(.+)$/); - if (embeddedOutputRedirect) { - const violation2 = checkBashPathAccess(embeddedOutputRedirect[1], "write", context); - if (violation2) return violation2; - continue; - } - const embeddedInputRedirect = token.match(/^(?:\d*<<|\d*<|<<|<)(.+)$/); - if (embeddedInputRedirect) { - const violation2 = checkBashPathAccess(embeddedInputRedirect[1], "read", context); - if (violation2) return violation2; - continue; - } - const embeddedLongOutput = token.match(/^--(?:output|out|outfile|output-file)=(.+)$/); - if (embeddedLongOutput) { - const violation2 = checkBashPathAccess(embeddedLongOutput[1], "write", context); - if (violation2) return violation2; - continue; - } - const embeddedShortOutput = token.match(/^-o(.+)$/); - if (embeddedShortOutput) { - const violation2 = checkBashPathAccess(embeddedShortOutput[1], "write", context); - if (violation2) return violation2; - continue; - } - const eqIndex = token.indexOf("="); - if (eqIndex > 0) { - const key = token.slice(0, eqIndex); - const value = token.slice(eqIndex + 1); - if (key.startsWith("-") && isPathLikeToken(value)) { - const violation2 = checkBashPathAccess(value, "read", context); - if (violation2) return violation2; - } - } - if (!isPathLikeToken(token)) { - expectWriteNext = false; - continue; - } - const access = i === destinationTokenIndex || expectWriteNext ? "write" : "read"; - const violation = checkBashPathAccess(token, access, context); - if (violation) return violation; - expectWriteNext = false; - } - return null; -} -function findBashCommandPathViolation(command, context) { - if (!command) return null; - const tokens = tokenizeBashCommand(command); - const segments = splitBashTokensIntoSegments(tokens); - for (const segment of segments) { - const violation = findBashPathViolationInSegment(segment, context); - if (violation) { - return violation; - } - } - return null; -} - -// src/core/security/BlocklistChecker.ts -function isCommandBlocked(command, patterns, enableBlocklist) { - if (!enableBlocklist) { - return false; - } - return patterns.some((pattern) => { + let result; try { - return new RegExp(pattern, "i").test(command); - } catch (e) { - return command.toLowerCase().includes(pattern.toLowerCase()); + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } catch (error48) { + (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error48); + throw error48; } - }); -} - -// src/core/tools/toolInput.ts -function getPathFromToolInput(toolName, toolInput) { - switch (toolName) { - case TOOL_READ: - case TOOL_WRITE: - case TOOL_EDIT: - case TOOL_NOTEBOOK_EDIT: - return toolInput.file_path || toolInput.notebook_path || null; - case TOOL_GLOB: - return toolInput.path || toolInput.pattern || null; - case TOOL_GREP: - return toolInput.path || null; - case TOOL_LS: - return toolInput.path || null; - default: - return null; + if (result !== "AUTHORIZED") { + throw new UnauthorizedError(); + } + return await this._startOrAuth(); } -} - -// src/core/types/chat.ts -var VIEW_TYPE_CLAUDIAN = "claudian-view"; - -// src/core/types/models.ts -var DEFAULT_CLAUDE_MODELS = [ - { value: "haiku", label: "Haiku", description: "Fast and efficient" }, - { value: "sonnet", label: "Sonnet", description: "Balanced performance" }, - { value: "opus", label: "Opus", description: "Most capable" } -]; -var THINKING_BUDGETS = [ - { value: "off", label: "Off", tokens: 0 }, - { value: "low", label: "Low", tokens: 4e3 }, - { value: "medium", label: "Med", tokens: 8e3 }, - { value: "high", label: "High", tokens: 16e3 }, - { value: "xhigh", label: "Ultra", tokens: 32e3 } -]; -var DEFAULT_THINKING_BUDGET = { - "haiku": "off", - "sonnet": "low", - "opus": "medium" -}; - -// src/core/types/settings.ts -var UNIX_BLOCKED_COMMANDS = [ - "rm -rf", - "chmod 777", - "chmod -R 777" -]; -var WINDOWS_BLOCKED_COMMANDS = [ - // CMD commands - "del /s /q", - "rd /s /q", - "rmdir /s /q", - "format", - "diskpart", - // PowerShell Remove-Item variants (full and abbreviated flags) - "Remove-Item -Recurse -Force", - "Remove-Item -Force -Recurse", - "Remove-Item -r -fo", - "Remove-Item -fo -r", - "Remove-Item -Recurse", - "Remove-Item -r", - // PowerShell aliases for Remove-Item - "ri -Recurse", - "ri -r", - "ri -Force", - "ri -fo", - "rm -r -fo", - "rm -Recurse", - "rm -Force", - "del -Recurse", - "del -Force", - "erase -Recurse", - "erase -Force", - // PowerShell directory removal aliases - "rd -Recurse", - "rmdir -Recurse", - // Dangerous disk/volume commands - "Format-Volume", - "Clear-Disk", - "Initialize-Disk", - "Remove-Partition" -]; -function getDefaultBlockedCommands() { - return { - unix: [...UNIX_BLOCKED_COMMANDS], - windows: [...WINDOWS_BLOCKED_COMMANDS] - }; -} -function getCurrentPlatformKey() { - return process.platform === "win32" ? "windows" : "unix"; -} -function getCurrentPlatformBlockedCommands(commands) { - return commands[getCurrentPlatformKey()]; -} -function getBashToolBlockedCommands(commands) { - if (process.platform === "win32") { - return Array.from(/* @__PURE__ */ new Set([...commands.unix, ...commands.windows])); - } - return getCurrentPlatformBlockedCommands(commands); -} -var DEFAULT_SETTINGS = { - userName: "", - enableBlocklist: true, - blockedCommands: getDefaultBlockedCommands(), - model: "haiku", - enableAutoTitleGeneration: true, - titleGenerationModel: "", - // Empty = auto (ANTHROPIC_DEFAULT_HAIKU_MODEL or claude-haiku-4-5) - lastClaudeModel: "haiku", - lastCustomModel: "", - lastEnvHash: "", - thinkingBudget: "off", - permissionMode: "yolo", - lastNonPlanPermissionMode: "yolo", - permissions: [], - excludedTags: [], - mediaFolder: "", - environmentVariables: "", - envSnippets: [], - systemPrompt: "", - allowedExportPaths: ["~/Desktop", "~/Downloads"], - allowedContextPaths: [], - slashCommands: [], - keyboardNavigation: { - scrollUpKey: "w", - scrollDownKey: "s", - focusInputKey: "i" - }, - claudeCliPath: "" - // Empty = auto-detect -}; - -// src/core/types/mcp.ts -function getMcpServerType(config2) { - if (config2.type === "sse") return "sse"; - if (config2.type === "http") return "http"; - if ("url" in config2) return "http"; - return "stdio"; -} -function isValidMcpServerConfig(obj) { - if (!obj || typeof obj !== "object") return false; - const config2 = obj; - if (config2.command && typeof config2.command === "string") return true; - if (config2.url && typeof config2.url === "string") return true; - return false; -} -var DEFAULT_MCP_SERVER = { - enabled: true, - contextSaving: true -}; - -// src/core/hooks/SecurityHooks.ts -function createBlocklistHook(getContext) { - return { - matcher: TOOL_BASH, - hooks: [ - async (hookInput) => { - var _a; - const input = hookInput; - const command = ((_a = input.tool_input) == null ? void 0 : _a.command) || ""; - const context = getContext(); - const bashToolCommands = getBashToolBlockedCommands(context.blockedCommands); - if (isCommandBlocked(command, bashToolCommands, context.enableBlocklist)) { - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Command blocked by blocklist: ${command}` - } - }; - } - return { continue: true }; - } - ] - }; -} -function createVaultRestrictionHook(context) { - return { - hooks: [ - async (hookInput) => { - var _a; - const input = hookInput; - const toolName = input.tool_name; - if (toolName === TOOL_BASH) { - const command = ((_a = input.tool_input) == null ? void 0 : _a.command) || ""; - const pathCheckContext = { - getPathAccessType: (p) => context.getPathAccessType(p) - }; - const violation = findBashCommandPathViolation(command, pathCheckContext); - if (violation) { - const reason = violation.type === "export_path_read" ? `Access denied: Command path "${violation.path}" is in an allowed export directory, but export paths are write-only.` : violation.type === "context_path_write" ? `Access denied: Command path "${violation.path}" is in an allowed context directory, but context paths are read-only.` : `Access denied: Command path "${violation.path}" is outside the vault. Agent is restricted to vault directory only.`; - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: reason - } - }; - } - return { continue: true }; - } - if (!isFileTool(toolName)) { - return { continue: true }; - } - const filePath = getPathFromToolInput(toolName, input.tool_input); - if (filePath) { - const accessType = context.getPathAccessType(filePath); - if (accessType === "vault" || accessType === "readwrite") { - return { continue: true }; - } - if (!isEditTool(toolName) && accessType === "context") { - return { continue: true }; - } - if (isEditTool(toolName)) { - if (accessType === "export") { - return { continue: true }; - } - if (accessType === "context") { - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Access denied: Path "${filePath}" is in an allowed context directory, but context paths are read-only.` - } - }; - } - } - if (!isEditTool(toolName) && accessType === "export") { - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Access denied: Path "${filePath}" is in an allowed export directory, but export paths are write-only.` - } - }; - } - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Access denied: Path "${filePath}" is outside the vault. Agent is restricted to vault directory only.` - } - }; - } - return { continue: true }; - } - ] - }; -} - -// src/core/images/imageLoader.ts -var fs5 = __toESM(require("fs")); -var path6 = __toESM(require("path")); - -// src/core/images/imageCache.ts -var import_crypto4 = require("crypto"); -var fs4 = __toESM(require("fs")); -var path5 = __toESM(require("path")); -var IMAGE_CACHE_DIR = ".claudian-cache/images"; -function ensureImageCacheDir(app) { - const vaultPath = getVaultPath(app); - if (!vaultPath) return null; - const cacheDir = path5.join(vaultPath, IMAGE_CACHE_DIR); - fs4.mkdirSync(cacheDir, { recursive: true }); - return cacheDir; -} -function saveImageToCache(app, buffer, mediaType, preferredName) { - const cacheDir = ensureImageCacheDir(app); - if (!cacheDir) return null; - const hash = (0, import_crypto4.createHash)("sha256").update(buffer).digest("hex"); - const ext = getExtension(mediaType, preferredName); - const filename = `${hash}${ext}`; - const relPath = path5.posix.join(IMAGE_CACHE_DIR, filename); - const absPath = path5.join(cacheDir, filename); - if (!fs4.existsSync(absPath)) { - fs4.writeFileSync(absPath, buffer); - } - return { relPath, absPath }; -} -function readCachedImageBase64(app, relPath) { - const absPath = getCacheAbsolutePath(app, relPath); - if (!absPath) return null; - try { - const buffer = fs4.readFileSync(absPath); - return buffer.toString("base64"); - } catch (e) { - return null; - } -} -function deleteCachedImages(app, relPaths) { - const seen = /* @__PURE__ */ new Set(); - for (const relPath of relPaths) { - const normalized = normalizeCacheRelPath(relPath); - if (!normalized || seen.has(normalized)) continue; - seen.add(normalized); - const absPath = getCacheAbsolutePath(app, normalized); - if (absPath && fs4.existsSync(absPath)) { - try { - fs4.unlinkSync(absPath); - } catch (e) { + async _commonHeaders() { + var _a3; + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers["Authorization"] = `Bearer ${tokens.access_token}`; } } - } -} -function getCacheAbsolutePath(app, relPath) { - const vaultPath = getVaultPath(app); - if (!vaultPath) return null; - const normalizedRel = normalizeCacheRelPath(relPath); - if (!normalizedRel) return null; - const absPath = path5.resolve(vaultPath, normalizedRel); - const cacheRoot = path5.resolve(vaultPath, IMAGE_CACHE_DIR); - if (!absPath.startsWith(cacheRoot)) { - return null; - } - return absPath; -} -function normalizeCacheRelPath(relPath) { - if (!relPath) return null; - const normalized = relPath.replace(/\\/g, "/"); - if (path5.isAbsolute(normalized)) return null; - if (!normalized.startsWith(IMAGE_CACHE_DIR)) return null; - return normalized; -} -function getExtension(mediaType, preferredName) { - if (preferredName) { - const ext = path5.extname(preferredName); - if (ext) return ext; - } - const subtype = mediaType.split("/")[1] || "png"; - return `.${subtype === "jpeg" ? "jpg" : subtype}`; -} - -// src/core/images/imageLoader.ts -function resolveImageFilePath(filePath, vaultPath) { - const normalized = normalizePathForFilesystem(filePath); - if (path6.isAbsolute(normalized)) { - return normalized; - } - if (vaultPath) { - return path6.join(vaultPath, normalized); - } - return null; -} -function readFileBase64(absPath) { - try { - const buffer = fs5.readFileSync(absPath); - return buffer.toString("base64"); - } catch (error2) { - console.warn("Failed to read image file:", absPath, error2); - return null; - } -} -function readImageAttachmentBase64(app, image, vaultPath) { - if (image.cachePath) { - const cached2 = readCachedImageBase64(app, image.cachePath); - if (cached2) return cached2; - } - if (image.filePath) { - const vault = vaultPath != null ? vaultPath : getVaultPath(app); - const absPath = resolveImageFilePath(image.filePath, vault); - if (absPath && fs5.existsSync(absPath)) { - return readFileBase64(absPath); + if (this._protocolVersion) { + headers["mcp-protocol-version"] = this._protocolVersion; } - } - return null; -} -function ensureImageAttachmentBase64(app, image, vaultPath) { - if (image.data) return image.data; - const base642 = readImageAttachmentBase64(app, image, vaultPath); - if (base642) { - image.data = base642; - } - return base642; -} -function toImageDataUri(mediaType, base642) { - return `data:${mediaType};base64,${base642}`; -} -function getImageAttachmentDataUri(app, image, vaultPath) { - const base642 = ensureImageAttachmentBase64(app, image, vaultPath); - if (!base642) return null; - return toImageDataUri(image.mediaType, base642); -} -async function hydrateImagesData(app, images, vaultPath) { - if (!images || images.length === 0) return void 0; - const hydrated = []; - for (const image of images) { - if (image.data) { - hydrated.push(image); - continue; - } - const base642 = readImageAttachmentBase64(app, image, vaultPath); - if (base642) { - hydrated.push({ ...image, data: base642 }); - } - } - return hydrated.length > 0 ? hydrated : void 0; -} - -// src/utils/date.ts -function getTodayDate() { - const now = /* @__PURE__ */ new Date(); - const readable = now.toLocaleDateString("en-US", { - weekday: "long", - year: "numeric", - month: "long", - day: "numeric" - }); - const iso = now.toISOString().split("T")[0]; - return `${readable} (${iso})`; -} - -// src/core/prompts/mainAgent.ts -function getBaseSystemPrompt(vaultPath) { - const vaultInfo = vaultPath ? ` - -Vault absolute path: ${vaultPath}` : ""; - return `## Time Context - -- **Current Date**: ${getTodayDate()} -- **Knowledge Status**: You possess extensive internal knowledge up to your training cutoff. You do not know the exact date of your cutoff, but you must assume that your internal weights are static and "past," while the Current Date is "present." - -## Identity & Role - -You are Claudian, an AI assistant for Obsidian vault management. You understand Markdown, YAML frontmatter, and Wiki-links. Use relative paths from vault root. Never overwrite without context. - -Working directory: vault root.${vaultInfo} - -## Paths - -ALL file ops use RELATIVE paths: "notes/file.md" NOT "/notes/file.md". Absolute paths FAIL. Export paths may use ~/absolute. - -## Message Format -path/to/note.md -User question -@filename.md for file mentions. - -## Obsidian -- Files: Markdown (.md), YAML frontmatter, Wiki-links [[note]], Tags #tag -- Dataview queries: don't break them - -## Tools - -- Read: Always read before editing. Can view images. -- Edit: Requires exact \`old_string\` match. -- Bash: Vault is working dir. Prefer Read/Write/Edit for files. -- Task: Spawn subagents with \`prompt\`, \`subagent_type\`. Use relative paths. -- TodoWrite: Track progress for 3+ step tasks. Format: {content, status, activeForm}. -- Skills: Use \`Skill\` tool when description matches need.`; -} -function getImageInstructions(mediaFolder) { - const folder = mediaFolder.trim(); - const mediaPath = folder ? "./" + folder : "."; - const examplePath = folder ? folder + "/" : ""; - return ` - -## Embedded Images in Notes - -**Proactive image reading**: When reading a note with embedded images, read them alongside text for full context. Images often contain critical information (diagrams, screenshots, charts). - -**Local images** (\`![[image.jpg]]\`): -- Located in media folder: \`${mediaPath}\` -- Read with: \`Read file_path="${examplePath}image.jpg"\` -- Formats: PNG, JPG/JPEG, GIF, WebP - -**External images** (\`![alt](url)\`): -- WebFetch does NOT support images -- Download to media folder \u2192 Read \u2192 Replace URL with wiki-link: - -\`\`\`bash -# Download to media folder with descriptive name -mkdir -p ${mediaPath} -img_name="downloaded_\\$(date +%s).png" -curl -sfo "${examplePath}$img_name" 'URL' -\`\`\` - -Then read with \`Read file_path="${examplePath}$img_name"\`, and replace the markdown link \`![alt](url)\` with \`![[${examplePath}$img_name]]\` in the note. - -**Benefits**: Image becomes a permanent vault asset, works offline, and uses Obsidian's native embed syntax.`; -} -function getExportInstructions(allowedExportPaths) { - if (!allowedExportPaths || allowedExportPaths.length === 0) { - return ""; - } - const uniquePaths = Array.from(new Set(allowedExportPaths.map((p) => p.trim()).filter(Boolean))); - if (uniquePaths.length === 0) { - return ""; - } - const formattedPaths = uniquePaths.map((p) => `- ${p}`).join("\n"); - return ` - -## Allowed Export Paths - -You are restricted to the vault by default. You may write exported files outside the vault ONLY to the following allowed export paths: - -${formattedPaths} - -Rules: -- Treat export paths as write-only (do not read/list files from them) -- If a path appears in both export and context lists, it is read-write for that root -- For vault files, always use relative paths -- For export destinations, you may use ~ or absolute paths - -Examples: - -\`\`\`bash -pandoc ./note.md -o ~/Desktop/note.docx -cp ./note.md ~/Desktop/note.md -cat ./note.md > ~/Desktop/note.md -\`\`\``; -} -function getContextPathInstructions(allowedContextPaths) { - if (!allowedContextPaths || allowedContextPaths.length === 0) { - return ""; - } - const uniquePaths = Array.from(new Set(allowedContextPaths.map((p) => p.trim()).filter(Boolean))); - if (uniquePaths.length === 0) { - return ""; - } - const formattedPaths = uniquePaths.map((p) => { - const normalized = p.replace(/\\/g, "/").replace(/\/+$/, ""); - const segments = normalized.split("/"); - const folderName = segments[segments.length - 1] || p; - return `- \`${folderName}\` \u2192 ${p}`; - }).join("\n"); - return ` - -## Extra Context Paths - -The user has selected these directories as relevant to their tasks. Proactively read from them when helpful: - -${formattedPaths} - -Rules: -- These paths are READ-ONLY (do not write, edit, or create files in them) -- If a path is in both context and export lists, it is read-write -- When user refers to a folder by name (e.g., "check Workspace"), use the corresponding path`; -} -function getEditorContextInstructions() { - return ` - -## Editor Selection - -User messages may include an \`\` tag showing text the user selected: - -\`\`\`xml - -selected text here -possibly multiple lines - -\`\`\` - -**When present:** The user selected this text before sending their message. Use this context to understand what they're referring to.`; -} -function getPlanModeInstructions() { - return ` - -### Plan Mode (EnterPlanMode / ExitPlanMode) - -You are in **plan mode** - a read-only exploration phase before implementation. - -**Available tools:** -- Read, Grep, Glob, LS (file exploration) -- WebSearch, WebFetch (research) -- TodoWrite (organize findings) - -**Disabled tools:** Write, Edit, Bash, NotebookEdit - you cannot modify files during planning. - -**Workflow:** -1. Call \`EnterPlanMode\` to begin (already done if you see this) -2. Explore the codebase to understand the task -3. Create a detailed implementation plan -4. Call \`ExitPlanMode\` when ready for user approval - -**Plan structure guidelines:** -- Start with a brief summary of the task -- List files to create/modify with specific changes -- Note dependencies and order of operations -- Identify potential risks or edge cases -- Keep it actionable - each step should be concrete - -**After approval:** The plan is appended to your system prompt and you gain full tool access for implementation.`; -} -async function buildSystemPrompt(settings = {}) { - var _a, _b; - const path = require("path"); - const fs = require("fs"); - - let prompt = getBaseSystemPrompt(settings.vaultPath); - // prompt += getImageInstructions(settings.mediaFolder || ""); - prompt += getExportInstructions(settings.allowedExportPaths || []); - prompt += getContextPathInstructions(settings.allowedContextPaths || []); - - // === TOKEN OPTIMIZATION: Keyword-based instruction retrieval === - if ((_a = settings.customPrompt) == null ? void 0 : _a.trim()) { - const THRESHOLD = 500; // Characters - const customPrompt = settings.customPrompt.trim(); - - if (customPrompt.length > THRESHOLD) { - // Large prompt: Use keyword-based retrieval - try { - const userQuery = (settings.userQuery || "").toLowerCase(); - const instructionsDir = path.join(settings.vaultPath || ".", ".claude", "memory", "instructions"); - - // Keyword mapping to instruction files - const keywordMap = { - 'safety.md': ['delete', 'remove', 'move', 'file', 'operation', 'approval', 'bulk'], - 'organization.md': ['para', 'folder', 'inbox', 'project', 'area', 'resource', 'archive', 'organize', 'structure'], - 'linking.md': ['link', 'connect', 'relation', 'backlink', 'reference', 'wiki', 'connection'], - 'standards.md': ['frontmatter', 'yaml', 'metadata', 'tag', 'format', 'naming', 'note'], - 'git.md': ['git', 'commit', 'push', 'pull', 'backup', 'version'] - }; - - // Detect relevant instruction files - const relevantFiles = []; - for (const [file, keywords] of Object.entries(keywordMap)) { - if (keywords.some(kw => userQuery.includes(kw))) { - relevantFiles.push(file); - } - } - - // Default files if no keywords matched - if (relevantFiles.length === 0) { - relevantFiles.push('safety.md', 'organization.md'); - } - - // Load relevant instructions (max 3 files) - const instructions = []; - for (const file of relevantFiles.slice(0, 3)) { - const filePath = path.join(instructionsDir, file); - if (fs.existsSync(filePath)) { - const content = fs.readFileSync(filePath, 'utf-8'); - instructions.push(content); - } - } - - if (instructions.length > 0) { - prompt += "\n\n## Relevant Custom Instructions\n\n"; - prompt += "_(Selected based on query keywords)_\n\n"; - prompt += instructions.join('\n\n---\n\n'); - } else { - // No instruction files found, use custom prompt - prompt += "\n\n## Custom Instructions\n\n" + customPrompt; - } - } catch (error) { - // Error in retrieval: fallback to direct load - console.error("[Instructions] Retrieval failed, using direct load:", error.message); - prompt += "\n\n## Custom Instructions\n\n" + customPrompt; - } - } else { - // Small prompt: Direct load - prompt += "\n\n## Custom Instructions\n\n" + customPrompt; - } - } - // === END TOKEN OPTIMIZATION === - - // if (settings.hasEditorContext) { - // prompt += getEditorContextInstructions(); - // } - if (settings.planMode) { - prompt += getPlanModeInstructions(); - } - if ((_b = settings.appendedPlan) == null ? void 0 : _b.trim()) { - prompt += "\n\n## Approved Implementation Plan\n\n\n" + settings.appendedPlan.trim() + "\n"; - prompt += "\n\n**IMPORTANT:** Follow this plan exactly. The user has approved this implementation. Execute the steps in order."; - } - return prompt; -} - -// src/core/sdk/selectModelUsage.ts -function selectModelUsage(usageByModel, messageModel, intendedModel) { - var _a, _b, _c; - const entries = Object.entries(usageByModel); - if (entries.length === 0) return null; - if (messageModel && usageByModel[messageModel]) { - return { modelName: messageModel, usage: usageByModel[messageModel] }; - } - if (intendedModel && usageByModel[intendedModel]) { - return { modelName: intendedModel, usage: usageByModel[intendedModel] }; - } - let bestEntry = null; - let maxTokens = -1; - for (const [modelName, usage] of entries) { - const contextTokens = ((_a = usage.inputTokens) != null ? _a : 0) + ((_b = usage.cacheCreationInputTokens) != null ? _b : 0) + ((_c = usage.cacheReadInputTokens) != null ? _c : 0); - if (contextTokens > maxTokens) { - maxTokens = contextTokens; - bestEntry = { modelName, usage }; - } - } - return bestEntry; -} - -// src/core/sdk/transformSDKMessage.ts -function* transformSDKMessage(message, options) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; - const parentToolUseId = (_a = message.parent_tool_use_id) != null ? _a : null; - switch (message.type) { - case "system": - if (message.subtype === "init" && message.session_id) { - yield { type: "session_init", sessionId: message.session_id }; - } - break; - case "assistant": - if (((_b = message.message) == null ? void 0 : _b.content) && Array.isArray(message.message.content)) { - for (const block of message.message.content) { - if (block.type === "thinking" && block.thinking) { - yield { type: "thinking", content: block.thinking, parentToolUseId }; - } else if (block.type === "text" && block.text) { - yield { type: "text", content: block.text, parentToolUseId }; - } else if (block.type === "tool_use") { - yield { - type: "tool_use", - id: block.id || `tool-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`, - name: block.name || "unknown", - input: block.input || {}, - parentToolUseId - }; - } - } - } - break; - case "user": - if (message._blocked && message._blockReason) { - yield { - type: "blocked", - content: message._blockReason - }; - break; - } - if (message.tool_use_result !== void 0 && message.parent_tool_use_id) { - yield { - type: "tool_result", - id: message.parent_tool_use_id, - content: typeof message.tool_use_result === "string" ? message.tool_use_result : JSON.stringify(message.tool_use_result, null, 2), - isError: false, - parentToolUseId - }; - } - if (((_c = message.message) == null ? void 0 : _c.content) && Array.isArray(message.message.content)) { - for (const block of message.message.content) { - if (block.type === "tool_result") { - yield { - type: "tool_result", - id: block.tool_use_id || message.parent_tool_use_id || "", - content: typeof block.content === "string" ? block.content : JSON.stringify(block.content, null, 2), - isError: block.is_error || false, - parentToolUseId - }; - } - } - } - break; - case "stream_event": { - const event = message.event; - if ((event == null ? void 0 : event.type) === "content_block_start" && ((_d = event.content_block) == null ? void 0 : _d.type) === "tool_use") { - yield { - type: "tool_use", - id: event.content_block.id || `tool-${Date.now()}`, - name: event.content_block.name || "unknown", - input: event.content_block.input || {}, - parentToolUseId - }; - } else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_e = event.content_block) == null ? void 0 : _e.type) === "thinking") { - if (event.content_block.thinking) { - yield { type: "thinking", content: event.content_block.thinking, parentToolUseId }; - } - } else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_f = event.content_block) == null ? void 0 : _f.type) === "text") { - if (event.content_block.text) { - yield { type: "text", content: event.content_block.text, parentToolUseId }; - } - } else if ((event == null ? void 0 : event.type) === "content_block_delta") { - if (((_g = event.delta) == null ? void 0 : _g.type) === "thinking_delta" && event.delta.thinking) { - yield { type: "thinking", content: event.delta.thinking, parentToolUseId }; - } else if (((_h = event.delta) == null ? void 0 : _h.type) === "text_delta" && event.delta.text) { - yield { type: "text", content: event.delta.text, parentToolUseId }; - } - } - break; - } - case "result": { - if (parentToolUseId) { - break; - } - const usageByModel = message.modelUsage; - if (usageByModel) { - const selected = selectModelUsage(usageByModel, message.model, options == null ? void 0 : options.intendedModel); - if (selected && selected.usage.contextWindow && selected.usage.contextWindow > 0) { - const { modelName, usage } = selected; - const inputTokens = (_i = usage.inputTokens) != null ? _i : 0; - const cacheCreationInputTokens = (_j = usage.cacheCreationInputTokens) != null ? _j : 0; - const cacheReadInputTokens = (_k = usage.cacheReadInputTokens) != null ? _k : 0; - const contextTokens = inputTokens + cacheCreationInputTokens + cacheReadInputTokens; - const percentage = Math.min(100, Math.max(0, Math.round(contextTokens / usage.contextWindow * 100))); - const usageInfo = { - model: modelName, - inputTokens, - cacheCreationInputTokens, - cacheReadInputTokens, - contextWindow: usage.contextWindow, - contextTokens, - percentage - }; - yield { type: "usage", usage: usageInfo }; - } - } - break; - } - case "error": - if (message.error) { - yield { type: "error", content: message.error }; - } - break; - } -} - -// src/core/sdk/typeGuards.ts -function isSessionInitEvent(event) { - return event.type === "session_init"; -} -function isStreamChunk(event) { - return event.type !== "session_init"; -} - -// src/core/security/ApprovalManager.ts -function getActionPattern(toolName, input) { - switch (toolName) { - case TOOL_BASH: - return typeof input.command === "string" ? input.command.trim() : ""; - case TOOL_READ: - case TOOL_WRITE: - case TOOL_EDIT: - return input.file_path || "*"; - case TOOL_NOTEBOOK_EDIT: - return input.notebook_path || input.file_path || "*"; - case TOOL_GLOB: - return input.pattern || "*"; - case TOOL_GREP: - return input.pattern || "*"; - default: - return JSON.stringify(input); - } -} -function getActionDescription(toolName, input) { - switch (toolName) { - case TOOL_BASH: - return `Run command: ${input.command}`; - case TOOL_READ: - return `Read file: ${input.file_path}`; - case TOOL_WRITE: - return `Write to file: ${input.file_path}`; - case TOOL_EDIT: - return `Edit file: ${input.file_path}`; - case TOOL_GLOB: - return `Search files matching: ${input.pattern}`; - case TOOL_GREP: - return `Search content matching: ${input.pattern}`; - default: - return `${toolName}: ${JSON.stringify(input)}`; - } -} -function matchesPattern(toolName, actionPattern, approvedPattern) { - if (toolName === TOOL_BASH) { - return actionPattern === approvedPattern; - } - const normalizedAction = normalizeMatchPattern(actionPattern); - const normalizedApproved = normalizeMatchPattern(approvedPattern); - if (normalizedApproved === "*") return true; - if (normalizedAction === normalizedApproved) return true; - if (toolName === TOOL_READ || toolName === TOOL_WRITE || toolName === TOOL_EDIT || toolName === TOOL_NOTEBOOK_EDIT) { - return isPathPrefixMatch(normalizedAction, normalizedApproved); - } - if (normalizedAction.startsWith(normalizedApproved)) return true; - return false; -} -function normalizeMatchPattern(value) { - return value.replace(/\\/g, "/"); -} -function isPathPrefixMatch(actionPath, approvedPath) { - if (!actionPath.startsWith(approvedPath)) { - return false; - } - if (approvedPath.endsWith("/")) { - return true; - } - if (actionPath.length === approvedPath.length) { - return true; - } - return actionPath.charAt(approvedPath.length) === "/"; -} -var ApprovalManager = class { - constructor(getPermanentApprovals) { - this.sessionApprovedActions = []; - this.persistCallback = null; - this.getPermanentApprovals = getPermanentApprovals; - } - /** - * Set callback for persisting permanent approvals. - */ - setPersistCallback(callback) { - this.persistCallback = callback; - } - /** - * Check if an action is pre-approved (either session or permanent). - */ - isActionApproved(toolName, input) { - const pattern = getActionPattern(toolName, input); - const sessionApproved = this.sessionApprovedActions.some( - (action) => action.toolName === toolName && matchesPattern(toolName, pattern, action.pattern) - ); - if (sessionApproved) return true; - const permanentApprovals = this.getPermanentApprovals(); - const permanentApproved = permanentApprovals.some( - (action) => action.toolName === toolName && matchesPattern(toolName, pattern, action.pattern) - ); - return permanentApproved; - } - /** - * Add an action to the approved list. - */ - async approveAction(toolName, input, scope) { - const pattern = getActionPattern(toolName, input); - const action = { - toolName, - pattern, - approvedAt: Date.now(), - scope - }; - if (scope === "session") { - this.sessionApprovedActions.push(action); - } else { - if (this.persistCallback) { - await this.persistCallback(action); - } - } - } - /** - * Clear session-scoped approvals. - */ - clearSessionApprovals() { - this.sessionApprovedActions = []; - } - /** - * Get session-scoped approvals (for testing/debugging). - */ - getSessionApprovals() { - return [...this.sessionApprovedActions]; - } -}; - -// src/core/agent/ClaudianService.ts -var SessionManager = class { - constructor() { - this.state = { - sessionId: null, - sessionModel: null, - pendingSessionModel: null, - wasInterrupted: false - }; - } - getSessionId() { - return this.state.sessionId; - } - setSessionId(id, defaultModel) { - this.state.sessionId = id; - this.state.sessionModel = id ? defaultModel != null ? defaultModel : null : null; - } - wasInterrupted() { - return this.state.wasInterrupted; - } - markInterrupted() { - this.state.wasInterrupted = true; - } - clearInterrupted() { - this.state.wasInterrupted = false; - } - setPendingModel(model) { - this.state.pendingSessionModel = model; - } - clearPendingModel() { - this.state.pendingSessionModel = null; - } - captureSession(sessionId) { - this.state.sessionId = sessionId; - this.state.sessionModel = this.state.pendingSessionModel; - this.state.pendingSessionModel = null; - } - invalidateSession() { - this.state.sessionId = null; - this.state.sessionModel = null; - } - reset() { - this.state = { - sessionId: null, - sessionModel: null, - pendingSessionModel: null, - wasInterrupted: false - }; - } -}; -var DiffStore = class { - constructor() { - this.originalContents = /* @__PURE__ */ new Map(); - this.pendingDiffData = /* @__PURE__ */ new Map(); - } - getOriginalContents() { - return this.originalContents; - } - getPendingDiffData() { - return this.pendingDiffData; - } - getDiffData(toolUseId) { - const data = this.pendingDiffData.get(toolUseId); - if (data) { - this.pendingDiffData.delete(toolUseId); - } - return data; - } - clear() { - this.originalContents.clear(); - this.pendingDiffData.clear(); - } -}; -var ClaudianService = class { - constructor(plugin, mcpManager) { - this.abortController = null; - this.resolvedClaudePath = null; - this.approvalCallback = null; - this.askUserQuestionCallback = null; - this.exitPlanModeCallback = null; - this.enterPlanModeCallback = null; - this.currentPlanFilePath = null; - this.approvedPlanContent = null; - this.vaultPath = null; - // Modular components - this.sessionManager = new SessionManager(); - this.diffStore = new DiffStore(); - // Store AskUserQuestion answers by tool_use_id - this.askUserQuestionAnswers = /* @__PURE__ */ new Map(); - this.plugin = plugin; - this.mcpManager = mcpManager; - this.approvalManager = new ApprovalManager( - () => this.plugin.settings.permissions - ); - this.approvalManager.setPersistCallback(async (action) => { - this.plugin.settings.permissions.push(action); - await this.plugin.saveSettings(); + const extraHeaders = normalizeHeaders((_a3 = this._requestInit) == null ? void 0 : _a3.headers); + return new Headers({ + ...headers, + ...extraHeaders }); } - /** Load MCP server configurations from storage. */ - async loadMcpServers() { - await this.mcpManager.loadServers(); - } - /** Reload MCP server configurations (call after settings change). */ - async reloadMcpServers() { - await this.mcpManager.loadServers(); - } - findClaudeCLI() { - var _a; - const customPath = (_a = this.plugin.settings.claudeCliPath) == null ? void 0 : _a.trim(); - if (customPath) { - const expandedPath = expandHomePath(customPath); - if (fs6.existsSync(expandedPath)) { - try { - const stat = fs6.statSync(expandedPath); - if (stat.isFile()) { - return expandedPath; + _startOrAuth() { + var _a3, _b, _c; + const fetchImpl = (_c = (_b = (_a3 = this == null ? void 0 : this._eventSourceInit) == null ? void 0 : _a3.fetch) != null ? _b : this._fetch) != null ? _c : fetch; + return new Promise((resolve4, reject) => { + this._eventSource = new EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url2, init) => { + const headers = await this._commonHeaders(); + headers.set("Accept", "text/event-stream"); + const response = await fetchImpl(url2, { + ...init, + headers + }); + if (response.status === 401 && response.headers.has("www-authenticate")) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; } - console.warn(`Claudian: Custom CLI path is a directory, not a file: ${expandedPath}`); - } catch (error2) { - const message = error2 instanceof Error ? error2.message : String(error2); - console.warn(`Claudian: Custom CLI path not accessible: ${expandedPath} (${message})`); + return response; } - } else { - console.warn(`Claudian: Custom CLI path not found: ${expandedPath}`); - } - } - return findClaudeCLIPath(); + }); + this._abortController = new AbortController(); + this._eventSource.onerror = (event) => { + var _a4; + if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve4, reject); + return; + } + const error48 = new SseError(event.code, event.message, event); + reject(error48); + (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48); + }; + this._eventSource.onopen = () => { + }; + this._eventSource.addEventListener("endpoint", (event) => { + var _a4; + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) { + throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } + } catch (error48) { + reject(error48); + (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48); + void this.close(); + return; + } + resolve4(); + }); + this._eventSource.onmessage = (event) => { + var _a4, _b2; + const messageEvent = event; + let message; + try { + message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } catch (error48) { + (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48); + return; + } + (_b2 = this.onmessage) == null ? void 0 : _b2.call(this, message); + }; + }); } - /** Sends a query to Claude and streams the response. */ - async *query(prompt, images, conversationHistory, queryOptions) { - const vaultPath = getVaultPath(this.plugin.app); - if (!vaultPath) { - yield { type: "error", content: "Could not determine vault path" }; - return; + async start() { + if (this._eventSource) { + throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically."); } - if (!this.resolvedClaudePath) { - this.resolvedClaudePath = this.findClaudeCLI(); + return await this._startOrAuth(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError("No auth provider"); } - if (!this.resolvedClaudePath) { - yield { type: "error", content: "Claude CLI not found. Please install Claude Code CLI." }; - return; + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== "AUTHORIZED") { + throw new UnauthorizedError("Failed to authorize"); } - this.abortController = new AbortController(); - const hydratedImages = await hydrateImagesData(this.plugin.app, images, vaultPath); - let queryPrompt = prompt; - if (this.sessionManager.wasInterrupted() && conversationHistory && conversationHistory.length > 0) { - const historyContext = buildContextFromHistory(conversationHistory); - if (historyContext) { - queryPrompt = `${historyContext} - -User: ${prompt}`; - } - this.sessionManager.invalidateSession(); - this.sessionManager.clearInterrupted(); - } - const noSessionButHasHistory = !this.sessionManager.getSessionId() && conversationHistory && conversationHistory.length > 0; - if (noSessionButHasHistory) { - if (conversationHistory && conversationHistory.length > 0) { - const historyContext = buildContextFromHistory(conversationHistory); - const lastUserMessage = getLastUserMessage(conversationHistory); - const actualPrompt = stripCurrentNotePrefix(prompt); - const shouldAppendPrompt = !lastUserMessage || lastUserMessage.content.trim() !== actualPrompt.trim(); - queryPrompt = historyContext ? shouldAppendPrompt ? `${historyContext} - -User: ${prompt}` : historyContext : prompt; - } - this.sessionManager.invalidateSession(); + } + async close() { + var _a3, _b, _c; + (_a3 = this._abortController) == null ? void 0 : _a3.abort(); + (_b = this._eventSource) == null ? void 0 : _b.close(); + (_c = this.onclose) == null ? void 0 : _c.call(this); + } + async send(message) { + var _a3, _b, _c, _d; + if (!this._endpoint) { + throw new Error("Not connected"); } try { - yield* this.queryViaSDK(queryPrompt, vaultPath, hydratedImages, queryOptions); - } catch (error2) { - if (isSessionExpiredError(error2) && conversationHistory && conversationHistory.length > 0) { - this.sessionManager.invalidateSession(); - const historyContext = buildContextFromHistory(conversationHistory); - const lastUserMessage = getLastUserMessage(conversationHistory); - const actualPrompt = stripCurrentNotePrefix(prompt); - const shouldAppendPrompt = !lastUserMessage || lastUserMessage.content.trim() !== actualPrompt.trim(); - const fullPrompt = historyContext ? shouldAppendPrompt ? `${historyContext} + const headers = await this._commonHeaders(); + headers.set("content-type", "application/json"); + const init = { + ...this._requestInit, + method: "POST", + headers, + body: JSON.stringify(message), + signal: (_a3 = this._abortController) == null ? void 0 : _a3.signal + }; + const response = await ((_b = this._fetch) != null ? _b : fetch)(this._endpoint, init); + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== "AUTHORIZED") { + throw new UnauthorizedError(); + } + return this.send(message); + } + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + await ((_c = response.body) == null ? void 0 : _c.cancel()); + } catch (error48) { + (_d = this.onerror) == null ? void 0 : _d.call(this, error48); + throw error48; + } + } + setProtocolVersion(version2) { + this._protocolVersion = version2; + } +}; -User: ${prompt}` : historyContext : prompt; - const retryImages = await hydrateImagesData(this.plugin.app, lastUserMessage == null ? void 0 : lastUserMessage.images, vaultPath); +// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js +var import_cross_spawn = __toESM(require_cross_spawn(), 1); +var import_node_process = __toESM(require("node:process"), 1); +var import_node_stream = require("node:stream"); + +// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js +var ReadBuffer = class { + append(chunk) { + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index = this._buffer.indexOf("\n"); + if (index === -1) { + return null; + } + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js +var DEFAULT_INHERITED_ENV_VARS = import_node_process.default.platform === "win32" ? [ + "APPDATA", + "HOMEDRIVE", + "HOMEPATH", + "LOCALAPPDATA", + "PATH", + "PROCESSOR_ARCHITECTURE", + "SYSTEMDRIVE", + "SYSTEMROOT", + "TEMP", + "USERNAME", + "USERPROFILE", + "PROGRAMFILES" +] : ( + /* list inspired by the default env inheritance of sudo */ + ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"] +); +function getDefaultEnvironment() { + const env = {}; + for (const key of DEFAULT_INHERITED_ENV_VARS) { + const value = import_node_process.default.env[key]; + if (value === void 0) { + continue; + } + if (value.startsWith("()")) { + continue; + } + env[key] = value; + } + return env; +} +var StdioClientTransport = class { + constructor(server) { + this._readBuffer = new ReadBuffer(); + this._stderrStream = null; + this._serverParams = server; + if (server.stderr === "pipe" || server.stderr === "overlapped") { + this._stderrStream = new import_node_stream.PassThrough(); + } + } + /** + * Starts the server process and prepares to communicate with it. + */ + async start() { + if (this._process) { + throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically."); + } + return new Promise((resolve4, reject) => { + var _a3, _b, _c, _d, _e; + this._process = (0, import_cross_spawn.default)(this._serverParams.command, (_a3 = this._serverParams.args) != null ? _a3 : [], { + // merge default env with server env because mcp server needs some env vars + env: { + ...getDefaultEnvironment(), + ...this._serverParams.env + }, + stdio: ["pipe", "pipe", (_b = this._serverParams.stderr) != null ? _b : "inherit"], + shell: false, + windowsHide: import_node_process.default.platform === "win32" && isElectron(), + cwd: this._serverParams.cwd + }); + this._process.on("error", (error48) => { + var _a4; + reject(error48); + (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48); + }); + this._process.on("spawn", () => { + resolve4(); + }); + this._process.on("close", (_code) => { + var _a4; + this._process = void 0; + (_a4 = this.onclose) == null ? void 0 : _a4.call(this); + }); + (_c = this._process.stdin) == null ? void 0 : _c.on("error", (error48) => { + var _a4; + (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48); + }); + (_d = this._process.stdout) == null ? void 0 : _d.on("data", (chunk) => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }); + (_e = this._process.stdout) == null ? void 0 : _e.on("error", (error48) => { + var _a4; + (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48); + }); + if (this._stderrStream && this._process.stderr) { + this._process.stderr.pipe(this._stderrStream); + } + }); + } + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr() { + var _a3, _b; + if (this._stderrStream) { + return this._stderrStream; + } + return (_b = (_a3 = this._process) == null ? void 0 : _a3.stderr) != null ? _b : null; + } + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid() { + var _a3, _b; + return (_b = (_a3 = this._process) == null ? void 0 : _a3.pid) != null ? _b : null; + } + processReadBuffer() { + var _a3, _b; + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + (_a3 = this.onmessage) == null ? void 0 : _a3.call(this, message); + } catch (error48) { + (_b = this.onerror) == null ? void 0 : _b.call(this, error48); + } + } + } + async close() { + var _a3; + if (this._process) { + const processToClose = this._process; + this._process = void 0; + const closePromise = new Promise((resolve4) => { + processToClose.once("close", () => { + resolve4(); + }); + }); + try { + (_a3 = processToClose.stdin) == null ? void 0 : _a3.end(); + } catch (e2) { + } + await Promise.race([closePromise, new Promise((resolve4) => setTimeout(resolve4, 2e3).unref())]); + if (processToClose.exitCode === null) { try { - yield* this.queryViaSDK(fullPrompt, vaultPath, retryImages, queryOptions); - } catch (retryError) { - const msg2 = retryError instanceof Error ? retryError.message : "Unknown error"; - yield { type: "error", content: msg2 }; + processToClose.kill("SIGTERM"); + } catch (e2) { + } + await Promise.race([closePromise, new Promise((resolve4) => setTimeout(resolve4, 2e3).unref())]); + } + if (processToClose.exitCode === null) { + try { + processToClose.kill("SIGKILL"); + } catch (e2) { + } + } + } + this._readBuffer.clear(); + } + send(message) { + return new Promise((resolve4) => { + var _a3; + if (!((_a3 = this._process) == null ? void 0 : _a3.stdin)) { + throw new Error("Not connected"); + } + const json2 = serializeMessage(message); + if (this._process.stdin.write(json2)) { + resolve4(); + } else { + this._process.stdin.once("drain", resolve4); + } + }); + } +}; +function isElectron() { + return "type" in import_node_process.default; +} + +// node_modules/eventsource-parser/dist/stream.js +var EventSourceParserStream = class extends TransformStream { + constructor({ onError, onRetry, onComment } = {}) { + let parser; + super({ + start(controller) { + parser = createParser({ + onEvent: (event) => { + controller.enqueue(event); + }, + onError(error48) { + onError === "terminate" ? controller.error(error48) : typeof onError == "function" && onError(error48); + }, + onRetry, + onComment + }); + }, + transform(chunk) { + parser.feed(chunk); + } + }); + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js +var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1e3, + maxReconnectionDelay: 3e4, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 +}; +var StreamableHTTPError = class extends Error { + constructor(code, message) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + } +}; +var StreamableHTTPClientTransport = class { + constructor(url2, opts) { + var _a3; + this._hasCompletedAuthFlow = false; + this._url = url2; + this._resourceMetadataUrl = void 0; + this._scope = void 0; + this._requestInit = opts == null ? void 0 : opts.requestInit; + this._authProvider = opts == null ? void 0 : opts.authProvider; + this._fetch = opts == null ? void 0 : opts.fetch; + this._fetchWithInit = createFetchWithInit(opts == null ? void 0 : opts.fetch, opts == null ? void 0 : opts.requestInit); + this._sessionId = opts == null ? void 0 : opts.sessionId; + this._reconnectionOptions = (_a3 = opts == null ? void 0 : opts.reconnectionOptions) != null ? _a3 : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + } + async _authThenStart() { + var _a3; + if (!this._authProvider) { + throw new UnauthorizedError("No auth provider"); + } + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } catch (error48) { + (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error48); + throw error48; + } + if (result !== "AUTHORIZED") { + throw new UnauthorizedError(); + } + return await this._startOrAuthSse({ resumptionToken: void 0 }); + } + async _commonHeaders() { + var _a3; + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers["Authorization"] = `Bearer ${tokens.access_token}`; + } + } + if (this._sessionId) { + headers["mcp-session-id"] = this._sessionId; + } + if (this._protocolVersion) { + headers["mcp-protocol-version"] = this._protocolVersion; + } + const extraHeaders = normalizeHeaders((_a3 = this._requestInit) == null ? void 0 : _a3.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + async _startOrAuthSse(options) { + var _a3, _b, _c, _d; + const { resumptionToken } = options; + try { + const headers = await this._commonHeaders(); + headers.set("Accept", "text/event-stream"); + if (resumptionToken) { + headers.set("last-event-id", resumptionToken); + } + const response = await ((_a3 = this._fetch) != null ? _a3 : fetch)(this._url, { + method: "GET", + headers, + signal: (_b = this._abortController) == null ? void 0 : _b.signal + }); + if (!response.ok) { + await ((_c = response.body) == null ? void 0 : _c.cancel()); + if (response.status === 401 && this._authProvider) { + return await this._authThenStart(); + } + if (response.status === 405) { + return; + } + throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); + } + this._handleSseStream(response.body, options, true); + } catch (error48) { + (_d = this.onerror) == null ? void 0 : _d.call(this, error48); + throw error48; + } + } + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + if (this._serverRetryMs !== void 0) { + return this._serverRetryMs; + } + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt using server-provided retry interval or backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + var _a3; + const maxRetries = this._reconnectionOptions.maxRetries; + if (attemptCount >= maxRetries) { + (_a3 = this.onerror) == null ? void 0 : _a3.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + return; + } + const delay = this._getNextReconnectionDelay(attemptCount); + this._reconnectionTimeout = setTimeout(() => { + this._startOrAuthSse(options).catch((error48) => { + var _a4; + (_a4 = this.onerror) == null ? void 0 : _a4.call(this, new Error(`Failed to reconnect SSE stream: ${error48 instanceof Error ? error48.message : String(error48)}`)); + this._scheduleReconnection(options, attemptCount + 1); + }); + }, delay); + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) { + return; + } + const { onresumptiontoken, replayMessageId } = options; + let lastEventId; + let hasPrimingEvent = false; + let receivedResponse = false; + const processStream = async () => { + var _a3, _b, _c, _d; + try { + const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ + onRetry: (retryMs) => { + this._serverRetryMs = retryMs; + } + })).getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) { + break; + } + if (event.id) { + lastEventId = event.id; + hasPrimingEvent = true; + onresumptiontoken == null ? void 0 : onresumptiontoken(event.id); + } + if (!event.data) { + continue; + } + if (!event.event || event.event === "message") { + try { + const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if (isJSONRPCResultResponse(message)) { + receivedResponse = true; + if (replayMessageId !== void 0) { + message.id = replayMessageId; + } + } + (_a3 = this.onmessage) == null ? void 0 : _a3.call(this, message); + } catch (error48) { + (_b = this.onerror) == null ? void 0 : _b.call(this, error48); + } + } + } + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + } catch (error48) { + (_c = this.onerror) == null ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error48}`)); + const canResume = isReconnectable || hasPrimingEvent; + const needsReconnect = canResume && !receivedResponse; + if (needsReconnect && this._abortController && !this._abortController.signal.aborted) { + try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } catch (error49) { + (_d = this.onerror) == null ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error49 instanceof Error ? error49.message : String(error49)}`)); + } + } + } + }; + processStream(); + } + async start() { + if (this._abortController) { + throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically."); + } + this._abortController = new AbortController(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError("No auth provider"); + } + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== "AUTHORIZED") { + throw new UnauthorizedError("Failed to authorize"); + } + } + async close() { + var _a3, _b; + if (this._reconnectionTimeout) { + clearTimeout(this._reconnectionTimeout); + this._reconnectionTimeout = void 0; + } + (_a3 = this._abortController) == null ? void 0 : _a3.abort(); + (_b = this.onclose) == null ? void 0 : _b.call(this); + } + async send(message, options) { + var _a3, _b, _c, _d, _e, _f, _g; + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => { + var _a4; + return (_a4 = this.onerror) == null ? void 0 : _a4.call(this, err); + }); + return; + } + const headers = await this._commonHeaders(); + headers.set("content-type", "application/json"); + headers.set("accept", "application/json, text/event-stream"); + const init = { + ...this._requestInit, + method: "POST", + headers, + body: JSON.stringify(message), + signal: (_a3 = this._abortController) == null ? void 0 : _a3.signal + }; + const response = await ((_b = this._fetch) != null ? _b : fetch)(this._url, init); + const sessionId = response.headers.get("mcp-session-id"); + if (sessionId) { + this._sessionId = sessionId; + } + if (!response.ok) { + const text = await response.text().catch(() => null); + if (response.status === 401 && this._authProvider) { + if (this._hasCompletedAuthFlow) { + throw new StreamableHTTPError(401, "Server returned 401 after successful authentication"); + } + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== "AUTHORIZED") { + throw new UnauthorizedError(); + } + this._hasCompletedAuthFlow = true; + return this.send(message); + } + if (response.status === 403 && this._authProvider) { + const { resourceMetadataUrl, scope, error: error48 } = extractWWWAuthenticateParams(response); + if (error48 === "insufficient_scope") { + const wwwAuthHeader = response.headers.get("WWW-Authenticate"); + if (this._lastUpscopingHeader === wwwAuthHeader) { + throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping"); + } + if (scope) { + this._scope = scope; + } + if (resourceMetadataUrl) { + this._resourceMetadataUrl = resourceMetadataUrl; + } + this._lastUpscopingHeader = wwwAuthHeader != null ? wwwAuthHeader : void 0; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetch + }); + if (result !== "AUTHORIZED") { + throw new UnauthorizedError(); + } + return this.send(message); + } + } + throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`); + } + this._hasCompletedAuthFlow = false; + this._lastUpscopingHeader = void 0; + if (response.status === 202) { + await ((_c = response.body) == null ? void 0 : _c.cancel()); + if (isInitializedNotification(message)) { + this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => { + var _a4; + return (_a4 = this.onerror) == null ? void 0 : _a4.call(this, err); + }); } return; } - const msg = error2 instanceof Error ? error2.message : "Unknown error"; - yield { type: "error", content: msg }; - } finally { - this.abortController = null; + const messages = Array.isArray(message) ? message : [message]; + const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0; + const contentType = response.headers.get("content-type"); + if (hasRequests) { + if (contentType == null ? void 0 : contentType.includes("text/event-stream")) { + this._handleSseStream(response.body, { onresumptiontoken }, false); + } else if (contentType == null ? void 0 : contentType.includes("application/json")) { + const data = await response.json(); + const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) { + (_d = this.onmessage) == null ? void 0 : _d.call(this, msg); + } + } else { + await ((_e = response.body) == null ? void 0 : _e.cancel()); + throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); + } + } else { + await ((_f = response.body) == null ? void 0 : _f.cancel()); + } + } catch (error48) { + (_g = this.onerror) == null ? void 0 : _g.call(this, error48); + throw error48; } } + get sessionId() { + return this._sessionId; + } /** - * Build a prompt with images as content blocks + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. */ - buildPromptWithImages(prompt, images) { - const validImages = (images || []).filter((img) => !!img.data); - if (validImages.length === 0) { - return prompt; - } - const content = []; - for (const image of validImages) { - content.push({ - type: "image", - source: { - type: "base64", - media_type: image.mediaType, - data: image.data - } - }); - } - if (prompt.trim()) { - content.push({ - type: "text", - text: prompt - }); - } - async function* messageGenerator() { - yield { - type: "user", - message: { - role: "user", - content - } - }; - } - return messageGenerator(); - } - async *queryViaSDK(prompt, cwd2, images, queryOptions) { - var _a, _b, _c; - const selectedModel = (queryOptions == null ? void 0 : queryOptions.model) || this.plugin.settings.model; - const permissionMode = this.plugin.settings.permissionMode; - this.sessionManager.setPendingModel(selectedModel); - this.vaultPath = cwd2; - const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables()); - const enhancedPath = getEnhancedPath(customEnv.PATH); - const queryPrompt = this.buildPromptWithImages(prompt, images); - const hasEditorContext = prompt.includes(" 0) { - options.mcpServers = mcpServers; - } - const disallowedMcpTools = this.mcpManager.getDisallowedMcpTools(combinedMentions); - if (disallowedMcpTools.length > 0) { - options.disallowedTools = disallowedMcpTools; - } - const blocklistHook = createBlocklistHook(() => ({ - blockedCommands: this.plugin.settings.blockedCommands, - enableBlocklist: this.plugin.settings.enableBlocklist - })); - const vaultRestrictionHook = createVaultRestrictionHook({ - getPathAccessType: (p) => this.getPathAccessType(p) - }); - const postCallback = { - trackEditedFile: async (name, input, isError) => { - if (name === "Write" && !isError) { - const filePath = input == null ? void 0 : input.file_path; - if (typeof filePath === "string" && this.isPlanFilePath(filePath)) { - this.currentPlanFilePath = this.resolvePlanPath(filePath); - } - } - } - }; - const fileHashPreHook = createFileHashPreHook( - this.vaultPath, - this.diffStore.getOriginalContents() - ); - const fileHashPostHook = createFileHashPostHook( - this.vaultPath, - this.diffStore.getOriginalContents(), - this.diffStore.getPendingDiffData(), - postCallback - ); - options.canUseTool = this.createUnifiedToolCallback(permissionMode); - options.hooks = { - PreToolUse: [blocklistHook, vaultRestrictionHook, fileHashPreHook], - PostToolUse: [fileHashPostHook] - }; - if (queryOptions == null ? void 0 : queryOptions.planMode) { - options.permissionMode = "plan"; - } else if (permissionMode === "yolo") { - options.permissionMode = "bypassPermissions"; - options.allowDangerouslySkipPermissions = true; - } else { - options.permissionMode = "default"; - } - const budgetSetting = this.plugin.settings.thinkingBudget; - const budgetConfig = THINKING_BUDGETS.find((b) => b.value === budgetSetting); - if (budgetConfig && budgetConfig.tokens > 0) { - options.maxThinkingTokens = budgetConfig.tokens; - } - if ((queryOptions == null ? void 0 : queryOptions.allowedTools) && queryOptions.allowedTools.length > 0) { - options.allowedTools = [...queryOptions.allowedTools, "Skill"]; - } - const sessionId = this.sessionManager.getSessionId(); - if (sessionId) { - options.resume = sessionId; + async terminateSession() { + var _a3, _b, _c, _d; + if (!this._sessionId) { + return; } try { - const response = query({ prompt: queryPrompt, options }); - let streamSessionId = this.sessionManager.getSessionId(); - for await (const message of response) { - if ((_c = this.abortController) == null ? void 0 : _c.signal.aborted) { - await response.interrupt(); - break; + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: "DELETE", + headers, + signal: (_a3 = this._abortController) == null ? void 0 : _a3.signal + }; + const response = await ((_b = this._fetch) != null ? _b : fetch)(this._url, init); + await ((_c = response.body) == null ? void 0 : _c.cancel()); + if (!response.ok && response.status !== 405) { + throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); + } + this._sessionId = void 0; + } catch (error48) { + (_d = this.onerror) == null ? void 0 : _d.call(this, error48); + throw error48; + } + } + setProtocolVersion(version2) { + this._protocolVersion = version2; + } + get protocolVersion() { + return this._protocolVersion; + } + /** + * Resume an SSE stream from a previous event ID. + * Opens a GET SSE connection with Last-Event-ID header to replay missed events. + * + * @param lastEventId The event ID to resume from + * @param options Optional callback to receive new resumption tokens + */ + async resumeStream(lastEventId, options) { + await this._startOrAuthSse({ + resumptionToken: lastEventId, + onresumptiontoken: options == null ? void 0 : options.onresumptiontoken + }); + } +}; + +// src/core/mcp/McpTester.ts +async function testMcpServer(server) { + var _a3; + const type = getMcpServerType(server.config); + let transport; + try { + if (type === "stdio") { + const config2 = server.config; + const { cmd, args } = parseCommand(config2.command, config2.args); + if (!cmd) { + return { success: false, tools: [], error: "Missing command" }; + } + transport = new StdioClientTransport({ + command: cmd, + args, + env: { ...process.env, ...config2.env, PATH: getEnhancedPath((_a3 = config2.env) == null ? void 0 : _a3.PATH) }, + stderr: "ignore" + }); + } else { + const config2 = server.config; + const url2 = new URL(config2.url); + const options = config2.headers ? { requestInit: { headers: config2.headers } } : void 0; + transport = type === "sse" ? new SSEClientTransport(url2, options) : new StreamableHTTPClientTransport(url2, options); + } + } catch (error48) { + return { + success: false, + tools: [], + error: error48 instanceof Error ? error48.message : "Invalid server configuration" + }; + } + const client = new Client({ name: "claudian-tester", version: "1.0.0" }); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 1e4); + try { + await client.connect(transport, { signal: controller.signal }); + const serverVersion = client.getServerVersion(); + let tools = []; + try { + const result = await client.listTools(void 0, { signal: controller.signal }); + tools = result.tools.map((t2) => ({ + name: t2.name, + description: t2.description, + inputSchema: t2.inputSchema + })); + } catch (e2) { + } + return { + success: true, + serverName: serverVersion == null ? void 0 : serverVersion.name, + serverVersion: serverVersion == null ? void 0 : serverVersion.version, + tools + }; + } catch (error48) { + if (controller.signal.aborted) { + return { success: false, tools: [], error: "Connection timeout (10s)" }; + } + return { + success: false, + tools: [], + error: error48 instanceof Error ? error48.message : "Unknown error" + }; + } finally { + clearTimeout(timeout); + try { + await client.close(); + } catch (e2) { + } + } +} + +// src/core/plugins/PluginManager.ts +var fs4 = __toESM(require("fs")); +var os4 = __toESM(require("os")); +var path4 = __toESM(require("path")); +var INSTALLED_PLUGINS_PATH = path4.join(os4.homedir(), ".claude", "plugins", "installed_plugins.json"); +var GLOBAL_SETTINGS_PATH = path4.join(os4.homedir(), ".claude", "settings.json"); +function readJsonFile(filePath) { + try { + if (!fs4.existsSync(filePath)) { + return null; + } + const content = fs4.readFileSync(filePath, "utf-8"); + return JSON.parse(content); + } catch (e2) { + return null; + } +} +function normalizePathForComparison2(p2) { + try { + const resolved = fs4.realpathSync(p2); + if (typeof resolved === "string" && resolved.length > 0) { + return resolved; + } + } catch (e2) { + } + return path4.resolve(p2); +} +function selectInstalledPluginEntry(entries, normalizedVaultPath) { + var _a3; + for (const entry of entries) { + if (entry.scope !== "project") continue; + if (!entry.projectPath) continue; + if (normalizePathForComparison2(entry.projectPath) === normalizedVaultPath) { + return entry; + } + } + return (_a3 = entries.find((e2) => e2.scope === "user")) != null ? _a3 : null; +} +function extractPluginName(pluginId) { + const atIndex = pluginId.indexOf("@"); + if (atIndex > 0) { + return pluginId.substring(0, atIndex); + } + return pluginId; +} +var PluginManager = class { + constructor(vaultPath, ccSettingsStorage) { + this.plugins = []; + this.vaultPath = vaultPath; + this.ccSettingsStorage = ccSettingsStorage; + } + async loadPlugins() { + var _a3, _b, _c, _d; + const installedPlugins = readJsonFile(INSTALLED_PLUGINS_PATH); + const globalSettings = readJsonFile(GLOBAL_SETTINGS_PATH); + const projectSettings = await this.loadProjectSettings(); + const globalEnabled = (_a3 = globalSettings == null ? void 0 : globalSettings.enabledPlugins) != null ? _a3 : {}; + const projectEnabled = (_b = projectSettings == null ? void 0 : projectSettings.enabledPlugins) != null ? _b : {}; + const plugins = []; + const normalizedVaultPath = normalizePathForComparison2(this.vaultPath); + if (installedPlugins == null ? void 0 : installedPlugins.plugins) { + for (const [pluginId, entries] of Object.entries(installedPlugins.plugins)) { + if (!entries || entries.length === 0) continue; + const entry = selectInstalledPluginEntry(entries, normalizedVaultPath); + if (!entry) continue; + const scope = entry.scope === "project" ? "project" : "user"; + const enabled = (_d = (_c = projectEnabled[pluginId]) != null ? _c : globalEnabled[pluginId]) != null ? _d : true; + plugins.push({ + id: pluginId, + name: extractPluginName(pluginId), + enabled, + scope, + installPath: entry.installPath + }); + } + } + this.plugins = plugins.sort((a, b3) => { + if (a.scope !== b3.scope) { + return a.scope === "project" ? -1 : 1; + } + return a.id.localeCompare(b3.id); + }); + } + async loadProjectSettings() { + const projectSettingsPath = path4.join(this.vaultPath, ".claude", "settings.json"); + return readJsonFile(projectSettingsPath); + } + getPlugins() { + return [...this.plugins]; + } + hasPlugins() { + return this.plugins.length > 0; + } + hasEnabledPlugins() { + return this.plugins.some((p2) => p2.enabled); + } + getEnabledCount() { + return this.plugins.filter((p2) => p2.enabled).length; + } + /** Used to detect changes that require restarting the persistent query. */ + getPluginsKey() { + const enabledPlugins = this.plugins.filter((p2) => p2.enabled).sort((a, b3) => a.id.localeCompare(b3.id)); + if (enabledPlugins.length === 0) { + return ""; + } + return enabledPlugins.map((p2) => `${p2.id}:${p2.installPath}`).join("|"); + } + /** Writes to project .claude/settings.json so CLI respects the state. */ + async togglePlugin(pluginId) { + const plugin = this.plugins.find((p2) => p2.id === pluginId); + if (!plugin) { + return; + } + const newEnabled = !plugin.enabled; + plugin.enabled = newEnabled; + await this.ccSettingsStorage.setPluginEnabled(pluginId, newEnabled); + } + async enablePlugin(pluginId) { + const plugin = this.plugins.find((p2) => p2.id === pluginId); + if (!plugin || plugin.enabled) { + return; + } + plugin.enabled = true; + await this.ccSettingsStorage.setPluginEnabled(pluginId, true); + } + async disablePlugin(pluginId) { + const plugin = this.plugins.find((p2) => p2.id === pluginId); + if (!plugin || !plugin.enabled) { + return; + } + plugin.enabled = false; + await this.ccSettingsStorage.setPluginEnabled(pluginId, false); + } +}; + +// src/utils/slashCommand.ts +function extractFirstParagraph(content) { + const paragraph = content.split(/\n\s*\n/).find((p2) => p2.trim()); + if (!paragraph) return void 0; + return paragraph.trim().replace(/\n/g, " "); +} +function validateCommandName(name) { + return validateSlugName(name, "Command"); +} +function isSkill(cmd) { + return cmd.id.startsWith("skill-"); +} +function parsedToSlashCommand(parsed, identity) { + return { + ...identity, + description: parsed.description, + argumentHint: parsed.argumentHint, + allowedTools: parsed.allowedTools, + model: parsed.model, + content: parsed.promptContent, + disableModelInvocation: parsed.disableModelInvocation, + userInvocable: parsed.userInvocable, + context: parsed.context, + agent: parsed.agent, + hooks: parsed.hooks + }; +} +function parseSlashCommandContent(content) { + var _a3, _b, _c, _d; + const parsed = parseFrontmatter(content); + if (!parsed) { + return { promptContent: content }; + } + const fm = parsed.frontmatter; + return { + // Existing fields — support both kebab-case (file format) and camelCase + description: extractString(fm, "description"), + argumentHint: (_a3 = extractString(fm, "argument-hint")) != null ? _a3 : extractString(fm, "argumentHint"), + allowedTools: (_b = extractStringArray(fm, "allowed-tools")) != null ? _b : extractStringArray(fm, "allowedTools"), + model: extractString(fm, "model"), + promptContent: parsed.body, + // Skill fields — kebab-case preferred (CC file format), camelCase for backwards compat + disableModelInvocation: (_c = extractBoolean(fm, "disable-model-invocation")) != null ? _c : extractBoolean(fm, "disableModelInvocation"), + userInvocable: (_d = extractBoolean(fm, "user-invocable")) != null ? _d : extractBoolean(fm, "userInvocable"), + context: extractString(fm, "context") === "fork" ? "fork" : void 0, + agent: extractString(fm, "agent"), + hooks: isRecord(fm.hooks) ? fm.hooks : void 0 + }; +} +function yamlString(value) { + if (value.includes(":") || value.includes("#") || value.includes("\n") || value.startsWith(" ") || value.endsWith(" ")) { + return `"${value.replace(/"/g, '\\"')}"`; + } + return value; +} +function serializeCommand(cmd) { + const parsed = parseSlashCommandContent(cmd.content); + return serializeSlashCommandMarkdown(cmd, parsed.promptContent); +} +function serializeSlashCommandMarkdown(cmd, body) { + const lines = ["---"]; + if (cmd.name) { + lines.push(`name: ${cmd.name}`); + } + if (cmd.description) { + lines.push(`description: ${yamlString(cmd.description)}`); + } + if (cmd.argumentHint) { + lines.push(`argument-hint: ${yamlString(cmd.argumentHint)}`); + } + if (cmd.allowedTools && cmd.allowedTools.length > 0) { + lines.push("allowed-tools:"); + for (const tool of cmd.allowedTools) { + lines.push(` - ${yamlString(tool)}`); + } + } + if (cmd.model) { + lines.push(`model: ${cmd.model}`); + } + if (cmd.disableModelInvocation !== void 0) { + lines.push(`disable-model-invocation: ${cmd.disableModelInvocation}`); + } + if (cmd.userInvocable !== void 0) { + lines.push(`user-invocable: ${cmd.userInvocable}`); + } + if (cmd.context) { + lines.push(`context: ${cmd.context}`); + } + if (cmd.agent) { + lines.push(`agent: ${cmd.agent}`); + } + if (cmd.hooks !== void 0) { + lines.push(`hooks: ${JSON.stringify(cmd.hooks)}`); + } + if (lines.length === 1) { + lines.push(""); + } + lines.push("---"); + lines.push(body); + return lines.join("\n"); +} + +// src/utils/agent.ts +function validateAgentName(name) { + return validateSlugName(name, "Agent"); +} +function pushYamlList(lines, key, items) { + if (!items || items.length === 0) return; + lines.push(`${key}:`); + for (const item of items) { + lines.push(` - ${yamlString(item)}`); + } +} +function serializeAgent(agent) { + const lines = ["---"]; + lines.push(`name: ${agent.name}`); + lines.push(`description: ${yamlString(agent.description)}`); + pushYamlList(lines, "tools", agent.tools); + pushYamlList(lines, "disallowedTools", agent.disallowedTools); + if (agent.model && agent.model !== "inherit") { + lines.push(`model: ${agent.model}`); + } + if (agent.permissionMode) { + lines.push(`permissionMode: ${agent.permissionMode}`); + } + pushYamlList(lines, "skills", agent.skills); + if (agent.hooks !== void 0) { + lines.push(`hooks: ${JSON.stringify(agent.hooks)}`); + } + if (agent.extraFrontmatter) { + for (const [key, value] of Object.entries(agent.extraFrontmatter)) { + lines.push(`${key}: ${JSON.stringify(value)}`); + } + } + lines.push("---"); + lines.push(agent.prompt); + return lines.join("\n"); +} + +// src/core/storage/AgentVaultStorage.ts +var AGENTS_PATH = ".claude/agents"; +var AgentVaultStorage = class { + constructor(adapter) { + this.adapter = adapter; + } + async loadAll() { + const agents = []; + try { + const files = await this.adapter.listFiles(AGENTS_PATH); + for (const filePath of files) { + if (!filePath.endsWith(".md")) continue; + try { + const content = await this.adapter.read(filePath); + const parsed = parseAgentFile(content); + if (!parsed) continue; + const { frontmatter, body } = parsed; + agents.push(buildAgentFromFrontmatter(frontmatter, body, { + id: frontmatter.name, + source: "vault", + filePath + })); + } catch (e2) { } - for (const event of transformSDKMessage(message, { intendedModel: selectedModel })) { - if (isSessionInitEvent(event)) { - this.sessionManager.captureSession(event.sessionId); - streamSessionId = event.sessionId; - } else if (isStreamChunk(event)) { - if (event.type === "usage") { - yield { ...event, sessionId: streamSessionId }; - } else { - yield event; + } + } catch (e2) { + } + return agents; + } + async save(agent) { + await this.adapter.write(this.resolvePath(agent), serializeAgent(agent)); + } + async delete(agent) { + await this.adapter.delete(this.resolvePath(agent)); + } + resolvePath(agent) { + var _a3; + return (_a3 = agent.filePath) != null ? _a3 : `${AGENTS_PATH}/${agent.name}.md`; + } +}; + +// src/core/storage/migrationConstants.ts +var CLAUDIAN_ONLY_FIELDS = /* @__PURE__ */ new Set([ + // User preferences + "userName", + // Security settings + "enableBlocklist", + "blockedCommands", + "permissionMode", + "lastNonPlanPermissionMode", + // Model & thinking + "model", + "thinkingBudget", + "enableAutoTitleGeneration", + "titleGenerationModel", + // Content settings + "excludedTags", + "mediaFolder", + "systemPrompt", + "allowedExportPaths", + "persistentExternalContextPaths", + // Environment (Claudian uses string format + snippets) + "environmentVariables", + "envSnippets", + // UI settings + "keyboardNavigation", + // CLI paths + "claudeCliPath", + "claudeCliPaths", + "loadUserClaudeSettings", + // Deprecated fields (removed completely, not migrated) + "allowedContextPaths", + "showToolUse", + "toolCallExpandedByDefault" +]); +function convertEnvObjectToString(env) { + if (!env || typeof env !== "object") { + return ""; + } + return Object.entries(env).filter(([key, value]) => typeof key === "string" && typeof value === "string").map(([key, value]) => `${key}=${value}`).join("\n"); +} +function mergeEnvironmentVariables(existing, additional) { + const envMap = /* @__PURE__ */ new Map(); + for (const line of existing.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const eqIndex = trimmed.indexOf("="); + if (eqIndex > 0) { + const key = trimmed.slice(0, eqIndex); + const value = trimmed.slice(eqIndex + 1); + envMap.set(key, value); + } + } + for (const line of additional.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const eqIndex = trimmed.indexOf("="); + if (eqIndex > 0) { + const key = trimmed.slice(0, eqIndex); + const value = trimmed.slice(eqIndex + 1); + envMap.set(key, value); + } + } + return Array.from(envMap.entries()).map(([key, value]) => `${key}=${value}`).join("\n"); +} + +// src/core/storage/CCSettingsStorage.ts +var CC_SETTINGS_PATH = ".claude/settings.json"; +var CC_SETTINGS_SCHEMA = "https://json.schemastore.org/claude-code-settings.json"; +function hasClaudianOnlyFields(data) { + return Object.keys(data).some((key) => CLAUDIAN_ONLY_FIELDS.has(key)); +} +function isLegacyPermissionsFormat(data) { + if (!data || typeof data !== "object") return false; + const obj = data; + if (!Array.isArray(obj.permissions)) return false; + if (obj.permissions.length === 0) return false; + const first = obj.permissions[0]; + return typeof first === "object" && first !== null && "toolName" in first && "pattern" in first; +} +function normalizeRuleList(value) { + if (!Array.isArray(value)) return []; + return value.filter((r2) => typeof r2 === "string"); +} +function normalizePermissions(permissions) { + if (!permissions || typeof permissions !== "object") { + return { ...DEFAULT_CC_PERMISSIONS }; + } + const p2 = permissions; + return { + allow: normalizeRuleList(p2.allow), + deny: normalizeRuleList(p2.deny), + ask: normalizeRuleList(p2.ask), + defaultMode: typeof p2.defaultMode === "string" ? p2.defaultMode : void 0, + additionalDirectories: Array.isArray(p2.additionalDirectories) ? p2.additionalDirectories.filter((d) => typeof d === "string") : void 0 + }; +} +var CCSettingsStorage = class { + constructor(adapter) { + this.adapter = adapter; + } + /** + * Load CC settings from .claude/settings.json. + * Returns default settings if file doesn't exist. + * Throws if file exists but cannot be read or parsed. + */ + async load() { + if (!await this.adapter.exists(CC_SETTINGS_PATH)) { + return { ...DEFAULT_CC_SETTINGS }; + } + const content = await this.adapter.read(CC_SETTINGS_PATH); + const stored = JSON.parse(content); + if (isLegacyPermissionsFormat(stored)) { + const legacyPerms = stored.permissions; + const ccPerms = legacyPermissionsToCCPermissions(legacyPerms); + return { + $schema: CC_SETTINGS_SCHEMA, + ...stored, + permissions: ccPerms + }; + } + return { + $schema: CC_SETTINGS_SCHEMA, + ...stored, + permissions: normalizePermissions(stored.permissions) + }; + } + /** + * Save CC settings to .claude/settings.json. + * Preserves unknown fields for CC compatibility. + * + * @param stripClaudianFields - If true, remove Claudian-only fields (only during migration) + */ + async save(settings11, stripClaudianFields = false) { + var _a3; + let existing = {}; + if (await this.adapter.exists(CC_SETTINGS_PATH)) { + try { + const content2 = await this.adapter.read(CC_SETTINGS_PATH); + const parsed = JSON.parse(content2); + if (stripClaudianFields && (isLegacyPermissionsFormat(parsed) || hasClaudianOnlyFields(parsed))) { + existing = {}; + for (const [key, value] of Object.entries(parsed)) { + if (!CLAUDIAN_ONLY_FIELDS.has(key)) { + existing[key] = value; } } + if (Array.isArray(existing.permissions)) { + delete existing.permissions; + } + } else { + existing = parsed; } + } catch (e2) { } - } catch (error2) { - const msg = error2 instanceof Error ? error2.message : "Unknown error"; - yield { type: "error", content: msg }; - } finally { - this.sessionManager.clearPendingModel(); } - yield { type: "done" }; + const merged = { + ...existing, + $schema: CC_SETTINGS_SCHEMA, + permissions: (_a3 = settings11.permissions) != null ? _a3 : { ...DEFAULT_CC_PERMISSIONS } + }; + if (settings11.enabledPlugins !== void 0) { + merged.enabledPlugins = settings11.enabledPlugins; + } + const content = JSON.stringify(merged, null, 2); + await this.adapter.write(CC_SETTINGS_PATH, content); } - /** Cancel the current query. */ - cancel() { - if (this.abortController) { - this.abortController.abort(); - this.sessionManager.markInterrupted(); + async exists() { + return this.adapter.exists(CC_SETTINGS_PATH); + } + async getPermissions() { + var _a3; + const settings11 = await this.load(); + return (_a3 = settings11.permissions) != null ? _a3 : { ...DEFAULT_CC_PERMISSIONS }; + } + async updatePermissions(permissions) { + const settings11 = await this.load(); + settings11.permissions = permissions; + await this.save(settings11); + } + async addAllowRule(rule) { + var _a3, _b; + const permissions = await this.getPermissions(); + if (!((_a3 = permissions.allow) == null ? void 0 : _a3.includes(rule))) { + permissions.allow = [...(_b = permissions.allow) != null ? _b : [], rule]; + await this.updatePermissions(permissions); } } - /** Reset the conversation session. */ - resetSession() { - this.sessionManager.reset(); - this.approvalManager.clearSessionApprovals(); - this.diffStore.clear(); - this.approvedPlanContent = null; - this.currentPlanFilePath = null; + async addDenyRule(rule) { + var _a3, _b; + const permissions = await this.getPermissions(); + if (!((_a3 = permissions.deny) == null ? void 0 : _a3.includes(rule))) { + permissions.deny = [...(_b = permissions.deny) != null ? _b : [], rule]; + await this.updatePermissions(permissions); + } } - /** Get the current session ID. */ - getSessionId() { - return this.sessionManager.getSessionId(); - } - /** Set the session ID (for restoring from saved conversation). */ - setSessionId(id) { - this.sessionManager.setSessionId(id, this.plugin.settings.model); - } - /** Cleanup resources. */ - cleanup() { - this.cancel(); - this.resetSession(); - this.resolvedClaudePath = null; - } - /** Sets the approval callback for UI prompts. */ - setApprovalCallback(callback) { - this.approvalCallback = callback; - } - /** Sets the AskUserQuestion callback for interactive questions. */ - setAskUserQuestionCallback(callback) { - this.askUserQuestionCallback = callback; - } - /** Sets the ExitPlanMode callback for plan approval. */ - setExitPlanModeCallback(callback) { - this.exitPlanModeCallback = callback; - } - /** Sets the EnterPlanMode callback for plan mode initiation. */ - setEnterPlanModeCallback(callback) { - this.enterPlanModeCallback = callback; - } - /** Sets the current plan file path (for ExitPlanMode handling). */ - setCurrentPlanFilePath(path12) { - this.currentPlanFilePath = path12; - } - /** Gets the current plan file path. */ - getCurrentPlanFilePath() { - return this.currentPlanFilePath; - } - /** Sets the approved plan content to be included in future system prompts. */ - setApprovedPlanContent(content) { - this.approvedPlanContent = content; - } - /** Gets the approved plan content. */ - getApprovedPlanContent() { - return this.approvedPlanContent; - } - /** Clears the approved plan content. */ - clearApprovedPlanContent() { - this.approvedPlanContent = null; - } - /** Get pending diff data for a tool_use_id (and remove it from pending). */ - getDiffData(toolUseId) { - return this.diffStore.getDiffData(toolUseId); - } - /** Clear all diff-related state. */ - clearDiffState() { - this.diffStore.clear(); - } - getPathAccessType(filePath) { - if (!this.vaultPath) return "vault"; - return getPathAccessType( - filePath, - this.plugin.settings.allowedContextPaths, - this.plugin.settings.allowedExportPaths, - this.vaultPath - ); - } - resolvePlanPath(filePath) { - const normalized = normalizePathForFilesystem(filePath); - return path7.resolve(normalized); - } - isPlanFilePath(filePath) { - const plansDir = path7.resolve(os2.homedir(), ".claude", "plans"); - const resolved = this.resolvePlanPath(filePath); - const normalizedPlans = process.platform === "win32" ? plansDir.toLowerCase() : plansDir; - const normalizedResolved = process.platform === "win32" ? resolved.toLowerCase() : resolved; - return normalizedResolved === normalizedPlans || normalizedResolved.startsWith(normalizedPlans + path7.sep); + async addAskRule(rule) { + var _a3, _b; + const permissions = await this.getPermissions(); + if (!((_a3 = permissions.ask) == null ? void 0 : _a3.includes(rule))) { + permissions.ask = [...(_b = permissions.ask) != null ? _b : [], rule]; + await this.updatePermissions(permissions); + } } /** - * Create unified callback that handles both YOLO and normal modes. - * AskUserQuestion, EnterPlanMode, and ExitPlanMode have special handling regardless of mode. + * Remove a rule from all lists. */ - createUnifiedToolCallback(mode) { - return async (toolName, input, context) => { - if (toolName === TOOL_ASK_USER_QUESTION) { - return this.handleAskUserQuestionTool(input, context == null ? void 0 : context.toolUseID); - } - if (toolName === TOOL_ENTER_PLAN_MODE) { - return this.handleEnterPlanModeTool(); - } - if (toolName === TOOL_EXIT_PLAN_MODE) { - return this.handleExitPlanModeTool(input, context == null ? void 0 : context.toolUseID); - } - if (mode === "yolo") { - return { behavior: "allow", updatedInput: input }; - } - return this.handleNormalModeApproval(toolName, input); + async removeRule(rule) { + var _a3, _b, _c; + const permissions = await this.getPermissions(); + permissions.allow = (_a3 = permissions.allow) == null ? void 0 : _a3.filter((r2) => r2 !== rule); + permissions.deny = (_b = permissions.deny) == null ? void 0 : _b.filter((r2) => r2 !== rule); + permissions.ask = (_c = permissions.ask) == null ? void 0 : _c.filter((r2) => r2 !== rule); + await this.updatePermissions(permissions); + } + /** + * Get enabled plugins map from CC settings. + * Returns empty object if not set. + */ + async getEnabledPlugins() { + var _a3; + const settings11 = await this.load(); + return (_a3 = settings11.enabledPlugins) != null ? _a3 : {}; + } + /** + * Set plugin enabled state. + * Writes to .claude/settings.json so CLI respects the state. + * + * @param pluginId - Full plugin ID (e.g., "plugin-name@source") + * @param enabled - true to enable, false to disable + */ + async setPluginEnabled(pluginId, enabled) { + var _a3; + const settings11 = await this.load(); + const enabledPlugins = (_a3 = settings11.enabledPlugins) != null ? _a3 : {}; + enabledPlugins[pluginId] = enabled; + settings11.enabledPlugins = enabledPlugins; + await this.save(settings11); + } + /** + * Get list of plugin IDs that are explicitly enabled. + * Used for PluginManager initialization. + */ + async getExplicitlyEnabledPluginIds() { + const enabledPlugins = await this.getEnabledPlugins(); + return Object.entries(enabledPlugins).filter(([, enabled]) => enabled).map(([id]) => id); + } + /** + * Check if a plugin is explicitly disabled. + * Returns true only if the plugin is set to false. + * Returns false if not set (inherits from global) or set to true. + */ + async isPluginDisabled(pluginId) { + const enabledPlugins = await this.getEnabledPlugins(); + return enabledPlugins[pluginId] === false; + } +}; + +// src/core/storage/ClaudianSettingsStorage.ts +var CLAUDIAN_SETTINGS_PATH = ".claude/claudian-settings.json"; +function normalizeCommandList(value, fallback) { + if (!Array.isArray(value)) { + return [...fallback]; + } + return value.filter((item) => typeof item === "string").map((item) => item.trim()).filter((item) => item.length > 0); +} +function normalizeBlockedCommands(value) { + const defaults = getDefaultBlockedCommands(); + if (Array.isArray(value)) { + return { + unix: normalizeCommandList(value, defaults.unix), + windows: [...defaults.windows] }; } - /** - * Handle AskUserQuestion tool - shows panel and returns answers. - */ - async handleAskUserQuestionTool(input, toolUseId) { - if (!this.askUserQuestionCallback) { - return { - behavior: "deny", - message: "No question handler available." - }; - } - try { - const answers = await this.askUserQuestionCallback(input); - if (answers === null) { - return { - behavior: "deny", - message: "User interrupted.", - interrupt: true - }; - } - if (toolUseId) { - this.askUserQuestionAnswers.set(toolUseId, answers); - } - return { - behavior: "allow", - updatedInput: { ...input, answers } - }; - } catch (e) { - return { - behavior: "deny", - message: "Failed to get user response.", - interrupt: true - }; + if (!value || typeof value !== "object") { + return defaults; + } + const candidate = value; + return { + unix: normalizeCommandList(candidate.unix, defaults.unix), + windows: normalizeCommandList(candidate.windows, defaults.windows) + }; +} +function normalizeHostnameCliPaths(value) { + if (!value || typeof value !== "object") { + return {}; + } + const result = {}; + for (const [key, val] of Object.entries(value)) { + if (typeof val === "string" && val.trim()) { + result[key] = val.trim(); } } - /** Get stored AskUserQuestion answers for a tool_use_id. */ - getAskUserQuestionAnswers(toolUseId) { - const answers = this.askUserQuestionAnswers.get(toolUseId); - if (answers) { - this.askUserQuestionAnswers.delete(toolUseId); - } - return answers; + return result; +} +var ClaudianSettingsStorage = class { + constructor(adapter) { + this.adapter = adapter; } /** - * Handle EnterPlanMode tool - notifies UI to activate plan mode after the reply ends. - */ - async handleEnterPlanModeTool() { - if (!this.enterPlanModeCallback) { - return { behavior: "allow", updatedInput: {} }; + * Load Claudian settings from .claude/claudian-settings.json. + * Returns default settings if file doesn't exist. + * Throws if file exists but cannot be read or parsed. + */ + async load() { + if (!await this.adapter.exists(CLAUDIAN_SETTINGS_PATH)) { + return this.getDefaults(); } - try { - await this.enterPlanModeCallback(); - } catch (e) { - } - return { behavior: "allow", updatedInput: {} }; + const content = await this.adapter.read(CLAUDIAN_SETTINGS_PATH); + const stored = JSON.parse(content); + const { activeConversationId: _activeConversationId, ...storedWithoutLegacy } = stored; + const blockedCommands = normalizeBlockedCommands(stored.blockedCommands); + const hostnameCliPaths = normalizeHostnameCliPaths(stored.claudeCliPathsByHost); + const legacyCliPath = typeof stored.claudeCliPath === "string" ? stored.claudeCliPath : ""; + return { + ...this.getDefaults(), + ...storedWithoutLegacy, + blockedCommands, + claudeCliPath: legacyCliPath, + claudeCliPathsByHost: hostnameCliPaths + }; + } + async save(settings11) { + const content = JSON.stringify(settings11, null, 2); + await this.adapter.write(CLAUDIAN_SETTINGS_PATH, content); + } + async exists() { + return this.adapter.exists(CLAUDIAN_SETTINGS_PATH); + } + async update(updates) { + const current = await this.load(); + await this.save({ ...current, ...updates }); } /** - * Handle ExitPlanMode tool - shows plan approval UI and handles decision. - * Reads plan content from the persisted file in ~/.claude/plans/. + * Read legacy activeConversationId from claudian-settings.json, if present. + * Used only for one-time migration to tabManagerState. */ - async handleExitPlanModeTool(input, toolUseId) { - if (!this.exitPlanModeCallback) { - return { - behavior: "deny", - message: "No plan mode handler available." - }; + async getLegacyActiveConversationId() { + if (!await this.adapter.exists(CLAUDIAN_SETTINGS_PATH)) { + return null; } - let planContent = null; - if (this.currentPlanFilePath && this.isPlanFilePath(this.currentPlanFilePath)) { - const planPath = this.resolvePlanPath(this.currentPlanFilePath); - try { - const fs10 = await import("fs"); - if (fs10.existsSync(planPath)) { - planContent = fs10.readFileSync(planPath, "utf-8"); - } - } catch (e) { - } - } - if (!planContent) { - planContent = typeof input.plan === "string" ? input.plan : null; - } - if (!planContent) { - return { - behavior: "deny", - message: "No plan content available." - }; - } - try { - const decision = await this.exitPlanModeCallback(planContent); - switch (decision.decision) { - case "approve": - return { - behavior: "deny", - message: "PLAN APPROVED. Plan mode has ended. The user has approved your plan and it has been saved. Implementation will begin with a new query that has full tool access.", - interrupt: true - }; - case "approve_new_session": - return { - behavior: "deny", - message: "PLAN APPROVED WITH NEW SESSION. Plan mode has ended. Implementation will begin with a fresh session that has full tool access.", - interrupt: true - }; - case "revise": { - const feedback = decision.feedback.trim(); - const feedbackSection = feedback ? ` - -User feedback: -${feedback}` : ""; - return { - behavior: "deny", - message: `Please revise the plan based on user feedback and call ExitPlanMode again when ready.${feedbackSection}`, - interrupt: false - }; - } - case "cancel": - return { - behavior: "deny", - message: "Plan cancelled by user.", - interrupt: true - }; - default: - return { - behavior: "deny", - message: "Unknown decision.", - interrupt: true - }; - } - } catch (e) { - return { - behavior: "deny", - message: "Failed to get plan approval.", - interrupt: true - }; + const content = await this.adapter.read(CLAUDIAN_SETTINGS_PATH); + const stored = JSON.parse(content); + const value = stored.activeConversationId; + if (typeof value === "string") { + return value; } + return null; } /** - * Handle normal mode approval - check approved actions, then prompt user. + * Remove legacy activeConversationId from claudian-settings.json. */ - async handleNormalModeApproval(toolName, input) { - if (this.approvalManager.isActionApproved(toolName, input)) { - return { behavior: "allow", updatedInput: input }; + async clearLegacyActiveConversationId() { + if (!await this.adapter.exists(CLAUDIAN_SETTINGS_PATH)) { + return; } - if (!this.approvalCallback) { - return { - behavior: "deny", - message: "No approval handler available. Please enable YOLO mode or configure permissions." - }; + const content = await this.adapter.read(CLAUDIAN_SETTINGS_PATH); + const stored = JSON.parse(content); + if (!("activeConversationId" in stored)) { + return; } - const description = getActionDescription(toolName, input); - try { - const decision = await this.approvalCallback(toolName, input, description); - if (decision === "cancel") { - return { - behavior: "deny", - message: "User interrupted.", - interrupt: true - }; - } - if (decision === "deny") { - return { - behavior: "deny", - message: "User denied this action.", - interrupt: false - }; - } - if (decision === "allow-always") { - await this.approvalManager.approveAction(toolName, input, "always"); - } else if (decision === "allow") { - await this.approvalManager.approveAction(toolName, input, "session"); - } - return { behavior: "allow", updatedInput: input }; - } catch (e) { - return { - behavior: "deny", - message: "Approval request failed.", - interrupt: true - }; + delete stored.activeConversationId; + const nextContent = JSON.stringify(stored, null, 2); + await this.adapter.write(CLAUDIAN_SETTINGS_PATH, nextContent); + } + async setLastModel(model, isCustom) { + if (isCustom) { + await this.update({ lastCustomModel: model }); + } else { + await this.update({ lastClaudeModel: model }); } } + async setLastEnvHash(hash2) { + await this.update({ lastEnvHash: hash2 }); + } + /** + * Get default settings (excluding separately loaded fields). + */ + getDefaults() { + const { + slashCommands: _, + ...defaults + } = DEFAULT_SETTINGS; + return defaults; + } }; // src/core/storage/McpStorage.ts @@ -24693,104 +37962,94 @@ var McpStorage = class _McpStorage { constructor(adapter) { this.adapter = adapter; } - /** Load MCP servers from .claude/mcp.json. */ async load() { - var _a, _b, _c, _d, _e; + var _a3, _b, _c, _d, _e; try { if (!await this.adapter.exists(MCP_CONFIG_PATH)) { return []; } const content = await this.adapter.read(MCP_CONFIG_PATH); - const file = JSON.parse(content); - if (!file.mcpServers || typeof file.mcpServers !== "object") { + const file2 = JSON.parse(content); + if (!file2.mcpServers || typeof file2.mcpServers !== "object") { return []; } - const claudianMeta = (_b = (_a = file._claudian) == null ? void 0 : _a.servers) != null ? _b : {}; + const claudianMeta = (_b = (_a3 = file2._claudian) == null ? void 0 : _a3.servers) != null ? _b : {}; const servers = []; - for (const [name, config2] of Object.entries(file.mcpServers)) { + for (const [name, config2] of Object.entries(file2.mcpServers)) { if (!isValidMcpServerConfig(config2)) { - console.warn(`[Claudian] Invalid MCP server config for "${name}", skipping`); continue; } - const meta = (_c = claudianMeta[name]) != null ? _c : {}; - const disabledTools = Array.isArray(meta.disabledTools) ? meta.disabledTools.filter((tool) => typeof tool === "string") : void 0; + const meta3 = (_c = claudianMeta[name]) != null ? _c : {}; + const disabledTools = Array.isArray(meta3.disabledTools) ? meta3.disabledTools.filter((tool) => typeof tool === "string") : void 0; const normalizedDisabledTools = disabledTools && disabledTools.length > 0 ? disabledTools : void 0; servers.push({ name, config: config2, - enabled: (_d = meta.enabled) != null ? _d : DEFAULT_MCP_SERVER.enabled, - contextSaving: (_e = meta.contextSaving) != null ? _e : DEFAULT_MCP_SERVER.contextSaving, + enabled: (_d = meta3.enabled) != null ? _d : DEFAULT_MCP_SERVER.enabled, + contextSaving: (_e = meta3.contextSaving) != null ? _e : DEFAULT_MCP_SERVER.contextSaving, disabledTools: normalizedDisabledTools, - description: meta.description + description: meta3.description }); } return servers; - } catch (error2) { - console.error("[Claudian] Failed to load MCP config:", error2); + } catch (e2) { return []; } } - /** Save MCP servers to .claude/mcp.json. */ async save(servers) { - var _a; - try { - const mcpServers = {}; - const claudianServers = {}; - for (const server of servers) { - mcpServers[server.name] = server.config; - const meta = {}; - if (server.enabled !== DEFAULT_MCP_SERVER.enabled) { - meta.enabled = server.enabled; - } - if (server.contextSaving !== DEFAULT_MCP_SERVER.contextSaving) { - meta.contextSaving = server.contextSaving; - } - const normalizedDisabledTools = (_a = server.disabledTools) == null ? void 0 : _a.map((tool) => tool.trim()).filter((tool) => tool.length > 0); - if (normalizedDisabledTools && normalizedDisabledTools.length > 0) { - meta.disabledTools = normalizedDisabledTools; - } - if (server.description) { - meta.description = server.description; - } - if (Object.keys(meta).length > 0) { - claudianServers[server.name] = meta; - } + var _a3; + const mcpServers = {}; + const claudianServers = {}; + for (const server of servers) { + mcpServers[server.name] = server.config; + const meta3 = {}; + if (server.enabled !== DEFAULT_MCP_SERVER.enabled) { + meta3.enabled = server.enabled; } - let existing = null; - if (await this.adapter.exists(MCP_CONFIG_PATH)) { - try { - const raw = await this.adapter.read(MCP_CONFIG_PATH); - const parsed = JSON.parse(raw); - if (parsed && typeof parsed === "object") { - existing = parsed; - } - } catch (e) { - existing = null; - } + if (server.contextSaving !== DEFAULT_MCP_SERVER.contextSaving) { + meta3.contextSaving = server.contextSaving; } - const file = existing ? { ...existing } : {}; - file.mcpServers = mcpServers; - const existingClaudian = existing && typeof existing._claudian === "object" ? existing._claudian : null; - if (Object.keys(claudianServers).length > 0) { - file._claudian = { ...existingClaudian != null ? existingClaudian : {}, servers: claudianServers }; - } else if (existingClaudian) { - const { servers: _servers, ...rest } = existingClaudian; - if (Object.keys(rest).length > 0) { - file._claudian = rest; - } else { - delete file._claudian; - } - } else { - delete file._claudian; + const normalizedDisabledTools = (_a3 = server.disabledTools) == null ? void 0 : _a3.map((tool) => tool.trim()).filter((tool) => tool.length > 0); + if (normalizedDisabledTools && normalizedDisabledTools.length > 0) { + meta3.disabledTools = normalizedDisabledTools; + } + if (server.description) { + meta3.description = server.description; + } + if (Object.keys(meta3).length > 0) { + claudianServers[server.name] = meta3; } - const content = JSON.stringify(file, null, 2); - await this.adapter.write(MCP_CONFIG_PATH, content); - } catch (error2) { - console.error("[Claudian] Failed to save MCP config:", error2); - throw error2; } + let existing = null; + if (await this.adapter.exists(MCP_CONFIG_PATH)) { + try { + const raw = await this.adapter.read(MCP_CONFIG_PATH); + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === "object") { + existing = parsed; + } + } catch (e2) { + existing = null; + } + } + const file2 = existing ? { ...existing } : {}; + file2.mcpServers = mcpServers; + const existingClaudian = existing && typeof existing._claudian === "object" ? existing._claudian : null; + if (Object.keys(claudianServers).length > 0) { + file2._claudian = { ...existingClaudian != null ? existingClaudian : {}, servers: claudianServers }; + } else if (existingClaudian) { + const { servers: _servers, ...rest } = existingClaudian; + if (Object.keys(rest).length > 0) { + file2._claudian = rest; + } else { + delete file2._claudian; + } + } else { + delete file2._claudian; + } + const content = JSON.stringify(file2, null, 2); + await this.adapter.write(MCP_CONFIG_PATH, content); } - /** Check if config file exists. */ async exists() { return this.adapter.exists(MCP_CONFIG_PATH); } @@ -24802,9 +38061,9 @@ var McpStorage = class _McpStorage { * 2. Single server with name: { "name": { "command": "..." } } * 3. Single server without name: { "command": "..." } */ - static parseClipboardConfig(json) { + static parseClipboardConfig(json2) { try { - const parsed = JSON.parse(json); + const parsed = JSON.parse(json2); if (!parsed || typeof parsed !== "object") { throw new Error("Invalid JSON object"); } @@ -24846,11 +38105,11 @@ var McpStorage = class _McpStorage { return { servers, needsName: false }; } throw new Error("Invalid MCP configuration format"); - } catch (error2) { - if (error2 instanceof SyntaxError) { + } catch (error48) { + if (error48 instanceof SyntaxError) { throw new Error("Invalid JSON"); } - throw error2; + throw error48; } } /** @@ -24864,7 +38123,7 @@ var McpStorage = class _McpStorage { } try { return _McpStorage.parseClipboardConfig(trimmed); - } catch (e) { + } catch (e2) { return null; } } @@ -24876,7 +38135,6 @@ var SessionStorage = class { constructor(adapter) { this.adapter = adapter; } - /** Load a conversation from its JSONL file. */ async loadConversation(id) { const filePath = this.getFilePath(id); try { @@ -24885,18 +38143,15 @@ var SessionStorage = class { } const content = await this.adapter.read(filePath); return this.parseJSONL(content); - } catch (error2) { - console.error(`[Claudian] Failed to load conversation ${id}:`, error2); + } catch (e2) { return null; } } - /** Save a conversation to its JSONL file. */ async saveConversation(conversation) { const filePath = this.getFilePath(conversation.id); const content = this.serializeToJSONL(conversation); await this.adapter.write(filePath, content); } - /** Delete a conversation's JSONL file. */ async deleteConversation(id) { const filePath = this.getFilePath(id); await this.adapter.delete(filePath); @@ -24909,23 +38164,21 @@ var SessionStorage = class { for (const filePath of files) { if (!filePath.endsWith(".jsonl")) continue; try { - const meta = await this.loadMetaOnly(filePath); - if (meta) { - metas.push(meta); + const meta3 = await this.loadMetaOnly(filePath); + if (meta3) { + metas.push(meta3); } - } catch (error2) { - console.error(`[Claudian] Failed to load meta from ${filePath}:`, error2); + } catch (e2) { } } - metas.sort((a, b) => b.updatedAt - a.updatedAt); - } catch (error2) { - console.error("[Claudian] Failed to list sessions:", error2); + metas.sort((a, b3) => b3.updatedAt - a.updatedAt); + } catch (e2) { } return metas; } - /** Load all conversations (full data). */ async loadAllConversations() { const conversations = []; + let failedCount = 0; try { const files = await this.adapter.listFiles(SESSIONS_PATH); for (const filePath of files) { @@ -24935,27 +38188,25 @@ var SessionStorage = class { const conversation = this.parseJSONL(content); if (conversation) { conversations.push(conversation); + } else { + failedCount++; } - } catch (error2) { - console.error(`[Claudian] Failed to load conversation from ${filePath}:`, error2); + } catch (e2) { + failedCount++; } } - conversations.sort((a, b) => b.updatedAt - a.updatedAt); - } catch (error2) { - console.error("[Claudian] Failed to load all conversations:", error2); + conversations.sort((a, b3) => b3.updatedAt - a.updatedAt); + } catch (e2) { } - return conversations; + return { conversations, failedCount }; } - /** Check if any sessions exist. */ async hasSessions() { const files = await this.adapter.listFiles(SESSIONS_PATH); - return files.some((f) => f.endsWith(".jsonl")); + return files.some((f3) => f3.endsWith(".jsonl")); } - /** Get the file path for a conversation. */ getFilePath(id) { return `${SESSIONS_PATH}/${id}.jsonl`; } - /** Load only metadata from a session file (first line). */ async loadMetaOnly(filePath) { const content = await this.adapter.read(filePath); const firstLine = content.split(/\r?\n/)[0]; @@ -24963,18 +38214,18 @@ var SessionStorage = class { try { const record2 = JSON.parse(firstLine); if (record2.type !== "meta") return null; - const lines = content.split(/\r?\n/).filter((l) => l.trim()); + const lines = content.split(/\r?\n/).filter((l3) => l3.trim()); const messageCount = lines.length - 1; let preview = "New conversation"; - for (let i = 1; i < lines.length; i++) { + for (let i2 = 1; i2 < lines.length; i2++) { try { - const msgRecord = JSON.parse(lines[i]); + const msgRecord = JSON.parse(lines[i2]); if (msgRecord.type === "message" && msgRecord.message.role === "user") { const content2 = msgRecord.message.content; preview = content2.substring(0, 50) + (content2.length > 50 ? "..." : ""); break; } - } catch (e) { + } catch (e2) { continue; } } @@ -24988,49 +38239,43 @@ var SessionStorage = class { preview, titleGenerationStatus: record2.titleGenerationStatus }; - } catch (e) { + } catch (e2) { return null; } } - /** Parse JSONL content into a Conversation object. */ parseJSONL(content) { - const lines = content.split(/\r?\n/).filter((l) => l.trim()); + const lines = content.split(/\r?\n/).filter((l3) => l3.trim()); if (lines.length === 0) return null; - let meta = null; + let meta3 = null; const messages = []; for (const line of lines) { try { const record2 = JSON.parse(line); if (record2.type === "meta") { - meta = record2; + meta3 = record2; } else if (record2.type === "message") { messages.push(record2.message); } - } catch (error2) { - console.warn("[Claudian] Failed to parse JSONL line:", error2); + } catch (e2) { } } - if (!meta) return null; + if (!meta3) return null; return { - id: meta.id, - title: meta.title, - createdAt: meta.createdAt, - updatedAt: meta.updatedAt, - lastResponseAt: meta.lastResponseAt, - sessionId: meta.sessionId, + id: meta3.id, + title: meta3.title, + createdAt: meta3.createdAt, + updatedAt: meta3.updatedAt, + lastResponseAt: meta3.lastResponseAt, + sessionId: meta3.sessionId, messages, - currentNote: meta.currentNote, - usage: meta.usage, - approvedPlan: meta.approvedPlan, - pendingPlanContent: meta.pendingPlanContent, - isInPlanMode: meta.isInPlanMode, - titleGenerationStatus: meta.titleGenerationStatus + currentNote: meta3.currentNote, + usage: meta3.usage, + titleGenerationStatus: meta3.titleGenerationStatus }; } - /** Serialize a Conversation to JSONL format. */ serializeToJSONL(conversation) { const lines = []; - const meta = { + const meta3 = { type: "meta", id: conversation.id, title: conversation.title, @@ -25040,205 +38285,197 @@ var SessionStorage = class { sessionId: conversation.sessionId, currentNote: conversation.currentNote, usage: conversation.usage, - approvedPlan: conversation.approvedPlan, - pendingPlanContent: conversation.pendingPlanContent, - isInPlanMode: conversation.isInPlanMode, titleGenerationStatus: conversation.titleGenerationStatus }; - lines.push(JSON.stringify(meta)); + lines.push(JSON.stringify(meta3)); for (const message of conversation.messages) { - const storedMessage = this.prepareMessageForStorage(message); const record2 = { type: "message", - message: storedMessage + message }; lines.push(JSON.stringify(record2)); } return lines.join("\n"); } - /** Prepare a message for storage (strip image data). */ - prepareMessageForStorage(message) { - if (!message.images || message.images.length === 0) { - return message; - } - const strippedImages = message.images.map((img) => { - if (!img.cachePath && !img.filePath) { - return img; + /** + * Detects if a session uses SDK-native storage. + * A session is "native" if no legacy JSONL file exists. + * + * Legacy sessions have id.jsonl (and optionally id.meta.json). + * Native sessions have only id.meta.json or no files yet (SDK stores messages). + */ + async isNativeSession(id) { + const legacyPath = `${SESSIONS_PATH}/${id}.jsonl`; + const legacyExists = await this.adapter.exists(legacyPath); + return !legacyExists; + } + getMetadataPath(id) { + return `${SESSIONS_PATH}/${id}.meta.json`; + } + async saveMetadata(metadata) { + const filePath = this.getMetadataPath(metadata.id); + const content = JSON.stringify(metadata, null, 2); + await this.adapter.write(filePath, content); + } + async loadMetadata(id) { + const filePath = this.getMetadataPath(id); + try { + if (!await this.adapter.exists(filePath)) { + return null; } - const { data: _, ...rest } = img; - return rest; - }); + const content = await this.adapter.read(filePath); + return JSON.parse(content); + } catch (e2) { + return null; + } + } + async deleteMetadata(id) { + const filePath = this.getMetadataPath(id); + await this.adapter.delete(filePath); + } + /** List all native session metadata (.meta.json files without .jsonl counterparts). */ + async listNativeMetadata() { + const metas = []; + try { + const files = await this.adapter.listFiles(SESSIONS_PATH); + const metaFiles = files.filter((f3) => f3.endsWith(".meta.json")); + for (const filePath of metaFiles) { + const fileName = filePath.split("/").pop() || ""; + const id = fileName.replace(".meta.json", ""); + const legacyPath = `${SESSIONS_PATH}/${id}.jsonl`; + const legacyExists = await this.adapter.exists(legacyPath); + if (legacyExists) { + continue; + } + try { + const content = await this.adapter.read(filePath); + const meta3 = JSON.parse(content); + metas.push(meta3); + } catch (e2) { + } + } + } catch (e2) { + } + return metas; + } + /** + * List all conversations, merging legacy JSONL and native metadata sources. + * Legacy conversations take precedence if both exist. + */ + async listAllConversations() { + const metas = []; + const legacyMetas = await this.listConversations(); + metas.push(...legacyMetas); + const nativeMetas = await this.listNativeMetadata(); + const legacyIds = new Set(legacyMetas.map((m) => m.id)); + for (const meta3 of nativeMetas) { + if (!legacyIds.has(meta3.id)) { + metas.push({ + id: meta3.id, + title: meta3.title, + createdAt: meta3.createdAt, + updatedAt: meta3.updatedAt, + lastResponseAt: meta3.lastResponseAt, + messageCount: 0, + // Native sessions don't track message count in metadata + preview: "SDK session", + // SDK stores messages, we don't parse them for preview + titleGenerationStatus: meta3.titleGenerationStatus, + isNative: true + }); + } + } + return metas.sort( + (a, b3) => { + var _a3, _b; + return ((_a3 = b3.lastResponseAt) != null ? _a3 : b3.createdAt) - ((_b = a.lastResponseAt) != null ? _b : a.createdAt); + } + ); + } + toSessionMetadata(conversation) { + const subagentData = this.extractSubagentData(conversation.messages); return { - ...message, - images: strippedImages + id: conversation.id, + title: conversation.title, + titleGenerationStatus: conversation.titleGenerationStatus, + createdAt: conversation.createdAt, + updatedAt: conversation.updatedAt, + lastResponseAt: conversation.lastResponseAt, + sessionId: conversation.sessionId, + sdkSessionId: conversation.sdkSessionId, + previousSdkSessionIds: conversation.previousSdkSessionIds, + currentNote: conversation.currentNote, + externalContextPaths: conversation.externalContextPaths, + enabledMcpServers: conversation.enabledMcpServers, + usage: conversation.usage, + legacyCutoffAt: conversation.legacyCutoffAt, + subagentData: Object.keys(subagentData).length > 0 ? subagentData : void 0 }; } + /** + * Extracts subagentData from messages for persistence. + * Collects subagent info from all assistant messages. + */ + extractSubagentData(messages) { + const result = {}; + for (const msg of messages) { + if (msg.role !== "assistant" || !msg.subagents) continue; + for (const subagent of msg.subagents) { + result[subagent.id] = subagent; + } + } + return result; + } }; -// src/core/storage/SettingsStorage.ts -var SETTINGS_PATH = ".claude/settings.json"; -function normalizeCommandList(value, fallback) { - if (!Array.isArray(value)) { - return [...fallback]; - } - return value.filter((item) => typeof item === "string").map((item) => item.trim()).filter((item) => item.length > 0); -} -function normalizeBlockedCommands(value) { - const defaults = getDefaultBlockedCommands(); - if (Array.isArray(value)) { - return { - unix: normalizeCommandList(value, defaults.unix), - windows: [...defaults.windows] - }; - } - if (!value || typeof value !== "object") { - return defaults; - } - const candidate = value; - return { - unix: normalizeCommandList(candidate.unix, defaults.unix), - windows: normalizeCommandList(candidate.windows, defaults.windows) - }; -} -var SettingsStorage = class { +// src/core/storage/SkillStorage.ts +var SKILLS_PATH = ".claude/skills"; +var SkillStorage = class { constructor(adapter) { this.adapter = adapter; } - /** Load settings from .claude/settings.json, merging with defaults. */ - async load() { - try { - if (!await this.adapter.exists(SETTINGS_PATH)) { - return this.getDefaults(); + async loadAll() { + const skills = []; + const folders = await this.adapter.listFolders(SKILLS_PATH); + for (const folder of folders) { + const skillName = folder.split("/").pop(); + const skillPath = `${SKILLS_PATH}/${skillName}/SKILL.md`; + try { + if (!await this.adapter.exists(skillPath)) continue; + const content = await this.adapter.read(skillPath); + const parsed = parseSlashCommandContent(content); + skills.push(parsedToSlashCommand(parsed, { + id: `skill-${skillName}`, + name: skillName, + source: "user" + })); + } catch (e2) { } - const content = await this.adapter.read(SETTINGS_PATH); - const stored = JSON.parse(content); - const blockedCommands = normalizeBlockedCommands(stored.blockedCommands); - return { - ...this.getDefaults(), - ...stored, - blockedCommands - }; - } catch (error2) { - console.error("[Claudian] Failed to load settings:", error2); - return this.getDefaults(); } + return skills; } - /** Save settings to .claude/settings.json. */ - async save(settings) { - try { - const content = JSON.stringify(settings, null, 2); - await this.adapter.write(SETTINGS_PATH, content); - } catch (error2) { - console.error("[Claudian] Failed to save settings:", error2); - throw error2; - } + async save(skill) { + const name = skill.name; + const dirPath = `${SKILLS_PATH}/${name}`; + const filePath = `${dirPath}/SKILL.md`; + await this.adapter.ensureFolder(dirPath); + await this.adapter.write(filePath, serializeCommand(skill)); } - /** Check if settings file exists. */ - async exists() { - return this.adapter.exists(SETTINGS_PATH); - } - /** Get default settings (excluding state fields). */ - getDefaults() { - const { - slashCommands: _, - lastEnvHash: __, - lastClaudeModel: ___, - lastCustomModel: ____, - ...defaults - } = DEFAULT_SETTINGS; - return defaults; + async delete(skillId) { + const name = skillId.replace(/^skill-/, ""); + const dirPath = `${SKILLS_PATH}/${name}`; + const filePath = `${dirPath}/SKILL.md`; + await this.adapter.delete(filePath); + await this.adapter.deleteFolder(dirPath); } }; -// src/utils/slashCommand.ts -function formatSlashCommandWarnings(errors) { - const maxItems = 3; - const head = errors.slice(0, maxItems); - const more = errors.length > maxItems ? ` -...and ${errors.length - maxItems} more` : ""; - return `Slash command expansion warnings: -- ${head.join("\n- ")}${more}`; -} -function parseSlashCommandContent(content) { - const frontmatterPattern = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/; - const match = content.match(frontmatterPattern); - if (!match) { - return { promptContent: content }; - } - const yamlContent = match[1]; - const promptContent = match[2]; - const result = { promptContent }; - const lines = yamlContent.split(/\r?\n/); - let arrayKey = null; - let arrayItems = []; - const flushArray = () => { - if (arrayKey === "allowed-tools") { - result.allowedTools = arrayItems; - } - arrayKey = null; - arrayItems = []; - }; - for (const line of lines) { - const trimmedLine = line.trim(); - if (arrayKey) { - if (trimmedLine.startsWith("- ")) { - arrayItems.push(unquoteYamlString(trimmedLine.slice(2).trim())); - continue; - } - if (trimmedLine === "") { - continue; - } - flushArray(); - } - const colonIndex = line.indexOf(":"); - if (colonIndex <= 0) { - continue; - } - const key = line.slice(0, colonIndex).trim(); - const value = line.slice(colonIndex + 1).trim(); - switch (key) { - case "description": - result.description = unquoteYamlString(value); - break; - case "argument-hint": - result.argumentHint = unquoteYamlString(value); - break; - case "model": - result.model = unquoteYamlString(value); - break; - case "allowed-tools": - if (!value) { - arrayKey = key; - arrayItems = []; - break; - } - if (value.startsWith("[") && value.endsWith("]")) { - result.allowedTools = value.slice(1, -1).split(",").map((s) => unquoteYamlString(s.trim())).filter(Boolean); - break; - } - result.allowedTools = [unquoteYamlString(value)].filter(Boolean); - break; - } - } - if (arrayKey) { - flushArray(); - } - return result; -} -function unquoteYamlString(value) { - if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) { - return value.slice(1, -1); - } - return value; -} - // src/core/storage/SlashCommandStorage.ts var COMMANDS_PATH = ".claude/commands"; var SlashCommandStorage = class { constructor(adapter) { this.adapter = adapter; } - /** Load all commands from .claude/commands/ recursively. */ async loadAll() { const commands = []; try { @@ -25250,32 +38487,25 @@ var SlashCommandStorage = class { if (command) { commands.push(command); } - } catch (error2) { - console.error(`[Claudian] Failed to load command from ${filePath}:`, error2); + } catch (e2) { } } - } catch (error2) { - console.error("[Claudian] Failed to list command files:", error2); + } catch (e2) { } return commands; } - /** Load a single command from a file path. */ async loadFromFile(filePath) { try { const content = await this.adapter.read(filePath); return this.parseFile(content, filePath); - } catch (error2) { - console.error(`[Claudian] Failed to read command file ${filePath}:`, error2); + } catch (e2) { return null; } } - /** Save a command to its file. */ async save(command) { const filePath = this.getFilePath(command); - const content = this.serializeCommand(command); - await this.adapter.write(filePath, content); + await this.adapter.write(filePath, serializeCommand(command)); } - /** Delete a command file by ID. */ async delete(commandId) { const files = await this.adapter.listFilesRecursive(COMMANDS_PATH); for (const filePath of files) { @@ -25287,71 +38517,25 @@ var SlashCommandStorage = class { } } } - /** Check if any commands exist. */ - async hasCommands() { - const files = await this.adapter.listFilesRecursive(COMMANDS_PATH); - return files.some((f) => f.endsWith(".md")); - } - /** Get the file path for a command. */ getFilePath(command) { const safeName = command.name.replace(/[^a-zA-Z0-9_/-]/g, "-"); return `${COMMANDS_PATH}/${safeName}.md`; } - /** Parse a command file into a SlashCommand object. */ parseFile(content, filePath) { const parsed = parseSlashCommandContent(content); - const id = this.filePathToId(filePath); - const name = this.filePathToName(filePath); - return { - id, - name, - description: parsed.description, - argumentHint: parsed.argumentHint, - allowedTools: parsed.allowedTools, - model: parsed.model, - content: parsed.promptContent - }; + return parsedToSlashCommand(parsed, { + id: this.filePathToId(filePath), + name: this.filePathToName(filePath) + }); } - /** Convert a file path to a command ID (reversible encoding). */ filePathToId(filePath) { const relativePath = filePath.replace(`${COMMANDS_PATH}/`, "").replace(/\.md$/, ""); const escaped = relativePath.replace(/-/g, "-_").replace(/\//g, "--"); return `cmd-${escaped}`; } - /** Convert a file path to a command name. */ filePathToName(filePath) { return filePath.replace(`${COMMANDS_PATH}/`, "").replace(/\.md$/, ""); } - /** Serialize a command to Markdown with YAML frontmatter. */ - serializeCommand(command) { - const lines = ["---"]; - if (command.description) { - lines.push(`description: ${this.yamlString(command.description)}`); - } - if (command.argumentHint) { - lines.push(`argument-hint: ${this.yamlString(command.argumentHint)}`); - } - if (command.allowedTools && command.allowedTools.length > 0) { - lines.push("allowed-tools:"); - for (const tool of command.allowedTools) { - lines.push(` - ${tool}`); - } - } - if (command.model) { - lines.push(`model: ${command.model}`); - } - lines.push("---"); - const parsed = parseSlashCommandContent(command.content); - lines.push(parsed.promptContent); - return lines.join("\n"); - } - /** Quote a YAML string if needed. */ - yamlString(value) { - if (value.includes(":") || value.includes("#") || value.includes("\n") || value.startsWith(" ") || value.endsWith(" ")) { - return `"${value.replace(/"/g, '\\"')}"`; - } - return value; - } }; // src/core/storage/VaultFileAdapter.ts @@ -25359,42 +38543,39 @@ var VaultFileAdapter = class { constructor(app) { this.app = app; } - /** Check if a file or folder exists. */ - async exists(path12) { - return this.app.vault.adapter.exists(path12); + async exists(path10) { + return this.app.vault.adapter.exists(path10); } - /** Read file contents as string. */ - async read(path12) { - return this.app.vault.adapter.read(path12); + async read(path10) { + return this.app.vault.adapter.read(path10); } - /** Write content to a file, creating parent directories if needed. */ - async write(path12, content) { - const folder = path12.substring(0, path12.lastIndexOf("/")); - if (folder && !await this.exists(folder)) { - await this.ensureFolder(folder); - } - await this.app.vault.adapter.write(path12, content); + async write(path10, content) { + await this.ensureParentFolder(path10); + await this.app.vault.adapter.write(path10, content); } - /** Append content to a file. Creates the file if it doesn't exist. */ - async append(path12, content) { - const folder = path12.substring(0, path12.lastIndexOf("/")); - if (folder && !await this.exists(folder)) { - await this.ensureFolder(folder); - } - if (await this.exists(path12)) { - const existing = await this.read(path12); - await this.app.vault.adapter.write(path12, existing + content); + async append(path10, content) { + await this.ensureParentFolder(path10); + if (await this.exists(path10)) { + const existing = await this.read(path10); + await this.app.vault.adapter.write(path10, existing + content); } else { - await this.app.vault.adapter.write(path12, content); + await this.app.vault.adapter.write(path10, content); } } - /** Delete a file if it exists. */ - async delete(path12) { - if (await this.exists(path12)) { - await this.app.vault.adapter.remove(path12); + async delete(path10) { + if (await this.exists(path10)) { + await this.app.vault.adapter.remove(path10); + } + } + /** Fails silently if non-empty or missing. */ + async deleteFolder(path10) { + try { + if (await this.exists(path10)) { + await this.app.vault.adapter.rmdir(path10, false); + } + } catch (e2) { } } - /** List files in a folder. Returns relative paths from the folder. */ async listFiles(folder) { if (!await this.exists(folder)) { return []; @@ -25424,10 +38605,16 @@ var VaultFileAdapter = class { await processFolder(folder); return allFiles; } + async ensureParentFolder(filePath) { + const folder = filePath.substring(0, filePath.lastIndexOf("/")); + if (folder && !await this.exists(folder)) { + await this.ensureFolder(folder); + } + } /** Ensure a folder exists, creating it and parent folders if needed. */ - async ensureFolder(path12) { - if (await this.exists(path12)) return; - const parts = path12.split("/").filter(Boolean); + async ensureFolder(path10) { + if (await this.exists(path10)) return; + const parts = path10.split("/").filter(Boolean); let current = ""; for (const part of parts) { current = current ? `${current}/${part}` : part; @@ -25440,13 +38627,12 @@ var VaultFileAdapter = class { async rename(oldPath, newPath) { await this.app.vault.adapter.rename(oldPath, newPath); } - /** Get file stats (mtime, size). */ - async stat(path12) { + async stat(path10) { try { - const stat = await this.app.vault.adapter.stat(path12); + const stat = await this.app.vault.adapter.stat(path10); if (!stat) return null; return { mtime: stat.mtime, size: stat.size }; - } catch (e) { + } catch (e2) { return null; } } @@ -25454,1056 +38640,332 @@ var VaultFileAdapter = class { // src/core/storage/StorageService.ts var CLAUDE_PATH = ".claude"; -var DEFAULT_STATE = { - activeConversationId: null, - lastEnvHash: "", - lastClaudeModel: "haiku", - lastCustomModel: "" -}; var StorageService = class { constructor(plugin) { this.plugin = plugin; this.app = plugin.app; this.adapter = new VaultFileAdapter(this.app); - this.settings = new SettingsStorage(this.adapter); + this.ccSettings = new CCSettingsStorage(this.adapter); + this.claudianSettings = new ClaudianSettingsStorage(this.adapter); this.commands = new SlashCommandStorage(this.adapter); + this.skills = new SkillStorage(this.adapter); this.sessions = new SessionStorage(this.adapter); this.mcp = new McpStorage(this.adapter); + this.agents = new AgentVaultStorage(this.adapter); } - /** Initialize storage, running migration if needed. */ async initialize() { await this.ensureDirectories(); - const settingsExist = await this.settings.exists(); - const legacyData = await this.loadLegacyData(); - if (legacyData && this.needsMigration(legacyData)) { - console.log("[Claudian] Migrating from legacy data.json to distributed storage..."); - const migrated = await this.runMigration(legacyData, { migrateSettings: !settingsExist }); - if (migrated) { - console.log("[Claudian] Migration complete."); - } else { - console.warn("[Claudian] Migration incomplete; will retry on next launch."); + await this.runMigrations(); + const cc = await this.ccSettings.load(); + const claudian = await this.claudianSettings.load(); + return { cc, claudian }; + } + async runMigrations() { + const ccExists = await this.ccSettings.exists(); + const claudianExists = await this.claudianSettings.exists(); + const dataJson = await this.loadDataJson(); + if (ccExists && !claudianExists) { + await this.migrateFromOldSettingsJson(); + } + if (dataJson) { + const hasState = this.hasStateToMigrate(dataJson); + const hasLegacyContent = this.hasLegacyContentToMigrate(dataJson); + if (hasState) { + await this.migrateFromDataJson(dataJson); + } + let legacyContentHadErrors = false; + if (hasLegacyContent) { + const result = await this.migrateLegacyDataJsonContent(dataJson); + legacyContentHadErrors = result.hadErrors; + } + if ((hasState || hasLegacyContent) && !legacyContentHadErrors) { + await this.clearLegacyDataJson(); } } - const settings = await this.settings.load(); - const state = await this.loadState(); - return { settings, state }; } - /** Check if migration is needed. */ - needsMigration(legacyData) { - if (!legacyData) return false; - const hasConversations = legacyData.conversations && legacyData.conversations.length > 0; - const hasSlashCommands = legacyData.slashCommands && legacyData.slashCommands.length > 0; - const stateKeys = /* @__PURE__ */ new Set([ - "conversations", - "slashCommands", - "activeConversationId", - "lastEnvHash", - "lastClaudeModel", - "lastCustomModel", - "migrationVersion" - ]); - const hasSettings = Object.keys(legacyData).some((key) => !stateKeys.has(key)); - return hasConversations || hasSlashCommands || hasSettings; + hasStateToMigrate(data) { + return data.lastEnvHash !== void 0 || data.lastClaudeModel !== void 0 || data.lastCustomModel !== void 0; } - /** Run migration from legacy data.json to distributed storage. */ - async runMigration(legacyData, options = { migrateSettings: true }) { + hasLegacyContentToMigrate(data) { + var _a3, _b, _c, _d; + return ((_b = (_a3 = data.slashCommands) == null ? void 0 : _a3.length) != null ? _b : 0) > 0 || ((_d = (_c = data.conversations) == null ? void 0 : _c.length) != null ? _d : 0) > 0; + } + /** + * Migrate from old settings.json (with Claudian fields) to split format. + * + * Handles: + * - Legacy Claudian fields (userName, model, etc.) → claudian-settings.json + * - Legacy permissions array → CC permissions object + * - CC env object → Claudian environmentVariables string + * - Preserves existing CC permissions if already in CC format + */ + async migrateFromOldSettingsJson() { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q2, _r, _s; + const content = await this.adapter.read(CC_SETTINGS_PATH); + const oldSettings = JSON.parse(content); + const hasClaudianFields = Array.from(CLAUDIAN_ONLY_FIELDS).some( + (field) => oldSettings[field] !== void 0 + ); + if (!hasClaudianFields) { + return; + } + let environmentVariables = (_a3 = oldSettings.environmentVariables) != null ? _a3 : ""; + if (oldSettings.env && typeof oldSettings.env === "object") { + const envFromCC = convertEnvObjectToString(oldSettings.env); + if (envFromCC) { + environmentVariables = mergeEnvironmentVariables(environmentVariables, envFromCC); + } + } + const claudianFields = { + userName: (_b = oldSettings.userName) != null ? _b : DEFAULT_SETTINGS.userName, + enableBlocklist: (_c = oldSettings.enableBlocklist) != null ? _c : DEFAULT_SETTINGS.enableBlocklist, + blockedCommands: normalizeBlockedCommands(oldSettings.blockedCommands), + model: (_d = oldSettings.model) != null ? _d : DEFAULT_SETTINGS.model, + thinkingBudget: (_e = oldSettings.thinkingBudget) != null ? _e : DEFAULT_SETTINGS.thinkingBudget, + permissionMode: (_f = oldSettings.permissionMode) != null ? _f : DEFAULT_SETTINGS.permissionMode, + excludedTags: (_g = oldSettings.excludedTags) != null ? _g : DEFAULT_SETTINGS.excludedTags, + mediaFolder: (_h = oldSettings.mediaFolder) != null ? _h : DEFAULT_SETTINGS.mediaFolder, + environmentVariables, + // Merged from both sources + envSnippets: (_i = oldSettings.envSnippets) != null ? _i : DEFAULT_SETTINGS.envSnippets, + systemPrompt: (_j = oldSettings.systemPrompt) != null ? _j : DEFAULT_SETTINGS.systemPrompt, + allowedExportPaths: (_k = oldSettings.allowedExportPaths) != null ? _k : DEFAULT_SETTINGS.allowedExportPaths, + persistentExternalContextPaths: DEFAULT_SETTINGS.persistentExternalContextPaths, + keyboardNavigation: (_l = oldSettings.keyboardNavigation) != null ? _l : DEFAULT_SETTINGS.keyboardNavigation, + claudeCliPath: (_m = oldSettings.claudeCliPath) != null ? _m : DEFAULT_SETTINGS.claudeCliPath, + claudeCliPathsByHost: DEFAULT_SETTINGS.claudeCliPathsByHost, + // Migration to hostname-based handled in main.ts + loadUserClaudeSettings: (_n = oldSettings.loadUserClaudeSettings) != null ? _n : DEFAULT_SETTINGS.loadUserClaudeSettings, + enableAutoTitleGeneration: (_o = oldSettings.enableAutoTitleGeneration) != null ? _o : DEFAULT_SETTINGS.enableAutoTitleGeneration, + titleGenerationModel: (_p = oldSettings.titleGenerationModel) != null ? _p : DEFAULT_SETTINGS.titleGenerationModel, + lastClaudeModel: DEFAULT_SETTINGS.lastClaudeModel, + lastCustomModel: DEFAULT_SETTINGS.lastCustomModel, + lastEnvHash: DEFAULT_SETTINGS.lastEnvHash + }; + await this.claudianSettings.save(claudianFields); + const savedClaudian = await this.claudianSettings.load(); + if (!savedClaudian || savedClaudian.userName === void 0) { + throw new Error("Failed to verify claudian-settings.json was saved correctly"); + } + let ccPermissions; + if (isLegacyPermissionsFormat(oldSettings)) { + ccPermissions = legacyPermissionsToCCPermissions(oldSettings.permissions); + } else if (oldSettings.permissions && typeof oldSettings.permissions === "object" && !Array.isArray(oldSettings.permissions)) { + const existingPerms = oldSettings.permissions; + ccPermissions = { + allow: (_q2 = existingPerms.allow) != null ? _q2 : [], + deny: (_r = existingPerms.deny) != null ? _r : [], + ask: (_s = existingPerms.ask) != null ? _s : [], + defaultMode: existingPerms.defaultMode, + additionalDirectories: existingPerms.additionalDirectories + }; + } else { + ccPermissions = { ...DEFAULT_CC_PERMISSIONS }; + } + const ccSettings = { + $schema: "https://json.schemastore.org/claude-code-settings.json", + permissions: ccPermissions + }; + await this.ccSettings.save(ccSettings, true); + } + async migrateFromDataJson(dataJson) { + const claudian = await this.claudianSettings.load(); + if (dataJson.lastEnvHash !== void 0 && !claudian.lastEnvHash) { + claudian.lastEnvHash = dataJson.lastEnvHash; + } + if (dataJson.lastClaudeModel !== void 0 && !claudian.lastClaudeModel) { + claudian.lastClaudeModel = dataJson.lastClaudeModel; + } + if (dataJson.lastCustomModel !== void 0 && !claudian.lastCustomModel) { + claudian.lastCustomModel = dataJson.lastCustomModel; + } + await this.claudianSettings.save(claudian); + } + async migrateLegacyDataJsonContent(dataJson) { let hadErrors = false; - if (options.migrateSettings) { - try { - await this.migrateSettings(legacyData); - } catch (error2) { - hadErrors = true; - console.error("[Claudian] Failed to migrate settings:", error2); + if (dataJson.slashCommands && dataJson.slashCommands.length > 0) { + for (const command of dataJson.slashCommands) { + try { + const filePath = this.commands.getFilePath(command); + if (await this.adapter.exists(filePath)) { + continue; + } + await this.commands.save(command); + } catch (e2) { + hadErrors = true; + } } } - if (await this.migrateSlashCommands(legacyData.slashCommands || [])) { - hadErrors = true; + if (dataJson.conversations && dataJson.conversations.length > 0) { + for (const conversation of dataJson.conversations) { + try { + const filePath = this.sessions.getFilePath(conversation.id); + if (await this.adapter.exists(filePath)) { + continue; + } + await this.sessions.saveConversation(conversation); + } catch (e2) { + hadErrors = true; + } + } } - if (await this.migrateConversations(legacyData.conversations || [])) { - hadErrors = true; - } - if (hadErrors) { - return false; - } - await this.saveState({ - activeConversationId: legacyData.activeConversationId || null, - lastEnvHash: legacyData.lastEnvHash || "", - lastClaudeModel: legacyData.lastClaudeModel || "haiku", - lastCustomModel: legacyData.lastCustomModel || "" - }); - return true; + return { hadErrors }; } - /** Load legacy data from Obsidian's data.json. */ - async loadLegacyData() { + async clearLegacyDataJson() { + const dataJson = await this.loadDataJson(); + if (!dataJson) { + return; + } + const cleaned = { ...dataJson }; + delete cleaned.lastEnvHash; + delete cleaned.lastClaudeModel; + delete cleaned.lastCustomModel; + delete cleaned.conversations; + delete cleaned.slashCommands; + delete cleaned.migrationVersion; + if (Object.keys(cleaned).length === 0) { + await this.plugin.saveData({}); + return; + } + await this.plugin.saveData(cleaned); + } + async loadDataJson() { try { const data = await this.plugin.loadData(); return data || null; - } catch (e) { + } catch (e2) { return null; } } - /** Load plugin state from data.json. */ - async loadState() { - var _a, _b, _c, _d; - try { - const data = await this.plugin.loadData(); - return { - activeConversationId: (_a = data == null ? void 0 : data.activeConversationId) != null ? _a : DEFAULT_STATE.activeConversationId, - lastEnvHash: (_b = data == null ? void 0 : data.lastEnvHash) != null ? _b : DEFAULT_STATE.lastEnvHash, - lastClaudeModel: (_c = data == null ? void 0 : data.lastClaudeModel) != null ? _c : DEFAULT_STATE.lastClaudeModel, - lastCustomModel: (_d = data == null ? void 0 : data.lastCustomModel) != null ? _d : DEFAULT_STATE.lastCustomModel - }; - } catch (e) { - return { ...DEFAULT_STATE }; - } - } - /** Save plugin state to data.json. */ - async saveState(state) { - await this.plugin.saveData(state); - } - /** Update specific state fields in data.json. */ - async updateState(updates) { - const current = await this.loadState(); - await this.saveState({ ...current, ...updates }); - } - /** Ensure all required directories exist. */ async ensureDirectories() { await this.adapter.ensureFolder(CLAUDE_PATH); await this.adapter.ensureFolder(COMMANDS_PATH); + await this.adapter.ensureFolder(SKILLS_PATH); await this.adapter.ensureFolder(SESSIONS_PATH); + await this.adapter.ensureFolder(AGENTS_PATH); } - /** Migrate settings from legacy format. */ - async migrateSettings(legacyData) { - const { - slashCommands: _, - conversations: __, - activeConversationId: ___, - lastEnvHash: ____, - lastClaudeModel: _____, - lastCustomModel: ______, - migrationVersion: _______, - ...settingsFields - } = legacyData; - const settings = { - ...this.getDefaultSettings(), - ...settingsFields - }; - await this.settings.save(settings); + async loadAllSlashCommands() { + const commands = await this.commands.loadAll(); + const skills = await this.skills.loadAll(); + return [...commands, ...skills]; } - /** Migrate slash commands to individual files. */ - async migrateSlashCommands(commands) { - let hadErrors = false; - for (const command of commands) { - try { - const filePath = this.commands.getFilePath(command); - if (await this.adapter.exists(filePath)) { - continue; - } - await this.commands.save(command); - } catch (error2) { - hadErrors = true; - console.error(`[Claudian] Failed to migrate command ${command.name}:`, error2); - } - } - return hadErrors; - } - /** Migrate conversations to individual JSONL files. */ - async migrateConversations(conversations) { - let hadErrors = false; - for (const conversation of conversations) { - try { - const filePath = this.sessions.getFilePath(conversation.id); - if (await this.adapter.exists(filePath)) { - continue; - } - await this.sessions.saveConversation(conversation); - } catch (error2) { - hadErrors = true; - console.error(`[Claudian] Failed to migrate conversation ${conversation.id}:`, error2); - } - } - return hadErrors; - } - /** Get default settings (excluding state fields and slashCommands). */ - getDefaultSettings() { - const { - slashCommands: _, - lastEnvHash: __, - lastClaudeModel: ___, - lastCustomModel: ____, - ...defaults - } = DEFAULT_SETTINGS; - return defaults; - } - /** Get the vault file adapter for direct file operations. */ getAdapter() { return this.adapter; } + async getPermissions() { + return this.ccSettings.getPermissions(); + } + async updatePermissions(permissions) { + return this.ccSettings.updatePermissions(permissions); + } + async addAllowRule(rule) { + return this.ccSettings.addAllowRule(createPermissionRule(rule)); + } + async addDenyRule(rule) { + return this.ccSettings.addDenyRule(createPermissionRule(rule)); + } + /** + * Remove a permission rule from all lists. + */ + async removePermissionRule(rule) { + return this.ccSettings.removeRule(createPermissionRule(rule)); + } + async updateClaudianSettings(updates) { + return this.claudianSettings.update(updates); + } + async saveClaudianSettings(settings11) { + return this.claudianSettings.save(settings11); + } + async loadClaudianSettings() { + return this.claudianSettings.load(); + } + /** + * Get legacy activeConversationId from storage (claudian-settings.json or data.json). + */ + async getLegacyActiveConversationId() { + const fromSettings = await this.claudianSettings.getLegacyActiveConversationId(); + if (fromSettings) { + return fromSettings; + } + const dataJson = await this.loadDataJson(); + if (dataJson && typeof dataJson.activeConversationId === "string") { + return dataJson.activeConversationId; + } + return null; + } + /** + * Remove legacy activeConversationId from storage after migration. + */ + async clearLegacyActiveConversationId() { + await this.claudianSettings.clearLegacyActiveConversationId(); + const dataJson = await this.loadDataJson(); + if (!dataJson || !("activeConversationId" in dataJson)) { + return; + } + const cleaned = { ...dataJson }; + delete cleaned.activeConversationId; + await this.plugin.saveData(cleaned); + } + /** + * Get tab manager state from data.json with runtime validation. + */ + async getTabManagerState() { + try { + const data = await this.plugin.loadData(); + if (data == null ? void 0 : data.tabManagerState) { + return this.validateTabManagerState(data.tabManagerState); + } + return null; + } catch (e2) { + return null; + } + } + /** + * Validates and sanitizes tab manager state from storage. + * Returns null if the data is invalid or corrupted. + */ + validateTabManagerState(data) { + if (!data || typeof data !== "object") { + return null; + } + const state = data; + if (!Array.isArray(state.openTabs)) { + return null; + } + const validatedTabs = []; + for (const tab of state.openTabs) { + if (!tab || typeof tab !== "object") { + continue; + } + const tabObj = tab; + if (typeof tabObj.tabId !== "string") { + continue; + } + validatedTabs.push({ + tabId: tabObj.tabId, + conversationId: typeof tabObj.conversationId === "string" ? tabObj.conversationId : null + }); + } + const activeTabId = typeof state.activeTabId === "string" ? state.activeTabId : null; + return { + openTabs: validatedTabs, + activeTabId + }; + } + async setTabManagerState(state) { + try { + const data = await this.plugin.loadData() || {}; + data.tabManagerState = state; + await this.plugin.saveData(data); + } catch (e2) { + } + } }; // src/features/chat/ClaudianView.ts -var import_obsidian25 = require("obsidian"); - -// src/core/commands/SlashCommandManager.ts -var import_child_process2 = require("child_process"); -var import_obsidian = require("obsidian"); -var SlashCommandManager = class { - constructor(app, vaultPath, options = {}) { - this.commands = /* @__PURE__ */ new Map(); - var _a; - this.app = app; - this.vaultPath = vaultPath; - this.bashRunner = (_a = options.bashRunner) != null ? _a : defaultBashRunner; - } - /** Registers commands from settings. */ - setCommands(commands) { - this.commands.clear(); - for (const cmd of commands) { - this.commands.set(cmd.name.toLowerCase(), cmd); - } - } - /** Gets all registered commands. */ - getCommands() { - return Array.from(this.commands.values()); - } - /** Gets a command by name. */ - getCommand(name) { - return this.commands.get(name.toLowerCase()); - } - /** Gets filtered commands matching a prefix. */ - getMatchingCommands(prefix) { - const prefixLower = prefix.toLowerCase(); - return this.getCommands().filter( - (cmd) => { - var _a; - return cmd.name.toLowerCase().includes(prefixLower) || ((_a = cmd.description) == null ? void 0 : _a.toLowerCase().includes(prefixLower)); - } - ).slice(0, 10); - } - /** - * Detects if input starts with a slash command. - * Returns the command name and arguments if found. - */ - detectCommand(input) { - const trimmed = input.trimStart(); - if (!trimmed.startsWith("/")) return null; - const match = trimmed.match(/^\/([a-zA-Z0-9_/-]+)(?:\s+([\s\S]*))?$/); - if (!match) return null; - const commandName = match[1]; - const args = (match[2] || "").trim(); - if (!this.commands.has(commandName.toLowerCase())) { - return null; - } - return { commandName, args }; - } - /** - * Expands a command with arguments. - * Processes frontmatter, placeholders, file references, and bash execution. - */ - async expandCommand(command, args, options = {}) { - const errors = []; - const parsed = parseSlashCommandContent(command.content); - let result = parsed.promptContent; - result = this.replaceArgumentPlaceholders(result, args); - try { - const bashResult = await this.executeInlineBash(result, options.bash); - result = bashResult.content; - errors.push(...bashResult.errors); - } catch (error2) { - errors.push(`Bash execution error: ${error2 instanceof Error ? error2.message : "Unknown error"}`); - } - try { - const fileResult = await this.resolveFileReferences(result); - result = fileResult.content; - errors.push(...fileResult.errors); - } catch (error2) { - errors.push(`File reference error: ${error2 instanceof Error ? error2.message : "Unknown error"}`); - } - return { - expandedPrompt: result.trim(), - allowedTools: command.allowedTools || parsed.allowedTools, - model: command.model || parsed.model, - errors - }; - } - /** - * Replaces argument placeholders in content. - * Handles $ARGUMENTS (all args) and $1, $2, etc. (positional). - */ - replaceArgumentPlaceholders(content, args) { - const argParts = this.parseArguments(args); - let result = content.replace(/\$ARGUMENTS/g, args); - for (let i = 0; i < argParts.length; i++) { - const pattern = new RegExp(`\\$${i + 1}(?![0-9])`, "g"); - result = result.replace(pattern, argParts[i]); - } - result = result.replace(/\$\d+/g, ""); - return result; - } - /** - * Parses arguments respecting quoted strings. - * "arg with spaces" and 'single quotes' are treated as single args. - */ - parseArguments(args) { - var _a, _b; - if (!args.trim()) return []; - const parts = []; - const regex = /[^\s"']+|"([^"]*)"|'([^']*)'/g; - let match; - while ((match = regex.exec(args)) !== null) { - parts.push((_b = (_a = match[1]) != null ? _a : match[2]) != null ? _b : match[0]); - } - return parts; - } - /** - * Resolves @file references in content. - * Replaces @path/to/file.md with file contents. - */ - async resolveFileReferences(content) { - var _a; - const pattern = /(^|[^\w])@(?:"([^"]+)"|'([^']+)'|([^\s]+\.\w+))/g; - const errors = []; - const matches = []; - let match; - while ((match = pattern.exec(content)) !== null) { - const prefix = (_a = match[1]) != null ? _a : ""; - const filePath = match[2] || match[3] || match[4]; - matches.push({ full: match[0], prefix, path: filePath, index: match.index }); - } - let result = content; - for (let i = matches.length - 1; i >= 0; i--) { - const m = matches[i]; - try { - const normalizedPath = m.path.replace(/\\/g, "/"); - const file = this.app.vault.getAbstractFileByPath(normalizedPath); - if (file instanceof import_obsidian.TFile) { - const fileContent = await this.app.vault.read(file); - result = result.slice(0, m.index) + m.prefix + fileContent + result.slice(m.index + m.full.length); - } else { - errors.push(`File reference not found: ${normalizedPath}`); - } - } catch (error2) { - errors.push( - `File reference failed: ${m.path} (${error2 instanceof Error ? error2.message : "Unknown error"})` - ); - } - } - return { content: result, errors }; - } - /** - * Executes inline bash commands. - * Replaces !`command` with command output. - */ - async executeInlineBash(content, bashOptions) { - var _a; - const pattern = /!`([^`]+)`/g; - const errors = []; - const matches = []; - let match; - while ((match = pattern.exec(content)) !== null) { - matches.push({ full: match[0], command: match[1], index: match.index }); - } - let result = content; - for (let i = matches.length - 1; i >= 0; i--) { - const m = matches[i]; - try { - if (!(bashOptions == null ? void 0 : bashOptions.enabled)) { - errors.push(`Inline bash is disabled: ${m.command}`); - result = result.slice(0, m.index) + `[Inline bash disabled]` + result.slice(m.index + m.full.length); - continue; - } - if ((_a = bashOptions.shouldBlockCommand) == null ? void 0 : _a.call(bashOptions, m.command)) { - errors.push(`Inline bash blocked by blocklist: ${m.command}`); - result = result.slice(0, m.index) + `[Blocked]` + result.slice(m.index + m.full.length); - continue; - } - if (bashOptions.requestApproval) { - const approved = await bashOptions.requestApproval(m.command); - if (!approved) { - errors.push(`Inline bash denied by user: ${m.command}`); - result = result.slice(0, m.index) + `[Denied]` + result.slice(m.index + m.full.length); - continue; - } - } - const output = await this.bashRunner(m.command, this.vaultPath); - result = result.slice(0, m.index) + output.trim() + result.slice(m.index + m.full.length); - } catch (error2) { - const errorMsg = `[Error: ${error2 instanceof Error ? error2.message : "Command failed"}]`; - errors.push(`Inline bash failed: ${m.command}`); - result = result.slice(0, m.index) + errorMsg + result.slice(m.index + m.full.length); - } - } - return { content: result, errors }; - } -}; -function defaultBashRunner(command, cwd2) { - return new Promise((resolve7, reject) => { - (0, import_child_process2.exec)( - command, - { - cwd: cwd2, - timeout: 1e4, - maxBuffer: 1024 * 1024, - // Enhance PATH for GUI apps (Obsidian has minimal PATH) - env: { ...process.env, PATH: getEnhancedPath() } - }, - (error2, stdout, stderr) => { - if (error2) { - reject(new Error(stderr || error2.message)); - } else { - resolve7(stdout); - } - } - ); - }); -} - -// src/ui/components/AskUserQuestionPanel.ts -function findInputElements(containerEl) { - const inputContainer = containerEl.querySelector(".claudian-input-container"); - const inputWrapper = containerEl.querySelector(".claudian-input-wrapper"); - return { inputContainer, inputWrapper }; -} -var AskUserQuestionPanel = class { - constructor(app, options) { - this.answers = /* @__PURE__ */ new Map(); - this.currentTabIndex = 0; - this.currentOptionIndex = 0; - this.isDestroyed = false; - this.documentKeydownHandler = null; - // DOM references - this.tabsEl = null; - this.questionContentEl = null; - this.otherInputEl = null; - // Input area references (for hiding/showing) - this.inputContainer = null; - this.inputWrapper = null; - this.app = app; - this.containerEl = options.containerEl; - this.questions = options.input.questions; - this.onSubmit = options.onSubmit; - this.onCancel = options.onCancel; - const { inputContainer, inputWrapper } = findInputElements(this.containerEl); - this.inputContainer = inputContainer; - this.inputWrapper = inputWrapper; - if (this.inputWrapper) { - this.inputWrapper.style.display = "none"; - } - this.panelEl = this.createPanel(); - if (this.inputContainer) { - this.inputContainer.appendChild(this.panelEl); - } else { - this.containerEl.appendChild(this.panelEl); - } - this.panelEl.focus(); - this.attachDocumentHandler(); - } - /** Create the panel DOM structure. */ - createPanel() { - const panel = document.createElement("div"); - panel.className = "claudian-ask-panel"; - panel.setAttribute("tabindex", "0"); - panel.setAttribute("role", "dialog"); - panel.setAttribute("aria-label", "Claude is asking a question"); - panel.addEventListener("keydown", this.handleKeyDown.bind(this)); - this.tabsEl = this.createTabs(panel); - this.questionContentEl = document.createElement("div"); - this.questionContentEl.className = "claudian-ask-panel-content"; - panel.appendChild(this.questionContentEl); - const hintEl = document.createElement("div"); - hintEl.className = "claudian-ask-panel-hint"; - hintEl.textContent = "Enter to select \xB7 Tab/Arrow keys to navigate \xB7 Esc to cancel"; - panel.appendChild(hintEl); - this.renderCurrentContent(); - return panel; - } - /** Create tab navigation row. */ - createTabs(parent) { - const tabsContainer = document.createElement("div"); - tabsContainer.className = "claudian-ask-panel-tabs"; - const leftArrow = document.createElement("span"); - leftArrow.className = "claudian-ask-panel-nav"; - leftArrow.textContent = "\u2190"; - leftArrow.addEventListener("click", () => this.navigateTab(-1)); - tabsContainer.appendChild(leftArrow); - this.questions.forEach((q, index) => { - const tab = document.createElement("button"); - tab.className = "claudian-ask-panel-tab"; - tab.setAttribute("data-tab-index", String(index)); - const check2 = document.createElement("span"); - check2.className = "claudian-ask-panel-tab-check"; - check2.textContent = "\u25CB"; - tab.appendChild(check2); - const label = document.createTextNode(` ${q.header || `Q${index + 1}`}`); - tab.appendChild(label); - if (index === 0) { - tab.classList.add("active"); - } - tab.addEventListener("click", () => this.switchToTab(index)); - tabsContainer.appendChild(tab); - }); - const submitTab = document.createElement("button"); - submitTab.className = "claudian-ask-panel-tab claudian-ask-panel-submit-tab"; - submitTab.setAttribute("data-tab-index", String(this.questions.length)); - const submitCheck = document.createElement("span"); - submitCheck.className = "claudian-ask-panel-tab-check"; - submitCheck.textContent = "\u2713"; - submitTab.appendChild(submitCheck); - const submitLabel = document.createTextNode(" Submit"); - submitTab.appendChild(submitLabel); - submitTab.addEventListener("click", () => this.switchToTab(this.questions.length)); - tabsContainer.appendChild(submitTab); - const rightArrow = document.createElement("span"); - rightArrow.className = "claudian-ask-panel-nav"; - rightArrow.textContent = "\u2192"; - rightArrow.addEventListener("click", () => this.navigateTab(1)); - tabsContainer.appendChild(rightArrow); - parent.appendChild(tabsContainer); - return tabsContainer; - } - /** Navigate tabs by direction. */ - navigateTab(direction) { - const newIndex = this.currentTabIndex + direction; - if (newIndex >= 0 && newIndex <= this.questions.length) { - this.switchToTab(newIndex); - } - } - /** Check if currently on Submit tab. */ - isOnSubmitTab() { - return this.currentTabIndex === this.questions.length; - } - /** Switch to a specific tab/question. */ - switchToTab(index) { - if (index < 0 || index > this.questions.length) return; - this.currentTabIndex = index; - this.currentOptionIndex = 0; - if (this.tabsEl) { - const tabs = this.tabsEl.querySelectorAll(".claudian-ask-panel-tab"); - tabs.forEach((tab, i) => { - tab.classList.toggle("active", i === index); - }); - } - this.renderCurrentContent(); - } - /** Render current tab content. */ - renderCurrentContent() { - if (this.isOnSubmitTab()) { - this.renderSubmitReview(); - } else { - this.renderCurrentQuestion(); - } - } - /** Render the current question. */ - renderCurrentQuestion() { - if (!this.questionContentEl) return; - this.questionContentEl.innerHTML = ""; - const question = this.questions[this.currentTabIndex]; - if (!question) return; - const questionTextEl = document.createElement("div"); - questionTextEl.className = "claudian-ask-panel-question"; - questionTextEl.textContent = question.question; - this.questionContentEl.appendChild(questionTextEl); - const optionsEl = document.createElement("div"); - optionsEl.className = "claudian-ask-panel-options"; - optionsEl.setAttribute("role", question.multiSelect ? "group" : "radiogroup"); - question.options.forEach((option, index) => { - const optionEl = this.createOptionElement(question, option, index); - optionsEl.appendChild(optionEl); - }); - const otherEl = this.createOtherOption(question); - optionsEl.appendChild(otherEl); - this.questionContentEl.appendChild(optionsEl); - this.updateOptionFocus(); - } - /** Render the Submit review panel. */ - renderSubmitReview() { - if (!this.questionContentEl) return; - this.questionContentEl.innerHTML = ""; - const titleEl = document.createElement("div"); - titleEl.className = "claudian-ask-panel-question"; - titleEl.textContent = "Review your answers"; - this.questionContentEl.appendChild(titleEl); - const summaryEl = document.createElement("div"); - summaryEl.className = "claudian-ask-panel-summary"; - this.questions.forEach((q) => { - const itemEl = document.createElement("div"); - itemEl.className = "claudian-ask-panel-summary-item"; - const questionEl = document.createElement("div"); - questionEl.className = "claudian-ask-panel-summary-question"; - questionEl.textContent = `\u25CF ${q.question}`; - itemEl.appendChild(questionEl); - const answerEl = document.createElement("div"); - answerEl.className = "claudian-ask-panel-summary-answer"; - const answer = this.answers.get(q.question); - if (answer) { - const answerText = Array.isArray(answer) ? answer.join(", ") : answer; - answerEl.textContent = ` \u2192 ${answerText}`; - } else { - answerEl.textContent = " \u2192 (not answered)"; - answerEl.classList.add("unanswered"); - } - itemEl.appendChild(answerEl); - summaryEl.appendChild(itemEl); - }); - this.questionContentEl.appendChild(summaryEl); - const promptEl = document.createElement("div"); - promptEl.className = "claudian-ask-panel-submit-prompt"; - promptEl.textContent = "Ready to submit your answers?"; - this.questionContentEl.appendChild(promptEl); - const optionsEl = document.createElement("div"); - optionsEl.className = "claudian-ask-panel-options"; - const submitOptionEl = this.createSubmitOption("Submit answers", 0, () => this.submit()); - optionsEl.appendChild(submitOptionEl); - const cancelOptionEl = this.createSubmitOption("Cancel", 1, () => this.cancel()); - optionsEl.appendChild(cancelOptionEl); - this.questionContentEl.appendChild(optionsEl); - this.updateSubmitOptionFocus(); - } - /** Create an option for the submit review. */ - createSubmitOption(label, index, onClick) { - const optionEl = document.createElement("div"); - optionEl.className = "claudian-ask-panel-option claudian-ask-panel-submit-option"; - optionEl.setAttribute("data-option-index", String(index)); - const caret = document.createElement("span"); - caret.className = "claudian-ask-panel-caret"; - caret.textContent = " "; - optionEl.appendChild(caret); - const indicator = document.createElement("span"); - indicator.className = "claudian-ask-panel-indicator"; - indicator.textContent = `${index + 1}.`; - optionEl.appendChild(indicator); - const labelEl = document.createElement("span"); - labelEl.className = "claudian-ask-panel-option-label"; - labelEl.textContent = label; - optionEl.appendChild(labelEl); - optionEl.addEventListener("click", () => { - this.currentOptionIndex = index; - this.updateSubmitOptionFocus(); - onClick(); - }); - return optionEl; - } - /** Update focus for submit options. */ - updateSubmitOptionFocus() { - if (!this.questionContentEl) return; - const options = this.questionContentEl.querySelectorAll(".claudian-ask-panel-submit-option"); - options.forEach((opt, i) => { - const caret = opt.querySelector(".claudian-ask-panel-caret"); - const isFocused = i === this.currentOptionIndex; - opt.classList.toggle("focused", isFocused); - if (caret) { - caret.textContent = isFocused ? ">" : " "; - } - }); - } - /** Create an option element. */ - createOptionElement(question, option, index) { - const optionEl = document.createElement("div"); - optionEl.className = "claudian-ask-panel-option"; - optionEl.setAttribute("data-option-index", String(index)); - const caret = document.createElement("span"); - caret.className = "claudian-ask-panel-caret"; - caret.textContent = " "; - optionEl.appendChild(caret); - const indicator = document.createElement("span"); - indicator.className = "claudian-ask-panel-indicator"; - if (question.multiSelect) { - indicator.textContent = `${index + 1}. [ ]`; - } else { - indicator.textContent = `${index + 1}.`; - } - optionEl.appendChild(indicator); - const textContainer = document.createElement("div"); - textContainer.className = "claudian-ask-panel-option-text"; - const labelRowEl = document.createElement("div"); - labelRowEl.className = "claudian-ask-panel-label-row"; - const labelEl = document.createElement("span"); - labelEl.className = "claudian-ask-panel-option-label"; - labelEl.textContent = option.label; - labelRowEl.appendChild(labelEl); - if (!question.multiSelect) { - const checkmarkEl = document.createElement("span"); - checkmarkEl.className = "claudian-ask-panel-checkmark"; - checkmarkEl.textContent = ""; - labelRowEl.appendChild(checkmarkEl); - } - textContainer.appendChild(labelRowEl); - if (option.description) { - const descEl = document.createElement("div"); - descEl.className = "claudian-ask-panel-option-desc"; - descEl.textContent = option.description; - textContainer.appendChild(descEl); - } - optionEl.appendChild(textContainer); - optionEl.addEventListener("click", () => { - this.currentOptionIndex = index; - this.selectOption(index); - }); - return optionEl; - } - /** Create the "Other" option with text input. */ - createOtherOption(question) { - const otherIndex = question.options.length; - const otherEl = document.createElement("div"); - otherEl.className = "claudian-ask-panel-option claudian-ask-panel-other"; - otherEl.setAttribute("data-option-index", String(otherIndex)); - const caret = document.createElement("span"); - caret.className = "claudian-ask-panel-caret"; - caret.textContent = " "; - otherEl.appendChild(caret); - const indicator = document.createElement("span"); - indicator.className = "claudian-ask-panel-indicator"; - if (question.multiSelect) { - indicator.textContent = `${otherIndex + 1}. [ ]`; - } else { - indicator.textContent = `${otherIndex + 1}.`; - } - otherEl.appendChild(indicator); - this.otherInputEl = document.createElement("input"); - this.otherInputEl.type = "text"; - this.otherInputEl.className = "claudian-ask-panel-other-input"; - this.otherInputEl.placeholder = "Type something."; - this.otherInputEl.addEventListener("keydown", (e) => { - if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") { - e.stopPropagation(); - return; - } - if (e.key === "Enter") { - e.preventDefault(); - e.stopPropagation(); - if (this.otherInputEl && this.otherInputEl.value.trim()) { - this.selectOther(this.otherInputEl.value.trim()); - } - } - }); - this.otherInputEl.addEventListener("focus", () => { - this.currentOptionIndex = otherIndex; - this.updateOptionFocus(); - }); - otherEl.appendChild(this.otherInputEl); - otherEl.addEventListener("click", (e) => { - var _a; - if (e.target !== this.otherInputEl) { - this.currentOptionIndex = otherIndex; - this.updateOptionFocus(); - (_a = this.otherInputEl) == null ? void 0 : _a.focus(); - } - }); - return otherEl; - } - /** Handle keyboard navigation. */ - handleKeyDown(e) { - var _a; - if (this.isDestroyed) return; - if (this.isOnSubmitTab()) { - this.handleSubmitTabKeyDown(e); - return; - } - const question = this.questions[this.currentTabIndex]; - if (!question) return; - const totalOptions = question.options.length + 1; - switch (e.key) { - case "ArrowUp": - e.preventDefault(); - this.currentOptionIndex = (this.currentOptionIndex - 1 + totalOptions) % totalOptions; - this.updateOptionFocus(); - break; - case "ArrowDown": - e.preventDefault(); - this.currentOptionIndex = (this.currentOptionIndex + 1) % totalOptions; - this.updateOptionFocus(); - break; - case "ArrowLeft": - e.preventDefault(); - this.navigateTab(-1); - break; - case "ArrowRight": - e.preventDefault(); - this.navigateTab(1); - break; - case "Tab": - e.preventDefault(); - if (e.shiftKey) { - this.navigateTab(-1); - } else { - this.navigateTab(1); - } - break; - case "Enter": - if (document.activeElement === this.otherInputEl) return; - e.preventDefault(); - if (this.currentOptionIndex < question.options.length) { - this.selectOption(this.currentOptionIndex); - } else if (this.otherInputEl && this.otherInputEl.value.trim()) { - this.selectOther(this.otherInputEl.value.trim()); - } - break; - case "Escape": - e.preventDefault(); - this.cancel(); - break; - // Number keys 1-9 for quick selection - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - if (document.activeElement !== this.otherInputEl) { - const num = parseInt(e.key, 10) - 1; - if (num < question.options.length) { - e.preventDefault(); - this.currentOptionIndex = num; - this.selectOption(num); - } else if (num === question.options.length) { - e.preventDefault(); - this.currentOptionIndex = num; - this.updateOptionFocus(); - (_a = this.otherInputEl) == null ? void 0 : _a.focus(); - } - } - break; - } - } - /** Handle keyboard navigation for Submit tab. */ - handleSubmitTabKeyDown(e) { - const totalOptions = 2; - switch (e.key) { - case "ArrowUp": - e.preventDefault(); - this.currentOptionIndex = (this.currentOptionIndex - 1 + totalOptions) % totalOptions; - this.updateSubmitOptionFocus(); - break; - case "ArrowDown": - e.preventDefault(); - this.currentOptionIndex = (this.currentOptionIndex + 1) % totalOptions; - this.updateSubmitOptionFocus(); - break; - case "ArrowLeft": - e.preventDefault(); - this.navigateTab(-1); - break; - case "ArrowRight": - break; - case "Tab": - e.preventDefault(); - if (e.shiftKey) { - this.navigateTab(-1); - } - break; - case "Enter": - e.preventDefault(); - if (this.currentOptionIndex === 0) { - this.submit(); - } else { - this.cancel(); - } - break; - case "Escape": - e.preventDefault(); - this.cancel(); - break; - case "1": - e.preventDefault(); - this.currentOptionIndex = 0; - this.updateSubmitOptionFocus(); - this.submit(); - break; - case "2": - e.preventDefault(); - this.currentOptionIndex = 1; - this.updateSubmitOptionFocus(); - this.cancel(); - break; - } - } - attachDocumentHandler() { - this.detachDocumentHandler(); - this.documentKeydownHandler = (e) => { - if (this.isDestroyed) return; - if (!this.isNavigationKey(e)) return; - e.preventDefault(); - e.stopPropagation(); - this.handleKeyDown(e); - }; - document.addEventListener("keydown", this.documentKeydownHandler, true); - } - detachDocumentHandler() { - if (this.documentKeydownHandler) { - document.removeEventListener("keydown", this.documentKeydownHandler, true); - this.documentKeydownHandler = null; - } - } - isNavigationKey(e) { - return e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Tab"; - } - /** Update visual focus indicator. */ - updateOptionFocus() { - var _a; - if (!this.questionContentEl) return; - const question = this.questions[this.currentTabIndex]; - if (!question) return; - const questionKey = question.question; - const answer = this.answers.get(questionKey); - const answerArray = Array.isArray(answer) ? answer : answer ? [answer] : []; - const options = this.questionContentEl.querySelectorAll(".claudian-ask-panel-option"); - options.forEach((opt, i) => { - const caret = opt.querySelector(".claudian-ask-panel-caret"); - const indicator = opt.querySelector(".claudian-ask-panel-indicator"); - const isFocused = i === this.currentOptionIndex; - let isSelected = false; - if (i < question.options.length) { - const optionLabel = question.options[i].label; - isSelected = answerArray.includes(optionLabel); - } else { - isSelected = answerArray.some((v) => typeof v === "string" && !question.options.some((o) => o.label === v)); - } - opt.classList.toggle("focused", isFocused); - opt.classList.toggle("selected", isSelected); - if (caret) { - caret.textContent = isFocused ? ">" : " "; - } - if (indicator) { - if (question.multiSelect) { - const checkbox = isSelected ? "[\u2713]" : "[ ]"; - indicator.textContent = `${i + 1}. ${checkbox}`; - } else { - indicator.textContent = `${i + 1}.`; - } - } - if (!question.multiSelect) { - const checkmark = opt.querySelector(".claudian-ask-panel-checkmark"); - if (checkmark) { - checkmark.textContent = isSelected ? " \u2713" : ""; - } - } - }); - if (this.currentOptionIndex === question.options.length) { - (_a = this.otherInputEl) == null ? void 0 : _a.focus(); - } else { - if (document.activeElement === this.otherInputEl) { - this.panelEl.focus(); - } - } - } - /** Select an option. */ - selectOption(optionIndex) { - const question = this.questions[this.currentTabIndex]; - if (!question || optionIndex >= question.options.length) return; - const option = question.options[optionIndex]; - const questionKey = question.question; - if (question.multiSelect) { - const current = this.answers.get(questionKey); - const currentArray = Array.isArray(current) ? current : []; - if (currentArray.includes(option.label)) { - const filtered = currentArray.filter((v) => v !== option.label); - if (filtered.length > 0) { - this.answers.set(questionKey, filtered); - } else { - this.answers.delete(questionKey); - } - } else { - this.answers.set(questionKey, [...currentArray, option.label]); - } - this.updateSelectionUI(); - } else { - this.answers.set(questionKey, option.label); - this.updateSelectionUI(); - this.autoAdvance(); - } - } - /** Select "Other" with custom text. */ - selectOther(text) { - const question = this.questions[this.currentTabIndex]; - if (!question) return; - const questionKey = question.question; - if (question.multiSelect) { - const current = this.answers.get(questionKey); - const currentArray = Array.isArray(current) ? current : []; - const filtered = currentArray.filter((v) => question.options.some((o) => o.label === v)); - this.answers.set(questionKey, [...filtered, text]); - this.updateSelectionUI(); - } else { - this.answers.set(questionKey, text); - this.updateSelectionUI(); - this.autoAdvance(); - } - } - /** Update selection UI indicators. */ - updateSelectionUI() { - this.updateOptionFocus(); - this.updateTabIndicators(); - } - /** Update tab checkbox indicators. */ - updateTabIndicators() { - if (!this.tabsEl) return; - const tabs = this.tabsEl.querySelectorAll(".claudian-ask-panel-tab"); - this.questions.forEach((q, i) => { - const hasAnswer = this.answers.has(q.question); - const tab = tabs[i]; - if (tab) { - tab.classList.toggle("answered", hasAnswer); - const check2 = tab.querySelector(".claudian-ask-panel-tab-check"); - if (check2) { - check2.textContent = hasAnswer ? "\u25CF" : "\u25CB"; - } - } - }); - } - /** Auto-advance to next question or Submit tab. */ - autoAdvance() { - this.switchToTab(this.currentTabIndex + 1); - } - /** Submit all answers. */ - submit() { - if (this.isDestroyed) return; - const answersRecord = {}; - this.answers.forEach((value, key) => { - answersRecord[key] = value; - }); - this.destroy(); - this.onSubmit(answersRecord); - } - /** Cancel and close panel. */ - cancel() { - if (this.isDestroyed) return; - this.destroy(); - this.onCancel(); - } - /** Clean up and remove panel, restore input area. */ - destroy() { - if (this.isDestroyed) return; - this.isDestroyed = true; - this.detachDocumentHandler(); - this.panelEl.remove(); - if (this.inputWrapper) { - this.inputWrapper.style.display = ""; - } - } -}; -function showAskUserQuestionPanel(app, containerEl, input) { - return new Promise((resolve7) => { - new AskUserQuestionPanel(app, { - containerEl, - input, - onSubmit: (answers) => resolve7(answers), - onCancel: () => resolve7(null) - }); - }); -} - -// src/ui/components/FileContext.ts -var import_obsidian4 = require("obsidian"); -var path9 = __toESM(require("path")); - -// src/ui/components/file-context/mention/MentionDropdownController.ts -var import_obsidian2 = require("obsidian"); +var import_obsidian19 = require("obsidian"); // src/features/chat/constants.ts -var MCP_ICON_SVG = `MCP`; var LOGO_SVG = { viewBox: "0 -.01 39.5 39.53", width: "18", @@ -26511,6 +38973,30 @@ var LOGO_SVG = { path: "m7.75 26.27 7.77-4.36.13-.38-.13-.21h-.38l-1.3-.08-4.44-.12-3.85-.16-3.73-.2-.94-.2-.88-1.16.09-.58.79-.53 1.13.1 2.5.17 3.75.26 2.72.16 4.03.42h.64l.09-.26-.22-.16-.17-.16-3.88-2.63-4.2-2.78-2.2-1.6-1.19-.81-.6-.76-.26-1.66 1.08-1.19 1.45.1.37.1 1.47 1.13 3.14 2.43 4.1 3.02.6.5.24-.17.03-.12-.27-.45-2.23-4.03-2.38-4.1-1.06-1.7-.28-1.02c-.1-.42-.17-.77-.17-1.2l1.23-1.67.68-.22 1.64.22.69.6 1.02 2.33 1.65 3.67 2.56 4.99.75 1.48.4 1.37.15.42h.26v-.24l.21-2.81.39-3.45.38-4.44.13-1.25.62-1.5 1.23-.81.96.46.79 1.13-.11.73-.47 3.05-.92 4.78-.6 3.2h.35l.4-.4 1.62-2.15 2.72-3.4 1.2-1.35 1.4-1.49.9-.71h1.7l1.25 1.86-.56 1.92-1.75 2.22-1.45 1.88-2.08 2.8-1.3 2.24.12.18.31-.03 4.7-1 2.54-.46 3.03-.52 1.37.64.15.65-.54 1.33-3.24.8-3.8.76-5.66 1.34-.07.05.08.1 2.55.24 1.09.06h2.67l4.97.37 1.3.86.78 1.05-.13.8-2 1.02-2.7-.64-6.3-1.5-2.16-.54h-.3v.18l1.8 1.76 3.3 2.98 4.13 3.84.21.95-.53.75-.56-.08-3.63-2.73-1.4-1.23-3.17-2.67h-.21v.28l.73 1.07 3.86 5.8.2 1.78-.28.58-1 .35-1.1-.2-2.26-3.17-2.33-3.57-1.88-3.2-.23.13-1.11 11.95-.52.61-1.2.46-1-.76-.53-1.23.53-2.43.64-3.17.52-2.52.47-3.13.28-1.04-.02-.07-.23.03-2.36 3.24-3.59 4.85-2.84 3.04-.68.27-1.18-.61.11-1.09.66-.97 3.93-5 2.37-3.1 1.53-1.79-.01-.26h-.09l-10.44 6.78-1.86.24-.8-.75.1-1.23.38-.4 3.14-2.16z", fill: "#d97757" }; +var COMPLETION_FLAVOR_WORDS = [ + "Baked", + "Cooked", + "Crunched", + "Brewed", + "Crafted", + "Forged", + "Conjured", + "Whipped up", + "Stirred", + "Simmered", + "Toasted", + "Saut\xE9ed", + "Finagled", + "Marinated", + "Distilled", + "Fermented", + "Percolated", + "Steeped", + "Roasted", + "Cured", + "Smoked", + "Cogitated" +]; var FLAVOR_TEXTS = [ // Classic "Thinking...", @@ -26598,18 +39084,17024 @@ var FLAVOR_TEXTS = [ "Give me a moment..." ]; -// src/utils/contextPath.ts -function normalizePathForComparison2(p) { - return normalizePathForComparison(p); +// node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs +var import_path2 = require("path"); +var import_url = require("url"); +var import_events = require("events"); +var import_child_process = require("child_process"); +var import_readline = require("readline"); +var f = __toESM(require("fs"), 1); +var import_promises = require("fs/promises"); +var import_path3 = require("path"); +var import_os = require("os"); +var import_path4 = require("path"); +var import_process = require("process"); +var import_fs = require("fs"); +var import_crypto = require("crypto"); +var import_crypto2 = require("crypto"); +var import_fs2 = require("fs"); +var import_path5 = require("path"); +var import_crypto3 = require("crypto"); +var import_path6 = require("path"); +var import_url2 = require("url"); +var import_meta = {}; +var XK = Object.create; +var { getPrototypeOf: QK, defineProperty: Y8, getOwnPropertyNames: $K } = Object; +var YK = Object.prototype.hasOwnProperty; +var K7 = (X, Q, $) => { + $ = X != null ? XK(QK(X)) : {}; + let Y = Q || !X || !X.__esModule ? Y8($, "default", { value: X, enumerable: true }) : $; + for (let W of $K(X)) if (!YK.call(Y, W)) Y8(Y, W, { get: () => X[W], enumerable: true }); + return Y; +}; +var P = (X, Q) => () => (Q || X((Q = { exports: {} }).exports, Q), Q.exports); +var U7 = (X, Q) => { + for (var $ in Q) Y8(X, $, { get: Q[$], enumerable: true, configurable: true, set: (Y) => Q[$] = () => Y }); +}; +var fX = P((YG) => { + Object.defineProperty(YG, "__esModule", { value: true }); + YG.regexpCode = YG.getEsmExportName = YG.getProperty = YG.safeStringify = YG.stringify = YG.strConcat = YG.addCodeArg = YG.str = YG._ = YG.nil = YG._Code = YG.Name = YG.IDENTIFIER = YG._CodeOrName = void 0; + class D9 { + } + YG._CodeOrName = D9; + YG.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + class h6 extends D9 { + constructor(X) { + super(); + if (!YG.IDENTIFIER.test(X)) throw Error("CodeGen: name must be a valid identifier"); + this.str = X; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + } + YG.Name = h6; + class s0 extends D9 { + constructor(X) { + super(); + this._items = typeof X === "string" ? [X] : X; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + let X = this._items[0]; + return X === "" || X === '""'; + } + get str() { + var X; + return (X = this._str) !== null && X !== void 0 ? X : this._str = this._items.reduce((Q, $) => `${Q}${$}`, ""); + } + get names() { + var X; + return (X = this._names) !== null && X !== void 0 ? X : this._names = this._items.reduce((Q, $) => { + if ($ instanceof h6) Q[$.str] = (Q[$.str] || 0) + 1; + return Q; + }, {}); + } + } + YG._Code = s0; + YG.nil = new s0(""); + function QG(X, ...Q) { + let $ = [X[0]], Y = 0; + while (Y < Q.length) s$($, Q[Y]), $.push(X[++Y]); + return new s0($); + } + YG._ = QG; + var a$ = new s0("+"); + function $G(X, ...Q) { + let $ = [hX(X[0])], Y = 0; + while (Y < Q.length) $.push(a$), s$($, Q[Y]), $.push(a$, hX(X[++Y])); + return BN($), new s0($); + } + YG.str = $G; + function s$(X, Q) { + if (Q instanceof s0) X.push(...Q._items); + else if (Q instanceof h6) X.push(Q); + else X.push(UN(Q)); + } + YG.addCodeArg = s$; + function BN(X) { + let Q = 1; + while (Q < X.length - 1) { + if (X[Q] === a$) { + let $ = zN(X[Q - 1], X[Q + 1]); + if ($ !== void 0) { + X.splice(Q - 1, 3, $); + continue; + } + X[Q++] = "+"; + } + Q++; + } + } + function zN(X, Q) { + if (Q === '""') return X; + if (X === '""') return Q; + if (typeof X == "string") { + if (Q instanceof h6 || X[X.length - 1] !== '"') return; + if (typeof Q != "string") return `${X.slice(0, -1)}${Q}"`; + if (Q[0] === '"') return X.slice(0, -1) + Q.slice(1); + return; + } + if (typeof Q == "string" && Q[0] === '"' && !(X instanceof h6)) return `"${X}${Q.slice(1)}`; + return; + } + function KN(X, Q) { + return Q.emptyStr() ? X : X.emptyStr() ? Q : $G`${X}${Q}`; + } + YG.strConcat = KN; + function UN(X) { + return typeof X == "number" || typeof X == "boolean" || X === null ? X : hX(Array.isArray(X) ? X.join(",") : X); + } + function VN(X) { + return new s0(hX(X)); + } + YG.stringify = VN; + function hX(X) { + return JSON.stringify(X).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + YG.safeStringify = hX; + function LN(X) { + return typeof X == "string" && YG.IDENTIFIER.test(X) ? new s0(`.${X}`) : QG`[${X}]`; + } + YG.getProperty = LN; + function qN(X) { + if (typeof X == "string" && YG.IDENTIFIER.test(X)) return new s0(`${X}`); + throw Error(`CodeGen: invalid export name: ${X}, use explicit $id name mapping`); + } + YG.getEsmExportName = qN; + function FN(X) { + return new s0(X.toString()); + } + YG.regexpCode = FN; +}); +var $Y = P((HG) => { + Object.defineProperty(HG, "__esModule", { value: true }); + HG.ValueScope = HG.ValueScopeName = HG.Scope = HG.varKinds = HG.UsedValueState = void 0; + var x0 = fX(); + class JG extends Error { + constructor(X) { + super(`CodeGen: "code" for ${X} not defined`); + this.value = X.value; + } + } + var w9; + (function(X) { + X[X.Started = 0] = "Started", X[X.Completed = 1] = "Completed"; + })(w9 || (HG.UsedValueState = w9 = {})); + HG.varKinds = { const: new x0.Name("const"), let: new x0.Name("let"), var: new x0.Name("var") }; + class XY { + constructor({ prefixes: X, parent: Q } = {}) { + this._names = {}, this._prefixes = X, this._parent = Q; + } + toName(X) { + return X instanceof x0.Name ? X : this.name(X); + } + name(X) { + return new x0.Name(this._newName(X)); + } + _newName(X) { + let Q = this._names[X] || this._nameGroup(X); + return `${X}${Q.index++}`; + } + _nameGroup(X) { + var Q, $; + if ((($ = (Q = this._parent) === null || Q === void 0 ? void 0 : Q._prefixes) === null || $ === void 0 ? void 0 : $.has(X)) || this._prefixes && !this._prefixes.has(X)) throw Error(`CodeGen: prefix "${X}" is not allowed in this scope`); + return this._names[X] = { prefix: X, index: 0 }; + } + } + HG.Scope = XY; + class QY extends x0.Name { + constructor(X, Q) { + super(Q); + this.prefix = X; + } + setValue(X, { property: Q, itemIndex: $ }) { + this.value = X, this.scopePath = x0._`.${new x0.Name(Q)}[${$}]`; + } + } + HG.ValueScopeName = QY; + var SN = x0._`\n`; + class GG extends XY { + constructor(X) { + super(X); + this._values = {}, this._scope = X.scope, this.opts = { ...X, _n: X.lines ? SN : x0.nil }; + } + get() { + return this._scope; + } + name(X) { + return new QY(X, this._newName(X)); + } + value(X, Q) { + var $; + if (Q.ref === void 0) throw Error("CodeGen: ref must be passed in value"); + let Y = this.toName(X), { prefix: W } = Y, J = ($ = Q.key) !== null && $ !== void 0 ? $ : Q.ref, G = this._values[W]; + if (G) { + let z2 = G.get(J); + if (z2) return z2; + } else G = this._values[W] = /* @__PURE__ */ new Map(); + G.set(J, Y); + let H = this._scope[W] || (this._scope[W] = []), B = H.length; + return H[B] = Q.ref, Y.setValue(Q, { property: W, itemIndex: B }), Y; + } + getValue(X, Q) { + let $ = this._values[X]; + if (!$) return; + return $.get(Q); + } + scopeRefs(X, Q = this._values) { + return this._reduceValues(Q, ($) => { + if ($.scopePath === void 0) throw Error(`CodeGen: name "${$}" has no value`); + return x0._`${X}${$.scopePath}`; + }); + } + scopeCode(X = this._values, Q, $) { + return this._reduceValues(X, (Y) => { + if (Y.value === void 0) throw Error(`CodeGen: name "${Y}" has no value`); + return Y.value.code; + }, Q, $); + } + _reduceValues(X, Q, $ = {}, Y) { + let W = x0.nil; + for (let J in X) { + let G = X[J]; + if (!G) continue; + let H = $[J] = $[J] || /* @__PURE__ */ new Map(); + G.forEach((B) => { + if (H.has(B)) return; + H.set(B, w9.Started); + let z2 = Q(B); + if (z2) { + let K = this.opts.es5 ? HG.varKinds.var : HG.varKinds.const; + W = x0._`${W}${K} ${B} = ${z2};${this.opts._n}`; + } else if (z2 = Y === null || Y === void 0 ? void 0 : Y(B)) W = x0._`${W}${z2}${this.opts._n}`; + else throw new JG(B); + H.set(B, w9.Completed); + }); + } + return W; + } + } + HG.ValueScope = GG; +}); +var c = P((y0) => { + Object.defineProperty(y0, "__esModule", { value: true }); + y0.or = y0.and = y0.not = y0.CodeGen = y0.operators = y0.varKinds = y0.ValueScopeName = y0.ValueScope = y0.Scope = y0.Name = y0.regexpCode = y0.stringify = y0.getProperty = y0.nil = y0.strConcat = y0.str = y0._ = void 0; + var t2 = fX(), e0 = $Y(), u1 = fX(); + Object.defineProperty(y0, "_", { enumerable: true, get: function() { + return u1._; + } }); + Object.defineProperty(y0, "str", { enumerable: true, get: function() { + return u1.str; + } }); + Object.defineProperty(y0, "strConcat", { enumerable: true, get: function() { + return u1.strConcat; + } }); + Object.defineProperty(y0, "nil", { enumerable: true, get: function() { + return u1.nil; + } }); + Object.defineProperty(y0, "getProperty", { enumerable: true, get: function() { + return u1.getProperty; + } }); + Object.defineProperty(y0, "stringify", { enumerable: true, get: function() { + return u1.stringify; + } }); + Object.defineProperty(y0, "regexpCode", { enumerable: true, get: function() { + return u1.regexpCode; + } }); + Object.defineProperty(y0, "Name", { enumerable: true, get: function() { + return u1.Name; + } }); + var b9 = $Y(); + Object.defineProperty(y0, "Scope", { enumerable: true, get: function() { + return b9.Scope; + } }); + Object.defineProperty(y0, "ValueScope", { enumerable: true, get: function() { + return b9.ValueScope; + } }); + Object.defineProperty(y0, "ValueScopeName", { enumerable: true, get: function() { + return b9.ValueScopeName; + } }); + Object.defineProperty(y0, "varKinds", { enumerable: true, get: function() { + return b9.varKinds; + } }); + y0.operators = { GT: new t2._Code(">"), GTE: new t2._Code(">="), LT: new t2._Code("<"), LTE: new t2._Code("<="), EQ: new t2._Code("==="), NEQ: new t2._Code("!=="), NOT: new t2._Code("!"), OR: new t2._Code("||"), AND: new t2._Code("&&"), ADD: new t2._Code("+") }; + class l1 { + optimizeNodes() { + return this; + } + optimizeNames(X, Q) { + return this; + } + } + class zG extends l1 { + constructor(X, Q, $) { + super(); + this.varKind = X, this.name = Q, this.rhs = $; + } + render({ es5: X, _n: Q }) { + let $ = X ? e0.varKinds.var : this.varKind, Y = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${$} ${this.name}${Y};` + Q; + } + optimizeNames(X, Q) { + if (!X[this.name.str]) return; + if (this.rhs) this.rhs = u6(this.rhs, X, Q); + return this; + } + get names() { + return this.rhs instanceof t2._CodeOrName ? this.rhs.names : {}; + } + } + class JY extends l1 { + constructor(X, Q, $) { + super(); + this.lhs = X, this.rhs = Q, this.sideEffects = $; + } + render({ _n: X }) { + return `${this.lhs} = ${this.rhs};` + X; + } + optimizeNames(X, Q) { + if (this.lhs instanceof t2.Name && !X[this.lhs.str] && !this.sideEffects) return; + return this.rhs = u6(this.rhs, X, Q), this; + } + get names() { + let X = this.lhs instanceof t2.Name ? {} : { ...this.lhs.names }; + return I9(X, this.rhs); + } + } + class KG extends JY { + constructor(X, Q, $, Y) { + super(X, $, Y); + this.op = Q; + } + render({ _n: X }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + X; + } + } + class UG extends l1 { + constructor(X) { + super(); + this.label = X, this.names = {}; + } + render({ _n: X }) { + return `${this.label}:` + X; + } + } + class VG extends l1 { + constructor(X) { + super(); + this.label = X, this.names = {}; + } + render({ _n: X }) { + return `break${this.label ? ` ${this.label}` : ""};` + X; + } + } + class LG extends l1 { + constructor(X) { + super(); + this.error = X; + } + render({ _n: X }) { + return `throw ${this.error};` + X; + } + get names() { + return this.error.names; + } + } + class qG extends l1 { + constructor(X) { + super(); + this.code = X; + } + render({ _n: X }) { + return `${this.code};` + X; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(X, Q) { + return this.code = u6(this.code, X, Q), this; + } + get names() { + return this.code instanceof t2._CodeOrName ? this.code.names : {}; + } + } + class P9 extends l1 { + constructor(X = []) { + super(); + this.nodes = X; + } + render(X) { + return this.nodes.reduce((Q, $) => Q + $.render(X), ""); + } + optimizeNodes() { + let { nodes: X } = this, Q = X.length; + while (Q--) { + let $ = X[Q].optimizeNodes(); + if (Array.isArray($)) X.splice(Q, 1, ...$); + else if ($) X[Q] = $; + else X.splice(Q, 1); + } + return X.length > 0 ? this : void 0; + } + optimizeNames(X, Q) { + let { nodes: $ } = this, Y = $.length; + while (Y--) { + let W = $[Y]; + if (W.optimizeNames(X, Q)) continue; + vN(X, W.names), $.splice(Y, 1); + } + return $.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((X, Q) => J6(X, Q.names), {}); + } + } + class m1 extends P9 { + render(X) { + return "{" + X._n + super.render(X) + "}" + X._n; + } + } + class FG extends P9 { + } + class uX extends m1 { + } + uX.kind = "else"; + class j1 extends m1 { + constructor(X, Q) { + super(Q); + this.condition = X; + } + render(X) { + let Q = `if(${this.condition})` + super.render(X); + if (this.else) Q += "else " + this.else.render(X); + return Q; + } + optimizeNodes() { + super.optimizeNodes(); + let X = this.condition; + if (X === true) return this.nodes; + let Q = this.else; + if (Q) { + let $ = Q.optimizeNodes(); + Q = this.else = Array.isArray($) ? new uX($) : $; + } + if (Q) { + if (X === false) return Q instanceof j1 ? Q : Q.nodes; + if (this.nodes.length) return this; + return new j1(wG(X), Q instanceof j1 ? [Q] : Q.nodes); + } + if (X === false || !this.nodes.length) return; + return this; + } + optimizeNames(X, Q) { + var $; + if (this.else = ($ = this.else) === null || $ === void 0 ? void 0 : $.optimizeNames(X, Q), !(super.optimizeNames(X, Q) || this.else)) return; + return this.condition = u6(this.condition, X, Q), this; + } + get names() { + let X = super.names; + if (I9(X, this.condition), this.else) J6(X, this.else.names); + return X; + } + } + j1.kind = "if"; + class f6 extends m1 { + } + f6.kind = "for"; + class NG extends f6 { + constructor(X) { + super(); + this.iteration = X; + } + render(X) { + return `for(${this.iteration})` + super.render(X); + } + optimizeNames(X, Q) { + if (!super.optimizeNames(X, Q)) return; + return this.iteration = u6(this.iteration, X, Q), this; + } + get names() { + return J6(super.names, this.iteration.names); + } + } + class OG extends f6 { + constructor(X, Q, $, Y) { + super(); + this.varKind = X, this.name = Q, this.from = $, this.to = Y; + } + render(X) { + let Q = X.es5 ? e0.varKinds.var : this.varKind, { name: $, from: Y, to: W } = this; + return `for(${Q} ${$}=${Y}; ${$}<${W}; ${$}++)` + super.render(X); + } + get names() { + let X = I9(super.names, this.from); + return I9(X, this.to); + } + } + class YY extends f6 { + constructor(X, Q, $, Y) { + super(); + this.loop = X, this.varKind = Q, this.name = $, this.iterable = Y; + } + render(X) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(X); + } + optimizeNames(X, Q) { + if (!super.optimizeNames(X, Q)) return; + return this.iterable = u6(this.iterable, X, Q), this; + } + get names() { + return J6(super.names, this.iterable.names); + } + } + class M9 extends m1 { + constructor(X, Q, $) { + super(); + this.name = X, this.args = Q, this.async = $; + } + render(X) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(X); + } + } + M9.kind = "func"; + class j9 extends P9 { + render(X) { + return "return " + super.render(X); + } + } + j9.kind = "return"; + class DG extends m1 { + render(X) { + let Q = "try" + super.render(X); + if (this.catch) Q += this.catch.render(X); + if (this.finally) Q += this.finally.render(X); + return Q; + } + optimizeNodes() { + var X, Q; + return super.optimizeNodes(), (X = this.catch) === null || X === void 0 || X.optimizeNodes(), (Q = this.finally) === null || Q === void 0 || Q.optimizeNodes(), this; + } + optimizeNames(X, Q) { + var $, Y; + return super.optimizeNames(X, Q), ($ = this.catch) === null || $ === void 0 || $.optimizeNames(X, Q), (Y = this.finally) === null || Y === void 0 || Y.optimizeNames(X, Q), this; + } + get names() { + let X = super.names; + if (this.catch) J6(X, this.catch.names); + if (this.finally) J6(X, this.finally.names); + return X; + } + } + class R9 extends m1 { + constructor(X) { + super(); + this.error = X; + } + render(X) { + return `catch(${this.error})` + super.render(X); + } + } + R9.kind = "catch"; + class E9 extends m1 { + render(X) { + return "finally" + super.render(X); + } + } + E9.kind = "finally"; + class AG { + constructor(X, Q = {}) { + this._values = {}, this._blockStarts = [], this._constants = {}, this.opts = { ...Q, _n: Q.lines ? ` +` : "" }, this._extScope = X, this._scope = new e0.Scope({ parent: X }), this._nodes = [new FG()]; + } + toString() { + return this._root.render(this.opts); + } + name(X) { + return this._scope.name(X); + } + scopeName(X) { + return this._extScope.name(X); + } + scopeValue(X, Q) { + let $ = this._extScope.value(X, Q); + return (this._values[$.prefix] || (this._values[$.prefix] = /* @__PURE__ */ new Set())).add($), $; + } + getScopeValue(X, Q) { + return this._extScope.getValue(X, Q); + } + scopeRefs(X) { + return this._extScope.scopeRefs(X, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(X, Q, $, Y) { + let W = this._scope.toName(Q); + if ($ !== void 0 && Y) this._constants[W.str] = $; + return this._leafNode(new zG(X, W, $)), W; + } + const(X, Q, $) { + return this._def(e0.varKinds.const, X, Q, $); + } + let(X, Q, $) { + return this._def(e0.varKinds.let, X, Q, $); + } + var(X, Q, $) { + return this._def(e0.varKinds.var, X, Q, $); + } + assign(X, Q, $) { + return this._leafNode(new JY(X, Q, $)); + } + add(X, Q) { + return this._leafNode(new KG(X, y0.operators.ADD, Q)); + } + code(X) { + if (typeof X == "function") X(); + else if (X !== t2.nil) this._leafNode(new qG(X)); + return this; + } + object(...X) { + let Q = ["{"]; + for (let [$, Y] of X) { + if (Q.length > 1) Q.push(","); + if (Q.push($), $ !== Y || this.opts.es5) Q.push(":"), (0, t2.addCodeArg)(Q, Y); + } + return Q.push("}"), new t2._Code(Q); + } + if(X, Q, $) { + if (this._blockNode(new j1(X)), Q && $) this.code(Q).else().code($).endIf(); + else if (Q) this.code(Q).endIf(); + else if ($) throw Error('CodeGen: "else" body without "then" body'); + return this; + } + elseIf(X) { + return this._elseNode(new j1(X)); + } + else() { + return this._elseNode(new uX()); + } + endIf() { + return this._endBlockNode(j1, uX); + } + _for(X, Q) { + if (this._blockNode(X), Q) this.code(Q).endFor(); + return this; + } + for(X, Q) { + return this._for(new NG(X), Q); + } + forRange(X, Q, $, Y, W = this.opts.es5 ? e0.varKinds.var : e0.varKinds.let) { + let J = this._scope.toName(X); + return this._for(new OG(W, J, Q, $), () => Y(J)); + } + forOf(X, Q, $, Y = e0.varKinds.const) { + let W = this._scope.toName(X); + if (this.opts.es5) { + let J = Q instanceof t2.Name ? Q : this.var("_arr", Q); + return this.forRange("_i", 0, t2._`${J}.length`, (G) => { + this.var(W, t2._`${J}[${G}]`), $(W); + }); + } + return this._for(new YY("of", Y, W, Q), () => $(W)); + } + forIn(X, Q, $, Y = this.opts.es5 ? e0.varKinds.var : e0.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(X, t2._`Object.keys(${Q})`, $); + let W = this._scope.toName(X); + return this._for(new YY("in", Y, W, Q), () => $(W)); + } + endFor() { + return this._endBlockNode(f6); + } + label(X) { + return this._leafNode(new UG(X)); + } + break(X) { + return this._leafNode(new VG(X)); + } + return(X) { + let Q = new j9(); + if (this._blockNode(Q), this.code(X), Q.nodes.length !== 1) throw Error('CodeGen: "return" should have one node'); + return this._endBlockNode(j9); + } + try(X, Q, $) { + if (!Q && !$) throw Error('CodeGen: "try" without "catch" and "finally"'); + let Y = new DG(); + if (this._blockNode(Y), this.code(X), Q) { + let W = this.name("e"); + this._currNode = Y.catch = new R9(W), Q(W); + } + if ($) this._currNode = Y.finally = new E9(), this.code($); + return this._endBlockNode(R9, E9); + } + throw(X) { + return this._leafNode(new LG(X)); + } + block(X, Q) { + if (this._blockStarts.push(this._nodes.length), X) this.code(X).endBlock(Q); + return this; + } + endBlock(X) { + let Q = this._blockStarts.pop(); + if (Q === void 0) throw Error("CodeGen: not in self-balancing block"); + let $ = this._nodes.length - Q; + if ($ < 0 || X !== void 0 && $ !== X) throw Error(`CodeGen: wrong number of nodes: ${$} vs ${X} expected`); + return this._nodes.length = Q, this; + } + func(X, Q = t2.nil, $, Y) { + if (this._blockNode(new M9(X, Q, $)), Y) this.code(Y).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(M9); + } + optimize(X = 1) { + while (X-- > 0) this._root.optimizeNodes(), this._root.optimizeNames(this._root.names, this._constants); + } + _leafNode(X) { + return this._currNode.nodes.push(X), this; + } + _blockNode(X) { + this._currNode.nodes.push(X), this._nodes.push(X); + } + _endBlockNode(X, Q) { + let $ = this._currNode; + if ($ instanceof X || Q && $ instanceof Q) return this._nodes.pop(), this; + throw Error(`CodeGen: not in block "${Q ? `${X.kind}/${Q.kind}` : X.kind}"`); + } + _elseNode(X) { + let Q = this._currNode; + if (!(Q instanceof j1)) throw Error('CodeGen: "else" without "if"'); + return this._currNode = Q.else = X, this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + let X = this._nodes; + return X[X.length - 1]; + } + set _currNode(X) { + let Q = this._nodes; + Q[Q.length - 1] = X; + } + } + y0.CodeGen = AG; + function J6(X, Q) { + for (let $ in Q) X[$] = (X[$] || 0) + (Q[$] || 0); + return X; + } + function I9(X, Q) { + return Q instanceof t2._CodeOrName ? J6(X, Q.names) : X; + } + function u6(X, Q, $) { + if (X instanceof t2.Name) return Y(X); + if (!W(X)) return X; + return new t2._Code(X._items.reduce((J, G) => { + if (G instanceof t2.Name) G = Y(G); + if (G instanceof t2._Code) J.push(...G._items); + else J.push(G); + return J; + }, [])); + function Y(J) { + let G = $[J.str]; + if (G === void 0 || Q[J.str] !== 1) return J; + return delete Q[J.str], G; + } + function W(J) { + return J instanceof t2._Code && J._items.some((G) => G instanceof t2.Name && Q[G.str] === 1 && $[G.str] !== void 0); + } + } + function vN(X, Q) { + for (let $ in Q) X[$] = (X[$] || 0) - (Q[$] || 0); + } + function wG(X) { + return typeof X == "boolean" || typeof X == "number" || X === null ? !X : t2._`!${WY(X)}`; + } + y0.not = wG; + var TN = MG(y0.operators.AND); + function _N(...X) { + return X.reduce(TN); + } + y0.and = _N; + var xN = MG(y0.operators.OR); + function yN(...X) { + return X.reduce(xN); + } + y0.or = yN; + function MG(X) { + return (Q, $) => Q === t2.nil ? $ : $ === t2.nil ? Q : t2._`${WY(Q)} ${X} ${WY($)}`; + } + function WY(X) { + return X instanceof t2.Name ? X : t2._`(${X})`; + } +}); +var e = P((CG) => { + Object.defineProperty(CG, "__esModule", { value: true }); + CG.checkStrictMode = CG.getErrorPath = CG.Type = CG.useFunc = CG.setEvaluated = CG.evaluatedPropsToName = CG.mergeEvaluated = CG.eachItem = CG.unescapeJsonPointer = CG.escapeJsonPointer = CG.escapeFragment = CG.unescapeFragment = CG.schemaRefOrVal = CG.schemaHasRulesButRef = CG.schemaHasRules = CG.checkUnknownRules = CG.alwaysValidSchema = CG.toHash = void 0; + var $0 = c(), uN = fX(); + function lN(X) { + let Q = {}; + for (let $ of X) Q[$] = true; + return Q; + } + CG.toHash = lN; + function mN(X, Q) { + if (typeof Q == "boolean") return Q; + if (Object.keys(Q).length === 0) return true; + return IG(X, Q), !bG(Q, X.self.RULES.all); + } + CG.alwaysValidSchema = mN; + function IG(X, Q = X.schema) { + let { opts: $, self: Y } = X; + if (!$.strictSchema) return; + if (typeof Q === "boolean") return; + let W = Y.RULES.keywords; + for (let J in Q) if (!W[J]) ZG(X, `unknown keyword: "${J}"`); + } + CG.checkUnknownRules = IG; + function bG(X, Q) { + if (typeof X == "boolean") return !X; + for (let $ in X) if (Q[$]) return true; + return false; + } + CG.schemaHasRules = bG; + function cN(X, Q) { + if (typeof X == "boolean") return !X; + for (let $ in X) if ($ !== "$ref" && Q.all[$]) return true; + return false; + } + CG.schemaHasRulesButRef = cN; + function pN({ topSchemaRef: X, schemaPath: Q }, $, Y, W) { + if (!W) { + if (typeof $ == "number" || typeof $ == "boolean") return $; + if (typeof $ == "string") return $0._`${$}`; + } + return $0._`${X}${Q}${(0, $0.getProperty)(Y)}`; + } + CG.schemaRefOrVal = pN; + function dN(X) { + return PG(decodeURIComponent(X)); + } + CG.unescapeFragment = dN; + function iN(X) { + return encodeURIComponent(HY(X)); + } + CG.escapeFragment = iN; + function HY(X) { + if (typeof X == "number") return `${X}`; + return X.replace(/~/g, "~0").replace(/\//g, "~1"); + } + CG.escapeJsonPointer = HY; + function PG(X) { + return X.replace(/~1/g, "/").replace(/~0/g, "~"); + } + CG.unescapeJsonPointer = PG; + function nN(X, Q) { + if (Array.isArray(X)) for (let $ of X) Q($); + else Q(X); + } + CG.eachItem = nN; + function RG({ mergeNames: X, mergeToName: Q, mergeValues: $, resultToName: Y }) { + return (W, J, G, H) => { + let B = G === void 0 ? J : G instanceof $0.Name ? (J instanceof $0.Name ? X(W, J, G) : Q(W, J, G), G) : J instanceof $0.Name ? (Q(W, G, J), J) : $(J, G); + return H === $0.Name && !(B instanceof $0.Name) ? Y(W, B) : B; + }; + } + CG.mergeEvaluated = { props: RG({ mergeNames: (X, Q, $) => X.if($0._`${$} !== true && ${Q} !== undefined`, () => { + X.if($0._`${Q} === true`, () => X.assign($, true), () => X.assign($, $0._`${$} || {}`).code($0._`Object.assign(${$}, ${Q})`)); + }), mergeToName: (X, Q, $) => X.if($0._`${$} !== true`, () => { + if (Q === true) X.assign($, true); + else X.assign($, $0._`${$} || {}`), BY(X, $, Q); + }), mergeValues: (X, Q) => X === true ? true : { ...X, ...Q }, resultToName: SG }), items: RG({ mergeNames: (X, Q, $) => X.if($0._`${$} !== true && ${Q} !== undefined`, () => X.assign($, $0._`${Q} === true ? true : ${$} > ${Q} ? ${$} : ${Q}`)), mergeToName: (X, Q, $) => X.if($0._`${$} !== true`, () => X.assign($, Q === true ? true : $0._`${$} > ${Q} ? ${$} : ${Q}`)), mergeValues: (X, Q) => X === true ? true : Math.max(X, Q), resultToName: (X, Q) => X.var("items", Q) }) }; + function SG(X, Q) { + if (Q === true) return X.var("props", true); + let $ = X.var("props", $0._`{}`); + if (Q !== void 0) BY(X, $, Q); + return $; + } + CG.evaluatedPropsToName = SG; + function BY(X, Q, $) { + Object.keys($).forEach((Y) => X.assign($0._`${Q}${(0, $0.getProperty)(Y)}`, true)); + } + CG.setEvaluated = BY; + var EG = {}; + function rN(X, Q) { + return X.scopeValue("func", { ref: Q, code: EG[Q.code] || (EG[Q.code] = new uN._Code(Q.code)) }); + } + CG.useFunc = rN; + var GY; + (function(X) { + X[X.Num = 0] = "Num", X[X.Str = 1] = "Str"; + })(GY || (CG.Type = GY = {})); + function oN(X, Q, $) { + if (X instanceof $0.Name) { + let Y = Q === GY.Num; + return $ ? Y ? $0._`"[" + ${X} + "]"` : $0._`"['" + ${X} + "']"` : Y ? $0._`"/" + ${X}` : $0._`"/" + ${X}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return $ ? (0, $0.getProperty)(X).toString() : "/" + HY(X); + } + CG.getErrorPath = oN; + function ZG(X, Q, $ = X.opts.strictSchema) { + if (!$) return; + if (Q = `strict mode: ${Q}`, $ === true) throw Error(Q); + X.self.logger.warn(Q); + } + CG.checkStrictMode = ZG; +}); +var R1 = P((vG) => { + Object.defineProperty(vG, "__esModule", { value: true }); + var P0 = c(), LO = { data: new P0.Name("data"), valCxt: new P0.Name("valCxt"), instancePath: new P0.Name("instancePath"), parentData: new P0.Name("parentData"), parentDataProperty: new P0.Name("parentDataProperty"), rootData: new P0.Name("rootData"), dynamicAnchors: new P0.Name("dynamicAnchors"), vErrors: new P0.Name("vErrors"), errors: new P0.Name("errors"), this: new P0.Name("this"), self: new P0.Name("self"), scope: new P0.Name("scope"), json: new P0.Name("json"), jsonPos: new P0.Name("jsonPos"), jsonLen: new P0.Name("jsonLen"), jsonPart: new P0.Name("jsonPart") }; + vG.default = LO; +}); +var lX = P((yG) => { + Object.defineProperty(yG, "__esModule", { value: true }); + yG.extendErrors = yG.resetErrorsCount = yG.reportExtraError = yG.reportError = yG.keyword$DataError = yG.keywordError = void 0; + var a = c(), Z9 = e(), v0 = R1(); + yG.keywordError = { message: ({ keyword: X }) => a.str`must pass "${X}" keyword validation` }; + yG.keyword$DataError = { message: ({ keyword: X, schemaType: Q }) => Q ? a.str`"${X}" keyword must be ${Q} ($data)` : a.str`"${X}" keyword is invalid ($data)` }; + function FO(X, Q = yG.keywordError, $, Y) { + let { it: W } = X, { gen: J, compositeRule: G, allErrors: H } = W, B = xG(X, Q, $); + if (Y !== null && Y !== void 0 ? Y : G || H) TG(J, B); + else _G(W, a._`[${B}]`); + } + yG.reportError = FO; + function NO(X, Q = yG.keywordError, $) { + let { it: Y } = X, { gen: W, compositeRule: J, allErrors: G } = Y, H = xG(X, Q, $); + if (TG(W, H), !(J || G)) _G(Y, v0.default.vErrors); + } + yG.reportExtraError = NO; + function OO(X, Q) { + X.assign(v0.default.errors, Q), X.if(a._`${v0.default.vErrors} !== null`, () => X.if(Q, () => X.assign(a._`${v0.default.vErrors}.length`, Q), () => X.assign(v0.default.vErrors, null))); + } + yG.resetErrorsCount = OO; + function DO({ gen: X, keyword: Q, schemaValue: $, data: Y, errsCount: W, it: J }) { + if (W === void 0) throw Error("ajv implementation error"); + let G = X.name("err"); + X.forRange("i", W, v0.default.errors, (H) => { + if (X.const(G, a._`${v0.default.vErrors}[${H}]`), X.if(a._`${G}.instancePath === undefined`, () => X.assign(a._`${G}.instancePath`, (0, a.strConcat)(v0.default.instancePath, J.errorPath))), X.assign(a._`${G}.schemaPath`, a.str`${J.errSchemaPath}/${Q}`), J.opts.verbose) X.assign(a._`${G}.schema`, $), X.assign(a._`${G}.data`, Y); + }); + } + yG.extendErrors = DO; + function TG(X, Q) { + let $ = X.const("err", Q); + X.if(a._`${v0.default.vErrors} === null`, () => X.assign(v0.default.vErrors, a._`[${$}]`), a._`${v0.default.vErrors}.push(${$})`), X.code(a._`${v0.default.errors}++`); + } + function _G(X, Q) { + let { gen: $, validateName: Y, schemaEnv: W } = X; + if (W.$async) $.throw(a._`new ${X.ValidationError}(${Q})`); + else $.assign(a._`${Y}.errors`, Q), $.return(false); + } + var G6 = { keyword: new a.Name("keyword"), schemaPath: new a.Name("schemaPath"), params: new a.Name("params"), propertyName: new a.Name("propertyName"), message: new a.Name("message"), schema: new a.Name("schema"), parentSchema: new a.Name("parentSchema") }; + function xG(X, Q, $) { + let { createErrors: Y } = X.it; + if (Y === false) return a._`{}`; + return AO(X, Q, $); + } + function AO(X, Q, $ = {}) { + let { gen: Y, it: W } = X, J = [wO(W, $), MO(X, $)]; + return jO(X, Q, J), Y.object(...J); + } + function wO({ errorPath: X }, { instancePath: Q }) { + let $ = Q ? a.str`${X}${(0, Z9.getErrorPath)(Q, Z9.Type.Str)}` : X; + return [v0.default.instancePath, (0, a.strConcat)(v0.default.instancePath, $)]; + } + function MO({ keyword: X, it: { errSchemaPath: Q } }, { schemaPath: $, parentSchema: Y }) { + let W = Y ? Q : a.str`${Q}/${X}`; + if ($) W = a.str`${W}${(0, Z9.getErrorPath)($, Z9.Type.Str)}`; + return [G6.schemaPath, W]; + } + function jO(X, { params: Q, message: $ }, Y) { + let { keyword: W, data: J, schemaValue: G, it: H } = X, { opts: B, propertyName: z2, topSchemaRef: K, schemaPath: V } = H; + if (Y.push([G6.keyword, W], [G6.params, typeof Q == "function" ? Q(X) : Q || a._`{}`]), B.messages) Y.push([G6.message, typeof $ == "function" ? $(X) : $]); + if (B.verbose) Y.push([G6.schema, G], [G6.parentSchema, a._`${K}${V}`], [v0.default.data, J]); + if (z2) Y.push([G6.propertyName, z2]); + } +}); +var lG = P((fG) => { + Object.defineProperty(fG, "__esModule", { value: true }); + fG.boolOrEmptySchema = fG.topBoolOrEmptySchema = void 0; + var PO = lX(), SO = c(), ZO = R1(), CO = { message: "boolean schema is false" }; + function kO(X) { + let { gen: Q, schema: $, validateName: Y } = X; + if ($ === false) hG(X, false); + else if (typeof $ == "object" && $.$async === true) Q.return(ZO.default.data); + else Q.assign(SO._`${Y}.errors`, null), Q.return(true); + } + fG.topBoolOrEmptySchema = kO; + function vO(X, Q) { + let { gen: $, schema: Y } = X; + if (Y === false) $.var(Q, false), hG(X); + else $.var(Q, true); + } + fG.boolOrEmptySchema = vO; + function hG(X, Q) { + let { gen: $, data: Y } = X, W = { gen: $, keyword: "false schema", data: Y, schema: false, schemaCode: false, schemaValue: false, params: {}, it: X }; + (0, PO.reportError)(W, CO, void 0, Q); + } +}); +var KY = P((mG) => { + Object.defineProperty(mG, "__esModule", { value: true }); + mG.getRules = mG.isJSONType = void 0; + var _O = ["string", "number", "integer", "boolean", "null", "object", "array"], xO = new Set(_O); + function yO(X) { + return typeof X == "string" && xO.has(X); + } + mG.isJSONType = yO; + function gO() { + let X = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } }; + return { types: { ...X, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, X.number, X.string, X.array, X.object], post: { rules: [] }, all: {}, keywords: {} }; + } + mG.getRules = gO; +}); +var UY = P((iG) => { + Object.defineProperty(iG, "__esModule", { value: true }); + iG.shouldUseRule = iG.shouldUseGroup = iG.schemaHasRulesForType = void 0; + function fO({ schema: X, self: Q }, $) { + let Y = Q.RULES.types[$]; + return Y && Y !== true && pG(X, Y); + } + iG.schemaHasRulesForType = fO; + function pG(X, Q) { + return Q.rules.some(($) => dG(X, $)); + } + iG.shouldUseGroup = pG; + function dG(X, Q) { + var $; + return X[Q.keyword] !== void 0 || (($ = Q.definition.implements) === null || $ === void 0 ? void 0 : $.some((Y) => X[Y] !== void 0)); + } + iG.shouldUseRule = dG; +}); +var mX = P((aG) => { + Object.defineProperty(aG, "__esModule", { value: true }); + aG.reportTypeError = aG.checkDataTypes = aG.checkDataType = aG.coerceAndCheckDataType = aG.getJSONTypes = aG.getSchemaTypes = aG.DataType = void 0; + var mO = KY(), cO = UY(), pO = lX(), m = c(), rG = e(), l6; + (function(X) { + X[X.Correct = 0] = "Correct", X[X.Wrong = 1] = "Wrong"; + })(l6 || (aG.DataType = l6 = {})); + function dO(X) { + let Q = oG(X.type); + if (Q.includes("null")) { + if (X.nullable === false) throw Error("type: null contradicts nullable: false"); + } else { + if (!Q.length && X.nullable !== void 0) throw Error('"nullable" cannot be used without "type"'); + if (X.nullable === true) Q.push("null"); + } + return Q; + } + aG.getSchemaTypes = dO; + function oG(X) { + let Q = Array.isArray(X) ? X : X ? [X] : []; + if (Q.every(mO.isJSONType)) return Q; + throw Error("type must be JSONType or JSONType[]: " + Q.join(",")); + } + aG.getJSONTypes = oG; + function iO(X, Q) { + let { gen: $, data: Y, opts: W } = X, J = nO(Q, W.coerceTypes), G = Q.length > 0 && !(J.length === 0 && Q.length === 1 && (0, cO.schemaHasRulesForType)(X, Q[0])); + if (G) { + let H = LY(Q, Y, W.strictNumbers, l6.Wrong); + $.if(H, () => { + if (J.length) rO(X, Q, J); + else qY(X); + }); + } + return G; + } + aG.coerceAndCheckDataType = iO; + var tG = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function nO(X, Q) { + return Q ? X.filter(($) => tG.has($) || Q === "array" && $ === "array") : []; + } + function rO(X, Q, $) { + let { gen: Y, data: W, opts: J } = X, G = Y.let("dataType", m._`typeof ${W}`), H = Y.let("coerced", m._`undefined`); + if (J.coerceTypes === "array") Y.if(m._`${G} == 'object' && Array.isArray(${W}) && ${W}.length == 1`, () => Y.assign(W, m._`${W}[0]`).assign(G, m._`typeof ${W}`).if(LY(Q, W, J.strictNumbers), () => Y.assign(H, W))); + Y.if(m._`${H} !== undefined`); + for (let z2 of $) if (tG.has(z2) || z2 === "array" && J.coerceTypes === "array") B(z2); + Y.else(), qY(X), Y.endIf(), Y.if(m._`${H} !== undefined`, () => { + Y.assign(W, H), oO(X, H); + }); + function B(z2) { + switch (z2) { + case "string": + Y.elseIf(m._`${G} == "number" || ${G} == "boolean"`).assign(H, m._`"" + ${W}`).elseIf(m._`${W} === null`).assign(H, m._`""`); + return; + case "number": + Y.elseIf(m._`${G} == "boolean" || ${W} === null + || (${G} == "string" && ${W} && ${W} == +${W})`).assign(H, m._`+${W}`); + return; + case "integer": + Y.elseIf(m._`${G} === "boolean" || ${W} === null + || (${G} === "string" && ${W} && ${W} == +${W} && !(${W} % 1))`).assign(H, m._`+${W}`); + return; + case "boolean": + Y.elseIf(m._`${W} === "false" || ${W} === 0 || ${W} === null`).assign(H, false).elseIf(m._`${W} === "true" || ${W} === 1`).assign(H, true); + return; + case "null": + Y.elseIf(m._`${W} === "" || ${W} === 0 || ${W} === false`), Y.assign(H, null); + return; + case "array": + Y.elseIf(m._`${G} === "string" || ${G} === "number" + || ${G} === "boolean" || ${W} === null`).assign(H, m._`[${W}]`); + } + } + } + function oO({ gen: X, parentData: Q, parentDataProperty: $ }, Y) { + X.if(m._`${Q} !== undefined`, () => X.assign(m._`${Q}[${$}]`, Y)); + } + function VY(X, Q, $, Y = l6.Correct) { + let W = Y === l6.Correct ? m.operators.EQ : m.operators.NEQ, J; + switch (X) { + case "null": + return m._`${Q} ${W} null`; + case "array": + J = m._`Array.isArray(${Q})`; + break; + case "object": + J = m._`${Q} && typeof ${Q} == "object" && !Array.isArray(${Q})`; + break; + case "integer": + J = G(m._`!(${Q} % 1) && !isNaN(${Q})`); + break; + case "number": + J = G(); + break; + default: + return m._`typeof ${Q} ${W} ${X}`; + } + return Y === l6.Correct ? J : (0, m.not)(J); + function G(H = m.nil) { + return (0, m.and)(m._`typeof ${Q} == "number"`, H, $ ? m._`isFinite(${Q})` : m.nil); + } + } + aG.checkDataType = VY; + function LY(X, Q, $, Y) { + if (X.length === 1) return VY(X[0], Q, $, Y); + let W, J = (0, rG.toHash)(X); + if (J.array && J.object) { + let G = m._`typeof ${Q} != "object"`; + W = J.null ? G : m._`!${Q} || ${G}`, delete J.null, delete J.array, delete J.object; + } else W = m.nil; + if (J.number) delete J.integer; + for (let G in J) W = (0, m.and)(W, VY(G, Q, $, Y)); + return W; + } + aG.checkDataTypes = LY; + var tO = { message: ({ schema: X }) => `must be ${X}`, params: ({ schema: X, schemaValue: Q }) => typeof X == "string" ? m._`{type: ${X}}` : m._`{type: ${Q}}` }; + function qY(X) { + let Q = aO(X); + (0, pO.reportError)(Q, tO); + } + aG.reportTypeError = qY; + function aO(X) { + let { gen: Q, data: $, schema: Y } = X, W = (0, rG.schemaRefOrVal)(X, Y, "type"); + return { gen: Q, keyword: "type", data: $, schema: Y.type, schemaCode: W, schemaValue: W, parentSchema: Y, params: {}, it: X }; + } +}); +var $3 = P((X3) => { + Object.defineProperty(X3, "__esModule", { value: true }); + X3.assignDefaults = void 0; + var m6 = c(), WD = e(); + function JD(X, Q) { + let { properties: $, items: Y } = X.schema; + if (Q === "object" && $) for (let W in $) eG(X, W, $[W].default); + else if (Q === "array" && Array.isArray(Y)) Y.forEach((W, J) => eG(X, J, W.default)); + } + X3.assignDefaults = JD; + function eG(X, Q, $) { + let { gen: Y, compositeRule: W, data: J, opts: G } = X; + if ($ === void 0) return; + let H = m6._`${J}${(0, m6.getProperty)(Q)}`; + if (W) { + (0, WD.checkStrictMode)(X, `default is ignored for: ${H}`); + return; + } + let B = m6._`${H} === undefined`; + if (G.useDefaults === "empty") B = m6._`${B} || ${H} === null || ${H} === ""`; + Y.if(B, m6._`${H} = ${(0, m6.stringify)($)}`); + } +}); +var d0 = P((J3) => { + Object.defineProperty(J3, "__esModule", { value: true }); + J3.validateUnion = J3.validateArray = J3.usePattern = J3.callValidateCode = J3.schemaProperties = J3.allSchemaProperties = J3.noPropertyInData = J3.propertyInData = J3.isOwnProperty = J3.hasPropFunc = J3.reportMissingProp = J3.checkMissingProp = J3.checkReportMissingProp = void 0; + var G0 = c(), FY = e(), c1 = R1(), GD = e(); + function HD(X, Q) { + let { gen: $, data: Y, it: W } = X; + $.if(OY($, Y, Q, W.opts.ownProperties), () => { + X.setParams({ missingProperty: G0._`${Q}` }, true), X.error(); + }); + } + J3.checkReportMissingProp = HD; + function BD({ gen: X, data: Q, it: { opts: $ } }, Y, W) { + return (0, G0.or)(...Y.map((J) => (0, G0.and)(OY(X, Q, J, $.ownProperties), G0._`${W} = ${J}`))); + } + J3.checkMissingProp = BD; + function zD(X, Q) { + X.setParams({ missingProperty: Q }, true), X.error(); + } + J3.reportMissingProp = zD; + function Y3(X) { + return X.scopeValue("func", { ref: Object.prototype.hasOwnProperty, code: G0._`Object.prototype.hasOwnProperty` }); + } + J3.hasPropFunc = Y3; + function NY(X, Q, $) { + return G0._`${Y3(X)}.call(${Q}, ${$})`; + } + J3.isOwnProperty = NY; + function KD(X, Q, $, Y) { + let W = G0._`${Q}${(0, G0.getProperty)($)} !== undefined`; + return Y ? G0._`${W} && ${NY(X, Q, $)}` : W; + } + J3.propertyInData = KD; + function OY(X, Q, $, Y) { + let W = G0._`${Q}${(0, G0.getProperty)($)} === undefined`; + return Y ? (0, G0.or)(W, (0, G0.not)(NY(X, Q, $))) : W; + } + J3.noPropertyInData = OY; + function W3(X) { + return X ? Object.keys(X).filter((Q) => Q !== "__proto__") : []; + } + J3.allSchemaProperties = W3; + function UD(X, Q) { + return W3(Q).filter(($) => !(0, FY.alwaysValidSchema)(X, Q[$])); + } + J3.schemaProperties = UD; + function VD({ schemaCode: X, data: Q, it: { gen: $, topSchemaRef: Y, schemaPath: W, errorPath: J }, it: G }, H, B, z2) { + let K = z2 ? G0._`${X}, ${Q}, ${Y}${W}` : Q, V = [[c1.default.instancePath, (0, G0.strConcat)(c1.default.instancePath, J)], [c1.default.parentData, G.parentData], [c1.default.parentDataProperty, G.parentDataProperty], [c1.default.rootData, c1.default.rootData]]; + if (G.opts.dynamicRef) V.push([c1.default.dynamicAnchors, c1.default.dynamicAnchors]); + let L = G0._`${K}, ${$.object(...V)}`; + return B !== G0.nil ? G0._`${H}.call(${B}, ${L})` : G0._`${H}(${L})`; + } + J3.callValidateCode = VD; + var LD = G0._`new RegExp`; + function qD({ gen: X, it: { opts: Q } }, $) { + let Y = Q.unicodeRegExp ? "u" : "", { regExp: W } = Q.code, J = W($, Y); + return X.scopeValue("pattern", { key: J.toString(), ref: J, code: G0._`${W.code === "new RegExp" ? LD : (0, GD.useFunc)(X, W)}(${$}, ${Y})` }); + } + J3.usePattern = qD; + function FD(X) { + let { gen: Q, data: $, keyword: Y, it: W } = X, J = Q.name("valid"); + if (W.allErrors) { + let H = Q.let("valid", true); + return G(() => Q.assign(H, false)), H; + } + return Q.var(J, true), G(() => Q.break()), J; + function G(H) { + let B = Q.const("len", G0._`${$}.length`); + Q.forRange("i", 0, B, (z2) => { + X.subschema({ keyword: Y, dataProp: z2, dataPropType: FY.Type.Num }, J), Q.if((0, G0.not)(J), H); + }); + } + } + J3.validateArray = FD; + function ND(X) { + let { gen: Q, schema: $, keyword: Y, it: W } = X; + if (!Array.isArray($)) throw Error("ajv implementation error"); + if ($.some((B) => (0, FY.alwaysValidSchema)(W, B)) && !W.opts.unevaluated) return; + let G = Q.let("valid", false), H = Q.name("_valid"); + Q.block(() => $.forEach((B, z2) => { + let K = X.subschema({ keyword: Y, schemaProp: z2, compositeRule: true }, H); + if (Q.assign(G, G0._`${G} || ${H}`), !X.mergeValidEvaluated(K, H)) Q.if((0, G0.not)(G)); + })), X.result(G, () => X.reset(), () => X.error(true)); + } + J3.validateUnion = ND; +}); +var U3 = P((z3) => { + Object.defineProperty(z3, "__esModule", { value: true }); + z3.validateKeywordUsage = z3.validSchemaType = z3.funcKeywordCode = z3.macroKeywordCode = void 0; + var T0 = c(), H6 = R1(), ZD = d0(), CD = lX(); + function kD(X, Q) { + let { gen: $, keyword: Y, schema: W, parentSchema: J, it: G } = X, H = Q.macro.call(G.self, W, J, G), B = B3($, Y, H); + if (G.opts.validateSchema !== false) G.self.validateSchema(H, true); + let z2 = $.name("valid"); + X.subschema({ schema: H, schemaPath: T0.nil, errSchemaPath: `${G.errSchemaPath}/${Y}`, topSchemaRef: B, compositeRule: true }, z2), X.pass(z2, () => X.error(true)); + } + z3.macroKeywordCode = kD; + function vD(X, Q) { + var $; + let { gen: Y, keyword: W, schema: J, parentSchema: G, $data: H, it: B } = X; + _D(B, Q); + let z2 = !H && Q.compile ? Q.compile.call(B.self, J, G, B) : Q.validate, K = B3(Y, W, z2), V = Y.let("valid"); + X.block$data(V, L), X.ok(($ = Q.valid) !== null && $ !== void 0 ? $ : V); + function L() { + if (Q.errors === false) { + if (q(), Q.modifying) H3(X); + N(() => X.error()); + } else { + let A = Q.async ? U() : F(); + if (Q.modifying) H3(X); + N(() => TD(X, A)); + } + } + function U() { + let A = Y.let("ruleErrs", null); + return Y.try(() => q(T0._`await `), (M) => Y.assign(V, false).if(T0._`${M} instanceof ${B.ValidationError}`, () => Y.assign(A, T0._`${M}.errors`), () => Y.throw(M))), A; + } + function F() { + let A = T0._`${K}.errors`; + return Y.assign(A, null), q(T0.nil), A; + } + function q(A = Q.async ? T0._`await ` : T0.nil) { + let M = B.opts.passContext ? H6.default.this : H6.default.self, R = !("compile" in Q && !H || Q.schema === false); + Y.assign(V, T0._`${A}${(0, ZD.callValidateCode)(X, K, M, R)}`, Q.modifying); + } + function N(A) { + var M; + Y.if((0, T0.not)((M = Q.valid) !== null && M !== void 0 ? M : V), A); + } + } + z3.funcKeywordCode = vD; + function H3(X) { + let { gen: Q, data: $, it: Y } = X; + Q.if(Y.parentData, () => Q.assign($, T0._`${Y.parentData}[${Y.parentDataProperty}]`)); + } + function TD(X, Q) { + let { gen: $ } = X; + $.if(T0._`Array.isArray(${Q})`, () => { + $.assign(H6.default.vErrors, T0._`${H6.default.vErrors} === null ? ${Q} : ${H6.default.vErrors}.concat(${Q})`).assign(H6.default.errors, T0._`${H6.default.vErrors}.length`), (0, CD.extendErrors)(X); + }, () => X.error()); + } + function _D({ schemaEnv: X }, Q) { + if (Q.async && !X.$async) throw Error("async keyword in sync schema"); + } + function B3(X, Q, $) { + if ($ === void 0) throw Error(`keyword "${Q}" failed to compile`); + return X.scopeValue("keyword", typeof $ == "function" ? { ref: $ } : { ref: $, code: (0, T0.stringify)($) }); + } + function xD(X, Q, $ = false) { + return !Q.length || Q.some((Y) => Y === "array" ? Array.isArray(X) : Y === "object" ? X && typeof X == "object" && !Array.isArray(X) : typeof X == Y || $ && typeof X > "u"); + } + z3.validSchemaType = xD; + function yD({ schema: X, opts: Q, self: $, errSchemaPath: Y }, W, J) { + if (Array.isArray(W.keyword) ? !W.keyword.includes(J) : W.keyword !== J) throw Error("ajv implementation error"); + let G = W.dependencies; + if (G === null || G === void 0 ? void 0 : G.some((H) => !Object.prototype.hasOwnProperty.call(X, H))) throw Error(`parent schema must have dependencies of ${J}: ${G.join(",")}`); + if (W.validateSchema) { + if (!W.validateSchema(X[J])) { + let B = `keyword "${J}" value is invalid at path "${Y}": ` + $.errorsText(W.validateSchema.errors); + if (Q.validateSchema === "log") $.logger.error(B); + else throw Error(B); + } + } + } + z3.validateKeywordUsage = yD; +}); +var F3 = P((L3) => { + Object.defineProperty(L3, "__esModule", { value: true }); + L3.extendSubschemaMode = L3.extendSubschemaData = L3.getSubschema = void 0; + var U1 = c(), V3 = e(); + function uD(X, { keyword: Q, schemaProp: $, schema: Y, schemaPath: W, errSchemaPath: J, topSchemaRef: G }) { + if (Q !== void 0 && Y !== void 0) throw Error('both "keyword" and "schema" passed, only one allowed'); + if (Q !== void 0) { + let H = X.schema[Q]; + return $ === void 0 ? { schema: H, schemaPath: U1._`${X.schemaPath}${(0, U1.getProperty)(Q)}`, errSchemaPath: `${X.errSchemaPath}/${Q}` } : { schema: H[$], schemaPath: U1._`${X.schemaPath}${(0, U1.getProperty)(Q)}${(0, U1.getProperty)($)}`, errSchemaPath: `${X.errSchemaPath}/${Q}/${(0, V3.escapeFragment)($)}` }; + } + if (Y !== void 0) { + if (W === void 0 || J === void 0 || G === void 0) throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + return { schema: Y, schemaPath: W, topSchemaRef: G, errSchemaPath: J }; + } + throw Error('either "keyword" or "schema" must be passed'); + } + L3.getSubschema = uD; + function lD(X, Q, { dataProp: $, dataPropType: Y, data: W, dataTypes: J, propertyName: G }) { + if (W !== void 0 && $ !== void 0) throw Error('both "data" and "dataProp" passed, only one allowed'); + let { gen: H } = Q; + if ($ !== void 0) { + let { errorPath: z2, dataPathArr: K, opts: V } = Q, L = H.let("data", U1._`${Q.data}${(0, U1.getProperty)($)}`, true); + B(L), X.errorPath = U1.str`${z2}${(0, V3.getErrorPath)($, Y, V.jsPropertySyntax)}`, X.parentDataProperty = U1._`${$}`, X.dataPathArr = [...K, X.parentDataProperty]; + } + if (W !== void 0) { + let z2 = W instanceof U1.Name ? W : H.let("data", W, true); + if (B(z2), G !== void 0) X.propertyName = G; + } + if (J) X.dataTypes = J; + function B(z2) { + X.data = z2, X.dataLevel = Q.dataLevel + 1, X.dataTypes = [], Q.definedProperties = /* @__PURE__ */ new Set(), X.parentData = Q.data, X.dataNames = [...Q.dataNames, z2]; + } + } + L3.extendSubschemaData = lD; + function mD(X, { jtdDiscriminator: Q, jtdMetadata: $, compositeRule: Y, createErrors: W, allErrors: J }) { + if (Y !== void 0) X.compositeRule = Y; + if (W !== void 0) X.createErrors = W; + if (J !== void 0) X.allErrors = J; + X.jtdDiscriminator = Q, X.jtdMetadata = $; + } + L3.extendSubschemaMode = mD; +}); +var DY = P((pv, N3) => { + N3.exports = function X(Q, $) { + if (Q === $) return true; + if (Q && $ && typeof Q == "object" && typeof $ == "object") { + if (Q.constructor !== $.constructor) return false; + var Y, W, J; + if (Array.isArray(Q)) { + if (Y = Q.length, Y != $.length) return false; + for (W = Y; W-- !== 0; ) if (!X(Q[W], $[W])) return false; + return true; + } + if (Q.constructor === RegExp) return Q.source === $.source && Q.flags === $.flags; + if (Q.valueOf !== Object.prototype.valueOf) return Q.valueOf() === $.valueOf(); + if (Q.toString !== Object.prototype.toString) return Q.toString() === $.toString(); + if (J = Object.keys(Q), Y = J.length, Y !== Object.keys($).length) return false; + for (W = Y; W-- !== 0; ) if (!Object.prototype.hasOwnProperty.call($, J[W])) return false; + for (W = Y; W-- !== 0; ) { + var G = J[W]; + if (!X(Q[G], $[G])) return false; + } + return true; + } + return Q !== Q && $ !== $; + }; +}); +var D3 = P((dv, O3) => { + var p1 = O3.exports = function(X, Q, $) { + if (typeof Q == "function") $ = Q, Q = {}; + $ = Q.cb || $; + var Y = typeof $ == "function" ? $ : $.pre || function() { + }, W = $.post || function() { + }; + C9(Q, Y, W, X, "", X); + }; + p1.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true }; + p1.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true }; + p1.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true }; + p1.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true }; + function C9(X, Q, $, Y, W, J, G, H, B, z2) { + if (Y && typeof Y == "object" && !Array.isArray(Y)) { + Q(Y, W, J, G, H, B, z2); + for (var K in Y) { + var V = Y[K]; + if (Array.isArray(V)) { + if (K in p1.arrayKeywords) for (var L = 0; L < V.length; L++) C9(X, Q, $, V[L], W + "/" + K + "/" + L, J, W, K, Y, L); + } else if (K in p1.propsKeywords) { + if (V && typeof V == "object") for (var U in V) C9(X, Q, $, V[U], W + "/" + K + "/" + dD(U), J, W, K, Y, U); + } else if (K in p1.keywords || X.allKeys && !(K in p1.skipKeywords)) C9(X, Q, $, V, W + "/" + K, J, W, K, Y); + } + $(Y, W, J, G, H, B, z2); + } + } + function dD(X) { + return X.replace(/~/g, "~0").replace(/\//g, "~1"); + } +}); +var cX = P((j3) => { + Object.defineProperty(j3, "__esModule", { value: true }); + j3.getSchemaRefs = j3.resolveUrl = j3.normalizeId = j3._getFullPath = j3.getFullPath = j3.inlineRef = void 0; + var iD = e(), nD = DY(), rD = D3(), oD = /* @__PURE__ */ new Set(["type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const"]); + function tD(X, Q = true) { + if (typeof X == "boolean") return true; + if (Q === true) return !AY(X); + if (!Q) return false; + return A3(X) <= Q; + } + j3.inlineRef = tD; + var aD = /* @__PURE__ */ new Set(["$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor"]); + function AY(X) { + for (let Q in X) { + if (aD.has(Q)) return true; + let $ = X[Q]; + if (Array.isArray($) && $.some(AY)) return true; + if (typeof $ == "object" && AY($)) return true; + } + return false; + } + function A3(X) { + let Q = 0; + for (let $ in X) { + if ($ === "$ref") return 1 / 0; + if (Q++, oD.has($)) continue; + if (typeof X[$] == "object") (0, iD.eachItem)(X[$], (Y) => Q += A3(Y)); + if (Q === 1 / 0) return 1 / 0; + } + return Q; + } + function w3(X, Q = "", $) { + if ($ !== false) Q = c6(Q); + let Y = X.parse(Q); + return M3(X, Y); + } + j3.getFullPath = w3; + function M3(X, Q) { + return X.serialize(Q).split("#")[0] + "#"; + } + j3._getFullPath = M3; + var sD = /#\/?$/; + function c6(X) { + return X ? X.replace(sD, "") : ""; + } + j3.normalizeId = c6; + function eD(X, Q, $) { + return $ = c6($), X.resolve(Q, $); + } + j3.resolveUrl = eD; + var XA = /^[a-z_][-a-z0-9._]*$/i; + function QA(X, Q) { + if (typeof X == "boolean") return {}; + let { schemaId: $, uriResolver: Y } = this.opts, W = c6(X[$] || Q), J = { "": W }, G = w3(Y, W, false), H = {}, B = /* @__PURE__ */ new Set(); + return rD(X, { allKeys: true }, (V, L, U, F) => { + if (F === void 0) return; + let q = G + L, N = J[F]; + if (typeof V[$] == "string") N = A.call(this, V[$]); + M.call(this, V.$anchor), M.call(this, V.$dynamicAnchor), J[L] = N; + function A(R) { + let S = this.opts.uriResolver.resolve; + if (R = c6(N ? S(N, R) : R), B.has(R)) throw K(R); + B.add(R); + let C = this.refs[R]; + if (typeof C == "string") C = this.refs[C]; + if (typeof C == "object") z2(V, C.schema, R); + else if (R !== c6(q)) if (R[0] === "#") z2(V, H[R], R), H[R] = V; + else this.refs[R] = q; + return R; + } + function M(R) { + if (typeof R == "string") { + if (!XA.test(R)) throw Error(`invalid anchor "${R}"`); + A.call(this, `#${R}`); + } + } + }), H; + function z2(V, L, U) { + if (L !== void 0 && !nD(V, L)) throw K(U); + } + function K(V) { + return Error(`reference "${V}" resolves to more than one schema`); + } + } + j3.getSchemaRefs = QA; +}); +var iX = P((h3) => { + Object.defineProperty(h3, "__esModule", { value: true }); + h3.getData = h3.KeywordCxt = h3.validateFunctionCode = void 0; + var S3 = lG(), E3 = mX(), MY = UY(), k9 = mX(), HA = $3(), dX = U3(), wY = F3(), _ = c(), u = R1(), BA = cX(), E1 = e(), pX = lX(); + function zA(X) { + if (k3(X)) { + if (v3(X), C3(X)) { + VA(X); + return; + } + } + Z3(X, () => (0, S3.topBoolOrEmptySchema)(X)); + } + h3.validateFunctionCode = zA; + function Z3({ gen: X, validateName: Q, schema: $, schemaEnv: Y, opts: W }, J) { + if (W.code.es5) X.func(Q, _._`${u.default.data}, ${u.default.valCxt}`, Y.$async, () => { + X.code(_._`"use strict"; ${I3($, W)}`), UA(X, W), X.code(J); + }); + else X.func(Q, _._`${u.default.data}, ${KA(W)}`, Y.$async, () => X.code(I3($, W)).code(J)); + } + function KA(X) { + return _._`{${u.default.instancePath}="", ${u.default.parentData}, ${u.default.parentDataProperty}, ${u.default.rootData}=${u.default.data}${X.dynamicRef ? _._`, ${u.default.dynamicAnchors}={}` : _.nil}}={}`; + } + function UA(X, Q) { + X.if(u.default.valCxt, () => { + if (X.var(u.default.instancePath, _._`${u.default.valCxt}.${u.default.instancePath}`), X.var(u.default.parentData, _._`${u.default.valCxt}.${u.default.parentData}`), X.var(u.default.parentDataProperty, _._`${u.default.valCxt}.${u.default.parentDataProperty}`), X.var(u.default.rootData, _._`${u.default.valCxt}.${u.default.rootData}`), Q.dynamicRef) X.var(u.default.dynamicAnchors, _._`${u.default.valCxt}.${u.default.dynamicAnchors}`); + }, () => { + if (X.var(u.default.instancePath, _._`""`), X.var(u.default.parentData, _._`undefined`), X.var(u.default.parentDataProperty, _._`undefined`), X.var(u.default.rootData, u.default.data), Q.dynamicRef) X.var(u.default.dynamicAnchors, _._`{}`); + }); + } + function VA(X) { + let { schema: Q, opts: $, gen: Y } = X; + Z3(X, () => { + if ($.$comment && Q.$comment) _3(X); + if (OA(X), Y.let(u.default.vErrors, null), Y.let(u.default.errors, 0), $.unevaluated) LA(X); + T3(X), wA(X); + }); + return; + } + function LA(X) { + let { gen: Q, validateName: $ } = X; + X.evaluated = Q.const("evaluated", _._`${$}.evaluated`), Q.if(_._`${X.evaluated}.dynamicProps`, () => Q.assign(_._`${X.evaluated}.props`, _._`undefined`)), Q.if(_._`${X.evaluated}.dynamicItems`, () => Q.assign(_._`${X.evaluated}.items`, _._`undefined`)); + } + function I3(X, Q) { + let $ = typeof X == "object" && X[Q.schemaId]; + return $ && (Q.code.source || Q.code.process) ? _._`/*# sourceURL=${$} */` : _.nil; + } + function qA(X, Q) { + if (k3(X)) { + if (v3(X), C3(X)) { + FA(X, Q); + return; + } + } + (0, S3.boolOrEmptySchema)(X, Q); + } + function C3({ schema: X, self: Q }) { + if (typeof X == "boolean") return !X; + for (let $ in X) if (Q.RULES.all[$]) return true; + return false; + } + function k3(X) { + return typeof X.schema != "boolean"; + } + function FA(X, Q) { + let { schema: $, gen: Y, opts: W } = X; + if (W.$comment && $.$comment) _3(X); + DA(X), AA(X); + let J = Y.const("_errs", u.default.errors); + T3(X, J), Y.var(Q, _._`${J} === ${u.default.errors}`); + } + function v3(X) { + (0, E1.checkUnknownRules)(X), NA(X); + } + function T3(X, Q) { + if (X.opts.jtd) return b3(X, [], false, Q); + let $ = (0, E3.getSchemaTypes)(X.schema), Y = (0, E3.coerceAndCheckDataType)(X, $); + b3(X, $, !Y, Q); + } + function NA(X) { + let { schema: Q, errSchemaPath: $, opts: Y, self: W } = X; + if (Q.$ref && Y.ignoreKeywordsWithRef && (0, E1.schemaHasRulesButRef)(Q, W.RULES)) W.logger.warn(`$ref: keywords ignored in schema at path "${$}"`); + } + function OA(X) { + let { schema: Q, opts: $ } = X; + if (Q.default !== void 0 && $.useDefaults && $.strictSchema) (0, E1.checkStrictMode)(X, "default is ignored in the schema root"); + } + function DA(X) { + let Q = X.schema[X.opts.schemaId]; + if (Q) X.baseId = (0, BA.resolveUrl)(X.opts.uriResolver, X.baseId, Q); + } + function AA(X) { + if (X.schema.$async && !X.schemaEnv.$async) throw Error("async schema in sync schema"); + } + function _3({ gen: X, schemaEnv: Q, schema: $, errSchemaPath: Y, opts: W }) { + let J = $.$comment; + if (W.$comment === true) X.code(_._`${u.default.self}.logger.log(${J})`); + else if (typeof W.$comment == "function") { + let G = _.str`${Y}/$comment`, H = X.scopeValue("root", { ref: Q.root }); + X.code(_._`${u.default.self}.opts.$comment(${J}, ${G}, ${H}.schema)`); + } + } + function wA(X) { + let { gen: Q, schemaEnv: $, validateName: Y, ValidationError: W, opts: J } = X; + if ($.$async) Q.if(_._`${u.default.errors} === 0`, () => Q.return(u.default.data), () => Q.throw(_._`new ${W}(${u.default.vErrors})`)); + else { + if (Q.assign(_._`${Y}.errors`, u.default.vErrors), J.unevaluated) MA(X); + Q.return(_._`${u.default.errors} === 0`); + } + } + function MA({ gen: X, evaluated: Q, props: $, items: Y }) { + if ($ instanceof _.Name) X.assign(_._`${Q}.props`, $); + if (Y instanceof _.Name) X.assign(_._`${Q}.items`, Y); + } + function b3(X, Q, $, Y) { + let { gen: W, schema: J, data: G, allErrors: H, opts: B, self: z2 } = X, { RULES: K } = z2; + if (J.$ref && (B.ignoreKeywordsWithRef || !(0, E1.schemaHasRulesButRef)(J, K))) { + W.block(() => y3(X, "$ref", K.all.$ref.definition)); + return; + } + if (!B.jtd) jA(X, Q); + W.block(() => { + for (let L of K.rules) V(L); + V(K.post); + }); + function V(L) { + if (!(0, MY.shouldUseGroup)(J, L)) return; + if (L.type) { + if (W.if((0, k9.checkDataType)(L.type, G, B.strictNumbers)), P3(X, L), Q.length === 1 && Q[0] === L.type && $) W.else(), (0, k9.reportTypeError)(X); + W.endIf(); + } else P3(X, L); + if (!H) W.if(_._`${u.default.errors} === ${Y || 0}`); + } + } + function P3(X, Q) { + let { gen: $, schema: Y, opts: { useDefaults: W } } = X; + if (W) (0, HA.assignDefaults)(X, Q.type); + $.block(() => { + for (let J of Q.rules) if ((0, MY.shouldUseRule)(Y, J)) y3(X, J.keyword, J.definition, Q.type); + }); + } + function jA(X, Q) { + if (X.schemaEnv.meta || !X.opts.strictTypes) return; + if (RA(X, Q), !X.opts.allowUnionTypes) EA(X, Q); + IA(X, X.dataTypes); + } + function RA(X, Q) { + if (!Q.length) return; + if (!X.dataTypes.length) { + X.dataTypes = Q; + return; + } + Q.forEach(($) => { + if (!x3(X.dataTypes, $)) jY(X, `type "${$}" not allowed by context "${X.dataTypes.join(",")}"`); + }), PA(X, Q); + } + function EA(X, Q) { + if (Q.length > 1 && !(Q.length === 2 && Q.includes("null"))) jY(X, "use allowUnionTypes to allow union type keyword"); + } + function IA(X, Q) { + let $ = X.self.RULES.all; + for (let Y in $) { + let W = $[Y]; + if (typeof W == "object" && (0, MY.shouldUseRule)(X.schema, W)) { + let { type: J } = W.definition; + if (J.length && !J.some((G) => bA(Q, G))) jY(X, `missing type "${J.join(",")}" for keyword "${Y}"`); + } + } + } + function bA(X, Q) { + return X.includes(Q) || Q === "number" && X.includes("integer"); + } + function x3(X, Q) { + return X.includes(Q) || Q === "integer" && X.includes("number"); + } + function PA(X, Q) { + let $ = []; + for (let Y of X.dataTypes) if (x3(Q, Y)) $.push(Y); + else if (Q.includes("integer") && Y === "number") $.push("integer"); + X.dataTypes = $; + } + function jY(X, Q) { + let $ = X.schemaEnv.baseId + X.errSchemaPath; + Q += ` at "${$}" (strictTypes)`, (0, E1.checkStrictMode)(X, Q, X.opts.strictTypes); + } + class RY { + constructor(X, Q, $) { + if ((0, dX.validateKeywordUsage)(X, Q, $), this.gen = X.gen, this.allErrors = X.allErrors, this.keyword = $, this.data = X.data, this.schema = X.schema[$], this.$data = Q.$data && X.opts.$data && this.schema && this.schema.$data, this.schemaValue = (0, E1.schemaRefOrVal)(X, this.schema, $, this.$data), this.schemaType = Q.schemaType, this.parentSchema = X.schema, this.params = {}, this.it = X, this.def = Q, this.$data) this.schemaCode = X.gen.const("vSchema", g3(this.$data, X)); + else if (this.schemaCode = this.schemaValue, !(0, dX.validSchemaType)(this.schema, Q.schemaType, Q.allowUndefined)) throw Error(`${$} value must be ${JSON.stringify(Q.schemaType)}`); + if ("code" in Q ? Q.trackErrors : Q.errors !== false) this.errsCount = X.gen.const("_errs", u.default.errors); + } + result(X, Q, $) { + this.failResult((0, _.not)(X), Q, $); + } + failResult(X, Q, $) { + if (this.gen.if(X), $) $(); + else this.error(); + if (Q) { + if (this.gen.else(), Q(), this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(X, Q) { + this.failResult((0, _.not)(X), void 0, Q); + } + fail(X) { + if (X === void 0) { + if (this.error(), !this.allErrors) this.gen.if(false); + return; + } + if (this.gen.if(X), this.error(), this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(X) { + if (!this.$data) return this.fail(X); + let { schemaCode: Q } = this; + this.fail(_._`${Q} !== undefined && (${(0, _.or)(this.invalid$data(), X)})`); + } + error(X, Q, $) { + if (Q) { + this.setParams(Q), this._error(X, $), this.setParams({}); + return; + } + this._error(X, $); + } + _error(X, Q) { + (X ? pX.reportExtraError : pX.reportError)(this, this.def.error, Q); + } + $dataError() { + (0, pX.reportError)(this, this.def.$dataError || pX.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw Error('add "trackErrors" to keyword definition'); + (0, pX.resetErrorsCount)(this.gen, this.errsCount); + } + ok(X) { + if (!this.allErrors) this.gen.if(X); + } + setParams(X, Q) { + if (Q) Object.assign(this.params, X); + else this.params = X; + } + block$data(X, Q, $ = _.nil) { + this.gen.block(() => { + this.check$data(X, $), Q(); + }); + } + check$data(X = _.nil, Q = _.nil) { + if (!this.$data) return; + let { gen: $, schemaCode: Y, schemaType: W, def: J } = this; + if ($.if((0, _.or)(_._`${Y} === undefined`, Q)), X !== _.nil) $.assign(X, true); + if (W.length || J.validateSchema) { + if ($.elseIf(this.invalid$data()), this.$dataError(), X !== _.nil) $.assign(X, false); + } + $.else(); + } + invalid$data() { + let { gen: X, schemaCode: Q, schemaType: $, def: Y, it: W } = this; + return (0, _.or)(J(), G()); + function J() { + if ($.length) { + if (!(Q instanceof _.Name)) throw Error("ajv implementation error"); + let H = Array.isArray($) ? $ : [$]; + return _._`${(0, k9.checkDataTypes)(H, Q, W.opts.strictNumbers, k9.DataType.Wrong)}`; + } + return _.nil; + } + function G() { + if (Y.validateSchema) { + let H = X.scopeValue("validate$data", { ref: Y.validateSchema }); + return _._`!${H}(${Q})`; + } + return _.nil; + } + } + subschema(X, Q) { + let $ = (0, wY.getSubschema)(this.it, X); + (0, wY.extendSubschemaData)($, this.it, X), (0, wY.extendSubschemaMode)($, X); + let Y = { ...this.it, ...$, items: void 0, props: void 0 }; + return qA(Y, Q), Y; + } + mergeEvaluated(X, Q) { + let { it: $, gen: Y } = this; + if (!$.opts.unevaluated) return; + if ($.props !== true && X.props !== void 0) $.props = E1.mergeEvaluated.props(Y, X.props, $.props, Q); + if ($.items !== true && X.items !== void 0) $.items = E1.mergeEvaluated.items(Y, X.items, $.items, Q); + } + mergeValidEvaluated(X, Q) { + let { it: $, gen: Y } = this; + if ($.opts.unevaluated && ($.props !== true || $.items !== true)) return Y.if(Q, () => this.mergeEvaluated(X, _.Name)), true; + } + } + h3.KeywordCxt = RY; + function y3(X, Q, $, Y) { + let W = new RY(X, $, Q); + if ("code" in $) $.code(W, Y); + else if (W.$data && $.validate) (0, dX.funcKeywordCode)(W, $); + else if ("macro" in $) (0, dX.macroKeywordCode)(W, $); + else if ($.compile || $.validate) (0, dX.funcKeywordCode)(W, $); + } + var SA = /^\/(?:[^~]|~0|~1)*$/, ZA = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function g3(X, { dataLevel: Q, dataNames: $, dataPathArr: Y }) { + let W, J; + if (X === "") return u.default.rootData; + if (X[0] === "/") { + if (!SA.test(X)) throw Error(`Invalid JSON-pointer: ${X}`); + W = X, J = u.default.rootData; + } else { + let z2 = ZA.exec(X); + if (!z2) throw Error(`Invalid JSON-pointer: ${X}`); + let K = +z2[1]; + if (W = z2[2], W === "#") { + if (K >= Q) throw Error(B("property/index", K)); + return Y[Q - K]; + } + if (K > Q) throw Error(B("data", K)); + if (J = $[Q - K], !W) return J; + } + let G = J, H = W.split("/"); + for (let z2 of H) if (z2) J = _._`${J}${(0, _.getProperty)((0, E1.unescapeJsonPointer)(z2))}`, G = _._`${G} && ${J}`; + return G; + function B(z2, K) { + return `Cannot access ${z2} ${K} levels up, current level is ${Q}`; + } + } + h3.getData = g3; +}); +var v9 = P((l3) => { + Object.defineProperty(l3, "__esModule", { value: true }); + class u3 extends Error { + constructor(X) { + super("validation failed"); + this.errors = X, this.ajv = this.validation = true; + } + } + l3.default = u3; +}); +var nX = P((c3) => { + Object.defineProperty(c3, "__esModule", { value: true }); + var EY = cX(); + class m3 extends Error { + constructor(X, Q, $, Y) { + super(Y || `can't resolve reference ${$} from id ${Q}`); + this.missingRef = (0, EY.resolveUrl)(X, Q, $), this.missingSchema = (0, EY.normalizeId)((0, EY.getFullPath)(X, this.missingRef)); + } + } + c3.default = m3; +}); +var _9 = P((i3) => { + Object.defineProperty(i3, "__esModule", { value: true }); + i3.resolveSchema = i3.getCompilingSchema = i3.resolveRef = i3.compileSchema = i3.SchemaEnv = void 0; + var X1 = c(), _A = v9(), B6 = R1(), Q1 = cX(), p3 = e(), xA = iX(); + class rX { + constructor(X) { + var Q; + this.refs = {}, this.dynamicAnchors = {}; + let $; + if (typeof X.schema == "object") $ = X.schema; + this.schema = X.schema, this.schemaId = X.schemaId, this.root = X.root || this, this.baseId = (Q = X.baseId) !== null && Q !== void 0 ? Q : (0, Q1.normalizeId)($ === null || $ === void 0 ? void 0 : $[X.schemaId || "$id"]), this.schemaPath = X.schemaPath, this.localRefs = X.localRefs, this.meta = X.meta, this.$async = $ === null || $ === void 0 ? void 0 : $.$async, this.refs = {}; + } + } + i3.SchemaEnv = rX; + function bY(X) { + let Q = d3.call(this, X); + if (Q) return Q; + let $ = (0, Q1.getFullPath)(this.opts.uriResolver, X.root.baseId), { es5: Y, lines: W } = this.opts.code, { ownProperties: J } = this.opts, G = new X1.CodeGen(this.scope, { es5: Y, lines: W, ownProperties: J }), H; + if (X.$async) H = G.scopeValue("Error", { ref: _A.default, code: X1._`require("ajv/dist/runtime/validation_error").default` }); + let B = G.scopeName("validate"); + X.validateName = B; + let z2 = { gen: G, allErrors: this.opts.allErrors, data: B6.default.data, parentData: B6.default.parentData, parentDataProperty: B6.default.parentDataProperty, dataNames: [B6.default.data], dataPathArr: [X1.nil], dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: G.scopeValue("schema", this.opts.code.source === true ? { ref: X.schema, code: (0, X1.stringify)(X.schema) } : { ref: X.schema }), validateName: B, ValidationError: H, schema: X.schema, schemaEnv: X, rootId: $, baseId: X.baseId || $, schemaPath: X1.nil, errSchemaPath: X.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: X1._`""`, opts: this.opts, self: this }, K; + try { + this._compilations.add(X), (0, xA.validateFunctionCode)(z2), G.optimize(this.opts.code.optimize); + let V = G.toString(); + if (K = `${G.scopeRefs(B6.default.scope)}return ${V}`, this.opts.code.process) K = this.opts.code.process(K, X); + let U = Function(`${B6.default.self}`, `${B6.default.scope}`, K)(this, this.scope.get()); + if (this.scope.value(B, { ref: U }), U.errors = null, U.schema = X.schema, U.schemaEnv = X, X.$async) U.$async = true; + if (this.opts.code.source === true) U.source = { validateName: B, validateCode: V, scopeValues: G._values }; + if (this.opts.unevaluated) { + let { props: F, items: q } = z2; + if (U.evaluated = { props: F instanceof X1.Name ? void 0 : F, items: q instanceof X1.Name ? void 0 : q, dynamicProps: F instanceof X1.Name, dynamicItems: q instanceof X1.Name }, U.source) U.source.evaluated = (0, X1.stringify)(U.evaluated); + } + return X.validate = U, X; + } catch (V) { + if (delete X.validate, delete X.validateName, K) this.logger.error("Error compiling schema, function code:", K); + throw V; + } finally { + this._compilations.delete(X); + } + } + i3.compileSchema = bY; + function yA(X, Q, $) { + var Y; + $ = (0, Q1.resolveUrl)(this.opts.uriResolver, Q, $); + let W = X.refs[$]; + if (W) return W; + let J = fA.call(this, X, $); + if (J === void 0) { + let G = (Y = X.localRefs) === null || Y === void 0 ? void 0 : Y[$], { schemaId: H } = this.opts; + if (G) J = new rX({ schema: G, schemaId: H, root: X, baseId: Q }); + } + if (J === void 0) return; + return X.refs[$] = gA.call(this, J); + } + i3.resolveRef = yA; + function gA(X) { + if ((0, Q1.inlineRef)(X.schema, this.opts.inlineRefs)) return X.schema; + return X.validate ? X : bY.call(this, X); + } + function d3(X) { + for (let Q of this._compilations) if (hA(Q, X)) return Q; + } + i3.getCompilingSchema = d3; + function hA(X, Q) { + return X.schema === Q.schema && X.root === Q.root && X.baseId === Q.baseId; + } + function fA(X, Q) { + let $; + while (typeof ($ = this.refs[Q]) == "string") Q = $; + return $ || this.schemas[Q] || T9.call(this, X, Q); + } + function T9(X, Q) { + let $ = this.opts.uriResolver.parse(Q), Y = (0, Q1._getFullPath)(this.opts.uriResolver, $), W = (0, Q1.getFullPath)(this.opts.uriResolver, X.baseId, void 0); + if (Object.keys(X.schema).length > 0 && Y === W) return IY.call(this, $, X); + let J = (0, Q1.normalizeId)(Y), G = this.refs[J] || this.schemas[J]; + if (typeof G == "string") { + let H = T9.call(this, X, G); + if (typeof (H === null || H === void 0 ? void 0 : H.schema) !== "object") return; + return IY.call(this, $, H); + } + if (typeof (G === null || G === void 0 ? void 0 : G.schema) !== "object") return; + if (!G.validate) bY.call(this, G); + if (J === (0, Q1.normalizeId)(Q)) { + let { schema: H } = G, { schemaId: B } = this.opts, z2 = H[B]; + if (z2) W = (0, Q1.resolveUrl)(this.opts.uriResolver, W, z2); + return new rX({ schema: H, schemaId: B, root: X, baseId: W }); + } + return IY.call(this, $, G); + } + i3.resolveSchema = T9; + var uA = /* @__PURE__ */ new Set(["properties", "patternProperties", "enum", "dependencies", "definitions"]); + function IY(X, { baseId: Q, schema: $, root: Y }) { + var W; + if (((W = X.fragment) === null || W === void 0 ? void 0 : W[0]) !== "/") return; + for (let H of X.fragment.slice(1).split("/")) { + if (typeof $ === "boolean") return; + let B = $[(0, p3.unescapeFragment)(H)]; + if (B === void 0) return; + $ = B; + let z2 = typeof $ === "object" && $[this.opts.schemaId]; + if (!uA.has(H) && z2) Q = (0, Q1.resolveUrl)(this.opts.uriResolver, Q, z2); + } + let J; + if (typeof $ != "boolean" && $.$ref && !(0, p3.schemaHasRulesButRef)($, this.RULES)) { + let H = (0, Q1.resolveUrl)(this.opts.uriResolver, Q, $.$ref); + J = T9.call(this, Y, H); + } + let { schemaId: G } = this.opts; + if (J = J || new rX({ schema: $, schemaId: G, root: Y, baseId: Q }), J.schema !== J.root.schema) return J; + return; + } +}); +var r3 = P((av, dA) => { + dA.exports = { $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", type: "object", required: ["$data"], properties: { $data: { type: "string", anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] } }, additionalProperties: false }; +}); +var t3 = P((sv, o3) => { + var iA = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, a: 10, A: 10, b: 11, B: 11, c: 12, C: 12, d: 13, D: 13, e: 14, E: 14, f: 15, F: 15 }; + o3.exports = { HEX: iA }; +}); +var WH = P((ev, YH) => { + var { HEX: nA } = t3(), rA = /^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u; + function XH(X) { + if ($H(X, ".") < 3) return { host: X, isIPV4: false }; + let Q = X.match(rA) || [], [$] = Q; + if ($) return { host: tA($, "."), isIPV4: true }; + else return { host: X, isIPV4: false }; + } + function PY(X, Q = false) { + let $ = "", Y = true; + for (let W of X) { + if (nA[W] === void 0) return; + if (W !== "0" && Y === true) Y = false; + if (!Y) $ += W; + } + if (Q && $.length === 0) $ = "0"; + return $; + } + function oA(X) { + let Q = 0, $ = { error: false, address: "", zone: "" }, Y = [], W = [], J = false, G = false, H = false; + function B() { + if (W.length) { + if (J === false) { + let z2 = PY(W); + if (z2 !== void 0) Y.push(z2); + else return $.error = true, false; + } + W.length = 0; + } + return true; + } + for (let z2 = 0; z2 < X.length; z2++) { + let K = X[z2]; + if (K === "[" || K === "]") continue; + if (K === ":") { + if (G === true) H = true; + if (!B()) break; + if (Q++, Y.push(":"), Q > 7) { + $.error = true; + break; + } + if (z2 - 1 >= 0 && X[z2 - 1] === ":") G = true; + continue; + } else if (K === "%") { + if (!B()) break; + J = true; + } else { + W.push(K); + continue; + } + } + if (W.length) if (J) $.zone = W.join(""); + else if (H) Y.push(W.join("")); + else Y.push(PY(W)); + return $.address = Y.join(""), $; + } + function QH(X) { + if ($H(X, ":") < 2) return { host: X, isIPV6: false }; + let Q = oA(X); + if (!Q.error) { + let { address: $, address: Y } = Q; + if (Q.zone) $ += "%" + Q.zone, Y += "%25" + Q.zone; + return { host: $, escapedHost: Y, isIPV6: true }; + } else return { host: X, isIPV6: false }; + } + function tA(X, Q) { + let $ = "", Y = true, W = X.length; + for (let J = 0; J < W; J++) { + let G = X[J]; + if (G === "0" && Y) { + if (J + 1 <= W && X[J + 1] === Q || J + 1 === W) $ += G, Y = false; + } else { + if (G === Q) Y = true; + else Y = false; + $ += G; + } + } + return $; + } + function $H(X, Q) { + let $ = 0; + for (let Y = 0; Y < X.length; Y++) if (X[Y] === Q) $++; + return $; + } + var a3 = /^\.\.?\//u, s3 = /^\/\.(?:\/|$)/u, e3 = /^\/\.\.(?:\/|$)/u, aA = /^\/?(?:.|\n)*?(?=\/|$)/u; + function sA(X) { + let Q = []; + while (X.length) if (X.match(a3)) X = X.replace(a3, ""); + else if (X.match(s3)) X = X.replace(s3, "/"); + else if (X.match(e3)) X = X.replace(e3, "/"), Q.pop(); + else if (X === "." || X === "..") X = ""; + else { + let $ = X.match(aA); + if ($) { + let Y = $[0]; + X = X.slice(Y.length), Q.push(Y); + } else throw Error("Unexpected dot segment condition"); + } + return Q.join(""); + } + function eA(X, Q) { + let $ = Q !== true ? escape : unescape; + if (X.scheme !== void 0) X.scheme = $(X.scheme); + if (X.userinfo !== void 0) X.userinfo = $(X.userinfo); + if (X.host !== void 0) X.host = $(X.host); + if (X.path !== void 0) X.path = $(X.path); + if (X.query !== void 0) X.query = $(X.query); + if (X.fragment !== void 0) X.fragment = $(X.fragment); + return X; + } + function Xw(X) { + let Q = []; + if (X.userinfo !== void 0) Q.push(X.userinfo), Q.push("@"); + if (X.host !== void 0) { + let $ = unescape(X.host), Y = XH($); + if (Y.isIPV4) $ = Y.host; + else { + let W = QH(Y.host); + if (W.isIPV6 === true) $ = `[${W.escapedHost}]`; + else $ = X.host; + } + Q.push($); + } + if (typeof X.port === "number" || typeof X.port === "string") Q.push(":"), Q.push(String(X.port)); + return Q.length ? Q.join("") : void 0; + } + YH.exports = { recomposeAuthority: Xw, normalizeComponentEncoding: eA, removeDotSegments: sA, normalizeIPv4: XH, normalizeIPv6: QH, stringArrayToHexStripped: PY }; +}); +var KH = P((XT, zH) => { + var Qw = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu, $w = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + function JH(X) { + return typeof X.secure === "boolean" ? X.secure : String(X.scheme).toLowerCase() === "wss"; + } + function GH(X) { + if (!X.host) X.error = X.error || "HTTP URIs must have a host."; + return X; + } + function HH(X) { + let Q = String(X.scheme).toLowerCase() === "https"; + if (X.port === (Q ? 443 : 80) || X.port === "") X.port = void 0; + if (!X.path) X.path = "/"; + return X; + } + function Yw(X) { + return X.secure = JH(X), X.resourceName = (X.path || "/") + (X.query ? "?" + X.query : ""), X.path = void 0, X.query = void 0, X; + } + function Ww(X) { + if (X.port === (JH(X) ? 443 : 80) || X.port === "") X.port = void 0; + if (typeof X.secure === "boolean") X.scheme = X.secure ? "wss" : "ws", X.secure = void 0; + if (X.resourceName) { + let [Q, $] = X.resourceName.split("?"); + X.path = Q && Q !== "/" ? Q : void 0, X.query = $, X.resourceName = void 0; + } + return X.fragment = void 0, X; + } + function Jw(X, Q) { + if (!X.path) return X.error = "URN can not be parsed", X; + let $ = X.path.match($w); + if ($) { + let Y = Q.scheme || X.scheme || "urn"; + X.nid = $[1].toLowerCase(), X.nss = $[2]; + let W = `${Y}:${Q.nid || X.nid}`, J = SY[W]; + if (X.path = void 0, J) X = J.parse(X, Q); + } else X.error = X.error || "URN can not be parsed."; + return X; + } + function Gw(X, Q) { + let $ = Q.scheme || X.scheme || "urn", Y = X.nid.toLowerCase(), W = `${$}:${Q.nid || Y}`, J = SY[W]; + if (J) X = J.serialize(X, Q); + let G = X, H = X.nss; + return G.path = `${Y || Q.nid}:${H}`, Q.skipEscape = true, G; + } + function Hw(X, Q) { + let $ = X; + if ($.uuid = $.nss, $.nss = void 0, !Q.tolerant && (!$.uuid || !Qw.test($.uuid))) $.error = $.error || "UUID is not valid."; + return $; + } + function Bw(X) { + let Q = X; + return Q.nss = (X.uuid || "").toLowerCase(), Q; + } + var BH = { scheme: "http", domainHost: true, parse: GH, serialize: HH }, zw = { scheme: "https", domainHost: BH.domainHost, parse: GH, serialize: HH }, x9 = { scheme: "ws", domainHost: true, parse: Yw, serialize: Ww }, Kw = { scheme: "wss", domainHost: x9.domainHost, parse: x9.parse, serialize: x9.serialize }, Uw = { scheme: "urn", parse: Jw, serialize: Gw, skipNormalize: true }, Vw = { scheme: "urn:uuid", parse: Hw, serialize: Bw, skipNormalize: true }, SY = { http: BH, https: zw, ws: x9, wss: Kw, urn: Uw, "urn:uuid": Vw }; + zH.exports = SY; +}); +var VH = P((QT, g9) => { + var { normalizeIPv6: Lw, normalizeIPv4: qw, removeDotSegments: oX, recomposeAuthority: Fw, normalizeComponentEncoding: y9 } = WH(), ZY = KH(); + function Nw(X, Q) { + if (typeof X === "string") X = V1(I1(X, Q), Q); + else if (typeof X === "object") X = I1(V1(X, Q), Q); + return X; + } + function Ow(X, Q, $) { + let Y = Object.assign({ scheme: "null" }, $), W = UH(I1(X, Y), I1(Q, Y), Y, true); + return V1(W, { ...Y, skipEscape: true }); + } + function UH(X, Q, $, Y) { + let W = {}; + if (!Y) X = I1(V1(X, $), $), Q = I1(V1(Q, $), $); + if ($ = $ || {}, !$.tolerant && Q.scheme) W.scheme = Q.scheme, W.userinfo = Q.userinfo, W.host = Q.host, W.port = Q.port, W.path = oX(Q.path || ""), W.query = Q.query; + else { + if (Q.userinfo !== void 0 || Q.host !== void 0 || Q.port !== void 0) W.userinfo = Q.userinfo, W.host = Q.host, W.port = Q.port, W.path = oX(Q.path || ""), W.query = Q.query; + else { + if (!Q.path) if (W.path = X.path, Q.query !== void 0) W.query = Q.query; + else W.query = X.query; + else { + if (Q.path.charAt(0) === "/") W.path = oX(Q.path); + else { + if ((X.userinfo !== void 0 || X.host !== void 0 || X.port !== void 0) && !X.path) W.path = "/" + Q.path; + else if (!X.path) W.path = Q.path; + else W.path = X.path.slice(0, X.path.lastIndexOf("/") + 1) + Q.path; + W.path = oX(W.path); + } + W.query = Q.query; + } + W.userinfo = X.userinfo, W.host = X.host, W.port = X.port; + } + W.scheme = X.scheme; + } + return W.fragment = Q.fragment, W; + } + function Dw(X, Q, $) { + if (typeof X === "string") X = unescape(X), X = V1(y9(I1(X, $), true), { ...$, skipEscape: true }); + else if (typeof X === "object") X = V1(y9(X, true), { ...$, skipEscape: true }); + if (typeof Q === "string") Q = unescape(Q), Q = V1(y9(I1(Q, $), true), { ...$, skipEscape: true }); + else if (typeof Q === "object") Q = V1(y9(Q, true), { ...$, skipEscape: true }); + return X.toLowerCase() === Q.toLowerCase(); + } + function V1(X, Q) { + let $ = { host: X.host, scheme: X.scheme, userinfo: X.userinfo, port: X.port, path: X.path, query: X.query, nid: X.nid, nss: X.nss, uuid: X.uuid, fragment: X.fragment, reference: X.reference, resourceName: X.resourceName, secure: X.secure, error: "" }, Y = Object.assign({}, Q), W = [], J = ZY[(Y.scheme || $.scheme || "").toLowerCase()]; + if (J && J.serialize) J.serialize($, Y); + if ($.path !== void 0) if (!Y.skipEscape) { + if ($.path = escape($.path), $.scheme !== void 0) $.path = $.path.split("%3A").join(":"); + } else $.path = unescape($.path); + if (Y.reference !== "suffix" && $.scheme) W.push($.scheme, ":"); + let G = Fw($); + if (G !== void 0) { + if (Y.reference !== "suffix") W.push("//"); + if (W.push(G), $.path && $.path.charAt(0) !== "/") W.push("/"); + } + if ($.path !== void 0) { + let H = $.path; + if (!Y.absolutePath && (!J || !J.absolutePath)) H = oX(H); + if (G === void 0) H = H.replace(/^\/\//u, "/%2F"); + W.push(H); + } + if ($.query !== void 0) W.push("?", $.query); + if ($.fragment !== void 0) W.push("#", $.fragment); + return W.join(""); + } + var Aw = Array.from({ length: 127 }, (X, Q) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(Q))); + function ww(X) { + let Q = 0; + for (let $ = 0, Y = X.length; $ < Y; ++$) if (Q = X.charCodeAt($), Q > 126 || Aw[Q]) return true; + return false; + } + var Mw = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + function I1(X, Q) { + let $ = Object.assign({}, Q), Y = { scheme: void 0, userinfo: void 0, host: "", port: void 0, path: "", query: void 0, fragment: void 0 }, W = X.indexOf("%") !== -1, J = false; + if ($.reference === "suffix") X = ($.scheme ? $.scheme + ":" : "") + "//" + X; + let G = X.match(Mw); + if (G) { + if (Y.scheme = G[1], Y.userinfo = G[3], Y.host = G[4], Y.port = parseInt(G[5], 10), Y.path = G[6] || "", Y.query = G[7], Y.fragment = G[8], isNaN(Y.port)) Y.port = G[5]; + if (Y.host) { + let B = qw(Y.host); + if (B.isIPV4 === false) { + let z2 = Lw(B.host); + Y.host = z2.host.toLowerCase(), J = z2.isIPV6; + } else Y.host = B.host, J = true; + } + if (Y.scheme === void 0 && Y.userinfo === void 0 && Y.host === void 0 && Y.port === void 0 && Y.query === void 0 && !Y.path) Y.reference = "same-document"; + else if (Y.scheme === void 0) Y.reference = "relative"; + else if (Y.fragment === void 0) Y.reference = "absolute"; + else Y.reference = "uri"; + if ($.reference && $.reference !== "suffix" && $.reference !== Y.reference) Y.error = Y.error || "URI is not a " + $.reference + " reference."; + let H = ZY[($.scheme || Y.scheme || "").toLowerCase()]; + if (!$.unicodeSupport && (!H || !H.unicodeSupport)) { + if (Y.host && ($.domainHost || H && H.domainHost) && J === false && ww(Y.host)) try { + Y.host = URL.domainToASCII(Y.host.toLowerCase()); + } catch (B) { + Y.error = Y.error || "Host's domain name can not be converted to ASCII: " + B; + } + } + if (!H || H && !H.skipNormalize) { + if (W && Y.scheme !== void 0) Y.scheme = unescape(Y.scheme); + if (W && Y.host !== void 0) Y.host = unescape(Y.host); + if (Y.path) Y.path = escape(unescape(Y.path)); + if (Y.fragment) Y.fragment = encodeURI(decodeURIComponent(Y.fragment)); + } + if (H && H.parse) H.parse(Y, $); + } else Y.error = Y.error || "URI can not be parsed."; + return Y; + } + var CY = { SCHEMES: ZY, normalize: Nw, resolve: Ow, resolveComponents: UH, equal: Dw, serialize: V1, parse: I1 }; + g9.exports = CY; + g9.exports.default = CY; + g9.exports.fastUri = CY; +}); +var FH = P((qH) => { + Object.defineProperty(qH, "__esModule", { value: true }); + var LH = VH(); + LH.code = 'require("ajv/dist/runtime/uri").default'; + qH.default = LH; +}); +var RH = P((b1) => { + Object.defineProperty(b1, "__esModule", { value: true }); + b1.CodeGen = b1.Name = b1.nil = b1.stringify = b1.str = b1._ = b1.KeywordCxt = void 0; + var Rw = iX(); + Object.defineProperty(b1, "KeywordCxt", { enumerable: true, get: function() { + return Rw.KeywordCxt; + } }); + var p6 = c(); + Object.defineProperty(b1, "_", { enumerable: true, get: function() { + return p6._; + } }); + Object.defineProperty(b1, "str", { enumerable: true, get: function() { + return p6.str; + } }); + Object.defineProperty(b1, "stringify", { enumerable: true, get: function() { + return p6.stringify; + } }); + Object.defineProperty(b1, "nil", { enumerable: true, get: function() { + return p6.nil; + } }); + Object.defineProperty(b1, "Name", { enumerable: true, get: function() { + return p6.Name; + } }); + Object.defineProperty(b1, "CodeGen", { enumerable: true, get: function() { + return p6.CodeGen; + } }); + var Ew = v9(), wH = nX(), Iw = KY(), tX = _9(), bw = c(), aX = cX(), h9 = mX(), vY = e(), NH = r3(), Pw = FH(), MH = (X, Q) => new RegExp(X, Q); + MH.code = "new RegExp"; + var Sw = ["removeAdditional", "useDefaults", "coerceTypes"], Zw = /* @__PURE__ */ new Set(["validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error"]), Cw = { errorDataPath: "", format: "`validateFormats: false` can be used instead.", nullable: '"nullable" keyword is supported by default.', jsonPointers: "Deprecated jsPropertySyntax can be used instead.", extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", sourceCode: "Use option `code: {source: true}`", strictDefaults: "It is default now, see option `strict`.", strictKeywords: "It is default now, see option `strict`.", uniqueItems: '"uniqueItems" keyword is always validated.', unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", cache: "Map is used as cache, schema object as key.", serialize: "Map is used as cache, schema object as key.", ajvErrors: "It is default now." }, kw = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }, OH = 200; + function vw(X) { + var Q, $, Y, W, J, G, H, B, z2, K, V, L, U, F, q, N, A, M, R, S, C, K0, U0, s, D0; + let q0 = X.strict, W1 = (Q = X.code) === null || Q === void 0 ? void 0 : Q.optimize, P1 = W1 === true || W1 === void 0 ? 1 : W1 || 0, U6 = (Y = ($ = X.code) === null || $ === void 0 ? void 0 : $.regExp) !== null && Y !== void 0 ? Y : MH, d = (W = X.uriResolver) !== null && W !== void 0 ? W : Pw.default; + return { strictSchema: (G = (J = X.strictSchema) !== null && J !== void 0 ? J : q0) !== null && G !== void 0 ? G : true, strictNumbers: (B = (H = X.strictNumbers) !== null && H !== void 0 ? H : q0) !== null && B !== void 0 ? B : true, strictTypes: (K = (z2 = X.strictTypes) !== null && z2 !== void 0 ? z2 : q0) !== null && K !== void 0 ? K : "log", strictTuples: (L = (V = X.strictTuples) !== null && V !== void 0 ? V : q0) !== null && L !== void 0 ? L : "log", strictRequired: (F = (U = X.strictRequired) !== null && U !== void 0 ? U : q0) !== null && F !== void 0 ? F : false, code: X.code ? { ...X.code, optimize: P1, regExp: U6 } : { optimize: P1, regExp: U6 }, loopRequired: (q = X.loopRequired) !== null && q !== void 0 ? q : OH, loopEnum: (N = X.loopEnum) !== null && N !== void 0 ? N : OH, meta: (A = X.meta) !== null && A !== void 0 ? A : true, messages: (M = X.messages) !== null && M !== void 0 ? M : true, inlineRefs: (R = X.inlineRefs) !== null && R !== void 0 ? R : true, schemaId: (S = X.schemaId) !== null && S !== void 0 ? S : "$id", addUsedSchema: (C = X.addUsedSchema) !== null && C !== void 0 ? C : true, validateSchema: (K0 = X.validateSchema) !== null && K0 !== void 0 ? K0 : true, validateFormats: (U0 = X.validateFormats) !== null && U0 !== void 0 ? U0 : true, unicodeRegExp: (s = X.unicodeRegExp) !== null && s !== void 0 ? s : true, int32range: (D0 = X.int32range) !== null && D0 !== void 0 ? D0 : true, uriResolver: d }; + } + class f9 { + constructor(X = {}) { + this.schemas = {}, this.refs = {}, this.formats = {}, this._compilations = /* @__PURE__ */ new Set(), this._loading = {}, this._cache = /* @__PURE__ */ new Map(), X = this.opts = { ...X, ...vw(X) }; + let { es5: Q, lines: $ } = this.opts.code; + this.scope = new bw.ValueScope({ scope: {}, prefixes: Zw, es5: Q, lines: $ }), this.logger = hw(X.logger); + let Y = X.validateFormats; + if (X.validateFormats = false, this.RULES = (0, Iw.getRules)(), DH.call(this, Cw, X, "NOT SUPPORTED"), DH.call(this, kw, X, "DEPRECATED", "warn"), this._metaOpts = yw.call(this), X.formats) _w.call(this); + if (this._addVocabularies(), this._addDefaultMetaSchema(), X.keywords) xw.call(this, X.keywords); + if (typeof X.meta == "object") this.addMetaSchema(X.meta); + Tw.call(this), X.validateFormats = Y; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + let { $data: X, meta: Q, schemaId: $ } = this.opts, Y = NH; + if ($ === "id") Y = { ...NH }, Y.id = Y.$id, delete Y.$id; + if (Q && X) this.addMetaSchema(Y, Y[$], false); + } + defaultMeta() { + let { meta: X, schemaId: Q } = this.opts; + return this.opts.defaultMeta = typeof X == "object" ? X[Q] || X : void 0; + } + validate(X, Q) { + let $; + if (typeof X == "string") { + if ($ = this.getSchema(X), !$) throw Error(`no schema with key or ref "${X}"`); + } else $ = this.compile(X); + let Y = $(Q); + if (!("$async" in $)) this.errors = $.errors; + return Y; + } + compile(X, Q) { + let $ = this._addSchema(X, Q); + return $.validate || this._compileSchemaEnv($); + } + compileAsync(X, Q) { + if (typeof this.opts.loadSchema != "function") throw Error("options.loadSchema should be a function"); + let { loadSchema: $ } = this.opts; + return Y.call(this, X, Q); + async function Y(z2, K) { + await W.call(this, z2.$schema); + let V = this._addSchema(z2, K); + return V.validate || J.call(this, V); + } + async function W(z2) { + if (z2 && !this.getSchema(z2)) await Y.call(this, { $ref: z2 }, true); + } + async function J(z2) { + try { + return this._compileSchemaEnv(z2); + } catch (K) { + if (!(K instanceof wH.default)) throw K; + return G.call(this, K), await H.call(this, K.missingSchema), J.call(this, z2); + } + } + function G({ missingSchema: z2, missingRef: K }) { + if (this.refs[z2]) throw Error(`AnySchema ${z2} is loaded but ${K} cannot be resolved`); + } + async function H(z2) { + let K = await B.call(this, z2); + if (!this.refs[z2]) await W.call(this, K.$schema); + if (!this.refs[z2]) this.addSchema(K, z2, Q); + } + async function B(z2) { + let K = this._loading[z2]; + if (K) return K; + try { + return await (this._loading[z2] = $(z2)); + } finally { + delete this._loading[z2]; + } + } + } + addSchema(X, Q, $, Y = this.opts.validateSchema) { + if (Array.isArray(X)) { + for (let J of X) this.addSchema(J, void 0, $, Y); + return this; + } + let W; + if (typeof X === "object") { + let { schemaId: J } = this.opts; + if (W = X[J], W !== void 0 && typeof W != "string") throw Error(`schema ${J} must be string`); + } + return Q = (0, aX.normalizeId)(Q || W), this._checkUnique(Q), this.schemas[Q] = this._addSchema(X, $, Q, Y, true), this; + } + addMetaSchema(X, Q, $ = this.opts.validateSchema) { + return this.addSchema(X, Q, true, $), this; + } + validateSchema(X, Q) { + if (typeof X == "boolean") return true; + let $; + if ($ = X.$schema, $ !== void 0 && typeof $ != "string") throw Error("$schema must be a string"); + if ($ = $ || this.opts.defaultMeta || this.defaultMeta(), !$) return this.logger.warn("meta-schema not available"), this.errors = null, true; + let Y = this.validate($, X); + if (!Y && Q) { + let W = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(W); + else throw Error(W); + } + return Y; + } + getSchema(X) { + let Q; + while (typeof (Q = AH.call(this, X)) == "string") X = Q; + if (Q === void 0) { + let { schemaId: $ } = this.opts, Y = new tX.SchemaEnv({ schema: {}, schemaId: $ }); + if (Q = tX.resolveSchema.call(this, Y, X), !Q) return; + this.refs[X] = Q; + } + return Q.validate || this._compileSchemaEnv(Q); + } + removeSchema(X) { + if (X instanceof RegExp) return this._removeAllSchemas(this.schemas, X), this._removeAllSchemas(this.refs, X), this; + switch (typeof X) { + case "undefined": + return this._removeAllSchemas(this.schemas), this._removeAllSchemas(this.refs), this._cache.clear(), this; + case "string": { + let Q = AH.call(this, X); + if (typeof Q == "object") this._cache.delete(Q.schema); + return delete this.schemas[X], delete this.refs[X], this; + } + case "object": { + let Q = X; + this._cache.delete(Q); + let $ = X[this.opts.schemaId]; + if ($) $ = (0, aX.normalizeId)($), delete this.schemas[$], delete this.refs[$]; + return this; + } + default: + throw Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(X) { + for (let Q of X) this.addKeyword(Q); + return this; + } + addKeyword(X, Q) { + let $; + if (typeof X == "string") { + if ($ = X, typeof Q == "object") this.logger.warn("these parameters are deprecated, see docs for addKeyword"), Q.keyword = $; + } else if (typeof X == "object" && Q === void 0) { + if (Q = X, $ = Q.keyword, Array.isArray($) && !$.length) throw Error("addKeywords: keyword must be string or non-empty array"); + } else throw Error("invalid addKeywords parameters"); + if (uw.call(this, $, Q), !Q) return (0, vY.eachItem)($, (W) => kY.call(this, W)), this; + mw.call(this, Q); + let Y = { ...Q, type: (0, h9.getJSONTypes)(Q.type), schemaType: (0, h9.getJSONTypes)(Q.schemaType) }; + return (0, vY.eachItem)($, Y.type.length === 0 ? (W) => kY.call(this, W, Y) : (W) => Y.type.forEach((J) => kY.call(this, W, Y, J))), this; + } + getKeyword(X) { + let Q = this.RULES.all[X]; + return typeof Q == "object" ? Q.definition : !!Q; + } + removeKeyword(X) { + let { RULES: Q } = this; + delete Q.keywords[X], delete Q.all[X]; + for (let $ of Q.rules) { + let Y = $.rules.findIndex((W) => W.keyword === X); + if (Y >= 0) $.rules.splice(Y, 1); + } + return this; + } + addFormat(X, Q) { + if (typeof Q == "string") Q = new RegExp(Q); + return this.formats[X] = Q, this; + } + errorsText(X = this.errors, { separator: Q = ", ", dataVar: $ = "data" } = {}) { + if (!X || X.length === 0) return "No errors"; + return X.map((Y) => `${$}${Y.instancePath} ${Y.message}`).reduce((Y, W) => Y + Q + W); + } + $dataMetaSchema(X, Q) { + let $ = this.RULES.all; + X = JSON.parse(JSON.stringify(X)); + for (let Y of Q) { + let W = Y.split("/").slice(1), J = X; + for (let G of W) J = J[G]; + for (let G in $) { + let H = $[G]; + if (typeof H != "object") continue; + let { $data: B } = H.definition, z2 = J[G]; + if (B && z2) J[G] = jH(z2); + } + } + return X; + } + _removeAllSchemas(X, Q) { + for (let $ in X) { + let Y = X[$]; + if (!Q || Q.test($)) { + if (typeof Y == "string") delete X[$]; + else if (Y && !Y.meta) this._cache.delete(Y.schema), delete X[$]; + } + } + } + _addSchema(X, Q, $, Y = this.opts.validateSchema, W = this.opts.addUsedSchema) { + let J, { schemaId: G } = this.opts; + if (typeof X == "object") J = X[G]; + else if (this.opts.jtd) throw Error("schema must be object"); + else if (typeof X != "boolean") throw Error("schema must be object or boolean"); + let H = this._cache.get(X); + if (H !== void 0) return H; + $ = (0, aX.normalizeId)(J || $); + let B = aX.getSchemaRefs.call(this, X, $); + if (H = new tX.SchemaEnv({ schema: X, schemaId: G, meta: Q, baseId: $, localRefs: B }), this._cache.set(H.schema, H), W && !$.startsWith("#")) { + if ($) this._checkUnique($); + this.refs[$] = H; + } + if (Y) this.validateSchema(X, true); + return H; + } + _checkUnique(X) { + if (this.schemas[X] || this.refs[X]) throw Error(`schema with key or id "${X}" already exists`); + } + _compileSchemaEnv(X) { + if (X.meta) this._compileMetaSchema(X); + else tX.compileSchema.call(this, X); + if (!X.validate) throw Error("ajv implementation error"); + return X.validate; + } + _compileMetaSchema(X) { + let Q = this.opts; + this.opts = this._metaOpts; + try { + tX.compileSchema.call(this, X); + } finally { + this.opts = Q; + } + } + } + f9.ValidationError = Ew.default; + f9.MissingRefError = wH.default; + b1.default = f9; + function DH(X, Q, $, Y = "error") { + for (let W in X) { + let J = W; + if (J in Q) this.logger[Y](`${$}: option ${W}. ${X[J]}`); + } + } + function AH(X) { + return X = (0, aX.normalizeId)(X), this.schemas[X] || this.refs[X]; + } + function Tw() { + let X = this.opts.schemas; + if (!X) return; + if (Array.isArray(X)) this.addSchema(X); + else for (let Q in X) this.addSchema(X[Q], Q); + } + function _w() { + for (let X in this.opts.formats) { + let Q = this.opts.formats[X]; + if (Q) this.addFormat(X, Q); + } + } + function xw(X) { + if (Array.isArray(X)) { + this.addVocabulary(X); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (let Q in X) { + let $ = X[Q]; + if (!$.keyword) $.keyword = Q; + this.addKeyword($); + } + } + function yw() { + let X = { ...this.opts }; + for (let Q of Sw) delete X[Q]; + return X; + } + var gw = { log() { + }, warn() { + }, error() { + } }; + function hw(X) { + if (X === false) return gw; + if (X === void 0) return console; + if (X.log && X.warn && X.error) return X; + throw Error("logger must implement log, warn and error methods"); + } + var fw = /^[a-z_$][a-z0-9_$:-]*$/i; + function uw(X, Q) { + let { RULES: $ } = this; + if ((0, vY.eachItem)(X, (Y) => { + if ($.keywords[Y]) throw Error(`Keyword ${Y} is already defined`); + if (!fw.test(Y)) throw Error(`Keyword ${Y} has invalid name`); + }), !Q) return; + if (Q.$data && !("code" in Q || "validate" in Q)) throw Error('$data keyword must have "code" or "validate" function'); + } + function kY(X, Q, $) { + var Y; + let W = Q === null || Q === void 0 ? void 0 : Q.post; + if ($ && W) throw Error('keyword with "post" flag cannot have "type"'); + let { RULES: J } = this, G = W ? J.post : J.rules.find(({ type: B }) => B === $); + if (!G) G = { type: $, rules: [] }, J.rules.push(G); + if (J.keywords[X] = true, !Q) return; + let H = { keyword: X, definition: { ...Q, type: (0, h9.getJSONTypes)(Q.type), schemaType: (0, h9.getJSONTypes)(Q.schemaType) } }; + if (Q.before) lw.call(this, G, H, Q.before); + else G.rules.push(H); + J.all[X] = H, (Y = Q.implements) === null || Y === void 0 || Y.forEach((B) => this.addKeyword(B)); + } + function lw(X, Q, $) { + let Y = X.rules.findIndex((W) => W.keyword === $); + if (Y >= 0) X.rules.splice(Y, 0, Q); + else X.rules.push(Q), this.logger.warn(`rule ${$} is not defined`); + } + function mw(X) { + let { metaSchema: Q } = X; + if (Q === void 0) return; + if (X.$data && this.opts.$data) Q = jH(Q); + X.validateSchema = this.compile(Q, true); + } + var cw = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function jH(X) { + return { anyOf: [X, cw] }; + } +}); +var IH = P((EH) => { + Object.defineProperty(EH, "__esModule", { value: true }); + var iw = { keyword: "id", code() { + throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } }; + EH.default = iw; +}); +var kH = P((ZH) => { + Object.defineProperty(ZH, "__esModule", { value: true }); + ZH.callRef = ZH.getValidate = void 0; + var rw = nX(), bH = d0(), g0 = c(), d6 = R1(), PH = _9(), u9 = e(), ow = { keyword: "$ref", schemaType: "string", code(X) { + let { gen: Q, schema: $, it: Y } = X, { baseId: W, schemaEnv: J, validateName: G, opts: H, self: B } = Y, { root: z2 } = J; + if (($ === "#" || $ === "#/") && W === z2.baseId) return V(); + let K = PH.resolveRef.call(B, z2, W, $); + if (K === void 0) throw new rw.default(Y.opts.uriResolver, W, $); + if (K instanceof PH.SchemaEnv) return L(K); + return U(K); + function V() { + if (J === z2) return l9(X, G, J, J.$async); + let F = Q.scopeValue("root", { ref: z2 }); + return l9(X, g0._`${F}.validate`, z2, z2.$async); + } + function L(F) { + let q = SH(X, F); + l9(X, q, F, F.$async); + } + function U(F) { + let q = Q.scopeValue("schema", H.code.source === true ? { ref: F, code: (0, g0.stringify)(F) } : { ref: F }), N = Q.name("valid"), A = X.subschema({ schema: F, dataTypes: [], schemaPath: g0.nil, topSchemaRef: q, errSchemaPath: $ }, N); + X.mergeEvaluated(A), X.ok(N); + } + } }; + function SH(X, Q) { + let { gen: $ } = X; + return Q.validate ? $.scopeValue("validate", { ref: Q.validate }) : g0._`${$.scopeValue("wrapper", { ref: Q })}.validate`; + } + ZH.getValidate = SH; + function l9(X, Q, $, Y) { + let { gen: W, it: J } = X, { allErrors: G, schemaEnv: H, opts: B } = J, z2 = B.passContext ? d6.default.this : g0.nil; + if (Y) K(); + else V(); + function K() { + if (!H.$async) throw Error("async schema referenced by sync schema"); + let F = W.let("valid"); + W.try(() => { + if (W.code(g0._`await ${(0, bH.callValidateCode)(X, Q, z2)}`), U(Q), !G) W.assign(F, true); + }, (q) => { + if (W.if(g0._`!(${q} instanceof ${J.ValidationError})`, () => W.throw(q)), L(q), !G) W.assign(F, false); + }), X.ok(F); + } + function V() { + X.result((0, bH.callValidateCode)(X, Q, z2), () => U(Q), () => L(Q)); + } + function L(F) { + let q = g0._`${F}.errors`; + W.assign(d6.default.vErrors, g0._`${d6.default.vErrors} === null ? ${q} : ${d6.default.vErrors}.concat(${q})`), W.assign(d6.default.errors, g0._`${d6.default.vErrors}.length`); + } + function U(F) { + var q; + if (!J.opts.unevaluated) return; + let N = (q = $ === null || $ === void 0 ? void 0 : $.validate) === null || q === void 0 ? void 0 : q.evaluated; + if (J.props !== true) if (N && !N.dynamicProps) { + if (N.props !== void 0) J.props = u9.mergeEvaluated.props(W, N.props, J.props); + } else { + let A = W.var("props", g0._`${F}.evaluated.props`); + J.props = u9.mergeEvaluated.props(W, A, J.props, g0.Name); + } + if (J.items !== true) if (N && !N.dynamicItems) { + if (N.items !== void 0) J.items = u9.mergeEvaluated.items(W, N.items, J.items); + } else { + let A = W.var("items", g0._`${F}.evaluated.items`); + J.items = u9.mergeEvaluated.items(W, A, J.items, g0.Name); + } + } + } + ZH.callRef = l9; + ZH.default = ow; +}); +var TH = P((vH) => { + Object.defineProperty(vH, "__esModule", { value: true }); + var sw = IH(), ew = kH(), XM = ["$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", sw.default, ew.default]; + vH.default = XM; +}); +var xH = P((_H) => { + Object.defineProperty(_H, "__esModule", { value: true }); + var m9 = c(), d1 = m9.operators, c9 = { maximum: { okStr: "<=", ok: d1.LTE, fail: d1.GT }, minimum: { okStr: ">=", ok: d1.GTE, fail: d1.LT }, exclusiveMaximum: { okStr: "<", ok: d1.LT, fail: d1.GTE }, exclusiveMinimum: { okStr: ">", ok: d1.GT, fail: d1.LTE } }, $M = { message: ({ keyword: X, schemaCode: Q }) => m9.str`must be ${c9[X].okStr} ${Q}`, params: ({ keyword: X, schemaCode: Q }) => m9._`{comparison: ${c9[X].okStr}, limit: ${Q}}` }, YM = { keyword: Object.keys(c9), type: "number", schemaType: "number", $data: true, error: $M, code(X) { + let { keyword: Q, data: $, schemaCode: Y } = X; + X.fail$data(m9._`${$} ${c9[Q].fail} ${Y} || isNaN(${$})`); + } }; + _H.default = YM; +}); +var gH = P((yH) => { + Object.defineProperty(yH, "__esModule", { value: true }); + var sX = c(), JM = { message: ({ schemaCode: X }) => sX.str`must be multiple of ${X}`, params: ({ schemaCode: X }) => sX._`{multipleOf: ${X}}` }, GM = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error: JM, code(X) { + let { gen: Q, data: $, schemaCode: Y, it: W } = X, J = W.opts.multipleOfPrecision, G = Q.let("res"), H = J ? sX._`Math.abs(Math.round(${G}) - ${G}) > 1e-${J}` : sX._`${G} !== parseInt(${G})`; + X.fail$data(sX._`(${Y} === 0 || (${G} = ${$}/${Y}, ${H}))`); + } }; + yH.default = GM; +}); +var uH = P((fH) => { + Object.defineProperty(fH, "__esModule", { value: true }); + function hH(X) { + let Q = X.length, $ = 0, Y = 0, W; + while (Y < Q) if ($++, W = X.charCodeAt(Y++), W >= 55296 && W <= 56319 && Y < Q) { + if (W = X.charCodeAt(Y), (W & 64512) === 56320) Y++; + } + return $; + } + fH.default = hH; + hH.code = 'require("ajv/dist/runtime/ucs2length").default'; +}); +var mH = P((lH) => { + Object.defineProperty(lH, "__esModule", { value: true }); + var z6 = c(), zM = e(), KM = uH(), UM = { message({ keyword: X, schemaCode: Q }) { + let $ = X === "maxLength" ? "more" : "fewer"; + return z6.str`must NOT have ${$} than ${Q} characters`; + }, params: ({ schemaCode: X }) => z6._`{limit: ${X}}` }, VM = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error: UM, code(X) { + let { keyword: Q, data: $, schemaCode: Y, it: W } = X, J = Q === "maxLength" ? z6.operators.GT : z6.operators.LT, G = W.opts.unicode === false ? z6._`${$}.length` : z6._`${(0, zM.useFunc)(X.gen, KM.default)}(${$})`; + X.fail$data(z6._`${G} ${J} ${Y}`); + } }; + lH.default = VM; +}); +var pH = P((cH) => { + Object.defineProperty(cH, "__esModule", { value: true }); + var qM = d0(), p9 = c(), FM = { message: ({ schemaCode: X }) => p9.str`must match pattern "${X}"`, params: ({ schemaCode: X }) => p9._`{pattern: ${X}}` }, NM = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error: FM, code(X) { + let { data: Q, $data: $, schema: Y, schemaCode: W, it: J } = X, G = J.opts.unicodeRegExp ? "u" : "", H = $ ? p9._`(new RegExp(${W}, ${G}))` : (0, qM.usePattern)(X, Y); + X.fail$data(p9._`!${H}.test(${Q})`); + } }; + cH.default = NM; +}); +var iH = P((dH) => { + Object.defineProperty(dH, "__esModule", { value: true }); + var eX = c(), DM = { message({ keyword: X, schemaCode: Q }) { + let $ = X === "maxProperties" ? "more" : "fewer"; + return eX.str`must NOT have ${$} than ${Q} properties`; + }, params: ({ schemaCode: X }) => eX._`{limit: ${X}}` }, AM = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error: DM, code(X) { + let { keyword: Q, data: $, schemaCode: Y } = X, W = Q === "maxProperties" ? eX.operators.GT : eX.operators.LT; + X.fail$data(eX._`Object.keys(${$}).length ${W} ${Y}`); + } }; + dH.default = AM; +}); +var rH = P((nH) => { + Object.defineProperty(nH, "__esModule", { value: true }); + var X4 = d0(), Q4 = c(), MM = e(), jM = { message: ({ params: { missingProperty: X } }) => Q4.str`must have required property '${X}'`, params: ({ params: { missingProperty: X } }) => Q4._`{missingProperty: ${X}}` }, RM = { keyword: "required", type: "object", schemaType: "array", $data: true, error: jM, code(X) { + let { gen: Q, schema: $, schemaCode: Y, data: W, $data: J, it: G } = X, { opts: H } = G; + if (!J && $.length === 0) return; + let B = $.length >= H.loopRequired; + if (G.allErrors) z2(); + else K(); + if (H.strictRequired) { + let U = X.parentSchema.properties, { definedProperties: F } = X.it; + for (let q of $) if ((U === null || U === void 0 ? void 0 : U[q]) === void 0 && !F.has(q)) { + let N = G.schemaEnv.baseId + G.errSchemaPath, A = `required property "${q}" is not defined at "${N}" (strictRequired)`; + (0, MM.checkStrictMode)(G, A, G.opts.strictRequired); + } + } + function z2() { + if (B || J) X.block$data(Q4.nil, V); + else for (let U of $) (0, X4.checkReportMissingProp)(X, U); + } + function K() { + let U = Q.let("missing"); + if (B || J) { + let F = Q.let("valid", true); + X.block$data(F, () => L(U, F)), X.ok(F); + } else Q.if((0, X4.checkMissingProp)(X, $, U)), (0, X4.reportMissingProp)(X, U), Q.else(); + } + function V() { + Q.forOf("prop", Y, (U) => { + X.setParams({ missingProperty: U }), Q.if((0, X4.noPropertyInData)(Q, W, U, H.ownProperties), () => X.error()); + }); + } + function L(U, F) { + X.setParams({ missingProperty: U }), Q.forOf(U, Y, () => { + Q.assign(F, (0, X4.propertyInData)(Q, W, U, H.ownProperties)), Q.if((0, Q4.not)(F), () => { + X.error(), Q.break(); + }); + }, Q4.nil); + } + } }; + nH.default = RM; +}); +var tH = P((oH) => { + Object.defineProperty(oH, "__esModule", { value: true }); + var $4 = c(), IM = { message({ keyword: X, schemaCode: Q }) { + let $ = X === "maxItems" ? "more" : "fewer"; + return $4.str`must NOT have ${$} than ${Q} items`; + }, params: ({ schemaCode: X }) => $4._`{limit: ${X}}` }, bM = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error: IM, code(X) { + let { keyword: Q, data: $, schemaCode: Y } = X, W = Q === "maxItems" ? $4.operators.GT : $4.operators.LT; + X.fail$data($4._`${$}.length ${W} ${Y}`); + } }; + oH.default = bM; +}); +var d9 = P((sH) => { + Object.defineProperty(sH, "__esModule", { value: true }); + var aH = DY(); + aH.code = 'require("ajv/dist/runtime/equal").default'; + sH.default = aH; +}); +var XB = P((eH) => { + Object.defineProperty(eH, "__esModule", { value: true }); + var TY = mX(), E0 = c(), ZM = e(), CM = d9(), kM = { message: ({ params: { i: X, j: Q } }) => E0.str`must NOT have duplicate items (items ## ${Q} and ${X} are identical)`, params: ({ params: { i: X, j: Q } }) => E0._`{i: ${X}, j: ${Q}}` }, vM = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error: kM, code(X) { + let { gen: Q, data: $, $data: Y, schema: W, parentSchema: J, schemaCode: G, it: H } = X; + if (!Y && !W) return; + let B = Q.let("valid"), z2 = J.items ? (0, TY.getSchemaTypes)(J.items) : []; + X.block$data(B, K, E0._`${G} === false`), X.ok(B); + function K() { + let F = Q.let("i", E0._`${$}.length`), q = Q.let("j"); + X.setParams({ i: F, j: q }), Q.assign(B, true), Q.if(E0._`${F} > 1`, () => (V() ? L : U)(F, q)); + } + function V() { + return z2.length > 0 && !z2.some((F) => F === "object" || F === "array"); + } + function L(F, q) { + let N = Q.name("item"), A = (0, TY.checkDataTypes)(z2, N, H.opts.strictNumbers, TY.DataType.Wrong), M = Q.const("indices", E0._`{}`); + Q.for(E0._`;${F}--;`, () => { + if (Q.let(N, E0._`${$}[${F}]`), Q.if(A, E0._`continue`), z2.length > 1) Q.if(E0._`typeof ${N} == "string"`, E0._`${N} += "_"`); + Q.if(E0._`typeof ${M}[${N}] == "number"`, () => { + Q.assign(q, E0._`${M}[${N}]`), X.error(), Q.assign(B, false).break(); + }).code(E0._`${M}[${N}] = ${F}`); + }); + } + function U(F, q) { + let N = (0, ZM.useFunc)(Q, CM.default), A = Q.name("outer"); + Q.label(A).for(E0._`;${F}--;`, () => Q.for(E0._`${q} = ${F}; ${q}--;`, () => Q.if(E0._`${N}(${$}[${F}], ${$}[${q}])`, () => { + X.error(), Q.assign(B, false).break(A); + }))); + } + } }; + eH.default = vM; +}); +var $B = P((QB) => { + Object.defineProperty(QB, "__esModule", { value: true }); + var _Y = c(), _M = e(), xM = d9(), yM = { message: "must be equal to constant", params: ({ schemaCode: X }) => _Y._`{allowedValue: ${X}}` }, gM = { keyword: "const", $data: true, error: yM, code(X) { + let { gen: Q, data: $, $data: Y, schemaCode: W, schema: J } = X; + if (Y || J && typeof J == "object") X.fail$data(_Y._`!${(0, _M.useFunc)(Q, xM.default)}(${$}, ${W})`); + else X.fail(_Y._`${J} !== ${$}`); + } }; + QB.default = gM; +}); +var WB = P((YB) => { + Object.defineProperty(YB, "__esModule", { value: true }); + var Y4 = c(), fM = e(), uM = d9(), lM = { message: "must be equal to one of the allowed values", params: ({ schemaCode: X }) => Y4._`{allowedValues: ${X}}` }, mM = { keyword: "enum", schemaType: "array", $data: true, error: lM, code(X) { + let { gen: Q, data: $, $data: Y, schema: W, schemaCode: J, it: G } = X; + if (!Y && W.length === 0) throw Error("enum must have non-empty array"); + let H = W.length >= G.opts.loopEnum, B, z2 = () => B !== null && B !== void 0 ? B : B = (0, fM.useFunc)(Q, uM.default), K; + if (H || Y) K = Q.let("valid"), X.block$data(K, V); + else { + if (!Array.isArray(W)) throw Error("ajv implementation error"); + let U = Q.const("vSchema", J); + K = (0, Y4.or)(...W.map((F, q) => L(U, q))); + } + X.pass(K); + function V() { + Q.assign(K, false), Q.forOf("v", J, (U) => Q.if(Y4._`${z2()}(${$}, ${U})`, () => Q.assign(K, true).break())); + } + function L(U, F) { + let q = W[F]; + return typeof q === "object" && q !== null ? Y4._`${z2()}(${$}, ${U}[${F}])` : Y4._`${$} === ${q}`; + } + } }; + YB.default = mM; +}); +var GB = P((JB) => { + Object.defineProperty(JB, "__esModule", { value: true }); + var pM = xH(), dM = gH(), iM = mH(), nM = pH(), rM = iH(), oM = rH(), tM = tH(), aM = XB(), sM = $B(), eM = WB(), Xj = [pM.default, dM.default, iM.default, nM.default, rM.default, oM.default, tM.default, aM.default, { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, sM.default, eM.default]; + JB.default = Xj; +}); +var yY = P((BB) => { + Object.defineProperty(BB, "__esModule", { value: true }); + BB.validateAdditionalItems = void 0; + var K6 = c(), xY = e(), $j = { message: ({ params: { len: X } }) => K6.str`must NOT have more than ${X} items`, params: ({ params: { len: X } }) => K6._`{limit: ${X}}` }, Yj = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error: $j, code(X) { + let { parentSchema: Q, it: $ } = X, { items: Y } = Q; + if (!Array.isArray(Y)) { + (0, xY.checkStrictMode)($, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + HB(X, Y); + } }; + function HB(X, Q) { + let { gen: $, schema: Y, data: W, keyword: J, it: G } = X; + G.items = true; + let H = $.const("len", K6._`${W}.length`); + if (Y === false) X.setParams({ len: Q.length }), X.pass(K6._`${H} <= ${Q.length}`); + else if (typeof Y == "object" && !(0, xY.alwaysValidSchema)(G, Y)) { + let z2 = $.var("valid", K6._`${H} <= ${Q.length}`); + $.if((0, K6.not)(z2), () => B(z2)), X.ok(z2); + } + function B(z2) { + $.forRange("i", Q.length, H, (K) => { + if (X.subschema({ keyword: J, dataProp: K, dataPropType: xY.Type.Num }, z2), !G.allErrors) $.if((0, K6.not)(z2), () => $.break()); + }); + } + } + BB.validateAdditionalItems = HB; + BB.default = Yj; +}); +var gY = P((VB) => { + Object.defineProperty(VB, "__esModule", { value: true }); + VB.validateTuple = void 0; + var KB = c(), i9 = e(), Jj = d0(), Gj = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code(X) { + let { schema: Q, it: $ } = X; + if (Array.isArray(Q)) return UB(X, "additionalItems", Q); + if ($.items = true, (0, i9.alwaysValidSchema)($, Q)) return; + X.ok((0, Jj.validateArray)(X)); + } }; + function UB(X, Q, $ = X.schema) { + let { gen: Y, parentSchema: W, data: J, keyword: G, it: H } = X; + if (K(W), H.opts.unevaluated && $.length && H.items !== true) H.items = i9.mergeEvaluated.items(Y, $.length, H.items); + let B = Y.name("valid"), z2 = Y.const("len", KB._`${J}.length`); + $.forEach((V, L) => { + if ((0, i9.alwaysValidSchema)(H, V)) return; + Y.if(KB._`${z2} > ${L}`, () => X.subschema({ keyword: G, schemaProp: L, dataProp: L }, B)), X.ok(B); + }); + function K(V) { + let { opts: L, errSchemaPath: U } = H, F = $.length, q = F === V.minItems && (F === V.maxItems || V[Q] === false); + if (L.strictTuples && !q) { + let N = `"${G}" is ${F}-tuple, but minItems or maxItems/${Q} are not specified or different at path "${U}"`; + (0, i9.checkStrictMode)(H, N, L.strictTuples); + } + } + } + VB.validateTuple = UB; + VB.default = Gj; +}); +var FB = P((qB) => { + Object.defineProperty(qB, "__esModule", { value: true }); + var Bj = gY(), zj = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: (X) => (0, Bj.validateTuple)(X, "items") }; + qB.default = zj; +}); +var DB = P((OB) => { + Object.defineProperty(OB, "__esModule", { value: true }); + var NB = c(), Uj = e(), Vj = d0(), Lj = yY(), qj = { message: ({ params: { len: X } }) => NB.str`must NOT have more than ${X} items`, params: ({ params: { len: X } }) => NB._`{limit: ${X}}` }, Fj = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error: qj, code(X) { + let { schema: Q, parentSchema: $, it: Y } = X, { prefixItems: W } = $; + if (Y.items = true, (0, Uj.alwaysValidSchema)(Y, Q)) return; + if (W) (0, Lj.validateAdditionalItems)(X, W); + else X.ok((0, Vj.validateArray)(X)); + } }; + OB.default = Fj; +}); +var wB = P((AB) => { + Object.defineProperty(AB, "__esModule", { value: true }); + var i0 = c(), n9 = e(), Oj = { message: ({ params: { min: X, max: Q } }) => Q === void 0 ? i0.str`must contain at least ${X} valid item(s)` : i0.str`must contain at least ${X} and no more than ${Q} valid item(s)`, params: ({ params: { min: X, max: Q } }) => Q === void 0 ? i0._`{minContains: ${X}}` : i0._`{minContains: ${X}, maxContains: ${Q}}` }, Dj = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error: Oj, code(X) { + let { gen: Q, schema: $, parentSchema: Y, data: W, it: J } = X, G, H, { minContains: B, maxContains: z2 } = Y; + if (J.opts.next) G = B === void 0 ? 1 : B, H = z2; + else G = 1; + let K = Q.const("len", i0._`${W}.length`); + if (X.setParams({ min: G, max: H }), H === void 0 && G === 0) { + (0, n9.checkStrictMode)(J, '"minContains" == 0 without "maxContains": "contains" keyword ignored'); + return; + } + if (H !== void 0 && G > H) { + (0, n9.checkStrictMode)(J, '"minContains" > "maxContains" is always invalid'), X.fail(); + return; + } + if ((0, n9.alwaysValidSchema)(J, $)) { + let q = i0._`${K} >= ${G}`; + if (H !== void 0) q = i0._`${q} && ${K} <= ${H}`; + X.pass(q); + return; + } + J.items = true; + let V = Q.name("valid"); + if (H === void 0 && G === 1) U(V, () => Q.if(V, () => Q.break())); + else if (G === 0) { + if (Q.let(V, true), H !== void 0) Q.if(i0._`${W}.length > 0`, L); + } else Q.let(V, false), L(); + X.result(V, () => X.reset()); + function L() { + let q = Q.name("_valid"), N = Q.let("count", 0); + U(q, () => Q.if(q, () => F(N))); + } + function U(q, N) { + Q.forRange("i", 0, K, (A) => { + X.subschema({ keyword: "contains", dataProp: A, dataPropType: n9.Type.Num, compositeRule: true }, q), N(); + }); + } + function F(q) { + if (Q.code(i0._`${q}++`), H === void 0) Q.if(i0._`${q} >= ${G}`, () => Q.assign(V, true).break()); + else if (Q.if(i0._`${q} > ${H}`, () => Q.assign(V, false).break()), G === 1) Q.assign(V, true); + else Q.if(i0._`${q} >= ${G}`, () => Q.assign(V, true)); + } + } }; + AB.default = Dj; +}); +var bB = P((RB) => { + Object.defineProperty(RB, "__esModule", { value: true }); + RB.validateSchemaDeps = RB.validatePropertyDeps = RB.error = void 0; + var hY = c(), wj = e(), W4 = d0(); + RB.error = { message: ({ params: { property: X, depsCount: Q, deps: $ } }) => { + let Y = Q === 1 ? "property" : "properties"; + return hY.str`must have ${Y} ${$} when property ${X} is present`; + }, params: ({ params: { property: X, depsCount: Q, deps: $, missingProperty: Y } }) => hY._`{property: ${X}, + missingProperty: ${Y}, + depsCount: ${Q}, + deps: ${$}}` }; + var Mj = { keyword: "dependencies", type: "object", schemaType: "object", error: RB.error, code(X) { + let [Q, $] = jj(X); + MB(X, Q), jB(X, $); + } }; + function jj({ schema: X }) { + let Q = {}, $ = {}; + for (let Y in X) { + if (Y === "__proto__") continue; + let W = Array.isArray(X[Y]) ? Q : $; + W[Y] = X[Y]; + } + return [Q, $]; + } + function MB(X, Q = X.schema) { + let { gen: $, data: Y, it: W } = X; + if (Object.keys(Q).length === 0) return; + let J = $.let("missing"); + for (let G in Q) { + let H = Q[G]; + if (H.length === 0) continue; + let B = (0, W4.propertyInData)($, Y, G, W.opts.ownProperties); + if (X.setParams({ property: G, depsCount: H.length, deps: H.join(", ") }), W.allErrors) $.if(B, () => { + for (let z2 of H) (0, W4.checkReportMissingProp)(X, z2); + }); + else $.if(hY._`${B} && (${(0, W4.checkMissingProp)(X, H, J)})`), (0, W4.reportMissingProp)(X, J), $.else(); + } + } + RB.validatePropertyDeps = MB; + function jB(X, Q = X.schema) { + let { gen: $, data: Y, keyword: W, it: J } = X, G = $.name("valid"); + for (let H in Q) { + if ((0, wj.alwaysValidSchema)(J, Q[H])) continue; + $.if((0, W4.propertyInData)($, Y, H, J.opts.ownProperties), () => { + let B = X.subschema({ keyword: W, schemaProp: H }, G); + X.mergeValidEvaluated(B, G); + }, () => $.var(G, true)), X.ok(G); + } + } + RB.validateSchemaDeps = jB; + RB.default = Mj; +}); +var ZB = P((SB) => { + Object.defineProperty(SB, "__esModule", { value: true }); + var PB = c(), Ij = e(), bj = { message: "property name must be valid", params: ({ params: X }) => PB._`{propertyName: ${X.propertyName}}` }, Pj = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error: bj, code(X) { + let { gen: Q, schema: $, data: Y, it: W } = X; + if ((0, Ij.alwaysValidSchema)(W, $)) return; + let J = Q.name("valid"); + Q.forIn("key", Y, (G) => { + X.setParams({ propertyName: G }), X.subschema({ keyword: "propertyNames", data: G, dataTypes: ["string"], propertyName: G, compositeRule: true }, J), Q.if((0, PB.not)(J), () => { + if (X.error(true), !W.allErrors) Q.break(); + }); + }), X.ok(J); + } }; + SB.default = Pj; +}); +var fY = P((CB) => { + Object.defineProperty(CB, "__esModule", { value: true }); + var r9 = d0(), $1 = c(), Zj = R1(), o9 = e(), Cj = { message: "must NOT have additional properties", params: ({ params: X }) => $1._`{additionalProperty: ${X.additionalProperty}}` }, kj = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error: Cj, code(X) { + let { gen: Q, schema: $, parentSchema: Y, data: W, errsCount: J, it: G } = X; + if (!J) throw Error("ajv implementation error"); + let { allErrors: H, opts: B } = G; + if (G.props = true, B.removeAdditional !== "all" && (0, o9.alwaysValidSchema)(G, $)) return; + let z2 = (0, r9.allSchemaProperties)(Y.properties), K = (0, r9.allSchemaProperties)(Y.patternProperties); + V(), X.ok($1._`${J} === ${Zj.default.errors}`); + function V() { + Q.forIn("key", W, (N) => { + if (!z2.length && !K.length) F(N); + else Q.if(L(N), () => F(N)); + }); + } + function L(N) { + let A; + if (z2.length > 8) { + let M = (0, o9.schemaRefOrVal)(G, Y.properties, "properties"); + A = (0, r9.isOwnProperty)(Q, M, N); + } else if (z2.length) A = (0, $1.or)(...z2.map((M) => $1._`${N} === ${M}`)); + else A = $1.nil; + if (K.length) A = (0, $1.or)(A, ...K.map((M) => $1._`${(0, r9.usePattern)(X, M)}.test(${N})`)); + return (0, $1.not)(A); + } + function U(N) { + Q.code($1._`delete ${W}[${N}]`); + } + function F(N) { + if (B.removeAdditional === "all" || B.removeAdditional && $ === false) { + U(N); + return; + } + if ($ === false) { + if (X.setParams({ additionalProperty: N }), X.error(), !H) Q.break(); + return; + } + if (typeof $ == "object" && !(0, o9.alwaysValidSchema)(G, $)) { + let A = Q.name("valid"); + if (B.removeAdditional === "failing") q(N, A, false), Q.if((0, $1.not)(A), () => { + X.reset(), U(N); + }); + else if (q(N, A), !H) Q.if((0, $1.not)(A), () => Q.break()); + } + } + function q(N, A, M) { + let R = { keyword: "additionalProperties", dataProp: N, dataPropType: o9.Type.Str }; + if (M === false) Object.assign(R, { compositeRule: true, createErrors: false, allErrors: false }); + X.subschema(R, A); + } + } }; + CB.default = kj; +}); +var _B = P((TB) => { + Object.defineProperty(TB, "__esModule", { value: true }); + var Tj = iX(), kB = d0(), uY = e(), vB = fY(), _j = { keyword: "properties", type: "object", schemaType: "object", code(X) { + let { gen: Q, schema: $, parentSchema: Y, data: W, it: J } = X; + if (J.opts.removeAdditional === "all" && Y.additionalProperties === void 0) vB.default.code(new Tj.KeywordCxt(J, vB.default, "additionalProperties")); + let G = (0, kB.allSchemaProperties)($); + for (let V of G) J.definedProperties.add(V); + if (J.opts.unevaluated && G.length && J.props !== true) J.props = uY.mergeEvaluated.props(Q, (0, uY.toHash)(G), J.props); + let H = G.filter((V) => !(0, uY.alwaysValidSchema)(J, $[V])); + if (H.length === 0) return; + let B = Q.name("valid"); + for (let V of H) { + if (z2(V)) K(V); + else { + if (Q.if((0, kB.propertyInData)(Q, W, V, J.opts.ownProperties)), K(V), !J.allErrors) Q.else().var(B, true); + Q.endIf(); + } + X.it.definedProperties.add(V), X.ok(B); + } + function z2(V) { + return J.opts.useDefaults && !J.compositeRule && $[V].default !== void 0; + } + function K(V) { + X.subschema({ keyword: "properties", schemaProp: V, dataProp: V }, B); + } + } }; + TB.default = _j; +}); +var fB = P((hB) => { + Object.defineProperty(hB, "__esModule", { value: true }); + var xB = d0(), t9 = c(), yB = e(), gB = e(), yj = { keyword: "patternProperties", type: "object", schemaType: "object", code(X) { + let { gen: Q, schema: $, data: Y, parentSchema: W, it: J } = X, { opts: G } = J, H = (0, xB.allSchemaProperties)($), B = H.filter((q) => (0, yB.alwaysValidSchema)(J, $[q])); + if (H.length === 0 || B.length === H.length && (!J.opts.unevaluated || J.props === true)) return; + let z2 = G.strictSchema && !G.allowMatchingProperties && W.properties, K = Q.name("valid"); + if (J.props !== true && !(J.props instanceof t9.Name)) J.props = (0, gB.evaluatedPropsToName)(Q, J.props); + let { props: V } = J; + L(); + function L() { + for (let q of H) { + if (z2) U(q); + if (J.allErrors) F(q); + else Q.var(K, true), F(q), Q.if(K); + } + } + function U(q) { + for (let N in z2) if (new RegExp(q).test(N)) (0, yB.checkStrictMode)(J, `property ${N} matches pattern ${q} (use allowMatchingProperties)`); + } + function F(q) { + Q.forIn("key", Y, (N) => { + Q.if(t9._`${(0, xB.usePattern)(X, q)}.test(${N})`, () => { + let A = B.includes(q); + if (!A) X.subschema({ keyword: "patternProperties", schemaProp: q, dataProp: N, dataPropType: gB.Type.Str }, K); + if (J.opts.unevaluated && V !== true) Q.assign(t9._`${V}[${N}]`, true); + else if (!A && !J.allErrors) Q.if((0, t9.not)(K), () => Q.break()); + }); + }); + } + } }; + hB.default = yj; +}); +var lB = P((uB) => { + Object.defineProperty(uB, "__esModule", { value: true }); + var hj = e(), fj = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code(X) { + let { gen: Q, schema: $, it: Y } = X; + if ((0, hj.alwaysValidSchema)(Y, $)) { + X.fail(); + return; + } + let W = Q.name("valid"); + X.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, W), X.failResult(W, () => X.reset(), () => X.error()); + }, error: { message: "must NOT be valid" } }; + uB.default = fj; +}); +var cB = P((mB) => { + Object.defineProperty(mB, "__esModule", { value: true }); + var lj = d0(), mj = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: lj.validateUnion, error: { message: "must match a schema in anyOf" } }; + mB.default = mj; +}); +var dB = P((pB) => { + Object.defineProperty(pB, "__esModule", { value: true }); + var a9 = c(), pj = e(), dj = { message: "must match exactly one schema in oneOf", params: ({ params: X }) => a9._`{passingSchemas: ${X.passing}}` }, ij = { keyword: "oneOf", schemaType: "array", trackErrors: true, error: dj, code(X) { + let { gen: Q, schema: $, parentSchema: Y, it: W } = X; + if (!Array.isArray($)) throw Error("ajv implementation error"); + if (W.opts.discriminator && Y.discriminator) return; + let J = $, G = Q.let("valid", false), H = Q.let("passing", null), B = Q.name("_valid"); + X.setParams({ passing: H }), Q.block(z2), X.result(G, () => X.reset(), () => X.error(true)); + function z2() { + J.forEach((K, V) => { + let L; + if ((0, pj.alwaysValidSchema)(W, K)) Q.var(B, true); + else L = X.subschema({ keyword: "oneOf", schemaProp: V, compositeRule: true }, B); + if (V > 0) Q.if(a9._`${B} && ${G}`).assign(G, false).assign(H, a9._`[${H}, ${V}]`).else(); + Q.if(B, () => { + if (Q.assign(G, true), Q.assign(H, V), L) X.mergeEvaluated(L, a9.Name); + }); + }); + } + } }; + pB.default = ij; +}); +var nB = P((iB) => { + Object.defineProperty(iB, "__esModule", { value: true }); + var rj = e(), oj = { keyword: "allOf", schemaType: "array", code(X) { + let { gen: Q, schema: $, it: Y } = X; + if (!Array.isArray($)) throw Error("ajv implementation error"); + let W = Q.name("valid"); + $.forEach((J, G) => { + if ((0, rj.alwaysValidSchema)(Y, J)) return; + let H = X.subschema({ keyword: "allOf", schemaProp: G }, W); + X.ok(W), X.mergeEvaluated(H); + }); + } }; + iB.default = oj; +}); +var aB = P((tB) => { + Object.defineProperty(tB, "__esModule", { value: true }); + var s9 = c(), oB = e(), aj = { message: ({ params: X }) => s9.str`must match "${X.ifClause}" schema`, params: ({ params: X }) => s9._`{failingKeyword: ${X.ifClause}}` }, sj = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error: aj, code(X) { + let { gen: Q, parentSchema: $, it: Y } = X; + if ($.then === void 0 && $.else === void 0) (0, oB.checkStrictMode)(Y, '"if" without "then" and "else" is ignored'); + let W = rB(Y, "then"), J = rB(Y, "else"); + if (!W && !J) return; + let G = Q.let("valid", true), H = Q.name("_valid"); + if (B(), X.reset(), W && J) { + let K = Q.let("ifClause"); + X.setParams({ ifClause: K }), Q.if(H, z2("then", K), z2("else", K)); + } else if (W) Q.if(H, z2("then")); + else Q.if((0, s9.not)(H), z2("else")); + X.pass(G, () => X.error(true)); + function B() { + let K = X.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, H); + X.mergeEvaluated(K); + } + function z2(K, V) { + return () => { + let L = X.subschema({ keyword: K }, H); + if (Q.assign(G, H), X.mergeValidEvaluated(L, G), V) Q.assign(V, s9._`${K}`); + else X.setParams({ ifClause: K }); + }; + } + } }; + function rB(X, Q) { + let $ = X.schema[Q]; + return $ !== void 0 && !(0, oB.alwaysValidSchema)(X, $); + } + tB.default = sj; +}); +var eB = P((sB) => { + Object.defineProperty(sB, "__esModule", { value: true }); + var XR = e(), QR = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword: X, parentSchema: Q, it: $ }) { + if (Q.if === void 0) (0, XR.checkStrictMode)($, `"${X}" without "if" is ignored`); + } }; + sB.default = QR; +}); +var Qz = P((Xz) => { + Object.defineProperty(Xz, "__esModule", { value: true }); + var YR = yY(), WR = FB(), JR = gY(), GR = DB(), HR = wB(), BR = bB(), zR = ZB(), KR = fY(), UR = _B(), VR = fB(), LR = lB(), qR = cB(), FR = dB(), NR = nB(), OR = aB(), DR = eB(); + function AR(X = false) { + let Q = [LR.default, qR.default, FR.default, NR.default, OR.default, DR.default, zR.default, KR.default, BR.default, UR.default, VR.default]; + if (X) Q.push(WR.default, GR.default); + else Q.push(YR.default, JR.default); + return Q.push(HR.default), Q; + } + Xz.default = AR; +}); +var Yz = P(($z) => { + Object.defineProperty($z, "__esModule", { value: true }); + var L0 = c(), MR = { message: ({ schemaCode: X }) => L0.str`must match format "${X}"`, params: ({ schemaCode: X }) => L0._`{format: ${X}}` }, jR = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error: MR, code(X, Q) { + let { gen: $, data: Y, $data: W, schema: J, schemaCode: G, it: H } = X, { opts: B, errSchemaPath: z2, schemaEnv: K, self: V } = H; + if (!B.validateFormats) return; + if (W) L(); + else U(); + function L() { + let F = $.scopeValue("formats", { ref: V.formats, code: B.code.formats }), q = $.const("fDef", L0._`${F}[${G}]`), N = $.let("fType"), A = $.let("format"); + $.if(L0._`typeof ${q} == "object" && !(${q} instanceof RegExp)`, () => $.assign(N, L0._`${q}.type || "string"`).assign(A, L0._`${q}.validate`), () => $.assign(N, L0._`"string"`).assign(A, q)), X.fail$data((0, L0.or)(M(), R())); + function M() { + if (B.strictSchema === false) return L0.nil; + return L0._`${G} && !${A}`; + } + function R() { + let S = K.$async ? L0._`(${q}.async ? await ${A}(${Y}) : ${A}(${Y}))` : L0._`${A}(${Y})`, C = L0._`(typeof ${A} == "function" ? ${S} : ${A}.test(${Y}))`; + return L0._`${A} && ${A} !== true && ${N} === ${Q} && !${C}`; + } + } + function U() { + let F = V.formats[J]; + if (!F) { + M(); + return; + } + if (F === true) return; + let [q, N, A] = R(F); + if (q === Q) X.pass(S()); + function M() { + if (B.strictSchema === false) { + V.logger.warn(C()); + return; + } + throw Error(C()); + function C() { + return `unknown format "${J}" ignored in schema at path "${z2}"`; + } + } + function R(C) { + let K0 = C instanceof RegExp ? (0, L0.regexpCode)(C) : B.code.formats ? L0._`${B.code.formats}${(0, L0.getProperty)(J)}` : void 0, U0 = $.scopeValue("formats", { key: J, ref: C, code: K0 }); + if (typeof C == "object" && !(C instanceof RegExp)) return [C.type || "string", C.validate, L0._`${U0}.validate`]; + return ["string", C, U0]; + } + function S() { + if (typeof F == "object" && !(F instanceof RegExp) && F.async) { + if (!K.$async) throw Error("async format in sync schema"); + return L0._`await ${A}(${Y})`; + } + return typeof N == "function" ? L0._`${A}(${Y})` : L0._`${A}.test(${Y})`; + } + } + } }; + $z.default = jR; +}); +var Jz = P((Wz) => { + Object.defineProperty(Wz, "__esModule", { value: true }); + var ER = Yz(), IR = [ER.default]; + Wz.default = IR; +}); +var Bz = P((Gz) => { + Object.defineProperty(Gz, "__esModule", { value: true }); + Gz.contentVocabulary = Gz.metadataVocabulary = void 0; + Gz.metadataVocabulary = ["title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples"]; + Gz.contentVocabulary = ["contentMediaType", "contentEncoding", "contentSchema"]; +}); +var Uz = P((Kz) => { + Object.defineProperty(Kz, "__esModule", { value: true }); + var SR = TH(), ZR = GB(), CR = Qz(), kR = Jz(), zz = Bz(), vR = [SR.default, ZR.default, (0, CR.default)(), kR.default, zz.metadataVocabulary, zz.contentVocabulary]; + Kz.default = vR; +}); +var Fz = P((Lz) => { + Object.defineProperty(Lz, "__esModule", { value: true }); + Lz.DiscrError = void 0; + var Vz; + (function(X) { + X.Tag = "tag", X.Mapping = "mapping"; + })(Vz || (Lz.DiscrError = Vz = {})); +}); +var Dz = P((Oz) => { + Object.defineProperty(Oz, "__esModule", { value: true }); + var i6 = c(), lY = Fz(), Nz = _9(), _R = nX(), xR = e(), yR = { message: ({ params: { discrError: X, tagName: Q } }) => X === lY.DiscrError.Tag ? `tag "${Q}" must be string` : `value of tag "${Q}" must be in oneOf`, params: ({ params: { discrError: X, tag: Q, tagName: $ } }) => i6._`{error: ${X}, tag: ${$}, tagValue: ${Q}}` }, gR = { keyword: "discriminator", type: "object", schemaType: "object", error: yR, code(X) { + let { gen: Q, data: $, schema: Y, parentSchema: W, it: J } = X, { oneOf: G } = W; + if (!J.opts.discriminator) throw Error("discriminator: requires discriminator option"); + let H = Y.propertyName; + if (typeof H != "string") throw Error("discriminator: requires propertyName"); + if (Y.mapping) throw Error("discriminator: mapping is not supported"); + if (!G) throw Error("discriminator: requires oneOf keyword"); + let B = Q.let("valid", false), z2 = Q.const("tag", i6._`${$}${(0, i6.getProperty)(H)}`); + Q.if(i6._`typeof ${z2} == "string"`, () => K(), () => X.error(false, { discrError: lY.DiscrError.Tag, tag: z2, tagName: H })), X.ok(B); + function K() { + let U = L(); + Q.if(false); + for (let F in U) Q.elseIf(i6._`${z2} === ${F}`), Q.assign(B, V(U[F])); + Q.else(), X.error(false, { discrError: lY.DiscrError.Mapping, tag: z2, tagName: H }), Q.endIf(); + } + function V(U) { + let F = Q.name("valid"), q = X.subschema({ keyword: "oneOf", schemaProp: U }, F); + return X.mergeEvaluated(q, i6.Name), F; + } + function L() { + var U; + let F = {}, q = A(W), N = true; + for (let S = 0; S < G.length; S++) { + let C = G[S]; + if ((C === null || C === void 0 ? void 0 : C.$ref) && !(0, xR.schemaHasRulesButRef)(C, J.self.RULES)) { + let U0 = C.$ref; + if (C = Nz.resolveRef.call(J.self, J.schemaEnv.root, J.baseId, U0), C instanceof Nz.SchemaEnv) C = C.schema; + if (C === void 0) throw new _R.default(J.opts.uriResolver, J.baseId, U0); + } + let K0 = (U = C === null || C === void 0 ? void 0 : C.properties) === null || U === void 0 ? void 0 : U[H]; + if (typeof K0 != "object") throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${H}"`); + N = N && (q || A(C)), M(K0, S); + } + if (!N) throw Error(`discriminator: "${H}" must be required`); + return F; + function A({ required: S }) { + return Array.isArray(S) && S.includes(H); + } + function M(S, C) { + if (S.const) R(S.const, C); + else if (S.enum) for (let K0 of S.enum) R(K0, C); + else throw Error(`discriminator: "properties/${H}" must have "const" or "enum"`); + } + function R(S, C) { + if (typeof S != "string" || S in F) throw Error(`discriminator: "${H}" values must be unique strings`); + F[S] = C; + } + } + } }; + Oz.default = gR; +}); +var Az = P((oT, fR) => { + fR.exports = { $schema: "http://json-schema.org/draft-07/schema#", $id: "http://json-schema.org/draft-07/schema#", title: "Core schema meta-schema", definitions: { schemaArray: { type: "array", minItems: 1, items: { $ref: "#" } }, nonNegativeInteger: { type: "integer", minimum: 0 }, nonNegativeIntegerDefault0: { allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] }, simpleTypes: { enum: ["array", "boolean", "integer", "null", "number", "object", "string"] }, stringArray: { type: "array", items: { type: "string" }, uniqueItems: true, default: [] } }, type: ["object", "boolean"], properties: { $id: { type: "string", format: "uri-reference" }, $schema: { type: "string", format: "uri" }, $ref: { type: "string", format: "uri-reference" }, $comment: { type: "string" }, title: { type: "string" }, description: { type: "string" }, default: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, multipleOf: { type: "number", exclusiveMinimum: 0 }, maximum: { type: "number" }, exclusiveMaximum: { type: "number" }, minimum: { type: "number" }, exclusiveMinimum: { type: "number" }, maxLength: { $ref: "#/definitions/nonNegativeInteger" }, minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, pattern: { type: "string", format: "regex" }, additionalItems: { $ref: "#" }, items: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], default: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, contains: { $ref: "#" }, maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, required: { $ref: "#/definitions/stringArray" }, additionalProperties: { $ref: "#" }, definitions: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, properties: { type: "object", additionalProperties: { $ref: "#" }, default: {} }, patternProperties: { type: "object", additionalProperties: { $ref: "#" }, propertyNames: { format: "regex" }, default: {} }, dependencies: { type: "object", additionalProperties: { anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } }, propertyNames: { $ref: "#" }, const: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [{ $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true }] }, format: { type: "string" }, contentMediaType: { type: "string" }, contentEncoding: { type: "string" }, if: { $ref: "#" }, then: { $ref: "#" }, else: { $ref: "#" }, allOf: { $ref: "#/definitions/schemaArray" }, anyOf: { $ref: "#/definitions/schemaArray" }, oneOf: { $ref: "#/definitions/schemaArray" }, not: { $ref: "#" } }, default: true }; +}); +var cY = P((h0, mY) => { + Object.defineProperty(h0, "__esModule", { value: true }); + h0.MissingRefError = h0.ValidationError = h0.CodeGen = h0.Name = h0.nil = h0.stringify = h0.str = h0._ = h0.KeywordCxt = h0.Ajv = void 0; + var uR = RH(), lR = Uz(), mR = Dz(), wz = Az(), cR = ["/properties"], e9 = "http://json-schema.org/draft-07/schema"; + class J4 extends uR.default { + _addVocabularies() { + if (super._addVocabularies(), lR.default.forEach((X) => this.addVocabulary(X)), this.opts.discriminator) this.addKeyword(mR.default); + } + _addDefaultMetaSchema() { + if (super._addDefaultMetaSchema(), !this.opts.meta) return; + let X = this.opts.$data ? this.$dataMetaSchema(wz, cR) : wz; + this.addMetaSchema(X, e9, false), this.refs["http://json-schema.org/schema"] = e9; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(e9) ? e9 : void 0); + } + } + h0.Ajv = J4; + mY.exports = h0 = J4; + mY.exports.Ajv = J4; + Object.defineProperty(h0, "__esModule", { value: true }); + h0.default = J4; + var pR = iX(); + Object.defineProperty(h0, "KeywordCxt", { enumerable: true, get: function() { + return pR.KeywordCxt; + } }); + var n6 = c(); + Object.defineProperty(h0, "_", { enumerable: true, get: function() { + return n6._; + } }); + Object.defineProperty(h0, "str", { enumerable: true, get: function() { + return n6.str; + } }); + Object.defineProperty(h0, "stringify", { enumerable: true, get: function() { + return n6.stringify; + } }); + Object.defineProperty(h0, "nil", { enumerable: true, get: function() { + return n6.nil; + } }); + Object.defineProperty(h0, "Name", { enumerable: true, get: function() { + return n6.Name; + } }); + Object.defineProperty(h0, "CodeGen", { enumerable: true, get: function() { + return n6.CodeGen; + } }); + var dR = v9(); + Object.defineProperty(h0, "ValidationError", { enumerable: true, get: function() { + return dR.default; + } }); + var iR = nX(); + Object.defineProperty(h0, "MissingRefError", { enumerable: true, get: function() { + return iR.default; + } }); +}); +var Cz = P((Sz) => { + Object.defineProperty(Sz, "__esModule", { value: true }); + Sz.formatNames = Sz.fastFormats = Sz.fullFormats = void 0; + function L1(X, Q) { + return { validate: X, compare: Q }; + } + Sz.fullFormats = { date: L1(Ez, nY), time: L1(dY(true), rY), "date-time": L1(Mz(true), bz), "iso-time": L1(dY(), Iz), "iso-date-time": L1(Mz(), Pz), duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri: XE, "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, regex: HE, uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, byte: QE, int32: { type: "number", validate: WE }, int64: { type: "number", validate: JE }, float: { type: "number", validate: Rz }, double: { type: "number", validate: Rz }, password: true, binary: true }; + Sz.fastFormats = { ...Sz.fullFormats, date: L1(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, nY), time: L1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, rY), "date-time": L1(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, bz), "iso-time": L1(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, Iz), "iso-date-time": L1(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, Pz), uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i }; + Sz.formatNames = Object.keys(Sz.fullFormats); + function oR(X) { + return X % 4 === 0 && (X % 100 !== 0 || X % 400 === 0); + } + var tR = /^(\d\d\d\d)-(\d\d)-(\d\d)$/, aR = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function Ez(X) { + let Q = tR.exec(X); + if (!Q) return false; + let $ = +Q[1], Y = +Q[2], W = +Q[3]; + return Y >= 1 && Y <= 12 && W >= 1 && W <= (Y === 2 && oR($) ? 29 : aR[Y]); + } + function nY(X, Q) { + if (!(X && Q)) return; + if (X > Q) return 1; + if (X < Q) return -1; + return 0; + } + var pY = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function dY(X) { + return function($) { + let Y = pY.exec($); + if (!Y) return false; + let W = +Y[1], J = +Y[2], G = +Y[3], H = Y[4], B = Y[5] === "-" ? -1 : 1, z2 = +(Y[6] || 0), K = +(Y[7] || 0); + if (z2 > 23 || K > 59 || X && !H) return false; + if (W <= 23 && J <= 59 && G < 60) return true; + let V = J - K * B, L = W - z2 * B - (V < 0 ? 1 : 0); + return (L === 23 || L === -1) && (V === 59 || V === -1) && G < 61; + }; + } + function rY(X, Q) { + if (!(X && Q)) return; + let $ = (/* @__PURE__ */ new Date("2020-01-01T" + X)).valueOf(), Y = (/* @__PURE__ */ new Date("2020-01-01T" + Q)).valueOf(); + if (!($ && Y)) return; + return $ - Y; + } + function Iz(X, Q) { + if (!(X && Q)) return; + let $ = pY.exec(X), Y = pY.exec(Q); + if (!($ && Y)) return; + if (X = $[1] + $[2] + $[3], Q = Y[1] + Y[2] + Y[3], X > Q) return 1; + if (X < Q) return -1; + return 0; + } + var iY = /t|\s/i; + function Mz(X) { + let Q = dY(X); + return function(Y) { + let W = Y.split(iY); + return W.length === 2 && Ez(W[0]) && Q(W[1]); + }; + } + function bz(X, Q) { + if (!(X && Q)) return; + let $ = new Date(X).valueOf(), Y = new Date(Q).valueOf(); + if (!($ && Y)) return; + return $ - Y; + } + function Pz(X, Q) { + if (!(X && Q)) return; + let [$, Y] = X.split(iY), [W, J] = Q.split(iY), G = nY($, W); + if (G === void 0) return; + return G || rY(Y, J); + } + var sR = /\/|:/, eR = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function XE(X) { + return sR.test(X) && eR.test(X); + } + var jz = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function QE(X) { + return jz.lastIndex = 0, jz.test(X); + } + var $E = -2147483648, YE = 2147483647; + function WE(X) { + return Number.isInteger(X) && X <= YE && X >= $E; + } + function JE(X) { + return Number.isInteger(X); + } + function Rz() { + return true; + } + var GE = /[^\\]\\Z/; + function HE(X) { + if (GE.test(X)) return false; + try { + return new RegExp(X), true; + } catch (Q) { + return false; + } + } +}); +var vz = P((kz) => { + Object.defineProperty(kz, "__esModule", { value: true }); + kz.formatLimitDefinition = void 0; + var zE = cY(), Y1 = c(), i1 = Y1.operators, X8 = { formatMaximum: { okStr: "<=", ok: i1.LTE, fail: i1.GT }, formatMinimum: { okStr: ">=", ok: i1.GTE, fail: i1.LT }, formatExclusiveMaximum: { okStr: "<", ok: i1.LT, fail: i1.GTE }, formatExclusiveMinimum: { okStr: ">", ok: i1.GT, fail: i1.LTE } }, KE = { message: ({ keyword: X, schemaCode: Q }) => Y1.str`should be ${X8[X].okStr} ${Q}`, params: ({ keyword: X, schemaCode: Q }) => Y1._`{comparison: ${X8[X].okStr}, limit: ${Q}}` }; + kz.formatLimitDefinition = { keyword: Object.keys(X8), type: "string", schemaType: "string", $data: true, error: KE, code(X) { + let { gen: Q, data: $, schemaCode: Y, keyword: W, it: J } = X, { opts: G, self: H } = J; + if (!G.validateFormats) return; + let B = new zE.KeywordCxt(J, H.RULES.all.format.definition, "format"); + if (B.$data) z2(); + else K(); + function z2() { + let L = Q.scopeValue("formats", { ref: H.formats, code: G.code.formats }), U = Q.const("fmt", Y1._`${L}[${B.schemaCode}]`); + X.fail$data((0, Y1.or)(Y1._`typeof ${U} != "object"`, Y1._`${U} instanceof RegExp`, Y1._`typeof ${U}.compare != "function"`, V(U))); + } + function K() { + let L = B.schema, U = H.formats[L]; + if (!U || U === true) return; + if (typeof U != "object" || U instanceof RegExp || typeof U.compare != "function") throw Error(`"${W}": format "${L}" does not define "compare" function`); + let F = Q.scopeValue("formats", { key: L, ref: U, code: G.code.formats ? Y1._`${G.code.formats}${(0, Y1.getProperty)(L)}` : void 0 }); + X.fail$data(V(F)); + } + function V(L) { + return Y1._`${L}.compare(${$}, ${Y}) ${X8[W].fail} 0`; + } + }, dependencies: ["format"] }; + var UE = (X) => { + return X.addKeyword(kz.formatLimitDefinition), X; + }; + kz.default = UE; +}); +var yz = P((G4, xz) => { + Object.defineProperty(G4, "__esModule", { value: true }); + var r6 = Cz(), LE = vz(), aY = c(), Tz = new aY.Name("fullFormats"), qE = new aY.Name("fastFormats"), sY = (X, Q = { keywords: true }) => { + if (Array.isArray(Q)) return _z(X, Q, r6.fullFormats, Tz), X; + let [$, Y] = Q.mode === "fast" ? [r6.fastFormats, qE] : [r6.fullFormats, Tz], W = Q.formats || r6.formatNames; + if (_z(X, W, $, Y), Q.keywords) (0, LE.default)(X); + return X; + }; + sY.get = (X, Q = "full") => { + let Y = (Q === "fast" ? r6.fastFormats : r6.fullFormats)[X]; + if (!Y) throw Error(`Unknown format "${X}"`); + return Y; + }; + function _z(X, Q, $, Y) { + var W, J; + (W = (J = X.opts.code).formats) !== null && W !== void 0 || (J.formats = aY._`require("ajv-formats/dist/formats").${Y}`); + for (let G of Q) X.addFormat(G, $[G]); + } + xz.exports = G4 = sY; + Object.defineProperty(G4, "__esModule", { value: true }); + G4.default = sY; +}); +var HK = 50; +function N6(X = HK) { + let Q = new AbortController(); + return (0, import_events.setMaxListeners)(X, Q.signal), Q; } -function normalizePathForDisplay(p) { - if (!p) return ""; - return p.replace(/\\/g, "/").replace(/\/+$/, ""); +var BK = typeof global == "object" && global && global.Object === Object && global; +var q7 = BK; +var zK = typeof self == "object" && self && self.Object === Object && self; +var KK = q7 || zK || Function("return this")(); +var O6 = KK; +var UK = O6.Symbol; +var D6 = UK; +var F7 = Object.prototype; +var VK = F7.hasOwnProperty; +var LK = F7.toString; +var e6 = D6 ? D6.toStringTag : void 0; +function qK(X) { + var Q = VK.call(X, e6), $ = X[e6]; + try { + X[e6] = void 0; + var Y = true; + } catch (J) { + } + var W = LK.call(X); + if (Y) if (Q) X[e6] = $; + else delete X[e6]; + return W; +} +var N7 = qK; +var FK = Object.prototype; +var NK = FK.toString; +function OK2(X) { + return NK.call(X); +} +var O7 = OK2; +var DK = "[object Null]"; +var AK = "[object Undefined]"; +var D7 = D6 ? D6.toStringTag : void 0; +function wK(X) { + if (X == null) return X === void 0 ? AK : DK; + return D7 && D7 in Object(X) ? N7(X) : O7(X); +} +var A7 = wK; +function MK(X) { + var Q = typeof X; + return X != null && (Q == "object" || Q == "function"); +} +var z4 = MK; +var jK = "[object AsyncFunction]"; +var RK = "[object Function]"; +var EK = "[object GeneratorFunction]"; +var IK = "[object Proxy]"; +function bK(X) { + if (!z4(X)) return false; + var Q = A7(X); + return Q == RK || Q == EK || Q == jK || Q == IK; +} +var w7 = bK; +var PK = O6["__core-js_shared__"]; +var K4 = PK; +var M7 = (function() { + var X = /[^.]+$/.exec(K4 && K4.keys && K4.keys.IE_PROTO || ""); + return X ? "Symbol(src)_1." + X : ""; +})(); +function SK(X) { + return !!M7 && M7 in X; +} +var j7 = SK; +var ZK = Function.prototype; +var CK = ZK.toString; +function kK(X) { + if (X != null) { + try { + return CK.call(X); + } catch (Q) { + } + try { + return X + ""; + } catch (Q) { + } + } + return ""; +} +var R7 = kK; +var vK = /[\\^$.*+?()[\]{}|]/g; +var TK = /^\[object .+?Constructor\]$/; +var _K = Function.prototype; +var xK = Object.prototype; +var yK = _K.toString; +var gK = xK.hasOwnProperty; +var hK = RegExp("^" + yK.call(gK).replace(vK, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); +function fK(X) { + if (!z4(X) || j7(X)) return false; + var Q = w7(X) ? hK : TK; + return Q.test(R7(X)); +} +var E7 = fK; +function uK(X, Q) { + return X == null ? void 0 : X[Q]; +} +var I7 = uK; +function lK(X, Q) { + var $ = I7(X, Q); + return E7($) ? $ : void 0; +} +var U4 = lK; +var mK = U4(Object, "create"); +var q1 = mK; +function cK() { + this.__data__ = q1 ? q1(null) : {}, this.size = 0; +} +var b7 = cK; +function pK(X) { + var Q = this.has(X) && delete this.__data__[X]; + return this.size -= Q ? 1 : 0, Q; +} +var P7 = pK; +var dK = "__lodash_hash_undefined__"; +var iK = Object.prototype; +var nK = iK.hasOwnProperty; +function rK(X) { + var Q = this.__data__; + if (q1) { + var $ = Q[X]; + return $ === dK ? void 0 : $; + } + return nK.call(Q, X) ? Q[X] : void 0; +} +var S7 = rK; +var oK = Object.prototype; +var tK = oK.hasOwnProperty; +function aK(X) { + var Q = this.__data__; + return q1 ? Q[X] !== void 0 : tK.call(Q, X); +} +var Z7 = aK; +var sK = "__lodash_hash_undefined__"; +function eK(X, Q) { + var $ = this.__data__; + return this.size += this.has(X) ? 0 : 1, $[X] = q1 && Q === void 0 ? sK : Q, this; +} +var C7 = eK; +function A6(X) { + var Q = -1, $ = X == null ? 0 : X.length; + this.clear(); + while (++Q < $) { + var Y = X[Q]; + this.set(Y[0], Y[1]); + } +} +A6.prototype.clear = b7; +A6.prototype.delete = P7; +A6.prototype.get = S7; +A6.prototype.has = Z7; +A6.prototype.set = C7; +var W8 = A6; +function XU() { + this.__data__ = [], this.size = 0; +} +var k7 = XU; +function QU(X, Q) { + return X === Q || X !== X && Q !== Q; +} +var v7 = QU; +function $U(X, Q) { + var $ = X.length; + while ($--) if (v7(X[$][0], Q)) return $; + return -1; +} +var Z1 = $U; +var YU = Array.prototype; +var WU = YU.splice; +function JU(X) { + var Q = this.__data__, $ = Z1(Q, X); + if ($ < 0) return false; + var Y = Q.length - 1; + if ($ == Y) Q.pop(); + else WU.call(Q, $, 1); + return --this.size, true; +} +var T7 = JU; +function GU(X) { + var Q = this.__data__, $ = Z1(Q, X); + return $ < 0 ? void 0 : Q[$][1]; +} +var _7 = GU; +function HU(X) { + return Z1(this.__data__, X) > -1; +} +var x7 = HU; +function BU(X, Q) { + var $ = this.__data__, Y = Z1($, X); + if (Y < 0) ++this.size, $.push([X, Q]); + else $[Y][1] = Q; + return this; +} +var y7 = BU; +function w6(X) { + var Q = -1, $ = X == null ? 0 : X.length; + this.clear(); + while (++Q < $) { + var Y = X[Q]; + this.set(Y[0], Y[1]); + } +} +w6.prototype.clear = k7; +w6.prototype.delete = T7; +w6.prototype.get = _7; +w6.prototype.has = x7; +w6.prototype.set = y7; +var g7 = w6; +var zU = U4(O6, "Map"); +var h7 = zU; +function KU() { + this.size = 0, this.__data__ = { hash: new W8(), map: new (h7 || g7)(), string: new W8() }; +} +var f7 = KU; +function UU(X) { + var Q = typeof X; + return Q == "string" || Q == "number" || Q == "symbol" || Q == "boolean" ? X !== "__proto__" : X === null; +} +var u7 = UU; +function VU(X, Q) { + var $ = X.__data__; + return u7(Q) ? $[typeof Q == "string" ? "string" : "hash"] : $.map; +} +var C1 = VU; +function LU(X) { + var Q = C1(this, X).delete(X); + return this.size -= Q ? 1 : 0, Q; +} +var l7 = LU; +function qU(X) { + return C1(this, X).get(X); +} +var m7 = qU; +function FU(X) { + return C1(this, X).has(X); +} +var c7 = FU; +function NU(X, Q) { + var $ = C1(this, X), Y = $.size; + return $.set(X, Q), this.size += $.size == Y ? 0 : 1, this; +} +var p7 = NU; +function M6(X) { + var Q = -1, $ = X == null ? 0 : X.length; + this.clear(); + while (++Q < $) { + var Y = X[Q]; + this.set(Y[0], Y[1]); + } +} +M6.prototype.clear = f7; +M6.prototype.delete = l7; +M6.prototype.get = m7; +M6.prototype.has = c7; +M6.prototype.set = p7; +var J8 = M6; +var OU = "Expected a function"; +function G8(X, Q) { + if (typeof X != "function" || Q != null && typeof Q != "function") throw TypeError(OU); + var $ = function() { + var Y = arguments, W = Q ? Q.apply(this, Y) : Y[0], J = $.cache; + if (J.has(W)) return J.get(W); + var G = X.apply(this, Y); + return $.cache = J.set(W, G) || J, G; + }; + return $.cache = new (G8.Cache || J8)(), $; +} +G8.Cache = J8; +var r1 = G8; +function d7(X) { + if (process.stderr.destroyed) return; + for (let Q = 0; Q < X.length; Q += 2e3) process.stderr.write(X.substring(Q, Q + 2e3)); +} +var i7 = r1((X) => { + if (!X || X.trim() === "") return null; + let Q = X.split(",").map((J) => J.trim()).filter(Boolean); + if (Q.length === 0) return null; + let $ = Q.some((J) => J.startsWith("!")), Y = Q.some((J) => !J.startsWith("!")); + if ($ && Y) return null; + let W = Q.map((J) => J.replace(/^!/, "").toLowerCase()); + return { include: $ ? [] : W, exclude: $ ? W : [], isExclusive: $ }; +}); +function DU(X) { + let Q = [], $ = X.match(/^MCP server ["']([^"']+)["']/); + if ($ && $[1]) Q.push("mcp"), Q.push($[1].toLowerCase()); + else { + let J = X.match(/^([^:[]+):/); + if (J && J[1]) Q.push(J[1].trim().toLowerCase()); + } + let Y = X.match(/^\[([^\]]+)]/); + if (Y && Y[1]) Q.push(Y[1].trim().toLowerCase()); + if (X.toLowerCase().includes("statsig event:")) Q.push("statsig"); + let W = X.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/); + if (W && W[1]) { + let J = W[1].trim().toLowerCase(); + if (J.length < 30 && !J.includes(" ")) Q.push(J); + } + return Array.from(new Set(Q)); +} +function AU(X, Q) { + if (!Q) return true; + if (X.length === 0) return false; + if (Q.isExclusive) return !X.some(($) => Q.exclude.includes($)); + else return X.some(($) => Q.include.includes($)); +} +function n7(X, Q) { + if (!Q) return true; + let $ = DU(X); + return AU($, Q); +} +function V4() { + var _a3; + return (_a3 = process.env.CLAUDE_CONFIG_DIR) != null ? _a3 : (0, import_path3.join)((0, import_os.homedir)(), ".claude"); +} +function H8(X) { + if (!X) return false; + if (typeof X === "boolean") return X; + let Q = X.toLowerCase().trim(); + return ["1", "true", "yes", "on"].includes(Q); +} +function r7(X) { + return { name: X, default: 3e4, validate: (Q) => { + if (!Q) return { effective: 3e4, status: "valid" }; + let $ = parseInt(Q, 10); + if (isNaN($) || $ <= 0) return { effective: 3e4, status: "invalid", message: `Invalid value "${Q}" (using default: 30000)` }; + if ($ > 15e4) return { effective: 15e4, status: "capped", message: `Capped from ${$} to 150000` }; + return { effective: $, status: "valid" }; + } }; +} +var o7 = r7("BASH_MAX_OUTPUT_LENGTH"); +var Db = r7("TASK_MAX_OUTPUT_LENGTH"); +var t7 = { name: "CLAUDE_CODE_MAX_OUTPUT_TOKENS", default: 32e3, validate: (X) => { + if (!X) return { effective: 32e3, status: "valid" }; + let Y = parseInt(X, 10); + if (isNaN(Y) || Y <= 0) return { effective: 32e3, status: "invalid", message: `Invalid value "${X}" (using default: 32000)` }; + if (Y > 64e3) return { effective: 64e3, status: "capped", message: `Capped from ${Y} to 64000` }; + return { effective: Y, status: "valid" }; +} }; +function IU() { + let X = ""; + if (typeof process < "u" && typeof process.cwd === "function") X = (0, import_fs.realpathSync)((0, import_process.cwd)()); + return { originalCwd: X, projectRoot: X, totalCostUSD: 0, totalAPIDuration: 0, totalAPIDurationWithoutRetries: 0, totalToolDuration: 0, startTime: Date.now(), lastInteractionTime: Date.now(), totalLinesAdded: 0, totalLinesRemoved: 0, hasUnknownModelCost: false, cwd: X, modelUsage: {}, mainLoopModelOverride: void 0, initialMainLoopModel: null, modelStrings: null, isInteractive: false, clientType: "cli", sessionIngressToken: void 0, oauthTokenFromFd: void 0, apiKeyFromFd: void 0, flagSettingsPath: void 0, allowedSettingSources: ["userSettings", "projectSettings", "localSettings", "flagSettings", "policySettings"], meter: null, sessionCounter: null, locCounter: null, prCounter: null, commitCounter: null, costCounter: null, tokenCounter: null, codeEditToolDecisionCounter: null, activeTimeCounter: null, sessionId: (0, import_crypto.randomUUID)(), parentSessionId: void 0, loggerProvider: null, eventLogger: null, meterProvider: null, tracerProvider: null, agentColorMap: /* @__PURE__ */ new Map(), agentColorIndex: 0, envVarValidators: [o7, t7], lastAPIRequest: null, inMemoryErrorLog: [], inlinePlugins: [], useCoworkPlugins: false, sessionBypassPermissionsMode: false, sessionTrustAccepted: false, sessionPersistenceDisabled: false, hasExitedPlanMode: false, needsPlanModeExitAttachment: false, hasExitedDelegateMode: false, needsDelegateModeExitAttachment: false, lspRecommendationShownThisSession: false, initJsonSchema: null, registeredHooks: null, planSlugCache: /* @__PURE__ */ new Map(), teleportedSessionInfo: null, invokedSkills: /* @__PURE__ */ new Map(), slowOperations: [], sdkBetas: void 0, mainThreadAgentType: void 0, isRemoteMode: false }; +} +var bU = IU(); +function a7() { + return bU.sessionId; +} +function s7({ writeFn: X, flushIntervalMs: Q = 1e3, maxBufferSize: $ = 100, immediateMode: Y = false }) { + let W = [], J = null; + function G() { + if (J) clearTimeout(J), J = null; + } + function H() { + if (W.length === 0) return; + X(W.join("")), W = [], G(); + } + function B() { + if (!J) J = setTimeout(H, Q); + } + return { write(z2) { + if (Y) { + X(z2); + return; + } + if (W.push(z2), B(), W.length >= $) H(); + }, flush: H, dispose() { + H(); + } }; +} +var e7 = /* @__PURE__ */ new Set(); +function XW(X) { + return e7.add(X), () => e7.delete(X); +} +var B8 = 1 / 0; +function PU(X) { + if (X === null) return "null"; + if (X === void 0) return "undefined"; + if (Array.isArray(X)) return `Array[${X.length}]`; + if (typeof X === "object") return `Object{${Object.keys(X).length} keys}`; + if (typeof X === "string") return `string(${X.length} chars)`; + return typeof X; +} +function QW(X, Q) { + let $ = performance.now(); + try { + return Q(); + } finally { + performance.now() - $ > B8; + } +} +function Z0(X, Q, $) { + let Y = PU(X); + return QW(`JSON.stringify(${Y})`, () => JSON.stringify(X, Q, $)); +} +var L4 = (X, Q) => { + let $ = typeof X === "string" ? X.length : 0; + return QW(`JSON.parse(${$} chars)`, () => JSON.parse(X, Q)); +}; +var SU = r1(() => { + return H8(process.env.DEBUG) || H8(process.env.DEBUG_SDK) || process.argv.includes("--debug") || process.argv.includes("-d") || YW() || process.argv.some((X) => X.startsWith("--debug=")); +}); +var ZU = r1(() => { + let X = process.argv.find(($) => $.startsWith("--debug=")); + if (!X) return null; + let Q = X.substring(8); + return i7(Q); +}); +var YW = r1(() => { + return process.argv.includes("--debug-to-stderr") || process.argv.includes("-d2e"); +}); +function CU(X) { + if (typeof process > "u" || typeof process.versions > "u" || typeof process.versions.node > "u") return false; + let Q = ZU(); + return n7(X, Q); +} +var kU = false; +var q4 = null; +function vU() { + if (!q4) q4 = s7({ writeFn: (X) => { + let Q = WW(); + if (!n0().existsSync((0, import_path4.dirname)(Q))) n0().mkdirSync((0, import_path4.dirname)(Q)); + n0().appendFileSync(Q, X), TU(); + }, flushIntervalMs: 1e3, maxBufferSize: 100, immediateMode: SU() }), XW(async () => q4 == null ? void 0 : q4.dispose()); + return q4; +} +function k1(X, { level: Q } = { level: "debug" }) { + if (!CU(X)) return; + if (kU && X.includes(` +`)) X = Z0(X); + let Y = `${(/* @__PURE__ */ new Date()).toISOString()} [${Q.toUpperCase()}] ${X.trim()} +`; + if (YW()) { + d7(Y); + return; + } + vU().write(Y); +} +function WW() { + var _a3; + return (_a3 = process.env.CLAUDE_CODE_DEBUG_LOGS_DIR) != null ? _a3 : (0, import_path4.join)(V4(), "debug", `${a7()}.txt`); +} +var TU = r1(() => { + if (process.argv[2] === "--ripgrep") return; + try { + let X = WW(), Q = (0, import_path4.dirname)(X), $ = (0, import_path4.join)(Q, "latest"); + if (!n0().existsSync(Q)) n0().mkdirSync(Q); + if (n0().existsSync($)) try { + n0().unlinkSync($); + } catch (e2) { + } + n0().symlinkSync(X, $); + } catch (e2) { + } +}); +function F0(X, Q) { + let $ = performance.now(); + try { + return Q(); + } finally { + performance.now() - $ > B8; + } +} +var yU = { cwd() { + return process.cwd(); +}, existsSync(X) { + return F0(`existsSync(${X})`, () => f.existsSync(X)); +}, async stat(X) { + return (0, import_promises.stat)(X); +}, statSync(X) { + return F0(`statSync(${X})`, () => f.statSync(X)); +}, lstatSync(X) { + return F0(`lstatSync(${X})`, () => f.lstatSync(X)); +}, readFileSync(X, Q) { + return F0(`readFileSync(${X})`, () => f.readFileSync(X, { encoding: Q.encoding })); +}, readFileBytesSync(X) { + return F0(`readFileBytesSync(${X})`, () => f.readFileSync(X)); +}, readSync(X, Q) { + return F0(`readSync(${X}, ${Q.length} bytes)`, () => { + let $ = void 0; + try { + $ = f.openSync(X, "r"); + let Y = Buffer.alloc(Q.length), W = f.readSync($, Y, 0, Q.length, 0); + return { buffer: Y, bytesRead: W }; + } finally { + if ($) f.closeSync($); + } + }); +}, appendFileSync(X, Q, $) { + return F0(`appendFileSync(${X}, ${Q.length} chars)`, () => { + if (!f.existsSync(X) && ($ == null ? void 0 : $.mode) !== void 0) { + let Y = f.openSync(X, "a", $.mode); + try { + f.appendFileSync(Y, Q); + } finally { + f.closeSync(Y); + } + } else f.appendFileSync(X, Q); + }); +}, copyFileSync(X, Q) { + return F0(`copyFileSync(${X} \u2192 ${Q})`, () => f.copyFileSync(X, Q)); +}, unlinkSync(X) { + return F0(`unlinkSync(${X})`, () => f.unlinkSync(X)); +}, renameSync(X, Q) { + return F0(`renameSync(${X} \u2192 ${Q})`, () => f.renameSync(X, Q)); +}, linkSync(X, Q) { + return F0(`linkSync(${X} \u2192 ${Q})`, () => f.linkSync(X, Q)); +}, symlinkSync(X, Q) { + return F0(`symlinkSync(${X} \u2192 ${Q})`, () => f.symlinkSync(X, Q)); +}, readlinkSync(X) { + return F0(`readlinkSync(${X})`, () => f.readlinkSync(X)); +}, realpathSync(X) { + return F0(`realpathSync(${X})`, () => f.realpathSync(X)); +}, mkdirSync(X, Q) { + return F0(`mkdirSync(${X})`, () => { + if (!f.existsSync(X)) { + let $ = { recursive: true }; + if ((Q == null ? void 0 : Q.mode) !== void 0) $.mode = Q.mode; + f.mkdirSync(X, $); + } + }); +}, readdirSync(X) { + return F0(`readdirSync(${X})`, () => f.readdirSync(X, { withFileTypes: true })); +}, readdirStringSync(X) { + return F0(`readdirStringSync(${X})`, () => f.readdirSync(X)); +}, isDirEmptySync(X) { + return F0(`isDirEmptySync(${X})`, () => { + return this.readdirSync(X).length === 0; + }); +}, rmdirSync(X) { + return F0(`rmdirSync(${X})`, () => f.rmdirSync(X)); +}, rmSync(X, Q) { + return F0(`rmSync(${X})`, () => f.rmSync(X, Q)); +}, createWriteStream(X) { + return f.createWriteStream(X); +} }; +var gU = yU; +function n0() { + return gU; +} +var F1 = class extends Error { +}; +function j6() { + return process.versions.bun !== void 0; +} +var F4 = null; +var GW = false; +function pU() { + if (GW) return F4; + if (GW = true, !process.env.DEBUG_CLAUDE_AGENT_SDK) return null; + let X = (0, import_path5.join)(V4(), "debug"); + if (F4 = (0, import_path5.join)(X, `sdk-${(0, import_crypto2.randomUUID)()}.txt`), !(0, import_fs2.existsSync)(X)) (0, import_fs2.mkdirSync)(X, { recursive: true }); + return process.stderr.write(`SDK debug logs: ${F4} +`), F4; +} +function N1(X) { + let Q = pU(); + if (!Q) return; + let Y = `${(/* @__PURE__ */ new Date()).toISOString()} ${X} +`; + (0, import_fs2.appendFileSync)(Q, Y); +} +function HW(X, Q) { + let $ = { ...X }; + if (Q) { + let Y = { sandbox: Q }; + if ($.settings) try { + Y = { ...L4($.settings), sandbox: Q }; + } catch (e2) { + } + $.settings = Z0(Y); + } + return $; +} +var XX = class { + constructor(X) { + __publicField(this, "options"); + __publicField(this, "process"); + __publicField(this, "processStdin"); + __publicField(this, "processStdout"); + __publicField(this, "ready", false); + __publicField(this, "abortController"); + __publicField(this, "exitError"); + __publicField(this, "exitListeners", []); + __publicField(this, "processExitHandler"); + __publicField(this, "abortHandler"); + this.options = X; + this.abortController = X.abortController || N6(), this.initialize(); + } + getDefaultExecutable() { + return j6() ? "bun" : "node"; + } + spawnLocalProcess(X) { + let { command: Q, args: $, cwd: Y, env: W, signal: J } = X, G = W.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr ? "pipe" : "ignore", H = (0, import_child_process.spawn)(Q, $, { cwd: Y, stdio: ["pipe", "pipe", G], signal: J, env: W, windowsHide: true }); + if (W.DEBUG_CLAUDE_AGENT_SDK || this.options.stderr) H.stderr.on("data", (z2) => { + let K = z2.toString(); + if (N1(K), this.options.stderr) this.options.stderr(K); + }); + return { stdin: H.stdin, stdout: H.stdout, get killed() { + return H.killed; + }, get exitCode() { + return H.exitCode; + }, kill: H.kill.bind(H), on: H.on.bind(H), once: H.once.bind(H), off: H.off.bind(H) }; + } + initialize() { + try { + let { additionalDirectories: X = [], agent: Q, betas: $, cwd: Y, executable: W = this.getDefaultExecutable(), executableArgs: J = [], extraArgs: G = {}, pathToClaudeCodeExecutable: H, env: B = { ...process.env }, maxThinkingTokens: z2, maxTurns: K, maxBudgetUsd: V, model: L, fallbackModel: U, jsonSchema: F, permissionMode: q, allowDangerouslySkipPermissions: N, permissionPromptToolName: A, continueConversation: M, resume: R, settingSources: S, allowedTools: C = [], disallowedTools: K0 = [], tools: U0, mcpServers: s, strictMcpConfig: D0, canUseTool: q0, includePartialMessages: W1, plugins: P1, sandbox: U6 } = this.options, d = ["--output-format", "stream-json", "--verbose", "--input-format", "stream-json"]; + if (z2 !== void 0) d.push("--max-thinking-tokens", z2.toString()); + if (K) d.push("--max-turns", K.toString()); + if (V !== void 0) d.push("--max-budget-usd", V.toString()); + if (L) d.push("--model", L); + if (Q) d.push("--agent", Q); + if ($ && $.length > 0) d.push("--betas", $.join(",")); + if (F) d.push("--json-schema", Z0(F)); + if (B.DEBUG_CLAUDE_AGENT_SDK) d.push("--debug-to-stderr"); + if (q0) { + if (A) throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other."); + d.push("--permission-prompt-tool", "stdio"); + } else if (A) d.push("--permission-prompt-tool", A); + if (M) d.push("--continue"); + if (R) d.push("--resume", R); + if (C.length > 0) d.push("--allowedTools", C.join(",")); + if (K0.length > 0) d.push("--disallowedTools", K0.join(",")); + if (U0 !== void 0) if (Array.isArray(U0)) if (U0.length === 0) d.push("--tools", ""); + else d.push("--tools", U0.join(",")); + else d.push("--tools", "default"); + if (s && Object.keys(s).length > 0) d.push("--mcp-config", Z0({ mcpServers: s })); + if (S) d.push("--setting-sources", S.join(",")); + if (D0) d.push("--strict-mcp-config"); + if (q) d.push("--permission-mode", q); + if (N) d.push("--allow-dangerously-skip-permissions"); + if (U) { + if (L && U === L) throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option."); + d.push("--fallback-model", U); + } + if (W1) d.push("--include-partial-messages"); + for (let S0 of X) d.push("--add-dir", S0); + if (P1 && P1.length > 0) for (let S0 of P1) if (S0.type === "local") d.push("--plugin-dir", S0.path); + else throw Error(`Unsupported plugin type: ${S0.type}`); + if (this.options.forkSession) d.push("--fork-session"); + if (this.options.resumeSessionAt) d.push("--resume-session-at", this.options.resumeSessionAt); + if (this.options.persistSession === false) d.push("--no-session-persistence"); + let Q8 = HW(G != null ? G : {}, U6); + for (let [S0, S1] of Object.entries(Q8)) if (S1 === null) d.push(`--${S0}`); + else d.push(`--${S0}`, S1); + if (!B.CLAUDE_CODE_ENTRYPOINT) B.CLAUDE_CODE_ENTRYPOINT = "sdk-ts"; + if (delete B.NODE_OPTIONS, B.DEBUG_CLAUDE_AGENT_SDK) B.DEBUG = "1"; + else delete B.DEBUG; + let o6 = nU(H), V6 = o6 ? H : W, t6 = o6 ? [...J, ...d] : [...J, H, ...d], a6 = { command: V6, args: t6, cwd: Y, env: B, signal: this.abortController.signal }; + if (this.options.spawnClaudeCodeProcess) N1(`Spawning Claude Code (custom): ${V6} ${t6.join(" ")}`), this.process = this.options.spawnClaudeCodeProcess(a6); + else { + if (!n0().existsSync(H)) { + let S1 = o6 ? `Claude Code native binary not found at ${H}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.` : `Claude Code executable not found at ${H}. Is options.pathToClaudeCodeExecutable set?`; + throw ReferenceError(S1); + } + N1(`Spawning Claude Code: ${V6} ${t6.join(" ")}`), this.process = this.spawnLocalProcess(a6); + } + this.processStdin = this.process.stdin, this.processStdout = this.process.stdout; + let B4 = () => { + if (this.process && !this.process.killed) this.process.kill("SIGTERM"); + }; + this.processExitHandler = B4, this.abortHandler = B4, process.on("exit", this.processExitHandler), this.abortController.signal.addEventListener("abort", this.abortHandler), this.process.on("error", (S0) => { + if (this.ready = false, this.abortController.signal.aborted) this.exitError = new F1("Claude Code process aborted by user"); + else this.exitError = Error(`Failed to spawn Claude Code process: ${S0.message}`), N1(this.exitError.message); + }), this.process.on("exit", (S0, S1) => { + if (this.ready = false, this.abortController.signal.aborted) this.exitError = new F1("Claude Code process aborted by user"); + else { + let s6 = this.getProcessExitError(S0, S1); + if (s6) this.exitError = s6, N1(s6.message); + } + }), this.ready = true; + } catch (X) { + throw this.ready = false, X; + } + } + getProcessExitError(X, Q) { + if (X !== 0 && X !== null) return Error(`Claude Code process exited with code ${X}`); + else if (Q) return Error(`Claude Code process terminated by signal ${Q}`); + return; + } + write(X) { + var _a3, _b; + if (this.abortController.signal.aborted) throw new F1("Operation aborted"); + if (!this.ready || !this.processStdin) throw Error("ProcessTransport is not ready for writing"); + if (((_a3 = this.process) == null ? void 0 : _a3.killed) || ((_b = this.process) == null ? void 0 : _b.exitCode) !== null) throw Error("Cannot write to terminated process"); + if (this.exitError) throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`); + N1(`[ProcessTransport] Writing to stdin: ${X.substring(0, 100)}`); + try { + if (!this.processStdin.write(X)) N1("[ProcessTransport] Write buffer full, data queued"); + } catch (Q) { + throw this.ready = false, Error(`Failed to write to process stdin: ${Q.message}`); + } + } + close() { + var _a3; + if (this.processStdin) this.processStdin.end(), this.processStdin = void 0; + if (this.abortHandler) this.abortController.signal.removeEventListener("abort", this.abortHandler), this.abortHandler = void 0; + for (let { handler: X } of this.exitListeners) (_a3 = this.process) == null ? void 0 : _a3.off("exit", X); + if (this.exitListeners = [], this.process && !this.process.killed) this.process.kill("SIGTERM"), setTimeout(() => { + if (this.process && !this.process.killed) this.process.kill("SIGKILL"); + }, 5e3); + if (this.ready = false, this.processExitHandler) process.off("exit", this.processExitHandler), this.processExitHandler = void 0; + } + isReady() { + return this.ready; + } + async *readMessages() { + if (!this.processStdout) throw Error("ProcessTransport output stream not available"); + let X = (0, import_readline.createInterface)({ input: this.processStdout }); + try { + for await (let Q of X) if (Q.trim()) try { + yield L4(Q); + } catch ($) { + throw N1(`Non-JSON stdout: ${Q}`), Error(`CLI output was not valid JSON. This may indicate an error during startup. Output: ${Q.slice(0, 200)}${Q.length > 200 ? "..." : ""}`); + } + await this.waitForExit(); + } catch (Q) { + throw Q; + } finally { + X.close(); + } + } + endInput() { + if (this.processStdin) this.processStdin.end(); + } + getInputStream() { + return this.processStdin; + } + onExit(X) { + if (!this.process) return () => { + }; + let Q = ($, Y) => { + let W = this.getProcessExitError($, Y); + X(W); + }; + return this.process.on("exit", Q), this.exitListeners.push({ callback: X, handler: Q }), () => { + if (this.process) this.process.off("exit", Q); + let $ = this.exitListeners.findIndex((Y) => Y.handler === Q); + if ($ !== -1) this.exitListeners.splice($, 1); + }; + } + async waitForExit() { + if (!this.process) { + if (this.exitError) throw this.exitError; + return; + } + if (this.process.exitCode !== null || this.process.killed) { + if (this.exitError) throw this.exitError; + return; + } + return new Promise((X, Q) => { + let $ = (W, J) => { + if (this.abortController.signal.aborted) { + Q(new F1("Operation aborted")); + return; + } + let G = this.getProcessExitError(W, J); + if (G) Q(G); + else X(); + }; + this.process.once("exit", $); + let Y = (W) => { + this.process.off("exit", $), Q(W); + }; + this.process.once("error", Y), this.process.once("exit", () => { + this.process.off("error", Y); + }); + }); + } +}; +function nU(X) { + return ![".js", ".mjs", ".tsx", ".ts", ".jsx"].some(($) => X.endsWith($)); +} +var QX = class { + constructor(X) { + __publicField(this, "returned"); + __publicField(this, "queue", []); + __publicField(this, "readResolve"); + __publicField(this, "readReject"); + __publicField(this, "isDone", false); + __publicField(this, "hasError"); + __publicField(this, "started", false); + this.returned = X; + } + [Symbol.asyncIterator]() { + if (this.started) throw Error("Stream can only be iterated once"); + return this.started = true, this; + } + next() { + if (this.queue.length > 0) return Promise.resolve({ done: false, value: this.queue.shift() }); + if (this.isDone) return Promise.resolve({ done: true, value: void 0 }); + if (this.hasError) return Promise.reject(this.hasError); + return new Promise((X, Q) => { + this.readResolve = X, this.readReject = Q; + }); + } + enqueue(X) { + if (this.readResolve) { + let Q = this.readResolve; + this.readResolve = void 0, this.readReject = void 0, Q({ done: false, value: X }); + } else this.queue.push(X); + } + done() { + if (this.isDone = true, this.readResolve) { + let X = this.readResolve; + this.readResolve = void 0, this.readReject = void 0, X({ done: true, value: void 0 }); + } + } + error(X) { + if (this.hasError = X, this.readReject) { + let Q = this.readReject; + this.readResolve = void 0, this.readReject = void 0, Q(X); + } + } + return() { + if (this.isDone = true, this.returned) this.returned(); + return Promise.resolve({ done: true, value: void 0 }); + } +}; +var K8 = class { + constructor(X) { + __publicField(this, "sendMcpMessage"); + __publicField(this, "isClosed", false); + __publicField(this, "onclose"); + __publicField(this, "onerror"); + __publicField(this, "onmessage"); + this.sendMcpMessage = X; + } + async start() { + } + async send(X) { + if (this.isClosed) throw Error("Transport is closed"); + this.sendMcpMessage(X); + } + async close() { + var _a3; + if (this.isClosed) return; + this.isClosed = true, (_a3 = this.onclose) == null ? void 0 : _a3.call(this); + } +}; +var $X = class { + constructor(X, Q, $, Y, W, J = /* @__PURE__ */ new Map(), G, H) { + __publicField(this, "transport"); + __publicField(this, "isSingleUserTurn"); + __publicField(this, "canUseTool"); + __publicField(this, "hooks"); + __publicField(this, "abortController"); + __publicField(this, "jsonSchema"); + __publicField(this, "initConfig"); + __publicField(this, "pendingControlResponses", /* @__PURE__ */ new Map()); + __publicField(this, "cleanupPerformed", false); + __publicField(this, "sdkMessages"); + __publicField(this, "inputStream", new QX()); + __publicField(this, "initialization"); + __publicField(this, "cancelControllers", /* @__PURE__ */ new Map()); + __publicField(this, "hookCallbacks", /* @__PURE__ */ new Map()); + __publicField(this, "nextCallbackId", 0); + __publicField(this, "sdkMcpTransports", /* @__PURE__ */ new Map()); + __publicField(this, "sdkMcpServerInstances", /* @__PURE__ */ new Map()); + __publicField(this, "pendingMcpResponses", /* @__PURE__ */ new Map()); + __publicField(this, "firstResultReceivedResolve"); + __publicField(this, "firstResultReceived", false); + this.transport = X; + this.isSingleUserTurn = Q; + this.canUseTool = $; + this.hooks = Y; + this.abortController = W; + this.jsonSchema = G; + this.initConfig = H; + for (let [B, z2] of J) this.connectSdkMcpServer(B, z2); + this.sdkMessages = this.readSdkMessages(), this.readMessages(), this.initialization = this.initialize(), this.initialization.catch(() => { + }); + } + hasBidirectionalNeeds() { + return this.sdkMcpTransports.size > 0 || this.hooks !== void 0 && Object.keys(this.hooks).length > 0 || this.canUseTool !== void 0; + } + setError(X) { + this.inputStream.error(X); + } + close() { + this.cleanup(); + } + cleanup(X) { + if (this.cleanupPerformed) return; + this.cleanupPerformed = true; + try { + this.transport.close(), this.pendingControlResponses.clear(), this.pendingMcpResponses.clear(), this.cancelControllers.clear(), this.hookCallbacks.clear(); + for (let Q of this.sdkMcpTransports.values()) try { + Q.close(); + } catch (e2) { + } + if (this.sdkMcpTransports.clear(), X) this.inputStream.error(X); + else this.inputStream.done(); + } catch (Q) { + } + } + next(...[X]) { + return this.sdkMessages.next(...[X]); + } + return(X) { + return this.sdkMessages.return(X); + } + throw(X) { + return this.sdkMessages.throw(X); + } + [Symbol.asyncIterator]() { + return this.sdkMessages; + } + [Symbol.asyncDispose]() { + return this.sdkMessages[Symbol.asyncDispose](); + } + async readMessages() { + try { + for await (let X of this.transport.readMessages()) { + if (X.type === "control_response") { + let Q = this.pendingControlResponses.get(X.response.request_id); + if (Q) Q(X.response); + continue; + } else if (X.type === "control_request") { + this.handleControlRequest(X); + continue; + } else if (X.type === "control_cancel_request") { + this.handleControlCancelRequest(X); + continue; + } else if (X.type === "keep_alive") continue; + if (X.type === "result") { + if (this.firstResultReceived = true, this.firstResultReceivedResolve) this.firstResultReceivedResolve(); + if (this.isSingleUserTurn) k1("[Query.readMessages] First result received for single-turn query, closing stdin"), this.transport.endInput(); + } + this.inputStream.enqueue(X); + } + if (this.firstResultReceivedResolve) this.firstResultReceivedResolve(); + this.inputStream.done(), this.cleanup(); + } catch (X) { + if (this.firstResultReceivedResolve) this.firstResultReceivedResolve(); + this.inputStream.error(X), this.cleanup(X); + } + } + async handleControlRequest(X) { + let Q = new AbortController(); + this.cancelControllers.set(X.request_id, Q); + try { + let $ = await this.processControlRequest(X, Q.signal), Y = { type: "control_response", response: { subtype: "success", request_id: X.request_id, response: $ } }; + await Promise.resolve(this.transport.write(Z0(Y) + ` +`)); + } catch ($) { + let Y = { type: "control_response", response: { subtype: "error", request_id: X.request_id, error: $.message || String($) } }; + await Promise.resolve(this.transport.write(Z0(Y) + ` +`)); + } finally { + this.cancelControllers.delete(X.request_id); + } + } + handleControlCancelRequest(X) { + let Q = this.cancelControllers.get(X.request_id); + if (Q) Q.abort(), this.cancelControllers.delete(X.request_id); + } + async processControlRequest(X, Q) { + if (X.request.subtype === "can_use_tool") { + if (!this.canUseTool) throw Error("canUseTool callback is not provided."); + return { ...await this.canUseTool(X.request.tool_name, X.request.input, { signal: Q, suggestions: X.request.permission_suggestions, blockedPath: X.request.blocked_path, decisionReason: X.request.decision_reason, toolUseID: X.request.tool_use_id, agentID: X.request.agent_id }), toolUseID: X.request.tool_use_id }; + } else if (X.request.subtype === "hook_callback") return await this.handleHookCallbacks(X.request.callback_id, X.request.input, X.request.tool_use_id, Q); + else if (X.request.subtype === "mcp_message") { + let $ = X.request, Y = this.sdkMcpTransports.get($.server_name); + if (!Y) throw Error(`SDK MCP server not found: ${$.server_name}`); + if ("method" in $.message && "id" in $.message && $.message.id !== null) return { mcp_response: await this.handleMcpControlRequest($.server_name, $, Y) }; + else { + if (Y.onmessage) Y.onmessage($.message); + return { mcp_response: { jsonrpc: "2.0", result: {}, id: 0 } }; + } + } + throw Error("Unsupported control request subtype: " + X.request.subtype); + } + async *readSdkMessages() { + for await (let X of this.inputStream) yield X; + } + async initialize() { + var _a3, _b, _c; + let X; + if (this.hooks) { + X = {}; + for (let [W, J] of Object.entries(this.hooks)) if (J.length > 0) X[W] = J.map((G) => { + let H = []; + for (let B of G.hooks) { + let z2 = `hook_${this.nextCallbackId++}`; + this.hookCallbacks.set(z2, B), H.push(z2); + } + return { matcher: G.matcher, hookCallbackIds: H, timeout: G.timeout }; + }); + } + let Q = this.sdkMcpTransports.size > 0 ? Array.from(this.sdkMcpTransports.keys()) : void 0, $ = { subtype: "initialize", hooks: X, sdkMcpServers: Q, jsonSchema: this.jsonSchema, systemPrompt: (_a3 = this.initConfig) == null ? void 0 : _a3.systemPrompt, appendSystemPrompt: (_b = this.initConfig) == null ? void 0 : _b.appendSystemPrompt, agents: (_c = this.initConfig) == null ? void 0 : _c.agents }; + return (await this.request($)).response; + } + async interrupt() { + await this.request({ subtype: "interrupt" }); + } + async setPermissionMode(X) { + await this.request({ subtype: "set_permission_mode", mode: X }); + } + async setModel(X) { + await this.request({ subtype: "set_model", model: X }); + } + async setMaxThinkingTokens(X) { + await this.request({ subtype: "set_max_thinking_tokens", max_thinking_tokens: X }); + } + async rewindFiles(X, Q) { + return (await this.request({ subtype: "rewind_files", user_message_id: X, dry_run: Q == null ? void 0 : Q.dryRun })).response; + } + async processPendingPermissionRequests(X) { + for (let Q of X) if (Q.request.subtype === "can_use_tool") this.handleControlRequest(Q).catch(() => { + }); + } + request(X) { + let Q = Math.random().toString(36).substring(2, 15), $ = { request_id: Q, type: "control_request", request: X }; + return new Promise((Y, W) => { + this.pendingControlResponses.set(Q, (J) => { + if (J.subtype === "success") Y(J); + else if (W(Error(J.error)), J.pending_permission_requests) this.processPendingPermissionRequests(J.pending_permission_requests); + }), Promise.resolve(this.transport.write(Z0($) + ` +`)); + }); + } + async supportedCommands() { + return (await this.initialization).commands; + } + async supportedModels() { + return (await this.initialization).models; + } + async mcpServerStatus() { + return (await this.request({ subtype: "mcp_status" })).response.mcpServers; + } + async setMcpServers(X) { + let Q = {}, $ = {}; + for (let [H, B] of Object.entries(X)) if (B.type === "sdk" && "instance" in B) Q[H] = B.instance; + else $[H] = B; + let Y = new Set(this.sdkMcpServerInstances.keys()), W = new Set(Object.keys(Q)); + for (let H of Y) if (!W.has(H)) await this.disconnectSdkMcpServer(H); + for (let [H, B] of Object.entries(Q)) if (!Y.has(H)) this.connectSdkMcpServer(H, B); + let J = {}; + for (let H of Object.keys(Q)) J[H] = { type: "sdk", name: H }; + return (await this.request({ subtype: "mcp_set_servers", servers: { ...$, ...J } })).response; + } + async accountInfo() { + return (await this.initialization).account; + } + async streamInput(X) { + var _a3; + k1("[Query.streamInput] Starting to process input stream"); + try { + let Q = 0; + for await (let $ of X) { + if (Q++, k1(`[Query.streamInput] Processing message ${Q}: ${$.type}`), (_a3 = this.abortController) == null ? void 0 : _a3.signal.aborted) break; + await Promise.resolve(this.transport.write(Z0($) + ` +`)); + } + if (k1(`[Query.streamInput] Finished processing ${Q} messages from input stream`), Q > 0 && this.hasBidirectionalNeeds()) k1("[Query.streamInput] Has bidirectional needs, waiting for first result"), await this.waitForFirstResult(); + k1("[Query] Calling transport.endInput() to close stdin to CLI process"), this.transport.endInput(); + } catch (Q) { + if (!(Q instanceof F1)) throw Q; + } + } + waitForFirstResult() { + if (this.firstResultReceived) return k1("[Query.waitForFirstResult] Result already received, returning immediately"), Promise.resolve(); + return new Promise((X) => { + var _a3, _b; + if ((_a3 = this.abortController) == null ? void 0 : _a3.signal.aborted) { + X(); + return; + } + (_b = this.abortController) == null ? void 0 : _b.signal.addEventListener("abort", () => X(), { once: true }), this.firstResultReceivedResolve = X; + }); + } + handleHookCallbacks(X, Q, $, Y) { + let W = this.hookCallbacks.get(X); + if (!W) throw Error(`No hook callback found for ID: ${X}`); + return W(Q, $, { signal: Y }); + } + connectSdkMcpServer(X, Q) { + let $ = new K8((Y) => this.sendMcpServerMessageToCli(X, Y)); + this.sdkMcpTransports.set(X, $), this.sdkMcpServerInstances.set(X, Q), Q.connect($); + } + async disconnectSdkMcpServer(X) { + let Q = this.sdkMcpTransports.get(X); + if (Q) await Q.close(), this.sdkMcpTransports.delete(X); + this.sdkMcpServerInstances.delete(X); + } + sendMcpServerMessageToCli(X, Q) { + if ("id" in Q && Q.id !== null && Q.id !== void 0) { + let Y = `${X}:${Q.id}`, W = this.pendingMcpResponses.get(Y); + if (W) { + W.resolve(Q), this.pendingMcpResponses.delete(Y); + return; + } + } + let $ = { type: "control_request", request_id: (0, import_crypto3.randomUUID)(), request: { subtype: "mcp_message", server_name: X, message: Q } }; + this.transport.write(Z0($) + ` +`); + } + handleMcpControlRequest(X, Q, $) { + let Y = "id" in Q.message ? Q.message.id : null, W = `${X}:${Y}`; + return new Promise((J, G) => { + let H = () => { + this.pendingMcpResponses.delete(W); + }, B = (K) => { + H(), J(K); + }, z2 = (K) => { + H(), G(K); + }; + if (this.pendingMcpResponses.set(W, { resolve: B, reject: z2 }), $.onmessage) $.onmessage(Q.message); + else { + H(), G(Error("No message handler registered")); + return; + } + }); + } +}; +var n; +(function(X) { + X.assertEqual = (W) => { + }; + function Q(W) { + } + X.assertIs = Q; + function $(W) { + throw Error(); + } + X.assertNever = $, X.arrayToEnum = (W) => { + let J = {}; + for (let G of W) J[G] = G; + return J; + }, X.getValidEnumValues = (W) => { + let J = X.objectKeys(W).filter((H) => typeof W[W[H]] !== "number"), G = {}; + for (let H of J) G[H] = W[H]; + return X.objectValues(G); + }, X.objectValues = (W) => { + return X.objectKeys(W).map(function(J) { + return W[J]; + }); + }, X.objectKeys = typeof Object.keys === "function" ? (W) => Object.keys(W) : (W) => { + let J = []; + for (let G in W) if (Object.prototype.hasOwnProperty.call(W, G)) J.push(G); + return J; + }, X.find = (W, J) => { + for (let G of W) if (J(G)) return G; + return; + }, X.isInteger = typeof Number.isInteger === "function" ? (W) => Number.isInteger(W) : (W) => typeof W === "number" && Number.isFinite(W) && Math.floor(W) === W; + function Y(W, J = " | ") { + return W.map((G) => typeof G === "string" ? `'${G}'` : G).join(J); + } + X.joinValues = Y, X.jsonStringifyReplacer = (W, J) => { + if (typeof J === "bigint") return J.toString(); + return J; + }; +})(n || (n = {})); +var KW; +(function(X) { + X.mergeShapes = (Q, $) => { + return { ...Q, ...$ }; + }; +})(KW || (KW = {})); +var E = n.arrayToEnum(["string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set"]); +var O1 = (X) => { + switch (typeof X) { + case "undefined": + return E.undefined; + case "string": + return E.string; + case "number": + return Number.isNaN(X) ? E.nan : E.number; + case "boolean": + return E.boolean; + case "function": + return E.function; + case "bigint": + return E.bigint; + case "symbol": + return E.symbol; + case "object": + if (Array.isArray(X)) return E.array; + if (X === null) return E.null; + if (X.then && typeof X.then === "function" && X.catch && typeof X.catch === "function") return E.promise; + if (typeof Map < "u" && X instanceof Map) return E.map; + if (typeof Set < "u" && X instanceof Set) return E.set; + if (typeof Date < "u" && X instanceof Date) return E.date; + return E.object; + default: + return E.unknown; + } +}; +var w = n.arrayToEnum(["invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite"]); +var f0 = class _f0 extends Error { + get errors() { + return this.issues; + } + constructor(X) { + super(); + this.issues = [], this.addIssue = ($) => { + this.issues = [...this.issues, $]; + }, this.addIssues = ($ = []) => { + this.issues = [...this.issues, ...$]; + }; + let Q = new.target.prototype; + if (Object.setPrototypeOf) Object.setPrototypeOf(this, Q); + else this.__proto__ = Q; + this.name = "ZodError", this.issues = X; + } + format(X) { + let Q = X || function(W) { + return W.message; + }, $ = { _errors: [] }, Y = (W) => { + for (let J of W.issues) if (J.code === "invalid_union") J.unionErrors.map(Y); + else if (J.code === "invalid_return_type") Y(J.returnTypeError); + else if (J.code === "invalid_arguments") Y(J.argumentsError); + else if (J.path.length === 0) $._errors.push(Q(J)); + else { + let G = $, H = 0; + while (H < J.path.length) { + let B = J.path[H]; + if (H !== J.path.length - 1) G[B] = G[B] || { _errors: [] }; + else G[B] = G[B] || { _errors: [] }, G[B]._errors.push(Q(J)); + G = G[B], H++; + } + } + }; + return Y(this), $; + } + static assert(X) { + if (!(X instanceof _f0)) throw Error(`Not a ZodError: ${X}`); + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, n.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(X = (Q) => Q.message) { + let Q = {}, $ = []; + for (let Y of this.issues) if (Y.path.length > 0) { + let W = Y.path[0]; + Q[W] = Q[W] || [], Q[W].push(X(Y)); + } else $.push(X(Y)); + return { formErrors: $, fieldErrors: Q }; + } + get formErrors() { + return this.flatten(); + } +}; +f0.create = (X) => { + return new f0(X); +}; +var tU = (X, Q) => { + let $; + switch (X.code) { + case w.invalid_type: + if (X.received === E.undefined) $ = "Required"; + else $ = `Expected ${X.expected}, received ${X.received}`; + break; + case w.invalid_literal: + $ = `Invalid literal value, expected ${JSON.stringify(X.expected, n.jsonStringifyReplacer)}`; + break; + case w.unrecognized_keys: + $ = `Unrecognized key(s) in object: ${n.joinValues(X.keys, ", ")}`; + break; + case w.invalid_union: + $ = "Invalid input"; + break; + case w.invalid_union_discriminator: + $ = `Invalid discriminator value. Expected ${n.joinValues(X.options)}`; + break; + case w.invalid_enum_value: + $ = `Invalid enum value. Expected ${n.joinValues(X.options)}, received '${X.received}'`; + break; + case w.invalid_arguments: + $ = "Invalid function arguments"; + break; + case w.invalid_return_type: + $ = "Invalid function return type"; + break; + case w.invalid_date: + $ = "Invalid date"; + break; + case w.invalid_string: + if (typeof X.validation === "object") if ("includes" in X.validation) { + if ($ = `Invalid input: must include "${X.validation.includes}"`, typeof X.validation.position === "number") $ = `${$} at one or more positions greater than or equal to ${X.validation.position}`; + } else if ("startsWith" in X.validation) $ = `Invalid input: must start with "${X.validation.startsWith}"`; + else if ("endsWith" in X.validation) $ = `Invalid input: must end with "${X.validation.endsWith}"`; + else n.assertNever(X.validation); + else if (X.validation !== "regex") $ = `Invalid ${X.validation}`; + else $ = "Invalid"; + break; + case w.too_small: + if (X.type === "array") $ = `Array must contain ${X.exact ? "exactly" : X.inclusive ? "at least" : "more than"} ${X.minimum} element(s)`; + else if (X.type === "string") $ = `String must contain ${X.exact ? "exactly" : X.inclusive ? "at least" : "over"} ${X.minimum} character(s)`; + else if (X.type === "number") $ = `Number must be ${X.exact ? "exactly equal to " : X.inclusive ? "greater than or equal to " : "greater than "}${X.minimum}`; + else if (X.type === "bigint") $ = `Number must be ${X.exact ? "exactly equal to " : X.inclusive ? "greater than or equal to " : "greater than "}${X.minimum}`; + else if (X.type === "date") $ = `Date must be ${X.exact ? "exactly equal to " : X.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(X.minimum))}`; + else $ = "Invalid input"; + break; + case w.too_big: + if (X.type === "array") $ = `Array must contain ${X.exact ? "exactly" : X.inclusive ? "at most" : "less than"} ${X.maximum} element(s)`; + else if (X.type === "string") $ = `String must contain ${X.exact ? "exactly" : X.inclusive ? "at most" : "under"} ${X.maximum} character(s)`; + else if (X.type === "number") $ = `Number must be ${X.exact ? "exactly" : X.inclusive ? "less than or equal to" : "less than"} ${X.maximum}`; + else if (X.type === "bigint") $ = `BigInt must be ${X.exact ? "exactly" : X.inclusive ? "less than or equal to" : "less than"} ${X.maximum}`; + else if (X.type === "date") $ = `Date must be ${X.exact ? "exactly" : X.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(X.maximum))}`; + else $ = "Invalid input"; + break; + case w.custom: + $ = "Invalid input"; + break; + case w.invalid_intersection_types: + $ = "Intersection results could not be merged"; + break; + case w.not_multiple_of: + $ = `Number must be a multiple of ${X.multipleOf}`; + break; + case w.not_finite: + $ = "Number must be finite"; + break; + default: + $ = Q.defaultError, n.assertNever(X); + } + return { message: $ }; +}; +var v1 = tU; +var aU = v1; +function YX() { + return aU; +} +var N4 = (X) => { + let { data: Q, path: $, errorMaps: Y, issueData: W } = X, J = [...$, ...W.path || []], G = { ...W, path: J }; + if (W.message !== void 0) return { ...W, path: J, message: W.message }; + let H = "", B = Y.filter((z2) => !!z2).slice().reverse(); + for (let z2 of B) H = z2(G, { data: Q, defaultError: H }).message; + return { ...W, path: J, message: H }; +}; +function b(X, Q) { + let $ = YX(), Y = N4({ issueData: Q, data: X.data, path: X.path, errorMaps: [X.common.contextualErrorMap, X.schemaErrorMap, $, $ === v1 ? void 0 : v1].filter((W) => !!W) }); + X.common.issues.push(Y); +} +var I0 = class _I0 { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") this.value = "aborted"; + } + static mergeArray(X, Q) { + let $ = []; + for (let Y of Q) { + if (Y.status === "aborted") return g; + if (Y.status === "dirty") X.dirty(); + $.push(Y.value); + } + return { status: X.value, value: $ }; + } + static async mergeObjectAsync(X, Q) { + let $ = []; + for (let Y of Q) { + let W = await Y.key, J = await Y.value; + $.push({ key: W, value: J }); + } + return _I0.mergeObjectSync(X, $); + } + static mergeObjectSync(X, Q) { + let $ = {}; + for (let Y of Q) { + let { key: W, value: J } = Y; + if (W.status === "aborted") return g; + if (J.status === "aborted") return g; + if (W.status === "dirty") X.dirty(); + if (J.status === "dirty") X.dirty(); + if (W.value !== "__proto__" && (typeof J.value < "u" || Y.alwaysSet)) $[W.value] = J.value; + } + return { status: X.value, value: $ }; + } +}; +var g = Object.freeze({ status: "aborted" }); +var R6 = (X) => ({ status: "dirty", value: X }); +var C0 = (X) => ({ status: "valid", value: X }); +var L8 = (X) => X.status === "aborted"; +var q8 = (X) => X.status === "dirty"; +var o1 = (X) => X.status === "valid"; +var WX = (X) => typeof Promise < "u" && X instanceof Promise; +var Z; +(function(X) { + X.errToObj = (Q) => typeof Q === "string" ? { message: Q } : Q || {}, X.toString = (Q) => typeof Q === "string" ? Q : Q == null ? void 0 : Q.message; +})(Z || (Z = {})); +var r0 = class { + constructor(X, Q, $, Y) { + this._cachedPath = [], this.parent = X, this.data = Q, this._path = $, this._key = Y; + } + get path() { + if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key); + else this._cachedPath.push(...this._path, this._key); + return this._cachedPath; + } +}; +var UW = (X, Q) => { + if (o1(Q)) return { success: true, data: Q.value }; + else { + if (!X.common.issues.length) throw Error("Validation failed but no issues detected."); + return { success: false, get error() { + if (this._error) return this._error; + let $ = new f0(X.common.issues); + return this._error = $, this._error; + } }; + } +}; +function l(X) { + if (!X) return {}; + let { errorMap: Q, invalid_type_error: $, required_error: Y, description: W } = X; + if (Q && ($ || Y)) throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + if (Q) return { errorMap: Q, description: W }; + return { errorMap: (G, H) => { + var _a3, _b; + let { message: B } = X; + if (G.code === "invalid_enum_value") return { message: B != null ? B : H.defaultError }; + if (typeof H.data > "u") return { message: (_a3 = B != null ? B : Y) != null ? _a3 : H.defaultError }; + if (G.code !== "invalid_type") return { message: H.defaultError }; + return { message: (_b = B != null ? B : $) != null ? _b : H.defaultError }; + }, description: W }; +} +var p = class { + get description() { + return this._def.description; + } + _getType(X) { + return O1(X.data); + } + _getOrReturnCtx(X, Q) { + return Q || { common: X.parent.common, data: X.data, parsedType: O1(X.data), schemaErrorMap: this._def.errorMap, path: X.path, parent: X.parent }; + } + _processInputParams(X) { + return { status: new I0(), ctx: { common: X.parent.common, data: X.data, parsedType: O1(X.data), schemaErrorMap: this._def.errorMap, path: X.path, parent: X.parent } }; + } + _parseSync(X) { + let Q = this._parse(X); + if (WX(Q)) throw Error("Synchronous parse encountered promise."); + return Q; + } + _parseAsync(X) { + let Q = this._parse(X); + return Promise.resolve(Q); + } + parse(X, Q) { + let $ = this.safeParse(X, Q); + if ($.success) return $.data; + throw $.error; + } + safeParse(X, Q) { + var _a3; + let $ = { common: { issues: [], async: (_a3 = Q == null ? void 0 : Q.async) != null ? _a3 : false, contextualErrorMap: Q == null ? void 0 : Q.errorMap }, path: (Q == null ? void 0 : Q.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data: X, parsedType: O1(X) }, Y = this._parseSync({ data: X, path: $.path, parent: $ }); + return UW($, Y); + } + "~validate"(X) { + var _a3, _b; + let Q = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data: X, parsedType: O1(X) }; + if (!this["~standard"].async) try { + let $ = this._parseSync({ data: X, path: [], parent: Q }); + return o1($) ? { value: $.value } : { issues: Q.common.issues }; + } catch ($) { + if ((_b = (_a3 = $ == null ? void 0 : $.message) == null ? void 0 : _a3.toLowerCase()) == null ? void 0 : _b.includes("encountered")) this["~standard"].async = true; + Q.common = { issues: [], async: true }; + } + return this._parseAsync({ data: X, path: [], parent: Q }).then(($) => o1($) ? { value: $.value } : { issues: Q.common.issues }); + } + async parseAsync(X, Q) { + let $ = await this.safeParseAsync(X, Q); + if ($.success) return $.data; + throw $.error; + } + async safeParseAsync(X, Q) { + let $ = { common: { issues: [], contextualErrorMap: Q == null ? void 0 : Q.errorMap, async: true }, path: (Q == null ? void 0 : Q.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data: X, parsedType: O1(X) }, Y = this._parse({ data: X, path: $.path, parent: $ }), W = await (WX(Y) ? Y : Promise.resolve(Y)); + return UW($, W); + } + refine(X, Q) { + let $ = (Y) => { + if (typeof Q === "string" || typeof Q > "u") return { message: Q }; + else if (typeof Q === "function") return Q(Y); + else return Q; + }; + return this._refinement((Y, W) => { + let J = X(Y), G = () => W.addIssue({ code: w.custom, ...$(Y) }); + if (typeof Promise < "u" && J instanceof Promise) return J.then((H) => { + if (!H) return G(), false; + else return true; + }); + if (!J) return G(), false; + else return true; + }); + } + refinement(X, Q) { + return this._refinement(($, Y) => { + if (!X($)) return Y.addIssue(typeof Q === "function" ? Q($, Y) : Q), false; + else return true; + }); + } + _refinement(X) { + return new H1({ schema: this, typeName: j.ZodEffects, effect: { type: "refinement", refinement: X } }); + } + superRefine(X) { + return this._refinement(X); + } + constructor(X) { + this.spa = this.safeParseAsync, this._def = X, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this), this["~standard"] = { version: 1, vendor: "zod", validate: (Q) => this["~validate"](Q) }; + } + optional() { + return G1.create(this, this._def); + } + nullable() { + return T1.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return J1.create(this); + } + promise() { + return S6.create(this, this._def); + } + or(X) { + return zX.create([this, X], this._def); + } + and(X) { + return KX.create(this, X, this._def); + } + transform(X) { + return new H1({ ...l(this._def), schema: this, typeName: j.ZodEffects, effect: { type: "transform", transform: X } }); + } + default(X) { + let Q = typeof X === "function" ? X : () => X; + return new qX({ ...l(this._def), innerType: this, defaultValue: Q, typeName: j.ZodDefault }); + } + brand() { + return new D8({ typeName: j.ZodBranded, type: this, ...l(this._def) }); + } + catch(X) { + let Q = typeof X === "function" ? X : () => X; + return new FX({ ...l(this._def), innerType: this, catchValue: Q, typeName: j.ZodCatch }); + } + describe(X) { + return new this.constructor({ ...this._def, description: X }); + } + pipe(X) { + return E4.create(this, X); + } + readonly() { + return NX.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var sU = /^c[^\s-]{8,}$/i; +var eU = /^[0-9a-z]+$/; +var XV = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var QV = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var $V = /^[a-z0-9_-]{21}$/i; +var YV = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var WV = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var JV = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var GV = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$"; +var F8; +var HV = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var BV = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +var zV = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var KV = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var UV = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var VV = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var VW = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))"; +var LV = new RegExp(`^${VW}$`); +function LW(X) { + let Q = "[0-5]\\d"; + if (X.precision) Q = `${Q}\\.\\d{${X.precision}}`; + else if (X.precision == null) Q = `${Q}(\\.\\d+)?`; + let $ = X.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${Q})${$}`; +} +function qV(X) { + return new RegExp(`^${LW(X)}$`); +} +function FV(X) { + let Q = `${VW}T${LW(X)}`, $ = []; + if ($.push(X.local ? "Z?" : "Z"), X.offset) $.push("([+-]\\d{2}:?\\d{2})"); + return Q = `${Q}(${$.join("|")})`, new RegExp(`^${Q}$`); +} +function NV(X, Q) { + if ((Q === "v4" || !Q) && HV.test(X)) return true; + if ((Q === "v6" || !Q) && zV.test(X)) return true; + return false; +} +function OV(X, Q) { + if (!YV.test(X)) return false; + try { + let [$] = X.split("."); + if (!$) return false; + let Y = $.replace(/-/g, "+").replace(/_/g, "/").padEnd($.length + (4 - $.length % 4) % 4, "="), W = JSON.parse(atob(Y)); + if (typeof W !== "object" || W === null) return false; + if ("typ" in W && (W == null ? void 0 : W.typ) !== "JWT") return false; + if (!W.alg) return false; + if (Q && W.alg !== Q) return false; + return true; + } catch (e2) { + return false; + } +} +function DV(X, Q) { + if ((Q === "v4" || !Q) && BV.test(X)) return true; + if ((Q === "v6" || !Q) && KV.test(X)) return true; + return false; +} +var A1 = class _A1 extends p { + _parse(X) { + if (this._def.coerce) X.data = String(X.data); + if (this._getType(X) !== E.string) { + let W = this._getOrReturnCtx(X); + return b(W, { code: w.invalid_type, expected: E.string, received: W.parsedType }), g; + } + let $ = new I0(), Y = void 0; + for (let W of this._def.checks) if (W.kind === "min") { + if (X.data.length < W.value) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.too_small, minimum: W.value, type: "string", inclusive: true, exact: false, message: W.message }), $.dirty(); + } else if (W.kind === "max") { + if (X.data.length > W.value) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.too_big, maximum: W.value, type: "string", inclusive: true, exact: false, message: W.message }), $.dirty(); + } else if (W.kind === "length") { + let J = X.data.length > W.value, G = X.data.length < W.value; + if (J || G) { + if (Y = this._getOrReturnCtx(X, Y), J) b(Y, { code: w.too_big, maximum: W.value, type: "string", inclusive: true, exact: true, message: W.message }); + else if (G) b(Y, { code: w.too_small, minimum: W.value, type: "string", inclusive: true, exact: true, message: W.message }); + $.dirty(); + } + } else if (W.kind === "email") { + if (!JV.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "email", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "emoji") { + if (!F8) F8 = new RegExp(GV, "u"); + if (!F8.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "emoji", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "uuid") { + if (!QV.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "uuid", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "nanoid") { + if (!$V.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "nanoid", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "cuid") { + if (!sU.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "cuid", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "cuid2") { + if (!eU.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "cuid2", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "ulid") { + if (!XV.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "ulid", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "url") try { + new URL(X.data); + } catch (e2) { + Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "url", code: w.invalid_string, message: W.message }), $.dirty(); + } + else if (W.kind === "regex") { + if (W.regex.lastIndex = 0, !W.regex.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "regex", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "trim") X.data = X.data.trim(); + else if (W.kind === "includes") { + if (!X.data.includes(W.value, W.position)) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.invalid_string, validation: { includes: W.value, position: W.position }, message: W.message }), $.dirty(); + } else if (W.kind === "toLowerCase") X.data = X.data.toLowerCase(); + else if (W.kind === "toUpperCase") X.data = X.data.toUpperCase(); + else if (W.kind === "startsWith") { + if (!X.data.startsWith(W.value)) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.invalid_string, validation: { startsWith: W.value }, message: W.message }), $.dirty(); + } else if (W.kind === "endsWith") { + if (!X.data.endsWith(W.value)) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.invalid_string, validation: { endsWith: W.value }, message: W.message }), $.dirty(); + } else if (W.kind === "datetime") { + if (!FV(W).test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.invalid_string, validation: "datetime", message: W.message }), $.dirty(); + } else if (W.kind === "date") { + if (!LV.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.invalid_string, validation: "date", message: W.message }), $.dirty(); + } else if (W.kind === "time") { + if (!qV(W).test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.invalid_string, validation: "time", message: W.message }), $.dirty(); + } else if (W.kind === "duration") { + if (!WV.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "duration", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "ip") { + if (!NV(X.data, W.version)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "ip", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "jwt") { + if (!OV(X.data, W.alg)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "jwt", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "cidr") { + if (!DV(X.data, W.version)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "cidr", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "base64") { + if (!UV.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "base64", code: w.invalid_string, message: W.message }), $.dirty(); + } else if (W.kind === "base64url") { + if (!VV.test(X.data)) Y = this._getOrReturnCtx(X, Y), b(Y, { validation: "base64url", code: w.invalid_string, message: W.message }), $.dirty(); + } else n.assertNever(W); + return { status: $.value, value: X.data }; + } + _regex(X, Q, $) { + return this.refinement((Y) => X.test(Y), { validation: Q, code: w.invalid_string, ...Z.errToObj($) }); + } + _addCheck(X) { + return new _A1({ ...this._def, checks: [...this._def.checks, X] }); + } + email(X) { + return this._addCheck({ kind: "email", ...Z.errToObj(X) }); + } + url(X) { + return this._addCheck({ kind: "url", ...Z.errToObj(X) }); + } + emoji(X) { + return this._addCheck({ kind: "emoji", ...Z.errToObj(X) }); + } + uuid(X) { + return this._addCheck({ kind: "uuid", ...Z.errToObj(X) }); + } + nanoid(X) { + return this._addCheck({ kind: "nanoid", ...Z.errToObj(X) }); + } + cuid(X) { + return this._addCheck({ kind: "cuid", ...Z.errToObj(X) }); + } + cuid2(X) { + return this._addCheck({ kind: "cuid2", ...Z.errToObj(X) }); + } + ulid(X) { + return this._addCheck({ kind: "ulid", ...Z.errToObj(X) }); + } + base64(X) { + return this._addCheck({ kind: "base64", ...Z.errToObj(X) }); + } + base64url(X) { + return this._addCheck({ kind: "base64url", ...Z.errToObj(X) }); + } + jwt(X) { + return this._addCheck({ kind: "jwt", ...Z.errToObj(X) }); + } + ip(X) { + return this._addCheck({ kind: "ip", ...Z.errToObj(X) }); + } + cidr(X) { + return this._addCheck({ kind: "cidr", ...Z.errToObj(X) }); + } + datetime(X) { + var _a3, _b; + if (typeof X === "string") return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: X }); + return this._addCheck({ kind: "datetime", precision: typeof (X == null ? void 0 : X.precision) > "u" ? null : X == null ? void 0 : X.precision, offset: (_a3 = X == null ? void 0 : X.offset) != null ? _a3 : false, local: (_b = X == null ? void 0 : X.local) != null ? _b : false, ...Z.errToObj(X == null ? void 0 : X.message) }); + } + date(X) { + return this._addCheck({ kind: "date", message: X }); + } + time(X) { + if (typeof X === "string") return this._addCheck({ kind: "time", precision: null, message: X }); + return this._addCheck({ kind: "time", precision: typeof (X == null ? void 0 : X.precision) > "u" ? null : X == null ? void 0 : X.precision, ...Z.errToObj(X == null ? void 0 : X.message) }); + } + duration(X) { + return this._addCheck({ kind: "duration", ...Z.errToObj(X) }); + } + regex(X, Q) { + return this._addCheck({ kind: "regex", regex: X, ...Z.errToObj(Q) }); + } + includes(X, Q) { + return this._addCheck({ kind: "includes", value: X, position: Q == null ? void 0 : Q.position, ...Z.errToObj(Q == null ? void 0 : Q.message) }); + } + startsWith(X, Q) { + return this._addCheck({ kind: "startsWith", value: X, ...Z.errToObj(Q) }); + } + endsWith(X, Q) { + return this._addCheck({ kind: "endsWith", value: X, ...Z.errToObj(Q) }); + } + min(X, Q) { + return this._addCheck({ kind: "min", value: X, ...Z.errToObj(Q) }); + } + max(X, Q) { + return this._addCheck({ kind: "max", value: X, ...Z.errToObj(Q) }); + } + length(X, Q) { + return this._addCheck({ kind: "length", value: X, ...Z.errToObj(Q) }); + } + nonempty(X) { + return this.min(1, Z.errToObj(X)); + } + trim() { + return new _A1({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); + } + toLowerCase() { + return new _A1({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); + } + toUpperCase() { + return new _A1({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); + } + get isDatetime() { + return !!this._def.checks.find((X) => X.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((X) => X.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((X) => X.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((X) => X.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((X) => X.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((X) => X.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((X) => X.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((X) => X.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((X) => X.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((X) => X.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((X) => X.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((X) => X.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((X) => X.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((X) => X.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((X) => X.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((X) => X.kind === "base64url"); + } + get minLength() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "min") { + if (X === null || Q.value > X) X = Q.value; + } + return X; + } + get maxLength() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "max") { + if (X === null || Q.value < X) X = Q.value; + } + return X; + } +}; +A1.create = (X) => { + var _a3; + return new A1({ checks: [], typeName: j.ZodString, coerce: (_a3 = X == null ? void 0 : X.coerce) != null ? _a3 : false, ...l(X) }); +}; +function AV(X, Q) { + let $ = (X.toString().split(".")[1] || "").length, Y = (Q.toString().split(".")[1] || "").length, W = $ > Y ? $ : Y, J = Number.parseInt(X.toFixed(W).replace(".", "")), G = Number.parseInt(Q.toFixed(W).replace(".", "")); + return J % G / 10 ** W; +} +var I6 = class _I6 extends p { + constructor() { + super(...arguments); + this.min = this.gte, this.max = this.lte, this.step = this.multipleOf; + } + _parse(X) { + if (this._def.coerce) X.data = Number(X.data); + if (this._getType(X) !== E.number) { + let W = this._getOrReturnCtx(X); + return b(W, { code: w.invalid_type, expected: E.number, received: W.parsedType }), g; + } + let $ = void 0, Y = new I0(); + for (let W of this._def.checks) if (W.kind === "int") { + if (!n.isInteger(X.data)) $ = this._getOrReturnCtx(X, $), b($, { code: w.invalid_type, expected: "integer", received: "float", message: W.message }), Y.dirty(); + } else if (W.kind === "min") { + if (W.inclusive ? X.data < W.value : X.data <= W.value) $ = this._getOrReturnCtx(X, $), b($, { code: w.too_small, minimum: W.value, type: "number", inclusive: W.inclusive, exact: false, message: W.message }), Y.dirty(); + } else if (W.kind === "max") { + if (W.inclusive ? X.data > W.value : X.data >= W.value) $ = this._getOrReturnCtx(X, $), b($, { code: w.too_big, maximum: W.value, type: "number", inclusive: W.inclusive, exact: false, message: W.message }), Y.dirty(); + } else if (W.kind === "multipleOf") { + if (AV(X.data, W.value) !== 0) $ = this._getOrReturnCtx(X, $), b($, { code: w.not_multiple_of, multipleOf: W.value, message: W.message }), Y.dirty(); + } else if (W.kind === "finite") { + if (!Number.isFinite(X.data)) $ = this._getOrReturnCtx(X, $), b($, { code: w.not_finite, message: W.message }), Y.dirty(); + } else n.assertNever(W); + return { status: Y.value, value: X.data }; + } + gte(X, Q) { + return this.setLimit("min", X, true, Z.toString(Q)); + } + gt(X, Q) { + return this.setLimit("min", X, false, Z.toString(Q)); + } + lte(X, Q) { + return this.setLimit("max", X, true, Z.toString(Q)); + } + lt(X, Q) { + return this.setLimit("max", X, false, Z.toString(Q)); + } + setLimit(X, Q, $, Y) { + return new _I6({ ...this._def, checks: [...this._def.checks, { kind: X, value: Q, inclusive: $, message: Z.toString(Y) }] }); + } + _addCheck(X) { + return new _I6({ ...this._def, checks: [...this._def.checks, X] }); + } + int(X) { + return this._addCheck({ kind: "int", message: Z.toString(X) }); + } + positive(X) { + return this._addCheck({ kind: "min", value: 0, inclusive: false, message: Z.toString(X) }); + } + negative(X) { + return this._addCheck({ kind: "max", value: 0, inclusive: false, message: Z.toString(X) }); + } + nonpositive(X) { + return this._addCheck({ kind: "max", value: 0, inclusive: true, message: Z.toString(X) }); + } + nonnegative(X) { + return this._addCheck({ kind: "min", value: 0, inclusive: true, message: Z.toString(X) }); + } + multipleOf(X, Q) { + return this._addCheck({ kind: "multipleOf", value: X, message: Z.toString(Q) }); + } + finite(X) { + return this._addCheck({ kind: "finite", message: Z.toString(X) }); + } + safe(X) { + return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: Z.toString(X) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: Z.toString(X) }); + } + get minValue() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "min") { + if (X === null || Q.value > X) X = Q.value; + } + return X; + } + get maxValue() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "max") { + if (X === null || Q.value < X) X = Q.value; + } + return X; + } + get isInt() { + return !!this._def.checks.find((X) => X.kind === "int" || X.kind === "multipleOf" && n.isInteger(X.value)); + } + get isFinite() { + let X = null, Q = null; + for (let $ of this._def.checks) if ($.kind === "finite" || $.kind === "int" || $.kind === "multipleOf") return true; + else if ($.kind === "min") { + if (Q === null || $.value > Q) Q = $.value; + } else if ($.kind === "max") { + if (X === null || $.value < X) X = $.value; + } + return Number.isFinite(Q) && Number.isFinite(X); + } +}; +I6.create = (X) => { + return new I6({ checks: [], typeName: j.ZodNumber, coerce: (X == null ? void 0 : X.coerce) || false, ...l(X) }); +}; +var b6 = class _b6 extends p { + constructor() { + super(...arguments); + this.min = this.gte, this.max = this.lte; + } + _parse(X) { + if (this._def.coerce) try { + X.data = BigInt(X.data); + } catch (e2) { + return this._getInvalidInput(X); + } + if (this._getType(X) !== E.bigint) return this._getInvalidInput(X); + let $ = void 0, Y = new I0(); + for (let W of this._def.checks) if (W.kind === "min") { + if (W.inclusive ? X.data < W.value : X.data <= W.value) $ = this._getOrReturnCtx(X, $), b($, { code: w.too_small, type: "bigint", minimum: W.value, inclusive: W.inclusive, message: W.message }), Y.dirty(); + } else if (W.kind === "max") { + if (W.inclusive ? X.data > W.value : X.data >= W.value) $ = this._getOrReturnCtx(X, $), b($, { code: w.too_big, type: "bigint", maximum: W.value, inclusive: W.inclusive, message: W.message }), Y.dirty(); + } else if (W.kind === "multipleOf") { + if (X.data % W.value !== BigInt(0)) $ = this._getOrReturnCtx(X, $), b($, { code: w.not_multiple_of, multipleOf: W.value, message: W.message }), Y.dirty(); + } else n.assertNever(W); + return { status: Y.value, value: X.data }; + } + _getInvalidInput(X) { + let Q = this._getOrReturnCtx(X); + return b(Q, { code: w.invalid_type, expected: E.bigint, received: Q.parsedType }), g; + } + gte(X, Q) { + return this.setLimit("min", X, true, Z.toString(Q)); + } + gt(X, Q) { + return this.setLimit("min", X, false, Z.toString(Q)); + } + lte(X, Q) { + return this.setLimit("max", X, true, Z.toString(Q)); + } + lt(X, Q) { + return this.setLimit("max", X, false, Z.toString(Q)); + } + setLimit(X, Q, $, Y) { + return new _b6({ ...this._def, checks: [...this._def.checks, { kind: X, value: Q, inclusive: $, message: Z.toString(Y) }] }); + } + _addCheck(X) { + return new _b6({ ...this._def, checks: [...this._def.checks, X] }); + } + positive(X) { + return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: Z.toString(X) }); + } + negative(X) { + return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: Z.toString(X) }); + } + nonpositive(X) { + return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: Z.toString(X) }); + } + nonnegative(X) { + return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: Z.toString(X) }); + } + multipleOf(X, Q) { + return this._addCheck({ kind: "multipleOf", value: X, message: Z.toString(Q) }); + } + get minValue() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "min") { + if (X === null || Q.value > X) X = Q.value; + } + return X; + } + get maxValue() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "max") { + if (X === null || Q.value < X) X = Q.value; + } + return X; + } +}; +b6.create = (X) => { + var _a3; + return new b6({ checks: [], typeName: j.ZodBigInt, coerce: (_a3 = X == null ? void 0 : X.coerce) != null ? _a3 : false, ...l(X) }); +}; +var O4 = class extends p { + _parse(X) { + if (this._def.coerce) X.data = Boolean(X.data); + if (this._getType(X) !== E.boolean) { + let $ = this._getOrReturnCtx(X); + return b($, { code: w.invalid_type, expected: E.boolean, received: $.parsedType }), g; + } + return C0(X.data); + } +}; +O4.create = (X) => { + return new O4({ typeName: j.ZodBoolean, coerce: (X == null ? void 0 : X.coerce) || false, ...l(X) }); +}; +var GX = class _GX extends p { + _parse(X) { + if (this._def.coerce) X.data = new Date(X.data); + if (this._getType(X) !== E.date) { + let W = this._getOrReturnCtx(X); + return b(W, { code: w.invalid_type, expected: E.date, received: W.parsedType }), g; + } + if (Number.isNaN(X.data.getTime())) { + let W = this._getOrReturnCtx(X); + return b(W, { code: w.invalid_date }), g; + } + let $ = new I0(), Y = void 0; + for (let W of this._def.checks) if (W.kind === "min") { + if (X.data.getTime() < W.value) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.too_small, message: W.message, inclusive: true, exact: false, minimum: W.value, type: "date" }), $.dirty(); + } else if (W.kind === "max") { + if (X.data.getTime() > W.value) Y = this._getOrReturnCtx(X, Y), b(Y, { code: w.too_big, message: W.message, inclusive: true, exact: false, maximum: W.value, type: "date" }), $.dirty(); + } else n.assertNever(W); + return { status: $.value, value: new Date(X.data.getTime()) }; + } + _addCheck(X) { + return new _GX({ ...this._def, checks: [...this._def.checks, X] }); + } + min(X, Q) { + return this._addCheck({ kind: "min", value: X.getTime(), message: Z.toString(Q) }); + } + max(X, Q) { + return this._addCheck({ kind: "max", value: X.getTime(), message: Z.toString(Q) }); + } + get minDate() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "min") { + if (X === null || Q.value > X) X = Q.value; + } + return X != null ? new Date(X) : null; + } + get maxDate() { + let X = null; + for (let Q of this._def.checks) if (Q.kind === "max") { + if (X === null || Q.value < X) X = Q.value; + } + return X != null ? new Date(X) : null; + } +}; +GX.create = (X) => { + return new GX({ checks: [], coerce: (X == null ? void 0 : X.coerce) || false, typeName: j.ZodDate, ...l(X) }); +}; +var D4 = class extends p { + _parse(X) { + if (this._getType(X) !== E.symbol) { + let $ = this._getOrReturnCtx(X); + return b($, { code: w.invalid_type, expected: E.symbol, received: $.parsedType }), g; + } + return C0(X.data); + } +}; +D4.create = (X) => { + return new D4({ typeName: j.ZodSymbol, ...l(X) }); +}; +var HX = class extends p { + _parse(X) { + if (this._getType(X) !== E.undefined) { + let $ = this._getOrReturnCtx(X); + return b($, { code: w.invalid_type, expected: E.undefined, received: $.parsedType }), g; + } + return C0(X.data); + } +}; +HX.create = (X) => { + return new HX({ typeName: j.ZodUndefined, ...l(X) }); +}; +var BX = class extends p { + _parse(X) { + if (this._getType(X) !== E.null) { + let $ = this._getOrReturnCtx(X); + return b($, { code: w.invalid_type, expected: E.null, received: $.parsedType }), g; + } + return C0(X.data); + } +}; +BX.create = (X) => { + return new BX({ typeName: j.ZodNull, ...l(X) }); +}; +var A4 = class extends p { + constructor() { + super(...arguments); + this._any = true; + } + _parse(X) { + return C0(X.data); + } +}; +A4.create = (X) => { + return new A4({ typeName: j.ZodAny, ...l(X) }); +}; +var t1 = class extends p { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(X) { + return C0(X.data); + } +}; +t1.create = (X) => { + return new t1({ typeName: j.ZodUnknown, ...l(X) }); +}; +var w1 = class extends p { + _parse(X) { + let Q = this._getOrReturnCtx(X); + return b(Q, { code: w.invalid_type, expected: E.never, received: Q.parsedType }), g; + } +}; +w1.create = (X) => { + return new w1({ typeName: j.ZodNever, ...l(X) }); +}; +var w4 = class extends p { + _parse(X) { + if (this._getType(X) !== E.undefined) { + let $ = this._getOrReturnCtx(X); + return b($, { code: w.invalid_type, expected: E.void, received: $.parsedType }), g; + } + return C0(X.data); + } +}; +w4.create = (X) => { + return new w4({ typeName: j.ZodVoid, ...l(X) }); +}; +var J1 = class _J1 extends p { + _parse(X) { + let { ctx: Q, status: $ } = this._processInputParams(X), Y = this._def; + if (Q.parsedType !== E.array) return b(Q, { code: w.invalid_type, expected: E.array, received: Q.parsedType }), g; + if (Y.exactLength !== null) { + let J = Q.data.length > Y.exactLength.value, G = Q.data.length < Y.exactLength.value; + if (J || G) b(Q, { code: J ? w.too_big : w.too_small, minimum: G ? Y.exactLength.value : void 0, maximum: J ? Y.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: Y.exactLength.message }), $.dirty(); + } + if (Y.minLength !== null) { + if (Q.data.length < Y.minLength.value) b(Q, { code: w.too_small, minimum: Y.minLength.value, type: "array", inclusive: true, exact: false, message: Y.minLength.message }), $.dirty(); + } + if (Y.maxLength !== null) { + if (Q.data.length > Y.maxLength.value) b(Q, { code: w.too_big, maximum: Y.maxLength.value, type: "array", inclusive: true, exact: false, message: Y.maxLength.message }), $.dirty(); + } + if (Q.common.async) return Promise.all([...Q.data].map((J, G) => { + return Y.type._parseAsync(new r0(Q, J, Q.path, G)); + })).then((J) => { + return I0.mergeArray($, J); + }); + let W = [...Q.data].map((J, G) => { + return Y.type._parseSync(new r0(Q, J, Q.path, G)); + }); + return I0.mergeArray($, W); + } + get element() { + return this._def.type; + } + min(X, Q) { + return new _J1({ ...this._def, minLength: { value: X, message: Z.toString(Q) } }); + } + max(X, Q) { + return new _J1({ ...this._def, maxLength: { value: X, message: Z.toString(Q) } }); + } + length(X, Q) { + return new _J1({ ...this._def, exactLength: { value: X, message: Z.toString(Q) } }); + } + nonempty(X) { + return this.min(1, X); + } +}; +J1.create = (X, Q) => { + return new J1({ type: X, minLength: null, maxLength: null, exactLength: null, typeName: j.ZodArray, ...l(Q) }); +}; +function E6(X) { + if (X instanceof V0) { + let Q = {}; + for (let $ in X.shape) { + let Y = X.shape[$]; + Q[$] = G1.create(E6(Y)); + } + return new V0({ ...X._def, shape: () => Q }); + } else if (X instanceof J1) return new J1({ ...X._def, type: E6(X.element) }); + else if (X instanceof G1) return G1.create(E6(X.unwrap())); + else if (X instanceof T1) return T1.create(E6(X.unwrap())); + else if (X instanceof M1) return M1.create(X.items.map((Q) => E6(Q))); + else return X; +} +var V0 = class _V0 extends p { + constructor() { + super(...arguments); + this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) return this._cached; + let X = this._def.shape(), Q = n.objectKeys(X); + return this._cached = { shape: X, keys: Q }, this._cached; + } + _parse(X) { + if (this._getType(X) !== E.object) { + let B = this._getOrReturnCtx(X); + return b(B, { code: w.invalid_type, expected: E.object, received: B.parsedType }), g; + } + let { status: $, ctx: Y } = this._processInputParams(X), { shape: W, keys: J } = this._getCached(), G = []; + if (!(this._def.catchall instanceof w1 && this._def.unknownKeys === "strip")) { + for (let B in Y.data) if (!J.includes(B)) G.push(B); + } + let H = []; + for (let B of J) { + let z2 = W[B], K = Y.data[B]; + H.push({ key: { status: "valid", value: B }, value: z2._parse(new r0(Y, K, Y.path, B)), alwaysSet: B in Y.data }); + } + if (this._def.catchall instanceof w1) { + let B = this._def.unknownKeys; + if (B === "passthrough") for (let z2 of G) H.push({ key: { status: "valid", value: z2 }, value: { status: "valid", value: Y.data[z2] } }); + else if (B === "strict") { + if (G.length > 0) b(Y, { code: w.unrecognized_keys, keys: G }), $.dirty(); + } else if (B === "strip") ; + else throw Error("Internal ZodObject error: invalid unknownKeys value."); + } else { + let B = this._def.catchall; + for (let z2 of G) { + let K = Y.data[z2]; + H.push({ key: { status: "valid", value: z2 }, value: B._parse(new r0(Y, K, Y.path, z2)), alwaysSet: z2 in Y.data }); + } + } + if (Y.common.async) return Promise.resolve().then(async () => { + let B = []; + for (let z2 of H) { + let K = await z2.key, V = await z2.value; + B.push({ key: K, value: V, alwaysSet: z2.alwaysSet }); + } + return B; + }).then((B) => { + return I0.mergeObjectSync($, B); + }); + else return I0.mergeObjectSync($, H); + } + get shape() { + return this._def.shape(); + } + strict(X) { + return Z.errToObj, new _V0({ ...this._def, unknownKeys: "strict", ...X !== void 0 ? { errorMap: (Q, $) => { + var _a3, _b, _c, _d; + let Y = (_c = (_b = (_a3 = this._def).errorMap) == null ? void 0 : _b.call(_a3, Q, $).message) != null ? _c : $.defaultError; + if (Q.code === "unrecognized_keys") return { message: (_d = Z.errToObj(X).message) != null ? _d : Y }; + return { message: Y }; + } } : {} }); + } + strip() { + return new _V0({ ...this._def, unknownKeys: "strip" }); + } + passthrough() { + return new _V0({ ...this._def, unknownKeys: "passthrough" }); + } + extend(X) { + return new _V0({ ...this._def, shape: () => ({ ...this._def.shape(), ...X }) }); + } + merge(X) { + return new _V0({ unknownKeys: X._def.unknownKeys, catchall: X._def.catchall, shape: () => ({ ...this._def.shape(), ...X._def.shape() }), typeName: j.ZodObject }); + } + setKey(X, Q) { + return this.augment({ [X]: Q }); + } + catchall(X) { + return new _V0({ ...this._def, catchall: X }); + } + pick(X) { + let Q = {}; + for (let $ of n.objectKeys(X)) if (X[$] && this.shape[$]) Q[$] = this.shape[$]; + return new _V0({ ...this._def, shape: () => Q }); + } + omit(X) { + let Q = {}; + for (let $ of n.objectKeys(this.shape)) if (!X[$]) Q[$] = this.shape[$]; + return new _V0({ ...this._def, shape: () => Q }); + } + deepPartial() { + return E6(this); + } + partial(X) { + let Q = {}; + for (let $ of n.objectKeys(this.shape)) { + let Y = this.shape[$]; + if (X && !X[$]) Q[$] = Y; + else Q[$] = Y.optional(); + } + return new _V0({ ...this._def, shape: () => Q }); + } + required(X) { + let Q = {}; + for (let $ of n.objectKeys(this.shape)) if (X && !X[$]) Q[$] = this.shape[$]; + else { + let W = this.shape[$]; + while (W instanceof G1) W = W._def.innerType; + Q[$] = W; + } + return new _V0({ ...this._def, shape: () => Q }); + } + keyof() { + return qW(n.objectKeys(this.shape)); + } +}; +V0.create = (X, Q) => { + return new V0({ shape: () => X, unknownKeys: "strip", catchall: w1.create(), typeName: j.ZodObject, ...l(Q) }); +}; +V0.strictCreate = (X, Q) => { + return new V0({ shape: () => X, unknownKeys: "strict", catchall: w1.create(), typeName: j.ZodObject, ...l(Q) }); +}; +V0.lazycreate = (X, Q) => { + return new V0({ shape: X, unknownKeys: "strip", catchall: w1.create(), typeName: j.ZodObject, ...l(Q) }); +}; +var zX = class extends p { + _parse(X) { + let { ctx: Q } = this._processInputParams(X), $ = this._def.options; + function Y(W) { + for (let G of W) if (G.result.status === "valid") return G.result; + for (let G of W) if (G.result.status === "dirty") return Q.common.issues.push(...G.ctx.common.issues), G.result; + let J = W.map((G) => new f0(G.ctx.common.issues)); + return b(Q, { code: w.invalid_union, unionErrors: J }), g; + } + if (Q.common.async) return Promise.all($.map(async (W) => { + let J = { ...Q, common: { ...Q.common, issues: [] }, parent: null }; + return { result: await W._parseAsync({ data: Q.data, path: Q.path, parent: J }), ctx: J }; + })).then(Y); + else { + let W = void 0, J = []; + for (let H of $) { + let B = { ...Q, common: { ...Q.common, issues: [] }, parent: null }, z2 = H._parseSync({ data: Q.data, path: Q.path, parent: B }); + if (z2.status === "valid") return z2; + else if (z2.status === "dirty" && !W) W = { result: z2, ctx: B }; + if (B.common.issues.length) J.push(B.common.issues); + } + if (W) return Q.common.issues.push(...W.ctx.common.issues), W.result; + let G = J.map((H) => new f0(H)); + return b(Q, { code: w.invalid_union, unionErrors: G }), g; + } + } + get options() { + return this._def.options; + } +}; +zX.create = (X, Q) => { + return new zX({ options: X, typeName: j.ZodUnion, ...l(Q) }); +}; +var D1 = (X) => { + if (X instanceof UX) return D1(X.schema); + else if (X instanceof H1) return D1(X.innerType()); + else if (X instanceof VX) return [X.value]; + else if (X instanceof a1) return X.options; + else if (X instanceof LX) return n.objectValues(X.enum); + else if (X instanceof qX) return D1(X._def.innerType); + else if (X instanceof HX) return [void 0]; + else if (X instanceof BX) return [null]; + else if (X instanceof G1) return [void 0, ...D1(X.unwrap())]; + else if (X instanceof T1) return [null, ...D1(X.unwrap())]; + else if (X instanceof D8) return D1(X.unwrap()); + else if (X instanceof NX) return D1(X.unwrap()); + else if (X instanceof FX) return D1(X._def.innerType); + else return []; +}; +var O8 = class _O8 extends p { + _parse(X) { + let { ctx: Q } = this._processInputParams(X); + if (Q.parsedType !== E.object) return b(Q, { code: w.invalid_type, expected: E.object, received: Q.parsedType }), g; + let $ = this.discriminator, Y = Q.data[$], W = this.optionsMap.get(Y); + if (!W) return b(Q, { code: w.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [$] }), g; + if (Q.common.async) return W._parseAsync({ data: Q.data, path: Q.path, parent: Q }); + else return W._parseSync({ data: Q.data, path: Q.path, parent: Q }); + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + static create(X, Q, $) { + let Y = /* @__PURE__ */ new Map(); + for (let W of Q) { + let J = D1(W.shape[X]); + if (!J.length) throw Error(`A discriminator value for key \`${X}\` could not be extracted from all schema options`); + for (let G of J) { + if (Y.has(G)) throw Error(`Discriminator property ${String(X)} has duplicate value ${String(G)}`); + Y.set(G, W); + } + } + return new _O8({ typeName: j.ZodDiscriminatedUnion, discriminator: X, options: Q, optionsMap: Y, ...l($) }); + } +}; +function N8(X, Q) { + let $ = O1(X), Y = O1(Q); + if (X === Q) return { valid: true, data: X }; + else if ($ === E.object && Y === E.object) { + let W = n.objectKeys(Q), J = n.objectKeys(X).filter((H) => W.indexOf(H) !== -1), G = { ...X, ...Q }; + for (let H of J) { + let B = N8(X[H], Q[H]); + if (!B.valid) return { valid: false }; + G[H] = B.data; + } + return { valid: true, data: G }; + } else if ($ === E.array && Y === E.array) { + if (X.length !== Q.length) return { valid: false }; + let W = []; + for (let J = 0; J < X.length; J++) { + let G = X[J], H = Q[J], B = N8(G, H); + if (!B.valid) return { valid: false }; + W.push(B.data); + } + return { valid: true, data: W }; + } else if ($ === E.date && Y === E.date && +X === +Q) return { valid: true, data: X }; + else return { valid: false }; +} +var KX = class extends p { + _parse(X) { + let { status: Q, ctx: $ } = this._processInputParams(X), Y = (W, J) => { + if (L8(W) || L8(J)) return g; + let G = N8(W.value, J.value); + if (!G.valid) return b($, { code: w.invalid_intersection_types }), g; + if (q8(W) || q8(J)) Q.dirty(); + return { status: Q.value, value: G.data }; + }; + if ($.common.async) return Promise.all([this._def.left._parseAsync({ data: $.data, path: $.path, parent: $ }), this._def.right._parseAsync({ data: $.data, path: $.path, parent: $ })]).then(([W, J]) => Y(W, J)); + else return Y(this._def.left._parseSync({ data: $.data, path: $.path, parent: $ }), this._def.right._parseSync({ data: $.data, path: $.path, parent: $ })); + } +}; +KX.create = (X, Q, $) => { + return new KX({ left: X, right: Q, typeName: j.ZodIntersection, ...l($) }); +}; +var M1 = class _M1 extends p { + _parse(X) { + let { status: Q, ctx: $ } = this._processInputParams(X); + if ($.parsedType !== E.array) return b($, { code: w.invalid_type, expected: E.array, received: $.parsedType }), g; + if ($.data.length < this._def.items.length) return b($, { code: w.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }), g; + if (!this._def.rest && $.data.length > this._def.items.length) b($, { code: w.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }), Q.dirty(); + let W = [...$.data].map((J, G) => { + let H = this._def.items[G] || this._def.rest; + if (!H) return null; + return H._parse(new r0($, J, $.path, G)); + }).filter((J) => !!J); + if ($.common.async) return Promise.all(W).then((J) => { + return I0.mergeArray(Q, J); + }); + else return I0.mergeArray(Q, W); + } + get items() { + return this._def.items; + } + rest(X) { + return new _M1({ ...this._def, rest: X }); + } +}; +M1.create = (X, Q) => { + if (!Array.isArray(X)) throw Error("You must pass an array of schemas to z.tuple([ ... ])"); + return new M1({ items: X, typeName: j.ZodTuple, rest: null, ...l(Q) }); +}; +var M4 = class _M4 extends p { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(X) { + let { status: Q, ctx: $ } = this._processInputParams(X); + if ($.parsedType !== E.object) return b($, { code: w.invalid_type, expected: E.object, received: $.parsedType }), g; + let Y = [], W = this._def.keyType, J = this._def.valueType; + for (let G in $.data) Y.push({ key: W._parse(new r0($, G, $.path, G)), value: J._parse(new r0($, $.data[G], $.path, G)), alwaysSet: G in $.data }); + if ($.common.async) return I0.mergeObjectAsync(Q, Y); + else return I0.mergeObjectSync(Q, Y); + } + get element() { + return this._def.valueType; + } + static create(X, Q, $) { + if (Q instanceof p) return new _M4({ keyType: X, valueType: Q, typeName: j.ZodRecord, ...l($) }); + return new _M4({ keyType: A1.create(), valueType: X, typeName: j.ZodRecord, ...l(Q) }); + } +}; +var j4 = class extends p { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(X) { + let { status: Q, ctx: $ } = this._processInputParams(X); + if ($.parsedType !== E.map) return b($, { code: w.invalid_type, expected: E.map, received: $.parsedType }), g; + let Y = this._def.keyType, W = this._def.valueType, J = [...$.data.entries()].map(([G, H], B) => { + return { key: Y._parse(new r0($, G, $.path, [B, "key"])), value: W._parse(new r0($, H, $.path, [B, "value"])) }; + }); + if ($.common.async) { + let G = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (let H of J) { + let B = await H.key, z2 = await H.value; + if (B.status === "aborted" || z2.status === "aborted") return g; + if (B.status === "dirty" || z2.status === "dirty") Q.dirty(); + G.set(B.value, z2.value); + } + return { status: Q.value, value: G }; + }); + } else { + let G = /* @__PURE__ */ new Map(); + for (let H of J) { + let { key: B, value: z2 } = H; + if (B.status === "aborted" || z2.status === "aborted") return g; + if (B.status === "dirty" || z2.status === "dirty") Q.dirty(); + G.set(B.value, z2.value); + } + return { status: Q.value, value: G }; + } + } +}; +j4.create = (X, Q, $) => { + return new j4({ valueType: Q, keyType: X, typeName: j.ZodMap, ...l($) }); +}; +var P6 = class _P6 extends p { + _parse(X) { + let { status: Q, ctx: $ } = this._processInputParams(X); + if ($.parsedType !== E.set) return b($, { code: w.invalid_type, expected: E.set, received: $.parsedType }), g; + let Y = this._def; + if (Y.minSize !== null) { + if ($.data.size < Y.minSize.value) b($, { code: w.too_small, minimum: Y.minSize.value, type: "set", inclusive: true, exact: false, message: Y.minSize.message }), Q.dirty(); + } + if (Y.maxSize !== null) { + if ($.data.size > Y.maxSize.value) b($, { code: w.too_big, maximum: Y.maxSize.value, type: "set", inclusive: true, exact: false, message: Y.maxSize.message }), Q.dirty(); + } + let W = this._def.valueType; + function J(H) { + let B = /* @__PURE__ */ new Set(); + for (let z2 of H) { + if (z2.status === "aborted") return g; + if (z2.status === "dirty") Q.dirty(); + B.add(z2.value); + } + return { status: Q.value, value: B }; + } + let G = [...$.data.values()].map((H, B) => W._parse(new r0($, H, $.path, B))); + if ($.common.async) return Promise.all(G).then((H) => J(H)); + else return J(G); + } + min(X, Q) { + return new _P6({ ...this._def, minSize: { value: X, message: Z.toString(Q) } }); + } + max(X, Q) { + return new _P6({ ...this._def, maxSize: { value: X, message: Z.toString(Q) } }); + } + size(X, Q) { + return this.min(X, Q).max(X, Q); + } + nonempty(X) { + return this.min(1, X); + } +}; +P6.create = (X, Q) => { + return new P6({ valueType: X, minSize: null, maxSize: null, typeName: j.ZodSet, ...l(Q) }); +}; +var JX = class _JX extends p { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(X) { + let { ctx: Q } = this._processInputParams(X); + if (Q.parsedType !== E.function) return b(Q, { code: w.invalid_type, expected: E.function, received: Q.parsedType }), g; + function $(G, H) { + return N4({ data: G, path: Q.path, errorMaps: [Q.common.contextualErrorMap, Q.schemaErrorMap, YX(), v1].filter((B) => !!B), issueData: { code: w.invalid_arguments, argumentsError: H } }); + } + function Y(G, H) { + return N4({ data: G, path: Q.path, errorMaps: [Q.common.contextualErrorMap, Q.schemaErrorMap, YX(), v1].filter((B) => !!B), issueData: { code: w.invalid_return_type, returnTypeError: H } }); + } + let W = { errorMap: Q.common.contextualErrorMap }, J = Q.data; + if (this._def.returns instanceof S6) { + let G = this; + return C0(async function(...H) { + let B = new f0([]), z2 = await G._def.args.parseAsync(H, W).catch((L) => { + throw B.addIssue($(H, L)), B; + }), K = await Reflect.apply(J, this, z2); + return await G._def.returns._def.type.parseAsync(K, W).catch((L) => { + throw B.addIssue(Y(K, L)), B; + }); + }); + } else { + let G = this; + return C0(function(...H) { + let B = G._def.args.safeParse(H, W); + if (!B.success) throw new f0([$(H, B.error)]); + let z2 = Reflect.apply(J, this, B.data), K = G._def.returns.safeParse(z2, W); + if (!K.success) throw new f0([Y(z2, K.error)]); + return K.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...X) { + return new _JX({ ...this._def, args: M1.create(X).rest(t1.create()) }); + } + returns(X) { + return new _JX({ ...this._def, returns: X }); + } + implement(X) { + return this.parse(X); + } + strictImplement(X) { + return this.parse(X); + } + static create(X, Q, $) { + return new _JX({ args: X ? X : M1.create([]).rest(t1.create()), returns: Q || t1.create(), typeName: j.ZodFunction, ...l($) }); + } +}; +var UX = class extends p { + get schema() { + return this._def.getter(); + } + _parse(X) { + let { ctx: Q } = this._processInputParams(X); + return this._def.getter()._parse({ data: Q.data, path: Q.path, parent: Q }); + } +}; +UX.create = (X, Q) => { + return new UX({ getter: X, typeName: j.ZodLazy, ...l(Q) }); +}; +var VX = class extends p { + _parse(X) { + if (X.data !== this._def.value) { + let Q = this._getOrReturnCtx(X); + return b(Q, { received: Q.data, code: w.invalid_literal, expected: this._def.value }), g; + } + return { status: "valid", value: X.data }; + } + get value() { + return this._def.value; + } +}; +VX.create = (X, Q) => { + return new VX({ value: X, typeName: j.ZodLiteral, ...l(Q) }); +}; +function qW(X, Q) { + return new a1({ values: X, typeName: j.ZodEnum, ...l(Q) }); +} +var a1 = class _a1 extends p { + _parse(X) { + if (typeof X.data !== "string") { + let Q = this._getOrReturnCtx(X), $ = this._def.values; + return b(Q, { expected: n.joinValues($), received: Q.parsedType, code: w.invalid_type }), g; + } + if (!this._cache) this._cache = new Set(this._def.values); + if (!this._cache.has(X.data)) { + let Q = this._getOrReturnCtx(X), $ = this._def.values; + return b(Q, { received: Q.data, code: w.invalid_enum_value, options: $ }), g; + } + return C0(X.data); + } + get options() { + return this._def.values; + } + get enum() { + let X = {}; + for (let Q of this._def.values) X[Q] = Q; + return X; + } + get Values() { + let X = {}; + for (let Q of this._def.values) X[Q] = Q; + return X; + } + get Enum() { + let X = {}; + for (let Q of this._def.values) X[Q] = Q; + return X; + } + extract(X, Q = this._def) { + return _a1.create(X, { ...this._def, ...Q }); + } + exclude(X, Q = this._def) { + return _a1.create(this.options.filter(($) => !X.includes($)), { ...this._def, ...Q }); + } +}; +a1.create = qW; +var LX = class extends p { + _parse(X) { + let Q = n.getValidEnumValues(this._def.values), $ = this._getOrReturnCtx(X); + if ($.parsedType !== E.string && $.parsedType !== E.number) { + let Y = n.objectValues(Q); + return b($, { expected: n.joinValues(Y), received: $.parsedType, code: w.invalid_type }), g; + } + if (!this._cache) this._cache = new Set(n.getValidEnumValues(this._def.values)); + if (!this._cache.has(X.data)) { + let Y = n.objectValues(Q); + return b($, { received: $.data, code: w.invalid_enum_value, options: Y }), g; + } + return C0(X.data); + } + get enum() { + return this._def.values; + } +}; +LX.create = (X, Q) => { + return new LX({ values: X, typeName: j.ZodNativeEnum, ...l(Q) }); +}; +var S6 = class extends p { + unwrap() { + return this._def.type; + } + _parse(X) { + let { ctx: Q } = this._processInputParams(X); + if (Q.parsedType !== E.promise && Q.common.async === false) return b(Q, { code: w.invalid_type, expected: E.promise, received: Q.parsedType }), g; + let $ = Q.parsedType === E.promise ? Q.data : Promise.resolve(Q.data); + return C0($.then((Y) => { + return this._def.type.parseAsync(Y, { path: Q.path, errorMap: Q.common.contextualErrorMap }); + })); + } +}; +S6.create = (X, Q) => { + return new S6({ type: X, typeName: j.ZodPromise, ...l(Q) }); +}; +var H1 = class extends p { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === j.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(X) { + let { status: Q, ctx: $ } = this._processInputParams(X), Y = this._def.effect || null, W = { addIssue: (J) => { + if (b($, J), J.fatal) Q.abort(); + else Q.dirty(); + }, get path() { + return $.path; + } }; + if (W.addIssue = W.addIssue.bind(W), Y.type === "preprocess") { + let J = Y.transform($.data, W); + if ($.common.async) return Promise.resolve(J).then(async (G) => { + if (Q.value === "aborted") return g; + let H = await this._def.schema._parseAsync({ data: G, path: $.path, parent: $ }); + if (H.status === "aborted") return g; + if (H.status === "dirty") return R6(H.value); + if (Q.value === "dirty") return R6(H.value); + return H; + }); + else { + if (Q.value === "aborted") return g; + let G = this._def.schema._parseSync({ data: J, path: $.path, parent: $ }); + if (G.status === "aborted") return g; + if (G.status === "dirty") return R6(G.value); + if (Q.value === "dirty") return R6(G.value); + return G; + } + } + if (Y.type === "refinement") { + let J = (G) => { + let H = Y.refinement(G, W); + if ($.common.async) return Promise.resolve(H); + if (H instanceof Promise) throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + return G; + }; + if ($.common.async === false) { + let G = this._def.schema._parseSync({ data: $.data, path: $.path, parent: $ }); + if (G.status === "aborted") return g; + if (G.status === "dirty") Q.dirty(); + return J(G.value), { status: Q.value, value: G.value }; + } else return this._def.schema._parseAsync({ data: $.data, path: $.path, parent: $ }).then((G) => { + if (G.status === "aborted") return g; + if (G.status === "dirty") Q.dirty(); + return J(G.value).then(() => { + return { status: Q.value, value: G.value }; + }); + }); + } + if (Y.type === "transform") if ($.common.async === false) { + let J = this._def.schema._parseSync({ data: $.data, path: $.path, parent: $ }); + if (!o1(J)) return g; + let G = Y.transform(J.value, W); + if (G instanceof Promise) throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead."); + return { status: Q.value, value: G }; + } else return this._def.schema._parseAsync({ data: $.data, path: $.path, parent: $ }).then((J) => { + if (!o1(J)) return g; + return Promise.resolve(Y.transform(J.value, W)).then((G) => ({ status: Q.value, value: G })); + }); + n.assertNever(Y); + } +}; +H1.create = (X, Q, $) => { + return new H1({ schema: X, typeName: j.ZodEffects, effect: Q, ...l($) }); +}; +H1.createWithPreprocess = (X, Q, $) => { + return new H1({ schema: Q, effect: { type: "preprocess", transform: X }, typeName: j.ZodEffects, ...l($) }); +}; +var G1 = class extends p { + _parse(X) { + if (this._getType(X) === E.undefined) return C0(void 0); + return this._def.innerType._parse(X); + } + unwrap() { + return this._def.innerType; + } +}; +G1.create = (X, Q) => { + return new G1({ innerType: X, typeName: j.ZodOptional, ...l(Q) }); +}; +var T1 = class extends p { + _parse(X) { + if (this._getType(X) === E.null) return C0(null); + return this._def.innerType._parse(X); + } + unwrap() { + return this._def.innerType; + } +}; +T1.create = (X, Q) => { + return new T1({ innerType: X, typeName: j.ZodNullable, ...l(Q) }); +}; +var qX = class extends p { + _parse(X) { + let { ctx: Q } = this._processInputParams(X), $ = Q.data; + if (Q.parsedType === E.undefined) $ = this._def.defaultValue(); + return this._def.innerType._parse({ data: $, path: Q.path, parent: Q }); + } + removeDefault() { + return this._def.innerType; + } +}; +qX.create = (X, Q) => { + return new qX({ innerType: X, typeName: j.ZodDefault, defaultValue: typeof Q.default === "function" ? Q.default : () => Q.default, ...l(Q) }); +}; +var FX = class extends p { + _parse(X) { + let { ctx: Q } = this._processInputParams(X), $ = { ...Q, common: { ...Q.common, issues: [] } }, Y = this._def.innerType._parse({ data: $.data, path: $.path, parent: { ...$ } }); + if (WX(Y)) return Y.then((W) => { + return { status: "valid", value: W.status === "valid" ? W.value : this._def.catchValue({ get error() { + return new f0($.common.issues); + }, input: $.data }) }; + }); + else return { status: "valid", value: Y.status === "valid" ? Y.value : this._def.catchValue({ get error() { + return new f0($.common.issues); + }, input: $.data }) }; + } + removeCatch() { + return this._def.innerType; + } +}; +FX.create = (X, Q) => { + return new FX({ innerType: X, typeName: j.ZodCatch, catchValue: typeof Q.catch === "function" ? Q.catch : () => Q.catch, ...l(Q) }); +}; +var R4 = class extends p { + _parse(X) { + if (this._getType(X) !== E.nan) { + let $ = this._getOrReturnCtx(X); + return b($, { code: w.invalid_type, expected: E.nan, received: $.parsedType }), g; + } + return { status: "valid", value: X.data }; + } +}; +R4.create = (X) => { + return new R4({ typeName: j.ZodNaN, ...l(X) }); +}; +var D8 = class extends p { + _parse(X) { + let { ctx: Q } = this._processInputParams(X), $ = Q.data; + return this._def.type._parse({ data: $, path: Q.path, parent: Q }); + } + unwrap() { + return this._def.type; + } +}; +var E4 = class _E4 extends p { + _parse(X) { + let { status: Q, ctx: $ } = this._processInputParams(X); + if ($.common.async) return (async () => { + let W = await this._def.in._parseAsync({ data: $.data, path: $.path, parent: $ }); + if (W.status === "aborted") return g; + if (W.status === "dirty") return Q.dirty(), R6(W.value); + else return this._def.out._parseAsync({ data: W.value, path: $.path, parent: $ }); + })(); + else { + let Y = this._def.in._parseSync({ data: $.data, path: $.path, parent: $ }); + if (Y.status === "aborted") return g; + if (Y.status === "dirty") return Q.dirty(), { status: "dirty", value: Y.value }; + else return this._def.out._parseSync({ data: Y.value, path: $.path, parent: $ }); + } + } + static create(X, Q) { + return new _E4({ in: X, out: Q, typeName: j.ZodPipeline }); + } +}; +var NX = class extends p { + _parse(X) { + let Q = this._def.innerType._parse(X), $ = (Y) => { + if (o1(Y)) Y.value = Object.freeze(Y.value); + return Y; + }; + return WX(Q) ? Q.then((Y) => $(Y)) : $(Q); + } + unwrap() { + return this._def.innerType; + } +}; +NX.create = (X, Q) => { + return new NX({ innerType: X, typeName: j.ZodReadonly, ...l(Q) }); +}; +var K2 = { object: V0.lazycreate }; +var j; +(function(X) { + X.ZodString = "ZodString", X.ZodNumber = "ZodNumber", X.ZodNaN = "ZodNaN", X.ZodBigInt = "ZodBigInt", X.ZodBoolean = "ZodBoolean", X.ZodDate = "ZodDate", X.ZodSymbol = "ZodSymbol", X.ZodUndefined = "ZodUndefined", X.ZodNull = "ZodNull", X.ZodAny = "ZodAny", X.ZodUnknown = "ZodUnknown", X.ZodNever = "ZodNever", X.ZodVoid = "ZodVoid", X.ZodArray = "ZodArray", X.ZodObject = "ZodObject", X.ZodUnion = "ZodUnion", X.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", X.ZodIntersection = "ZodIntersection", X.ZodTuple = "ZodTuple", X.ZodRecord = "ZodRecord", X.ZodMap = "ZodMap", X.ZodSet = "ZodSet", X.ZodFunction = "ZodFunction", X.ZodLazy = "ZodLazy", X.ZodLiteral = "ZodLiteral", X.ZodEnum = "ZodEnum", X.ZodEffects = "ZodEffects", X.ZodNativeEnum = "ZodNativeEnum", X.ZodOptional = "ZodOptional", X.ZodNullable = "ZodNullable", X.ZodDefault = "ZodDefault", X.ZodCatch = "ZodCatch", X.ZodPromise = "ZodPromise", X.ZodBranded = "ZodBranded", X.ZodPipeline = "ZodPipeline", X.ZodReadonly = "ZodReadonly"; +})(j || (j = {})); +var U2 = A1.create; +var V2 = I6.create; +var L2 = R4.create; +var q2 = b6.create; +var F2 = O4.create; +var N2 = GX.create; +var O2 = D4.create; +var D2 = HX.create; +var A2 = BX.create; +var w2 = A4.create; +var M2 = t1.create; +var j2 = w1.create; +var R2 = w4.create; +var E2 = J1.create; +var FW = V0.create; +var I2 = V0.strictCreate; +var b2 = zX.create; +var P2 = O8.create; +var S2 = KX.create; +var Z2 = M1.create; +var C2 = M4.create; +var k2 = j4.create; +var v2 = P6.create; +var T2 = JX.create; +var _2 = UX.create; +var x2 = VX.create; +var y2 = a1.create; +var g2 = LX.create; +var h2 = S6.create; +var f2 = H1.create; +var u2 = G1.create; +var l2 = T1.create; +var m2 = H1.createWithPreprocess; +var c2 = E4.create; +var wV = Object.freeze({ status: "aborted" }); +function O(X, Q, $) { + var _a3; + function Y(H, B) { + var _a4, _b; + var z2; + Object.defineProperty(H, "_zod", { value: (_a4 = H._zod) != null ? _a4 : {}, enumerable: false }), (_b = (z2 = H._zod).traits) != null ? _b : z2.traits = /* @__PURE__ */ new Set(), H._zod.traits.add(X), Q(H, B); + for (let K in G.prototype) if (!(K in H)) Object.defineProperty(H, K, { value: G.prototype[K].bind(H) }); + H._zod.constr = G, H._zod.def = B; + } + let W = (_a3 = $ == null ? void 0 : $.Parent) != null ? _a3 : Object; + class J extends W { + } + Object.defineProperty(J, "name", { value: X }); + function G(H) { + var _a4; + var B; + let z2 = ($ == null ? void 0 : $.Parent) ? new J() : this; + Y(z2, H), (_a4 = (B = z2._zod).deferred) != null ? _a4 : B.deferred = []; + for (let K of z2._zod.deferred) K(); + return z2; + } + return Object.defineProperty(G, "init", { value: Y }), Object.defineProperty(G, Symbol.hasInstance, { value: (H) => { + var _a4, _b; + if (($ == null ? void 0 : $.Parent) && H instanceof $.Parent) return true; + return (_b = (_a4 = H == null ? void 0 : H._zod) == null ? void 0 : _a4.traits) == null ? void 0 : _b.has(X); + } }), Object.defineProperty(G, "name", { value: X }), G; +} +var _1 = class extends Error { + constructor() { + super("Encountered Promise during synchronous parse. Use .parseAsync() instead."); + } +}; +var I4 = {}; +function u0(X) { + if (X) Object.assign(I4, X); + return I4; +} +var i = {}; +U7(i, { unwrapMessage: () => OX, stringifyPrimitive: () => S4, required: () => hV, randomString: () => ZV, propertyKeyTypes: () => E8, promiseAllObject: () => SV, primitiveTypes: () => NW, prefixIssues: () => B1, pick: () => TV, partial: () => gV, optionalKeys: () => I8, omit: () => _V, numKeys: () => CV, nullish: () => wX, normalizeParams: () => y, merge: () => yV, jsonStringifyReplacer: () => w8, joinValues: () => b4, issue: () => P8, isPlainObject: () => C6, isObject: () => Z6, getSizableOrigin: () => DW, getParsedType: () => kV, getLengthableOrigin: () => jX, getEnumValues: () => DX, getElementAtPath: () => PV, floatSafeRemainder: () => M8, finalizeIssue: () => o0, extend: () => xV, escapeRegex: () => x1, esc: () => s1, defineLazy: () => Y0, createTransparentProxy: () => vV, clone: () => l0, cleanRegex: () => MX, cleanEnum: () => fV, captureStackTrace: () => P4, cached: () => AX, assignProp: () => j8, assertNotEqual: () => RV, assertNever: () => IV, assertIs: () => EV, assertEqual: () => jV, assert: () => bV, allowsEval: () => R8, aborted: () => e1, NUMBER_FORMAT_RANGES: () => b8, Class: () => AW, BIGINT_FORMAT_RANGES: () => OW }); +function jV(X) { + return X; +} +function RV(X) { + return X; +} +function EV(X) { +} +function IV(X) { + throw Error(); +} +function bV(X) { +} +function DX(X) { + let Q = Object.values(X).filter((Y) => typeof Y === "number"); + return Object.entries(X).filter(([Y, W]) => Q.indexOf(+Y) === -1).map(([Y, W]) => W); +} +function b4(X, Q = "|") { + return X.map(($) => S4($)).join(Q); +} +function w8(X, Q) { + if (typeof Q === "bigint") return Q.toString(); + return Q; +} +function AX(X) { + return { get value() { + { + let $ = X(); + return Object.defineProperty(this, "value", { value: $ }), $; + } + throw Error("cached value already set"); + } }; +} +function wX(X) { + return X === null || X === void 0; +} +function MX(X) { + let Q = X.startsWith("^") ? 1 : 0, $ = X.endsWith("$") ? X.length - 1 : X.length; + return X.slice(Q, $); +} +function M8(X, Q) { + let $ = (X.toString().split(".")[1] || "").length, Y = (Q.toString().split(".")[1] || "").length, W = $ > Y ? $ : Y, J = Number.parseInt(X.toFixed(W).replace(".", "")), G = Number.parseInt(Q.toFixed(W).replace(".", "")); + return J % G / 10 ** W; +} +function Y0(X, Q, $) { + Object.defineProperty(X, Q, { get() { + { + let W = $(); + return X[Q] = W, W; + } + throw Error("cached value already set"); + }, set(W) { + Object.defineProperty(X, Q, { value: W }); + }, configurable: true }); +} +function j8(X, Q, $) { + Object.defineProperty(X, Q, { value: $, writable: true, enumerable: true, configurable: true }); +} +function PV(X, Q) { + if (!Q) return X; + return Q.reduce(($, Y) => $ == null ? void 0 : $[Y], X); +} +function SV(X) { + let Q = Object.keys(X), $ = Q.map((Y) => X[Y]); + return Promise.all($).then((Y) => { + let W = {}; + for (let J = 0; J < Q.length; J++) W[Q[J]] = Y[J]; + return W; + }); +} +function ZV(X = 10) { + let $ = ""; + for (let Y = 0; Y < X; Y++) $ += "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)]; + return $; +} +function s1(X) { + return JSON.stringify(X); +} +var P4 = Error.captureStackTrace ? Error.captureStackTrace : (...X) => { +}; +function Z6(X) { + return typeof X === "object" && X !== null && !Array.isArray(X); +} +var R8 = AX(() => { + var _a3; + if (typeof navigator < "u" && ((_a3 = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a3.includes("Cloudflare"))) return false; + try { + return new Function(""), true; + } catch (X) { + return false; + } +}); +function C6(X) { + if (Z6(X) === false) return false; + let Q = X.constructor; + if (Q === void 0) return true; + let $ = Q.prototype; + if (Z6($) === false) return false; + if (Object.prototype.hasOwnProperty.call($, "isPrototypeOf") === false) return false; + return true; +} +function CV(X) { + let Q = 0; + for (let $ in X) if (Object.prototype.hasOwnProperty.call(X, $)) Q++; + return Q; +} +var kV = (X) => { + let Q = typeof X; + switch (Q) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(X) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(X)) return "array"; + if (X === null) return "null"; + if (X.then && typeof X.then === "function" && X.catch && typeof X.catch === "function") return "promise"; + if (typeof Map < "u" && X instanceof Map) return "map"; + if (typeof Set < "u" && X instanceof Set) return "set"; + if (typeof Date < "u" && X instanceof Date) return "date"; + if (typeof File < "u" && X instanceof File) return "file"; + return "object"; + default: + throw Error(`Unknown data type: ${Q}`); + } +}; +var E8 = /* @__PURE__ */ new Set(["string", "number", "symbol"]); +var NW = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); +function x1(X) { + return X.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function l0(X, Q, $) { + let Y = new X._zod.constr(Q != null ? Q : X._zod.def); + if (!Q || ($ == null ? void 0 : $.parent)) Y._zod.parent = X; + return Y; +} +function y(X) { + let Q = X; + if (!Q) return {}; + if (typeof Q === "string") return { error: () => Q }; + if ((Q == null ? void 0 : Q.message) !== void 0) { + if ((Q == null ? void 0 : Q.error) !== void 0) throw Error("Cannot specify both `message` and `error` params"); + Q.error = Q.message; + } + if (delete Q.message, typeof Q.error === "string") return { ...Q, error: () => Q.error }; + return Q; +} +function vV(X) { + let Q; + return new Proxy({}, { get($, Y, W) { + return Q != null ? Q : Q = X(), Reflect.get(Q, Y, W); + }, set($, Y, W, J) { + return Q != null ? Q : Q = X(), Reflect.set(Q, Y, W, J); + }, has($, Y) { + return Q != null ? Q : Q = X(), Reflect.has(Q, Y); + }, deleteProperty($, Y) { + return Q != null ? Q : Q = X(), Reflect.deleteProperty(Q, Y); + }, ownKeys($) { + return Q != null ? Q : Q = X(), Reflect.ownKeys(Q); + }, getOwnPropertyDescriptor($, Y) { + return Q != null ? Q : Q = X(), Reflect.getOwnPropertyDescriptor(Q, Y); + }, defineProperty($, Y, W) { + return Q != null ? Q : Q = X(), Reflect.defineProperty(Q, Y, W); + } }); +} +function S4(X) { + if (typeof X === "bigint") return X.toString() + "n"; + if (typeof X === "string") return `"${X}"`; + return `${X}`; +} +function I8(X) { + return Object.keys(X).filter((Q) => { + return X[Q]._zod.optin === "optional" && X[Q]._zod.optout === "optional"; + }); +} +var b8 = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }; +var OW = { int64: [BigInt("-9223372036854775808"), BigInt("9223372036854775807")], uint64: [BigInt(0), BigInt("18446744073709551615")] }; +function TV(X, Q) { + let $ = {}, Y = X._zod.def; + for (let W in Q) { + if (!(W in Y.shape)) throw Error(`Unrecognized key: "${W}"`); + if (!Q[W]) continue; + $[W] = Y.shape[W]; + } + return l0(X, { ...X._zod.def, shape: $, checks: [] }); +} +function _V(X, Q) { + let $ = { ...X._zod.def.shape }, Y = X._zod.def; + for (let W in Q) { + if (!(W in Y.shape)) throw Error(`Unrecognized key: "${W}"`); + if (!Q[W]) continue; + delete $[W]; + } + return l0(X, { ...X._zod.def, shape: $, checks: [] }); +} +function xV(X, Q) { + if (!C6(Q)) throw Error("Invalid input to extend: expected a plain object"); + let $ = { ...X._zod.def, get shape() { + let Y = { ...X._zod.def.shape, ...Q }; + return j8(this, "shape", Y), Y; + }, checks: [] }; + return l0(X, $); +} +function yV(X, Q) { + return l0(X, { ...X._zod.def, get shape() { + let $ = { ...X._zod.def.shape, ...Q._zod.def.shape }; + return j8(this, "shape", $), $; + }, catchall: Q._zod.def.catchall, checks: [] }); +} +function gV(X, Q, $) { + let Y = Q._zod.def.shape, W = { ...Y }; + if ($) for (let J in $) { + if (!(J in Y)) throw Error(`Unrecognized key: "${J}"`); + if (!$[J]) continue; + W[J] = X ? new X({ type: "optional", innerType: Y[J] }) : Y[J]; + } + else for (let J in Y) W[J] = X ? new X({ type: "optional", innerType: Y[J] }) : Y[J]; + return l0(Q, { ...Q._zod.def, shape: W, checks: [] }); +} +function hV(X, Q, $) { + let Y = Q._zod.def.shape, W = { ...Y }; + if ($) for (let J in $) { + if (!(J in W)) throw Error(`Unrecognized key: "${J}"`); + if (!$[J]) continue; + W[J] = new X({ type: "nonoptional", innerType: Y[J] }); + } + else for (let J in Y) W[J] = new X({ type: "nonoptional", innerType: Y[J] }); + return l0(Q, { ...Q._zod.def, shape: W, checks: [] }); +} +function e1(X, Q = 0) { + var _a3; + for (let $ = Q; $ < X.issues.length; $++) if (((_a3 = X.issues[$]) == null ? void 0 : _a3.continue) !== true) return true; + return false; +} +function B1(X, Q) { + return Q.map(($) => { + var _a3; + var Y; + return (_a3 = (Y = $).path) != null ? _a3 : Y.path = [], $.path.unshift(X), $; + }); +} +function OX(X) { + return typeof X === "string" ? X : X == null ? void 0 : X.message; +} +function o0(X, Q, $) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + let Y = { ...X, path: (_a3 = X.path) != null ? _a3 : [] }; + if (!X.message) { + let W = (_k = (_j = (_h = (_f = OX((_d = (_c = (_b = X.inst) == null ? void 0 : _b._zod.def) == null ? void 0 : _c.error) == null ? void 0 : _d.call(_c, X))) != null ? _f : OX((_e = Q == null ? void 0 : Q.error) == null ? void 0 : _e.call(Q, X))) != null ? _h : OX((_g = $.customError) == null ? void 0 : _g.call($, X))) != null ? _j : OX((_i = $.localeError) == null ? void 0 : _i.call($, X))) != null ? _k : "Invalid input"; + Y.message = W; + } + if (delete Y.inst, delete Y.continue, !(Q == null ? void 0 : Q.reportInput)) delete Y.input; + return Y; +} +function DW(X) { + if (X instanceof Set) return "set"; + if (X instanceof Map) return "map"; + if (X instanceof File) return "file"; + return "unknown"; +} +function jX(X) { + if (Array.isArray(X)) return "array"; + if (typeof X === "string") return "string"; + return "unknown"; +} +function P8(...X) { + let [Q, $, Y] = X; + if (typeof Q === "string") return { message: Q, code: "custom", input: $, inst: Y }; + return { ...Q }; +} +function fV(X) { + return Object.entries(X).filter(([Q, $]) => { + return Number.isNaN(Number.parseInt(Q, 10)); + }).map((Q) => Q[1]); +} +var AW = class { + constructor(...X) { + } +}; +var wW = (X, Q) => { + X.name = "$ZodError", Object.defineProperty(X, "_zod", { value: X._zod, enumerable: false }), Object.defineProperty(X, "issues", { value: Q, enumerable: false }), Object.defineProperty(X, "message", { get() { + return JSON.stringify(Q, w8, 2); + }, enumerable: true }); +}; +var Z4 = O("$ZodError", wW); +var RX = O("$ZodError", wW, { Parent: Error }); +function S8(X, Q = ($) => $.message) { + let $ = {}, Y = []; + for (let W of X.issues) if (W.path.length > 0) $[W.path[0]] = $[W.path[0]] || [], $[W.path[0]].push(Q(W)); + else Y.push(Q(W)); + return { formErrors: Y, fieldErrors: $ }; +} +function Z8(X, Q) { + let $ = Q || function(J) { + return J.message; + }, Y = { _errors: [] }, W = (J) => { + for (let G of J.issues) if (G.code === "invalid_union" && G.errors.length) G.errors.map((H) => W({ issues: H })); + else if (G.code === "invalid_key") W({ issues: G.issues }); + else if (G.code === "invalid_element") W({ issues: G.issues }); + else if (G.path.length === 0) Y._errors.push($(G)); + else { + let H = Y, B = 0; + while (B < G.path.length) { + let z2 = G.path[B]; + if (B !== G.path.length - 1) H[z2] = H[z2] || { _errors: [] }; + else H[z2] = H[z2] || { _errors: [] }, H[z2]._errors.push($(G)); + H = H[z2], B++; + } + } + }; + return W(X), Y; +} +var C8 = (X) => (Q, $, Y, W) => { + var _a3; + let J = Y ? Object.assign(Y, { async: false }) : { async: false }, G = Q._zod.run({ value: $, issues: [] }, J); + if (G instanceof Promise) throw new _1(); + if (G.issues.length) { + let H = new ((_a3 = W == null ? void 0 : W.Err) != null ? _a3 : X)(G.issues.map((B) => o0(B, J, u0()))); + throw P4(H, W == null ? void 0 : W.callee), H; + } + return G.value; +}; +var k8 = C8(RX); +var v8 = (X) => async (Q, $, Y, W) => { + var _a3; + let J = Y ? Object.assign(Y, { async: true }) : { async: true }, G = Q._zod.run({ value: $, issues: [] }, J); + if (G instanceof Promise) G = await G; + if (G.issues.length) { + let H = new ((_a3 = W == null ? void 0 : W.Err) != null ? _a3 : X)(G.issues.map((B) => o0(B, J, u0()))); + throw P4(H, W == null ? void 0 : W.callee), H; + } + return G.value; +}; +var T8 = v8(RX); +var _8 = (X) => (Q, $, Y) => { + let W = Y ? { ...Y, async: false } : { async: false }, J = Q._zod.run({ value: $, issues: [] }, W); + if (J instanceof Promise) throw new _1(); + return J.issues.length ? { success: false, error: new (X != null ? X : Z4)(J.issues.map((G) => o0(G, W, u0()))) } : { success: true, data: J.value }; +}; +var X6 = _8(RX); +var x8 = (X) => async (Q, $, Y) => { + let W = Y ? Object.assign(Y, { async: true }) : { async: true }, J = Q._zod.run({ value: $, issues: [] }, W); + if (J instanceof Promise) J = await J; + return J.issues.length ? { success: false, error: new X(J.issues.map((G) => o0(G, W, u0()))) } : { success: true, data: J.value }; +}; +var Q6 = x8(RX); +var MW = /^[cC][^\s-]{8,}$/; +var jW = /^[0-9a-z]+$/; +var RW = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var EW = /^[0-9a-vA-V]{20}$/; +var IW = /^[A-Za-z0-9]{27}$/; +var bW = /^[a-zA-Z0-9_-]{21}$/; +var PW = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +var SW = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +var y8 = (X) => { + if (!X) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${X}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +var ZW = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +function CW() { + return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); +} +var kW = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var vW = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; +var TW = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +var _W = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var xW = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +var g8 = /^[A-Za-z0-9_-]*$/; +var yW = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +var gW = /^\+(?:[0-9]){6,14}[0-9]$/; +var hW = "(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))"; +var fW = new RegExp(`^${hW}$`); +function uW(X) { + return typeof X.precision === "number" ? X.precision === -1 ? "(?:[01]\\d|2[0-3]):[0-5]\\d" : X.precision === 0 ? "(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d" : `(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${X.precision}}` : "(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"; +} +function lW(X) { + return new RegExp(`^${uW(X)}$`); +} +function mW(X) { + let Q = uW({ precision: X.precision }), $ = ["Z"]; + if (X.local) $.push(""); + if (X.offset) $.push("([+-]\\d{2}:\\d{2})"); + let Y = `${Q}(?:${$.join("|")})`; + return new RegExp(`^${hW}T(?:${Y})$`); +} +var cW = (X) => { + var _a3, _b; + let Q = X ? `[\\s\\S]{${(_a3 = X == null ? void 0 : X.minimum) != null ? _a3 : 0},${(_b = X == null ? void 0 : X.maximum) != null ? _b : ""}}` : "[\\s\\S]*"; + return new RegExp(`^${Q}$`); +}; +var pW = /^\d+$/; +var dW = /^-?\d+(?:\.\d+)?/i; +var iW = /true|false/i; +var nW = /null/i; +var rW = /^[^A-Z]*$/; +var oW = /^[^a-z]*$/; +var w0 = O("$ZodCheck", (X, Q) => { + var _a3, _b; + var $; + (_a3 = X._zod) != null ? _a3 : X._zod = {}, X._zod.def = Q, (_b = ($ = X._zod).onattach) != null ? _b : $.onattach = []; +}); +var tW = { number: "number", bigint: "bigint", object: "date" }; +var h8 = O("$ZodCheckLessThan", (X, Q) => { + w0.init(X, Q); + let $ = tW[typeof Q.value]; + X._zod.onattach.push((Y) => { + var _a3; + let W = Y._zod.bag, J = (_a3 = Q.inclusive ? W.maximum : W.exclusiveMaximum) != null ? _a3 : Number.POSITIVE_INFINITY; + if (Q.value < J) if (Q.inclusive) W.maximum = Q.value; + else W.exclusiveMaximum = Q.value; + }), X._zod.check = (Y) => { + if (Q.inclusive ? Y.value <= Q.value : Y.value < Q.value) return; + Y.issues.push({ origin: $, code: "too_big", maximum: Q.value, input: Y.value, inclusive: Q.inclusive, inst: X, continue: !Q.abort }); + }; +}); +var f8 = O("$ZodCheckGreaterThan", (X, Q) => { + w0.init(X, Q); + let $ = tW[typeof Q.value]; + X._zod.onattach.push((Y) => { + var _a3; + let W = Y._zod.bag, J = (_a3 = Q.inclusive ? W.minimum : W.exclusiveMinimum) != null ? _a3 : Number.NEGATIVE_INFINITY; + if (Q.value > J) if (Q.inclusive) W.minimum = Q.value; + else W.exclusiveMinimum = Q.value; + }), X._zod.check = (Y) => { + if (Q.inclusive ? Y.value >= Q.value : Y.value > Q.value) return; + Y.issues.push({ origin: $, code: "too_small", minimum: Q.value, input: Y.value, inclusive: Q.inclusive, inst: X, continue: !Q.abort }); + }; +}); +var aW = O("$ZodCheckMultipleOf", (X, Q) => { + w0.init(X, Q), X._zod.onattach.push(($) => { + var _a3; + var Y; + (_a3 = (Y = $._zod.bag).multipleOf) != null ? _a3 : Y.multipleOf = Q.value; + }), X._zod.check = ($) => { + if (typeof $.value !== typeof Q.value) throw Error("Cannot mix number and bigint in multiple_of check."); + if (typeof $.value === "bigint" ? $.value % Q.value === BigInt(0) : M8($.value, Q.value) === 0) return; + $.issues.push({ origin: typeof $.value, code: "not_multiple_of", divisor: Q.value, input: $.value, inst: X, continue: !Q.abort }); + }; +}); +var sW = O("$ZodCheckNumberFormat", (X, Q) => { + var _a3; + w0.init(X, Q), Q.format = Q.format || "float64"; + let $ = (_a3 = Q.format) == null ? void 0 : _a3.includes("int"), Y = $ ? "int" : "number", [W, J] = b8[Q.format]; + X._zod.onattach.push((G) => { + let H = G._zod.bag; + if (H.format = Q.format, H.minimum = W, H.maximum = J, $) H.pattern = pW; + }), X._zod.check = (G) => { + let H = G.value; + if ($) { + if (!Number.isInteger(H)) { + G.issues.push({ expected: Y, format: Q.format, code: "invalid_type", input: H, inst: X }); + return; + } + if (!Number.isSafeInteger(H)) { + if (H > 0) G.issues.push({ input: H, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst: X, origin: Y, continue: !Q.abort }); + else G.issues.push({ input: H, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst: X, origin: Y, continue: !Q.abort }); + return; + } + } + if (H < W) G.issues.push({ origin: "number", input: H, code: "too_small", minimum: W, inclusive: true, inst: X, continue: !Q.abort }); + if (H > J) G.issues.push({ origin: "number", input: H, code: "too_big", maximum: J, inst: X }); + }; +}); +var eW = O("$ZodCheckMaxLength", (X, Q) => { + w0.init(X, Q), X._zod.when = ($) => { + let Y = $.value; + return !wX(Y) && Y.length !== void 0; + }, X._zod.onattach.push(($) => { + var _a3; + let Y = (_a3 = $._zod.bag.maximum) != null ? _a3 : Number.POSITIVE_INFINITY; + if (Q.maximum < Y) $._zod.bag.maximum = Q.maximum; + }), X._zod.check = ($) => { + let Y = $.value; + if (Y.length <= Q.maximum) return; + let J = jX(Y); + $.issues.push({ origin: J, code: "too_big", maximum: Q.maximum, inclusive: true, input: Y, inst: X, continue: !Q.abort }); + }; +}); +var XJ = O("$ZodCheckMinLength", (X, Q) => { + w0.init(X, Q), X._zod.when = ($) => { + let Y = $.value; + return !wX(Y) && Y.length !== void 0; + }, X._zod.onattach.push(($) => { + var _a3; + let Y = (_a3 = $._zod.bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY; + if (Q.minimum > Y) $._zod.bag.minimum = Q.minimum; + }), X._zod.check = ($) => { + let Y = $.value; + if (Y.length >= Q.minimum) return; + let J = jX(Y); + $.issues.push({ origin: J, code: "too_small", minimum: Q.minimum, inclusive: true, input: Y, inst: X, continue: !Q.abort }); + }; +}); +var QJ = O("$ZodCheckLengthEquals", (X, Q) => { + w0.init(X, Q), X._zod.when = ($) => { + let Y = $.value; + return !wX(Y) && Y.length !== void 0; + }, X._zod.onattach.push(($) => { + let Y = $._zod.bag; + Y.minimum = Q.length, Y.maximum = Q.length, Y.length = Q.length; + }), X._zod.check = ($) => { + let Y = $.value, W = Y.length; + if (W === Q.length) return; + let J = jX(Y), G = W > Q.length; + $.issues.push({ origin: J, ...G ? { code: "too_big", maximum: Q.length } : { code: "too_small", minimum: Q.length }, inclusive: true, exact: true, input: $.value, inst: X, continue: !Q.abort }); + }; +}); +var EX = O("$ZodCheckStringFormat", (X, Q) => { + var _a3, _b; + var $, Y; + if (w0.init(X, Q), X._zod.onattach.push((W) => { + var _a4; + let J = W._zod.bag; + if (J.format = Q.format, Q.pattern) (_a4 = J.patterns) != null ? _a4 : J.patterns = /* @__PURE__ */ new Set(), J.patterns.add(Q.pattern); + }), Q.pattern) (_a3 = ($ = X._zod).check) != null ? _a3 : $.check = (W) => { + if (Q.pattern.lastIndex = 0, Q.pattern.test(W.value)) return; + W.issues.push({ origin: "string", code: "invalid_format", format: Q.format, input: W.value, ...Q.pattern ? { pattern: Q.pattern.toString() } : {}, inst: X, continue: !Q.abort }); + }; + else (_b = (Y = X._zod).check) != null ? _b : Y.check = () => { + }; +}); +var $J = O("$ZodCheckRegex", (X, Q) => { + EX.init(X, Q), X._zod.check = ($) => { + if (Q.pattern.lastIndex = 0, Q.pattern.test($.value)) return; + $.issues.push({ origin: "string", code: "invalid_format", format: "regex", input: $.value, pattern: Q.pattern.toString(), inst: X, continue: !Q.abort }); + }; +}); +var YJ = O("$ZodCheckLowerCase", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = rW, EX.init(X, Q); +}); +var WJ = O("$ZodCheckUpperCase", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = oW, EX.init(X, Q); +}); +var JJ = O("$ZodCheckIncludes", (X, Q) => { + w0.init(X, Q); + let $ = x1(Q.includes), Y = new RegExp(typeof Q.position === "number" ? `^.{${Q.position}}${$}` : $); + Q.pattern = Y, X._zod.onattach.push((W) => { + var _a3; + let J = W._zod.bag; + (_a3 = J.patterns) != null ? _a3 : J.patterns = /* @__PURE__ */ new Set(), J.patterns.add(Y); + }), X._zod.check = (W) => { + if (W.value.includes(Q.includes, Q.position)) return; + W.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: Q.includes, input: W.value, inst: X, continue: !Q.abort }); + }; +}); +var GJ = O("$ZodCheckStartsWith", (X, Q) => { + var _a3; + w0.init(X, Q); + let $ = new RegExp(`^${x1(Q.prefix)}.*`); + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = $, X._zod.onattach.push((Y) => { + var _a4; + let W = Y._zod.bag; + (_a4 = W.patterns) != null ? _a4 : W.patterns = /* @__PURE__ */ new Set(), W.patterns.add($); + }), X._zod.check = (Y) => { + if (Y.value.startsWith(Q.prefix)) return; + Y.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: Q.prefix, input: Y.value, inst: X, continue: !Q.abort }); + }; +}); +var HJ = O("$ZodCheckEndsWith", (X, Q) => { + var _a3; + w0.init(X, Q); + let $ = new RegExp(`.*${x1(Q.suffix)}$`); + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = $, X._zod.onattach.push((Y) => { + var _a4; + let W = Y._zod.bag; + (_a4 = W.patterns) != null ? _a4 : W.patterns = /* @__PURE__ */ new Set(), W.patterns.add($); + }), X._zod.check = (Y) => { + if (Y.value.endsWith(Q.suffix)) return; + Y.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: Q.suffix, input: Y.value, inst: X, continue: !Q.abort }); + }; +}); +var BJ = O("$ZodCheckOverwrite", (X, Q) => { + w0.init(X, Q), X._zod.check = ($) => { + $.value = Q.tx($.value); + }; +}); +var u8 = class { + constructor(X = []) { + if (this.content = [], this.indent = 0, this) this.args = X; + } + indented(X) { + this.indent += 1, X(this), this.indent -= 1; + } + write(X) { + if (typeof X === "function") { + X(this, { execution: "sync" }), X(this, { execution: "async" }); + return; + } + let $ = X.split(` +`).filter((J) => J), Y = Math.min(...$.map((J) => J.length - J.trimStart().length)), W = $.map((J) => J.slice(Y)).map((J) => " ".repeat(this.indent * 2) + J); + for (let J of W) this.content.push(J); + } + compile() { + var _a3; + let X = Function, Q = this == null ? void 0 : this.args, Y = [...((_a3 = this == null ? void 0 : this.content) != null ? _a3 : [""]).map((W) => ` ${W}`)]; + return new X(...Q, Y.join(` +`)); + } +}; +var KJ = { major: 4, minor: 0, patch: 0 }; +var X0 = O("$ZodType", (X, Q) => { + var _a3, _b, _c; + var $; + X != null ? X : X = {}, X._zod.def = Q, X._zod.bag = X._zod.bag || {}, X._zod.version = KJ; + let Y = [...(_a3 = X._zod.def.checks) != null ? _a3 : []]; + if (X._zod.traits.has("$ZodCheck")) Y.unshift(X); + for (let W of Y) for (let J of W._zod.onattach) J(X); + if (Y.length === 0) (_b = ($ = X._zod).deferred) != null ? _b : $.deferred = [], (_c = X._zod.deferred) == null ? void 0 : _c.push(() => { + X._zod.run = X._zod.parse; + }); + else { + let W = (J, G, H) => { + let B = e1(J), z2; + for (let K of G) { + if (K._zod.when) { + if (!K._zod.when(J)) continue; + } else if (B) continue; + let V = J.issues.length, L = K._zod.check(J); + if (L instanceof Promise && (H == null ? void 0 : H.async) === false) throw new _1(); + if (z2 || L instanceof Promise) z2 = (z2 != null ? z2 : Promise.resolve()).then(async () => { + if (await L, J.issues.length === V) return; + if (!B) B = e1(J, V); + }); + else { + if (J.issues.length === V) continue; + if (!B) B = e1(J, V); + } + } + if (z2) return z2.then(() => { + return J; + }); + return J; + }; + X._zod.run = (J, G) => { + let H = X._zod.parse(J, G); + if (H instanceof Promise) { + if (G.async === false) throw new _1(); + return H.then((B) => W(B, Y, G)); + } + return W(H, Y, G); + }; + } + X["~standard"] = { validate: (W) => { + var _a4; + try { + let J = X6(X, W); + return J.success ? { value: J.data } : { issues: (_a4 = J.error) == null ? void 0 : _a4.issues }; + } catch (J) { + return Q6(X, W).then((G) => { + var _a5; + return G.success ? { value: G.data } : { issues: (_a5 = G.error) == null ? void 0 : _a5.issues }; + }); + } + }, vendor: "zod", version: 1 }; +}); +var IX = O("$ZodString", (X, Q) => { + var _a3, _b, _c; + X0.init(X, Q), X._zod.pattern = (_c = [...(_b = (_a3 = X == null ? void 0 : X._zod.bag) == null ? void 0 : _a3.patterns) != null ? _b : []].pop()) != null ? _c : cW(X._zod.bag), X._zod.parse = ($, Y) => { + if (Q.coerce) try { + $.value = String($.value); + } catch (W) { + } + if (typeof $.value === "string") return $; + return $.issues.push({ expected: "string", code: "invalid_type", input: $.value, inst: X }), $; + }; +}); +var W0 = O("$ZodStringFormat", (X, Q) => { + EX.init(X, Q), IX.init(X, Q); +}); +var m8 = O("$ZodGUID", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = SW, W0.init(X, Q); +}); +var c8 = O("$ZodUUID", (X, Q) => { + var _a3, _b; + if (Q.version) { + let Y = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }[Q.version]; + if (Y === void 0) throw Error(`Invalid UUID version: "${Q.version}"`); + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = y8(Y); + } else (_b = Q.pattern) != null ? _b : Q.pattern = y8(); + W0.init(X, Q); +}); +var p8 = O("$ZodEmail", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = ZW, W0.init(X, Q); +}); +var d8 = O("$ZodURL", (X, Q) => { + W0.init(X, Q), X._zod.check = ($) => { + try { + let Y = $.value, W = new URL(Y), J = W.href; + if (Q.hostname) { + if (Q.hostname.lastIndex = 0, !Q.hostname.test(W.hostname)) $.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: yW.source, input: $.value, inst: X, continue: !Q.abort }); + } + if (Q.protocol) { + if (Q.protocol.lastIndex = 0, !Q.protocol.test(W.protocol.endsWith(":") ? W.protocol.slice(0, -1) : W.protocol)) $.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: Q.protocol.source, input: $.value, inst: X, continue: !Q.abort }); + } + if (!Y.endsWith("/") && J.endsWith("/")) $.value = J.slice(0, -1); + else $.value = J; + return; + } catch (Y) { + $.issues.push({ code: "invalid_format", format: "url", input: $.value, inst: X, continue: !Q.abort }); + } + }; +}); +var i8 = O("$ZodEmoji", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = CW(), W0.init(X, Q); +}); +var n8 = O("$ZodNanoID", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = bW, W0.init(X, Q); +}); +var r8 = O("$ZodCUID", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = MW, W0.init(X, Q); +}); +var o8 = O("$ZodCUID2", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = jW, W0.init(X, Q); +}); +var t8 = O("$ZodULID", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = RW, W0.init(X, Q); +}); +var a8 = O("$ZodXID", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = EW, W0.init(X, Q); +}); +var s8 = O("$ZodKSUID", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = IW, W0.init(X, Q); +}); +var wJ = O("$ZodISODateTime", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = mW(Q), W0.init(X, Q); +}); +var MJ = O("$ZodISODate", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = fW, W0.init(X, Q); +}); +var jJ = O("$ZodISOTime", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = lW(Q), W0.init(X, Q); +}); +var RJ = O("$ZodISODuration", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = PW, W0.init(X, Q); +}); +var e8 = O("$ZodIPv4", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = kW, W0.init(X, Q), X._zod.onattach.push(($) => { + let Y = $._zod.bag; + Y.format = "ipv4"; + }); +}); +var XQ = O("$ZodIPv6", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = vW, W0.init(X, Q), X._zod.onattach.push(($) => { + let Y = $._zod.bag; + Y.format = "ipv6"; + }), X._zod.check = ($) => { + try { + new URL(`http://[${$.value}]`); + } catch (e2) { + $.issues.push({ code: "invalid_format", format: "ipv6", input: $.value, inst: X, continue: !Q.abort }); + } + }; +}); +var QQ = O("$ZodCIDRv4", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = TW, W0.init(X, Q); +}); +var $Q = O("$ZodCIDRv6", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = _W, W0.init(X, Q), X._zod.check = ($) => { + let [Y, W] = $.value.split("/"); + try { + if (!W) throw Error(); + let J = Number(W); + if (`${J}` !== W) throw Error(); + if (J < 0 || J > 128) throw Error(); + new URL(`http://[${Y}]`); + } catch (e2) { + $.issues.push({ code: "invalid_format", format: "cidrv6", input: $.value, inst: X, continue: !Q.abort }); + } + }; +}); +function EJ(X) { + if (X === "") return true; + if (X.length % 4 !== 0) return false; + try { + return atob(X), true; + } catch (e2) { + return false; + } +} +var YQ = O("$ZodBase64", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = xW, W0.init(X, Q), X._zod.onattach.push(($) => { + $._zod.bag.contentEncoding = "base64"; + }), X._zod.check = ($) => { + if (EJ($.value)) return; + $.issues.push({ code: "invalid_format", format: "base64", input: $.value, inst: X, continue: !Q.abort }); + }; +}); +function lV(X) { + if (!g8.test(X)) return false; + let Q = X.replace(/[-_]/g, (Y) => Y === "-" ? "+" : "/"), $ = Q.padEnd(Math.ceil(Q.length / 4) * 4, "="); + return EJ($); +} +var WQ = O("$ZodBase64URL", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = g8, W0.init(X, Q), X._zod.onattach.push(($) => { + $._zod.bag.contentEncoding = "base64url"; + }), X._zod.check = ($) => { + if (lV($.value)) return; + $.issues.push({ code: "invalid_format", format: "base64url", input: $.value, inst: X, continue: !Q.abort }); + }; +}); +var JQ = O("$ZodE164", (X, Q) => { + var _a3; + (_a3 = Q.pattern) != null ? _a3 : Q.pattern = gW, W0.init(X, Q); +}); +function mV(X, Q = null) { + try { + let $ = X.split("."); + if ($.length !== 3) return false; + let [Y] = $; + if (!Y) return false; + let W = JSON.parse(atob(Y)); + if ("typ" in W && (W == null ? void 0 : W.typ) !== "JWT") return false; + if (!W.alg) return false; + if (Q && (!("alg" in W) || W.alg !== Q)) return false; + return true; + } catch (e2) { + return false; + } +} +var GQ = O("$ZodJWT", (X, Q) => { + W0.init(X, Q), X._zod.check = ($) => { + if (mV($.value, Q.alg)) return; + $.issues.push({ code: "invalid_format", format: "jwt", input: $.value, inst: X, continue: !Q.abort }); + }; +}); +var v4 = O("$ZodNumber", (X, Q) => { + var _a3; + X0.init(X, Q), X._zod.pattern = (_a3 = X._zod.bag.pattern) != null ? _a3 : dW, X._zod.parse = ($, Y) => { + if (Q.coerce) try { + $.value = Number($.value); + } catch (G) { + } + let W = $.value; + if (typeof W === "number" && !Number.isNaN(W) && Number.isFinite(W)) return $; + let J = typeof W === "number" ? Number.isNaN(W) ? "NaN" : !Number.isFinite(W) ? "Infinity" : void 0 : void 0; + return $.issues.push({ expected: "number", code: "invalid_type", input: W, inst: X, ...J ? { received: J } : {} }), $; + }; +}); +var HQ = O("$ZodNumber", (X, Q) => { + sW.init(X, Q), v4.init(X, Q); +}); +var BQ = O("$ZodBoolean", (X, Q) => { + X0.init(X, Q), X._zod.pattern = iW, X._zod.parse = ($, Y) => { + if (Q.coerce) try { + $.value = Boolean($.value); + } catch (J) { + } + let W = $.value; + if (typeof W === "boolean") return $; + return $.issues.push({ expected: "boolean", code: "invalid_type", input: W, inst: X }), $; + }; +}); +var zQ = O("$ZodNull", (X, Q) => { + X0.init(X, Q), X._zod.pattern = nW, X._zod.values = /* @__PURE__ */ new Set([null]), X._zod.parse = ($, Y) => { + let W = $.value; + if (W === null) return $; + return $.issues.push({ expected: "null", code: "invalid_type", input: W, inst: X }), $; + }; +}); +var KQ = O("$ZodUnknown", (X, Q) => { + X0.init(X, Q), X._zod.parse = ($) => $; +}); +var UQ = O("$ZodNever", (X, Q) => { + X0.init(X, Q), X._zod.parse = ($, Y) => { + return $.issues.push({ expected: "never", code: "invalid_type", input: $.value, inst: X }), $; + }; +}); +function UJ(X, Q, $) { + if (X.issues.length) Q.issues.push(...B1($, X.issues)); + Q.value[$] = X.value; +} +var VQ = O("$ZodArray", (X, Q) => { + X0.init(X, Q), X._zod.parse = ($, Y) => { + let W = $.value; + if (!Array.isArray(W)) return $.issues.push({ expected: "array", code: "invalid_type", input: W, inst: X }), $; + $.value = Array(W.length); + let J = []; + for (let G = 0; G < W.length; G++) { + let H = W[G], B = Q.element._zod.run({ value: H, issues: [] }, Y); + if (B instanceof Promise) J.push(B.then((z2) => UJ(z2, $, G))); + else UJ(B, $, G); + } + if (J.length) return Promise.all(J).then(() => $); + return $; + }; +}); +function k4(X, Q, $) { + if (X.issues.length) Q.issues.push(...B1($, X.issues)); + Q.value[$] = X.value; +} +function VJ(X, Q, $, Y) { + if (X.issues.length) if (Y[$] === void 0) if ($ in Y) Q.value[$] = void 0; + else Q.value[$] = X.value; + else Q.issues.push(...B1($, X.issues)); + else if (X.value === void 0) { + if ($ in Y) Q.value[$] = void 0; + } else Q.value[$] = X.value; +} +var T4 = O("$ZodObject", (X, Q) => { + X0.init(X, Q); + let $ = AX(() => { + let V = Object.keys(Q.shape); + for (let U of V) if (!(Q.shape[U] instanceof X0)) throw Error(`Invalid element at key "${U}": expected a Zod schema`); + let L = I8(Q.shape); + return { shape: Q.shape, keys: V, keySet: new Set(V), numKeys: V.length, optionalKeys: new Set(L) }; + }); + Y0(X._zod, "propValues", () => { + var _a3; + let V = Q.shape, L = {}; + for (let U in V) { + let F = V[U]._zod; + if (F.values) { + (_a3 = L[U]) != null ? _a3 : L[U] = /* @__PURE__ */ new Set(); + for (let q of F.values) L[U].add(q); + } + } + return L; + }); + let Y = (V) => { + let L = new u8(["shape", "payload", "ctx"]), U = $.value, F = (M) => { + let R = s1(M); + return `shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`; + }; + L.write("const input = payload.value;"); + let q = /* @__PURE__ */ Object.create(null), N = 0; + for (let M of U.keys) q[M] = `key_${N++}`; + L.write("const newResult = {}"); + for (let M of U.keys) if (U.optionalKeys.has(M)) { + let R = q[M]; + L.write(`const ${R} = ${F(M)};`); + let S = s1(M); + L.write(` + if (${R}.issues.length) { + if (input[${S}] === undefined) { + if (${S} in input) { + newResult[${S}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${R}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${S}, ...iss.path] : [${S}], + })) + ); + } + } else if (${R}.value === undefined) { + if (${S} in input) newResult[${S}] = undefined; + } else { + newResult[${S}] = ${R}.value; + } + `); + } else { + let R = q[M]; + L.write(`const ${R} = ${F(M)};`), L.write(` + if (${R}.issues.length) payload.issues = payload.issues.concat(${R}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${s1(M)}, ...iss.path] : [${s1(M)}] + })));`), L.write(`newResult[${s1(M)}] = ${R}.value`); + } + L.write("payload.value = newResult;"), L.write("return payload;"); + let A = L.compile(); + return (M, R) => A(V, M, R); + }, W, J = Z6, G = !I4.jitless, B = G && R8.value, z2 = Q.catchall, K; + X._zod.parse = (V, L) => { + K != null ? K : K = $.value; + let U = V.value; + if (!J(U)) return V.issues.push({ expected: "object", code: "invalid_type", input: U, inst: X }), V; + let F = []; + if (G && B && (L == null ? void 0 : L.async) === false && L.jitless !== true) { + if (!W) W = Y(Q.shape); + V = W(V, L); + } else { + V.value = {}; + let R = K.shape; + for (let S of K.keys) { + let C = R[S], K0 = C._zod.run({ value: U[S], issues: [] }, L), U0 = C._zod.optin === "optional" && C._zod.optout === "optional"; + if (K0 instanceof Promise) F.push(K0.then((s) => U0 ? VJ(s, V, S, U) : k4(s, V, S))); + else if (U0) VJ(K0, V, S, U); + else k4(K0, V, S); + } + } + if (!z2) return F.length ? Promise.all(F).then(() => V) : V; + let q = [], N = K.keySet, A = z2._zod, M = A.def.type; + for (let R of Object.keys(U)) { + if (N.has(R)) continue; + if (M === "never") { + q.push(R); + continue; + } + let S = A.run({ value: U[R], issues: [] }, L); + if (S instanceof Promise) F.push(S.then((C) => k4(C, V, R))); + else k4(S, V, R); + } + if (q.length) V.issues.push({ code: "unrecognized_keys", keys: q, input: U, inst: X }); + if (!F.length) return V; + return Promise.all(F).then(() => { + return V; + }); + }; +}); +function LJ(X, Q, $, Y) { + for (let W of X) if (W.issues.length === 0) return Q.value = W.value, Q; + return Q.issues.push({ code: "invalid_union", input: Q.value, inst: $, errors: X.map((W) => W.issues.map((J) => o0(J, Y, u0()))) }), Q; +} +var _4 = O("$ZodUnion", (X, Q) => { + X0.init(X, Q), Y0(X._zod, "optin", () => Q.options.some(($) => $._zod.optin === "optional") ? "optional" : void 0), Y0(X._zod, "optout", () => Q.options.some(($) => $._zod.optout === "optional") ? "optional" : void 0), Y0(X._zod, "values", () => { + if (Q.options.every(($) => $._zod.values)) return new Set(Q.options.flatMap(($) => Array.from($._zod.values))); + return; + }), Y0(X._zod, "pattern", () => { + if (Q.options.every(($) => $._zod.pattern)) { + let $ = Q.options.map((Y) => Y._zod.pattern); + return new RegExp(`^(${$.map((Y) => MX(Y.source)).join("|")})$`); + } + return; + }), X._zod.parse = ($, Y) => { + let W = false, J = []; + for (let G of Q.options) { + let H = G._zod.run({ value: $.value, issues: [] }, Y); + if (H instanceof Promise) J.push(H), W = true; + else { + if (H.issues.length === 0) return H; + J.push(H); + } + } + if (!W) return LJ(J, $, X, Y); + return Promise.all(J).then((G) => { + return LJ(G, $, X, Y); + }); + }; +}); +var LQ = O("$ZodDiscriminatedUnion", (X, Q) => { + _4.init(X, Q); + let $ = X._zod.parse; + Y0(X._zod, "propValues", () => { + let W = {}; + for (let J of Q.options) { + let G = J._zod.propValues; + if (!G || Object.keys(G).length === 0) throw Error(`Invalid discriminated union option at index "${Q.options.indexOf(J)}"`); + for (let [H, B] of Object.entries(G)) { + if (!W[H]) W[H] = /* @__PURE__ */ new Set(); + for (let z2 of B) W[H].add(z2); + } + } + return W; + }); + let Y = AX(() => { + let W = Q.options, J = /* @__PURE__ */ new Map(); + for (let G of W) { + let H = G._zod.propValues[Q.discriminator]; + if (!H || H.size === 0) throw Error(`Invalid discriminated union option at index "${Q.options.indexOf(G)}"`); + for (let B of H) { + if (J.has(B)) throw Error(`Duplicate discriminator value "${String(B)}"`); + J.set(B, G); + } + } + return J; + }); + X._zod.parse = (W, J) => { + let G = W.value; + if (!Z6(G)) return W.issues.push({ code: "invalid_type", expected: "object", input: G, inst: X }), W; + let H = Y.value.get(G == null ? void 0 : G[Q.discriminator]); + if (H) return H._zod.run(W, J); + if (Q.unionFallback) return $(W, J); + return W.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", input: G, path: [Q.discriminator], inst: X }), W; + }; +}); +var qQ = O("$ZodIntersection", (X, Q) => { + X0.init(X, Q), X._zod.parse = ($, Y) => { + let W = $.value, J = Q.left._zod.run({ value: W, issues: [] }, Y), G = Q.right._zod.run({ value: W, issues: [] }, Y); + if (J instanceof Promise || G instanceof Promise) return Promise.all([J, G]).then(([B, z2]) => { + return qJ($, B, z2); + }); + return qJ($, J, G); + }; +}); +function l8(X, Q) { + if (X === Q) return { valid: true, data: X }; + if (X instanceof Date && Q instanceof Date && +X === +Q) return { valid: true, data: X }; + if (C6(X) && C6(Q)) { + let $ = Object.keys(Q), Y = Object.keys(X).filter((J) => $.indexOf(J) !== -1), W = { ...X, ...Q }; + for (let J of Y) { + let G = l8(X[J], Q[J]); + if (!G.valid) return { valid: false, mergeErrorPath: [J, ...G.mergeErrorPath] }; + W[J] = G.data; + } + return { valid: true, data: W }; + } + if (Array.isArray(X) && Array.isArray(Q)) { + if (X.length !== Q.length) return { valid: false, mergeErrorPath: [] }; + let $ = []; + for (let Y = 0; Y < X.length; Y++) { + let W = X[Y], J = Q[Y], G = l8(W, J); + if (!G.valid) return { valid: false, mergeErrorPath: [Y, ...G.mergeErrorPath] }; + $.push(G.data); + } + return { valid: true, data: $ }; + } + return { valid: false, mergeErrorPath: [] }; +} +function qJ(X, Q, $) { + if (Q.issues.length) X.issues.push(...Q.issues); + if ($.issues.length) X.issues.push(...$.issues); + if (e1(X)) return X; + let Y = l8(Q.value, $.value); + if (!Y.valid) throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Y.mergeErrorPath)}`); + return X.value = Y.data, X; +} +var FQ = O("$ZodRecord", (X, Q) => { + X0.init(X, Q), X._zod.parse = ($, Y) => { + let W = $.value; + if (!C6(W)) return $.issues.push({ expected: "record", code: "invalid_type", input: W, inst: X }), $; + let J = []; + if (Q.keyType._zod.values) { + let G = Q.keyType._zod.values; + $.value = {}; + for (let B of G) if (typeof B === "string" || typeof B === "number" || typeof B === "symbol") { + let z2 = Q.valueType._zod.run({ value: W[B], issues: [] }, Y); + if (z2 instanceof Promise) J.push(z2.then((K) => { + if (K.issues.length) $.issues.push(...B1(B, K.issues)); + $.value[B] = K.value; + })); + else { + if (z2.issues.length) $.issues.push(...B1(B, z2.issues)); + $.value[B] = z2.value; + } + } + let H; + for (let B in W) if (!G.has(B)) H = H != null ? H : [], H.push(B); + if (H && H.length > 0) $.issues.push({ code: "unrecognized_keys", input: W, inst: X, keys: H }); + } else { + $.value = {}; + for (let G of Reflect.ownKeys(W)) { + if (G === "__proto__") continue; + let H = Q.keyType._zod.run({ value: G, issues: [] }, Y); + if (H instanceof Promise) throw Error("Async schemas not supported in object keys currently"); + if (H.issues.length) { + $.issues.push({ origin: "record", code: "invalid_key", issues: H.issues.map((z2) => o0(z2, Y, u0())), input: G, path: [G], inst: X }), $.value[H.value] = H.value; + continue; + } + let B = Q.valueType._zod.run({ value: W[G], issues: [] }, Y); + if (B instanceof Promise) J.push(B.then((z2) => { + if (z2.issues.length) $.issues.push(...B1(G, z2.issues)); + $.value[H.value] = z2.value; + })); + else { + if (B.issues.length) $.issues.push(...B1(G, B.issues)); + $.value[H.value] = B.value; + } + } + } + if (J.length) return Promise.all(J).then(() => $); + return $; + }; +}); +var NQ = O("$ZodEnum", (X, Q) => { + X0.init(X, Q); + let $ = DX(Q.entries); + X._zod.values = new Set($), X._zod.pattern = new RegExp(`^(${$.filter((Y) => E8.has(typeof Y)).map((Y) => typeof Y === "string" ? x1(Y) : Y.toString()).join("|")})$`), X._zod.parse = (Y, W) => { + let J = Y.value; + if (X._zod.values.has(J)) return Y; + return Y.issues.push({ code: "invalid_value", values: $, input: J, inst: X }), Y; + }; +}); +var OQ = O("$ZodLiteral", (X, Q) => { + X0.init(X, Q), X._zod.values = new Set(Q.values), X._zod.pattern = new RegExp(`^(${Q.values.map(($) => typeof $ === "string" ? x1($) : $ ? $.toString() : String($)).join("|")})$`), X._zod.parse = ($, Y) => { + let W = $.value; + if (X._zod.values.has(W)) return $; + return $.issues.push({ code: "invalid_value", values: Q.values, input: W, inst: X }), $; + }; +}); +var DQ = O("$ZodTransform", (X, Q) => { + X0.init(X, Q), X._zod.parse = ($, Y) => { + let W = Q.transform($.value, $); + if (Y.async) return (W instanceof Promise ? W : Promise.resolve(W)).then((G) => { + return $.value = G, $; + }); + if (W instanceof Promise) throw new _1(); + return $.value = W, $; + }; +}); +var AQ = O("$ZodOptional", (X, Q) => { + X0.init(X, Q), X._zod.optin = "optional", X._zod.optout = "optional", Y0(X._zod, "values", () => { + return Q.innerType._zod.values ? /* @__PURE__ */ new Set([...Q.innerType._zod.values, void 0]) : void 0; + }), Y0(X._zod, "pattern", () => { + let $ = Q.innerType._zod.pattern; + return $ ? new RegExp(`^(${MX($.source)})?$`) : void 0; + }), X._zod.parse = ($, Y) => { + if (Q.innerType._zod.optin === "optional") return Q.innerType._zod.run($, Y); + if ($.value === void 0) return $; + return Q.innerType._zod.run($, Y); + }; +}); +var wQ = O("$ZodNullable", (X, Q) => { + X0.init(X, Q), Y0(X._zod, "optin", () => Q.innerType._zod.optin), Y0(X._zod, "optout", () => Q.innerType._zod.optout), Y0(X._zod, "pattern", () => { + let $ = Q.innerType._zod.pattern; + return $ ? new RegExp(`^(${MX($.source)}|null)$`) : void 0; + }), Y0(X._zod, "values", () => { + return Q.innerType._zod.values ? /* @__PURE__ */ new Set([...Q.innerType._zod.values, null]) : void 0; + }), X._zod.parse = ($, Y) => { + if ($.value === null) return $; + return Q.innerType._zod.run($, Y); + }; +}); +var MQ = O("$ZodDefault", (X, Q) => { + X0.init(X, Q), X._zod.optin = "optional", Y0(X._zod, "values", () => Q.innerType._zod.values), X._zod.parse = ($, Y) => { + if ($.value === void 0) return $.value = Q.defaultValue, $; + let W = Q.innerType._zod.run($, Y); + if (W instanceof Promise) return W.then((J) => FJ(J, Q)); + return FJ(W, Q); + }; +}); +function FJ(X, Q) { + if (X.value === void 0) X.value = Q.defaultValue; + return X; +} +var jQ = O("$ZodPrefault", (X, Q) => { + X0.init(X, Q), X._zod.optin = "optional", Y0(X._zod, "values", () => Q.innerType._zod.values), X._zod.parse = ($, Y) => { + if ($.value === void 0) $.value = Q.defaultValue; + return Q.innerType._zod.run($, Y); + }; +}); +var RQ = O("$ZodNonOptional", (X, Q) => { + X0.init(X, Q), Y0(X._zod, "values", () => { + let $ = Q.innerType._zod.values; + return $ ? new Set([...$].filter((Y) => Y !== void 0)) : void 0; + }), X._zod.parse = ($, Y) => { + let W = Q.innerType._zod.run($, Y); + if (W instanceof Promise) return W.then((J) => NJ(J, X)); + return NJ(W, X); + }; +}); +function NJ(X, Q) { + if (!X.issues.length && X.value === void 0) X.issues.push({ code: "invalid_type", expected: "nonoptional", input: X.value, inst: Q }); + return X; +} +var EQ = O("$ZodCatch", (X, Q) => { + X0.init(X, Q), X._zod.optin = "optional", Y0(X._zod, "optout", () => Q.innerType._zod.optout), Y0(X._zod, "values", () => Q.innerType._zod.values), X._zod.parse = ($, Y) => { + let W = Q.innerType._zod.run($, Y); + if (W instanceof Promise) return W.then((J) => { + if ($.value = J.value, J.issues.length) $.value = Q.catchValue({ ...$, error: { issues: J.issues.map((G) => o0(G, Y, u0())) }, input: $.value }), $.issues = []; + return $; + }); + if ($.value = W.value, W.issues.length) $.value = Q.catchValue({ ...$, error: { issues: W.issues.map((J) => o0(J, Y, u0())) }, input: $.value }), $.issues = []; + return $; + }; +}); +var IQ = O("$ZodPipe", (X, Q) => { + X0.init(X, Q), Y0(X._zod, "values", () => Q.in._zod.values), Y0(X._zod, "optin", () => Q.in._zod.optin), Y0(X._zod, "optout", () => Q.out._zod.optout), X._zod.parse = ($, Y) => { + let W = Q.in._zod.run($, Y); + if (W instanceof Promise) return W.then((J) => OJ(J, Q, Y)); + return OJ(W, Q, Y); + }; +}); +function OJ(X, Q, $) { + if (e1(X)) return X; + return Q.out._zod.run({ value: X.value, issues: X.issues }, $); +} +var bQ = O("$ZodReadonly", (X, Q) => { + X0.init(X, Q), Y0(X._zod, "propValues", () => Q.innerType._zod.propValues), Y0(X._zod, "values", () => Q.innerType._zod.values), Y0(X._zod, "optin", () => Q.innerType._zod.optin), Y0(X._zod, "optout", () => Q.innerType._zod.optout), X._zod.parse = ($, Y) => { + let W = Q.innerType._zod.run($, Y); + if (W instanceof Promise) return W.then(DJ); + return DJ(W); + }; +}); +function DJ(X) { + return X.value = Object.freeze(X.value), X; +} +var PQ = O("$ZodCustom", (X, Q) => { + w0.init(X, Q), X0.init(X, Q), X._zod.parse = ($, Y) => { + return $; + }, X._zod.check = ($) => { + let Y = $.value, W = Q.fn(Y); + if (W instanceof Promise) return W.then((J) => AJ(J, $, Y, X)); + AJ(W, $, Y, X); + return; + }; +}); +function AJ(X, Q, $, Y) { + var _a3; + if (!X) { + let W = { code: "custom", input: $, inst: Y, path: [...(_a3 = Y._zod.def.path) != null ? _a3 : []], continue: !Y._zod.def.abort }; + if (Y._zod.def.params) W.params = Y._zod.def.params; + Q.issues.push(P8(W)); + } +} +var cV = (X) => { + let Q = typeof X; + switch (Q) { + case "number": + return Number.isNaN(X) ? "NaN" : "number"; + case "object": { + if (Array.isArray(X)) return "array"; + if (X === null) return "null"; + if (Object.getPrototypeOf(X) !== Object.prototype && X.constructor) return X.constructor.name; + } + } + return Q; +}; +var pV = () => { + let X = { string: { unit: "characters", verb: "to have" }, file: { unit: "bytes", verb: "to have" }, array: { unit: "items", verb: "to have" }, set: { unit: "items", verb: "to have" } }; + function Q(Y) { + var _a3; + return (_a3 = X[Y]) != null ? _a3 : null; + } + let $ = { regex: "input", email: "email address", url: "URL", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO datetime", date: "ISO date", time: "ISO time", duration: "ISO duration", ipv4: "IPv4 address", ipv6: "IPv6 address", cidrv4: "IPv4 range", cidrv6: "IPv6 range", base64: "base64-encoded string", base64url: "base64url-encoded string", json_string: "JSON string", e164: "E.164 number", jwt: "JWT", template_literal: "input" }; + return (Y) => { + var _a3, _b, _c, _d; + switch (Y.code) { + case "invalid_type": + return `Invalid input: expected ${Y.expected}, received ${cV(Y.input)}`; + case "invalid_value": + if (Y.values.length === 1) return `Invalid input: expected ${S4(Y.values[0])}`; + return `Invalid option: expected one of ${b4(Y.values, "|")}`; + case "too_big": { + let W = Y.inclusive ? "<=" : "<", J = Q(Y.origin); + if (J) return `Too big: expected ${(_a3 = Y.origin) != null ? _a3 : "value"} to have ${W}${Y.maximum.toString()} ${(_b = J.unit) != null ? _b : "elements"}`; + return `Too big: expected ${(_c = Y.origin) != null ? _c : "value"} to be ${W}${Y.maximum.toString()}`; + } + case "too_small": { + let W = Y.inclusive ? ">=" : ">", J = Q(Y.origin); + if (J) return `Too small: expected ${Y.origin} to have ${W}${Y.minimum.toString()} ${J.unit}`; + return `Too small: expected ${Y.origin} to be ${W}${Y.minimum.toString()}`; + } + case "invalid_format": { + let W = Y; + if (W.format === "starts_with") return `Invalid string: must start with "${W.prefix}"`; + if (W.format === "ends_with") return `Invalid string: must end with "${W.suffix}"`; + if (W.format === "includes") return `Invalid string: must include "${W.includes}"`; + if (W.format === "regex") return `Invalid string: must match pattern ${W.pattern}`; + return `Invalid ${(_d = $[W.format]) != null ? _d : Y.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${Y.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${Y.keys.length > 1 ? "s" : ""}: ${b4(Y.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${Y.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${Y.origin}`; + default: + return "Invalid input"; + } + }; +}; +function SQ() { + return { localeError: pV() }; +} +var x4 = class { + constructor() { + this._map = /* @__PURE__ */ new WeakMap(), this._idmap = /* @__PURE__ */ new Map(); + } + add(X, ...Q) { + let $ = Q[0]; + if (this._map.set(X, $), $ && typeof $ === "object" && "id" in $) { + if (this._idmap.has($.id)) throw Error(`ID ${$.id} already exists in the registry`); + this._idmap.set($.id, X); + } + return this; + } + remove(X) { + return this._map.delete(X), this; + } + get(X) { + var _a3; + let Q = X._zod.parent; + if (Q) { + let $ = { ...(_a3 = this.get(Q)) != null ? _a3 : {} }; + return delete $.id, { ...$, ...this._map.get(X) }; + } + return this._map.get(X); + } + has(X) { + return this._map.has(X); + } +}; +function IJ() { + return new x4(); +} +var y1 = IJ(); +function ZQ(X, Q) { + return new X({ type: "string", ...y(Q) }); +} +function CQ(X, Q) { + return new X({ type: "string", format: "email", check: "string_format", abort: false, ...y(Q) }); +} +function y4(X, Q) { + return new X({ type: "string", format: "guid", check: "string_format", abort: false, ...y(Q) }); +} +function kQ(X, Q) { + return new X({ type: "string", format: "uuid", check: "string_format", abort: false, ...y(Q) }); +} +function vQ(X, Q) { + return new X({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...y(Q) }); +} +function TQ(X, Q) { + return new X({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...y(Q) }); +} +function _Q(X, Q) { + return new X({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...y(Q) }); +} +function xQ(X, Q) { + return new X({ type: "string", format: "url", check: "string_format", abort: false, ...y(Q) }); +} +function yQ(X, Q) { + return new X({ type: "string", format: "emoji", check: "string_format", abort: false, ...y(Q) }); +} +function gQ(X, Q) { + return new X({ type: "string", format: "nanoid", check: "string_format", abort: false, ...y(Q) }); +} +function hQ(X, Q) { + return new X({ type: "string", format: "cuid", check: "string_format", abort: false, ...y(Q) }); +} +function fQ(X, Q) { + return new X({ type: "string", format: "cuid2", check: "string_format", abort: false, ...y(Q) }); +} +function uQ(X, Q) { + return new X({ type: "string", format: "ulid", check: "string_format", abort: false, ...y(Q) }); +} +function lQ(X, Q) { + return new X({ type: "string", format: "xid", check: "string_format", abort: false, ...y(Q) }); +} +function mQ(X, Q) { + return new X({ type: "string", format: "ksuid", check: "string_format", abort: false, ...y(Q) }); +} +function cQ(X, Q) { + return new X({ type: "string", format: "ipv4", check: "string_format", abort: false, ...y(Q) }); +} +function pQ(X, Q) { + return new X({ type: "string", format: "ipv6", check: "string_format", abort: false, ...y(Q) }); +} +function dQ(X, Q) { + return new X({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...y(Q) }); +} +function iQ(X, Q) { + return new X({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...y(Q) }); +} +function nQ(X, Q) { + return new X({ type: "string", format: "base64", check: "string_format", abort: false, ...y(Q) }); +} +function rQ(X, Q) { + return new X({ type: "string", format: "base64url", check: "string_format", abort: false, ...y(Q) }); +} +function oQ(X, Q) { + return new X({ type: "string", format: "e164", check: "string_format", abort: false, ...y(Q) }); +} +function tQ(X, Q) { + return new X({ type: "string", format: "jwt", check: "string_format", abort: false, ...y(Q) }); +} +function bJ(X, Q) { + return new X({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...y(Q) }); +} +function PJ(X, Q) { + return new X({ type: "string", format: "date", check: "string_format", ...y(Q) }); +} +function SJ(X, Q) { + return new X({ type: "string", format: "time", check: "string_format", precision: null, ...y(Q) }); +} +function ZJ(X, Q) { + return new X({ type: "string", format: "duration", check: "string_format", ...y(Q) }); +} +function aQ(X, Q) { + return new X({ type: "number", checks: [], ...y(Q) }); +} +function sQ(X, Q) { + return new X({ type: "number", check: "number_format", abort: false, format: "safeint", ...y(Q) }); +} +function eQ(X, Q) { + return new X({ type: "boolean", ...y(Q) }); +} +function X$(X, Q) { + return new X({ type: "null", ...y(Q) }); +} +function Q$(X) { + return new X({ type: "unknown" }); +} +function $$(X, Q) { + return new X({ type: "never", ...y(Q) }); +} +function g4(X, Q) { + return new h8({ check: "less_than", ...y(Q), value: X, inclusive: false }); +} +function bX(X, Q) { + return new h8({ check: "less_than", ...y(Q), value: X, inclusive: true }); +} +function h4(X, Q) { + return new f8({ check: "greater_than", ...y(Q), value: X, inclusive: false }); +} +function PX(X, Q) { + return new f8({ check: "greater_than", ...y(Q), value: X, inclusive: true }); +} +function f4(X, Q) { + return new aW({ check: "multiple_of", ...y(Q), value: X }); +} +function u4(X, Q) { + return new eW({ check: "max_length", ...y(Q), maximum: X }); +} +function k6(X, Q) { + return new XJ({ check: "min_length", ...y(Q), minimum: X }); +} +function l4(X, Q) { + return new QJ({ check: "length_equals", ...y(Q), length: X }); +} +function Y$(X, Q) { + return new $J({ check: "string_format", format: "regex", ...y(Q), pattern: X }); +} +function W$(X) { + return new YJ({ check: "string_format", format: "lowercase", ...y(X) }); +} +function J$(X) { + return new WJ({ check: "string_format", format: "uppercase", ...y(X) }); +} +function G$(X, Q) { + return new JJ({ check: "string_format", format: "includes", ...y(Q), includes: X }); +} +function H$(X, Q) { + return new GJ({ check: "string_format", format: "starts_with", ...y(Q), prefix: X }); +} +function B$(X, Q) { + return new HJ({ check: "string_format", format: "ends_with", ...y(Q), suffix: X }); +} +function $6(X) { + return new BJ({ check: "overwrite", tx: X }); +} +function z$(X) { + return $6((Q) => Q.normalize(X)); +} +function K$() { + return $6((X) => X.trim()); +} +function U$() { + return $6((X) => X.toLowerCase()); +} +function V$() { + return $6((X) => X.toUpperCase()); +} +function CJ(X, Q, $) { + return new X({ type: "array", element: Q, ...y($) }); +} +function L$(X, Q, $) { + var _a3; + let Y = y($); + return (_a3 = Y.abort) != null ? _a3 : Y.abort = true, new X({ type: "custom", check: "custom", fn: Q, ...Y }); +} +function q$(X, Q, $) { + return new X({ type: "custom", check: "custom", fn: Q, ...y($) }); +} +var PL = O("ZodMiniType", (X, Q) => { + if (!X._zod) throw Error("Uninitialized schema in ZodMiniType."); + X0.init(X, Q), X.def = Q, X.parse = ($, Y) => k8(X, $, Y, { callee: X.parse }), X.safeParse = ($, Y) => X6(X, $, Y), X.parseAsync = async ($, Y) => T8(X, $, Y, { callee: X.parseAsync }), X.safeParseAsync = async ($, Y) => Q6(X, $, Y), X.check = (...$) => { + var _a3; + return X.clone({ ...Q, checks: [...(_a3 = Q.checks) != null ? _a3 : [], ...$.map((Y) => typeof Y === "function" ? { _zod: { check: Y, def: { check: "custom" }, onattach: [] } } : Y)] }); + }, X.clone = ($, Y) => l0(X, $, Y), X.brand = () => X, X.register = ($, Y) => { + return $.add(X, Y), X; + }; +}); +var SL = O("ZodMiniObject", (X, Q) => { + T4.init(X, Q), PL.init(X, Q), i.defineLazy(X, "shape", () => Q.shape); +}); +var SX = {}; +U7(SX, { time: () => w$, duration: () => M$, datetime: () => D$, date: () => A$, ZodISOTime: () => yJ, ZodISODuration: () => gJ, ZodISODateTime: () => _J, ZodISODate: () => xJ }); +var _J = O("ZodISODateTime", (X, Q) => { + wJ.init(X, Q), H0.init(X, Q); +}); +function D$(X) { + return bJ(_J, X); +} +var xJ = O("ZodISODate", (X, Q) => { + MJ.init(X, Q), H0.init(X, Q); +}); +function A$(X) { + return PJ(xJ, X); +} +var yJ = O("ZodISOTime", (X, Q) => { + jJ.init(X, Q), H0.init(X, Q); +}); +function w$(X) { + return SJ(yJ, X); +} +var gJ = O("ZodISODuration", (X, Q) => { + RJ.init(X, Q), H0.init(X, Q); +}); +function M$(X) { + return ZJ(gJ, X); +} +var hJ = (X, Q) => { + Z4.init(X, Q), X.name = "ZodError", Object.defineProperties(X, { format: { value: ($) => Z8(X, $) }, flatten: { value: ($) => S8(X, $) }, addIssue: { value: ($) => X.issues.push($) }, addIssues: { value: ($) => X.issues.push(...$) }, isEmpty: { get() { + return X.issues.length === 0; + } } }); +}; +var oS = O("ZodError", hJ); +var ZX = O("ZodError", hJ, { Parent: Error }); +var fJ = C8(ZX); +var uJ = v8(ZX); +var lJ = _8(ZX); +var mJ = x8(ZX); +var z0 = O("ZodType", (X, Q) => { + return X0.init(X, Q), X.def = Q, Object.defineProperty(X, "_def", { value: Q }), X.check = (...$) => { + var _a3; + return X.clone({ ...Q, checks: [...(_a3 = Q.checks) != null ? _a3 : [], ...$.map((Y) => typeof Y === "function" ? { _zod: { check: Y, def: { check: "custom" }, onattach: [] } } : Y)] }); + }, X.clone = ($, Y) => l0(X, $, Y), X.brand = () => X, X.register = ($, Y) => { + return $.add(X, Y), X; + }, X.parse = ($, Y) => fJ(X, $, Y, { callee: X.parse }), X.safeParse = ($, Y) => lJ(X, $, Y), X.parseAsync = async ($, Y) => uJ(X, $, Y, { callee: X.parseAsync }), X.safeParseAsync = async ($, Y) => mJ(X, $, Y), X.spa = X.safeParseAsync, X.refine = ($, Y) => X.check(Iq($, Y)), X.superRefine = ($) => X.check(bq($)), X.overwrite = ($) => X.check($6($)), X.optional = () => v(X), X.nullable = () => dJ(X), X.nullish = () => v(dJ(X)), X.nonoptional = ($) => Dq(X, $), X.array = () => r(X), X.or = ($) => J0([X, $]), X.and = ($) => i4(X, $), X.transform = ($) => R$(X, tJ($)), X.default = ($) => Fq(X, $), X.prefault = ($) => Oq(X, $), X.catch = ($) => wq(X, $), X.pipe = ($) => R$(X, $), X.readonly = () => Rq(X), X.describe = ($) => { + let Y = X.clone(); + return y1.add(Y, { description: $ }), Y; + }, Object.defineProperty(X, "description", { get() { + var _a3; + return (_a3 = y1.get(X)) == null ? void 0 : _a3.description; + }, configurable: true }), X.meta = (...$) => { + if ($.length === 0) return y1.get(X); + let Y = X.clone(); + return y1.add(Y, $[0]), Y; + }, X.isOptional = () => X.safeParse(void 0).success, X.isNullable = () => X.safeParse(null).success, X; +}); +var iJ = O("_ZodString", (X, Q) => { + var _a3, _b, _c; + IX.init(X, Q), z0.init(X, Q); + let $ = X._zod.bag; + X.format = (_a3 = $.format) != null ? _a3 : null, X.minLength = (_b = $.minimum) != null ? _b : null, X.maxLength = (_c = $.maximum) != null ? _c : null, X.regex = (...Y) => X.check(Y$(...Y)), X.includes = (...Y) => X.check(G$(...Y)), X.startsWith = (...Y) => X.check(H$(...Y)), X.endsWith = (...Y) => X.check(B$(...Y)), X.min = (...Y) => X.check(k6(...Y)), X.max = (...Y) => X.check(u4(...Y)), X.length = (...Y) => X.check(l4(...Y)), X.nonempty = (...Y) => X.check(k6(1, ...Y)), X.lowercase = (Y) => X.check(W$(Y)), X.uppercase = (Y) => X.check(J$(Y)), X.trim = () => X.check(K$()), X.normalize = (...Y) => X.check(z$(...Y)), X.toLowerCase = () => X.check(U$()), X.toUpperCase = () => X.check(V$()); +}); +var gL = O("ZodString", (X, Q) => { + IX.init(X, Q), iJ.init(X, Q), X.email = ($) => X.check(CQ(hL, $)), X.url = ($) => X.check(xQ(fL, $)), X.jwt = ($) => X.check(tQ(Xq, $)), X.emoji = ($) => X.check(yQ(uL, $)), X.guid = ($) => X.check(y4(cJ, $)), X.uuid = ($) => X.check(kQ(d4, $)), X.uuidv4 = ($) => X.check(vQ(d4, $)), X.uuidv6 = ($) => X.check(TQ(d4, $)), X.uuidv7 = ($) => X.check(_Q(d4, $)), X.nanoid = ($) => X.check(gQ(lL, $)), X.guid = ($) => X.check(y4(cJ, $)), X.cuid = ($) => X.check(hQ(mL, $)), X.cuid2 = ($) => X.check(fQ(cL, $)), X.ulid = ($) => X.check(uQ(pL, $)), X.base64 = ($) => X.check(nQ(aL, $)), X.base64url = ($) => X.check(rQ(sL, $)), X.xid = ($) => X.check(lQ(dL, $)), X.ksuid = ($) => X.check(mQ(iL, $)), X.ipv4 = ($) => X.check(cQ(nL, $)), X.ipv6 = ($) => X.check(pQ(rL, $)), X.cidrv4 = ($) => X.check(dQ(oL, $)), X.cidrv6 = ($) => X.check(iQ(tL, $)), X.e164 = ($) => X.check(oQ(eL, $)), X.datetime = ($) => X.check(D$($)), X.date = ($) => X.check(A$($)), X.time = ($) => X.check(w$($)), X.duration = ($) => X.check(M$($)); +}); +function D(X) { + return ZQ(gL, X); +} +var H0 = O("ZodStringFormat", (X, Q) => { + W0.init(X, Q), iJ.init(X, Q); +}); +var hL = O("ZodEmail", (X, Q) => { + p8.init(X, Q), H0.init(X, Q); +}); +var cJ = O("ZodGUID", (X, Q) => { + m8.init(X, Q), H0.init(X, Q); +}); +var d4 = O("ZodUUID", (X, Q) => { + c8.init(X, Q), H0.init(X, Q); +}); +var fL = O("ZodURL", (X, Q) => { + d8.init(X, Q), H0.init(X, Q); +}); +var uL = O("ZodEmoji", (X, Q) => { + i8.init(X, Q), H0.init(X, Q); +}); +var lL = O("ZodNanoID", (X, Q) => { + n8.init(X, Q), H0.init(X, Q); +}); +var mL = O("ZodCUID", (X, Q) => { + r8.init(X, Q), H0.init(X, Q); +}); +var cL = O("ZodCUID2", (X, Q) => { + o8.init(X, Q), H0.init(X, Q); +}); +var pL = O("ZodULID", (X, Q) => { + t8.init(X, Q), H0.init(X, Q); +}); +var dL = O("ZodXID", (X, Q) => { + a8.init(X, Q), H0.init(X, Q); +}); +var iL = O("ZodKSUID", (X, Q) => { + s8.init(X, Q), H0.init(X, Q); +}); +var nL = O("ZodIPv4", (X, Q) => { + e8.init(X, Q), H0.init(X, Q); +}); +var rL = O("ZodIPv6", (X, Q) => { + XQ.init(X, Q), H0.init(X, Q); +}); +var oL = O("ZodCIDRv4", (X, Q) => { + QQ.init(X, Q), H0.init(X, Q); +}); +var tL = O("ZodCIDRv6", (X, Q) => { + $Q.init(X, Q), H0.init(X, Q); +}); +var aL = O("ZodBase64", (X, Q) => { + YQ.init(X, Q), H0.init(X, Q); +}); +var sL = O("ZodBase64URL", (X, Q) => { + WQ.init(X, Q), H0.init(X, Q); +}); +var eL = O("ZodE164", (X, Q) => { + JQ.init(X, Q), H0.init(X, Q); +}); +var Xq = O("ZodJWT", (X, Q) => { + GQ.init(X, Q), H0.init(X, Q); +}); +var nJ = O("ZodNumber", (X, Q) => { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i; + v4.init(X, Q), z0.init(X, Q), X.gt = (Y, W) => X.check(h4(Y, W)), X.gte = (Y, W) => X.check(PX(Y, W)), X.min = (Y, W) => X.check(PX(Y, W)), X.lt = (Y, W) => X.check(g4(Y, W)), X.lte = (Y, W) => X.check(bX(Y, W)), X.max = (Y, W) => X.check(bX(Y, W)), X.int = (Y) => X.check(pJ(Y)), X.safe = (Y) => X.check(pJ(Y)), X.positive = (Y) => X.check(h4(0, Y)), X.nonnegative = (Y) => X.check(PX(0, Y)), X.negative = (Y) => X.check(g4(0, Y)), X.nonpositive = (Y) => X.check(bX(0, Y)), X.multipleOf = (Y, W) => X.check(f4(Y, W)), X.step = (Y, W) => X.check(f4(Y, W)), X.finite = () => X; + let $ = X._zod.bag; + X.minValue = (_c = Math.max((_a3 = $.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY, (_b = $.exclusiveMinimum) != null ? _b : Number.NEGATIVE_INFINITY)) != null ? _c : null, X.maxValue = (_f = Math.min((_d = $.maximum) != null ? _d : Number.POSITIVE_INFINITY, (_e = $.exclusiveMaximum) != null ? _e : Number.POSITIVE_INFINITY)) != null ? _f : null, X.isInt = ((_g = $.format) != null ? _g : "").includes("int") || Number.isSafeInteger((_h = $.multipleOf) != null ? _h : 0.5), X.isFinite = true, X.format = (_i = $.format) != null ? _i : null; +}); +function Q0(X) { + return aQ(nJ, X); +} +var Qq = O("ZodNumberFormat", (X, Q) => { + HQ.init(X, Q), nJ.init(X, Q); +}); +function pJ(X) { + return sQ(Qq, X); +} +var $q = O("ZodBoolean", (X, Q) => { + BQ.init(X, Q), z0.init(X, Q); +}); +function M0(X) { + return eQ($q, X); +} +var Yq = O("ZodNull", (X, Q) => { + zQ.init(X, Q), z0.init(X, Q); +}); +function E$(X) { + return X$(Yq, X); +} +var Wq = O("ZodUnknown", (X, Q) => { + KQ.init(X, Q), z0.init(X, Q); +}); +function N0() { + return Q$(Wq); +} +var Jq = O("ZodNever", (X, Q) => { + UQ.init(X, Q), z0.init(X, Q); +}); +function Gq(X) { + return $$(Jq, X); +} +var Hq = O("ZodArray", (X, Q) => { + VQ.init(X, Q), z0.init(X, Q), X.element = Q.element, X.min = ($, Y) => X.check(k6($, Y)), X.nonempty = ($) => X.check(k6(1, $)), X.max = ($, Y) => X.check(u4($, Y)), X.length = ($, Y) => X.check(l4($, Y)), X.unwrap = () => X.element; +}); +function r(X, Q) { + return CJ(Hq, X, Q); +} +var rJ = O("ZodObject", (X, Q) => { + T4.init(X, Q), z0.init(X, Q), i.defineLazy(X, "shape", () => Q.shape), X.keyof = () => j0(Object.keys(X._zod.def.shape)), X.catchall = ($) => X.clone({ ...X._zod.def, catchall: $ }), X.passthrough = () => X.clone({ ...X._zod.def, catchall: N0() }), X.loose = () => X.clone({ ...X._zod.def, catchall: N0() }), X.strict = () => X.clone({ ...X._zod.def, catchall: Gq() }), X.strip = () => X.clone({ ...X._zod.def, catchall: void 0 }), X.extend = ($) => { + return i.extend(X, $); + }, X.merge = ($) => i.merge(X, $), X.pick = ($) => i.pick(X, $), X.omit = ($) => i.omit(X, $), X.partial = (...$) => i.partial(aJ, X, $[0]), X.required = (...$) => i.required(sJ, X, $[0]); +}); +function I(X, Q) { + let $ = { type: "object", get shape() { + return i.assignProp(this, "shape", { ...X }), this.shape; + }, ...i.normalizeParams(Q) }; + return new rJ($); +} +function c0(X, Q) { + return new rJ({ type: "object", get shape() { + return i.assignProp(this, "shape", { ...X }), this.shape; + }, catchall: N0(), ...i.normalizeParams(Q) }); +} +var oJ = O("ZodUnion", (X, Q) => { + _4.init(X, Q), z0.init(X, Q), X.options = Q.options; +}); +function J0(X, Q) { + return new oJ({ type: "union", options: X, ...i.normalizeParams(Q) }); +} +var Bq = O("ZodDiscriminatedUnion", (X, Q) => { + oJ.init(X, Q), LQ.init(X, Q); +}); +function I$(X, Q, $) { + return new Bq({ type: "union", options: Q, discriminator: X, ...i.normalizeParams($) }); +} +var zq = O("ZodIntersection", (X, Q) => { + qQ.init(X, Q), z0.init(X, Q); +}); +function i4(X, Q) { + return new zq({ type: "intersection", left: X, right: Q }); +} +var Kq = O("ZodRecord", (X, Q) => { + FQ.init(X, Q), z0.init(X, Q), X.keyType = Q.keyType, X.valueType = Q.valueType; +}); +function O0(X, Q, $) { + return new Kq({ type: "record", keyType: X, valueType: Q, ...i.normalizeParams($) }); +} +var j$ = O("ZodEnum", (X, Q) => { + NQ.init(X, Q), z0.init(X, Q), X.enum = Q.entries, X.options = Object.values(Q.entries); + let $ = new Set(Object.keys(Q.entries)); + X.extract = (Y, W) => { + let J = {}; + for (let G of Y) if ($.has(G)) J[G] = Q.entries[G]; + else throw Error(`Key ${G} not found in enum`); + return new j$({ ...Q, checks: [], ...i.normalizeParams(W), entries: J }); + }, X.exclude = (Y, W) => { + let J = { ...Q.entries }; + for (let G of Y) if ($.has(G)) delete J[G]; + else throw Error(`Key ${G} not found in enum`); + return new j$({ ...Q, checks: [], ...i.normalizeParams(W), entries: J }); + }; +}); +function j0(X, Q) { + let $ = Array.isArray(X) ? Object.fromEntries(X.map((Y) => [Y, Y])) : X; + return new j$({ type: "enum", entries: $, ...i.normalizeParams(Q) }); +} +var Uq = O("ZodLiteral", (X, Q) => { + OQ.init(X, Q), z0.init(X, Q), X.values = new Set(Q.values), Object.defineProperty(X, "value", { get() { + if (Q.values.length > 1) throw Error("This schema contains multiple valid literal values. Use `.values` instead."); + return Q.values[0]; + } }); +}); +function T(X, Q) { + return new Uq({ type: "literal", values: Array.isArray(X) ? X : [X], ...i.normalizeParams(Q) }); +} +var Vq = O("ZodTransform", (X, Q) => { + DQ.init(X, Q), z0.init(X, Q), X._zod.parse = ($, Y) => { + $.addIssue = (J) => { + var _a3, _b, _c, _d; + if (typeof J === "string") $.issues.push(i.issue(J, $.value, Q)); + else { + let G = J; + if (G.fatal) G.continue = false; + (_a3 = G.code) != null ? _a3 : G.code = "custom", (_b = G.input) != null ? _b : G.input = $.value, (_c = G.inst) != null ? _c : G.inst = X, (_d = G.continue) != null ? _d : G.continue = true, $.issues.push(i.issue(G)); + } + }; + let W = Q.transform($.value, $); + if (W instanceof Promise) return W.then((J) => { + return $.value = J, $; + }); + return $.value = W, $; + }; +}); +function tJ(X) { + return new Vq({ type: "transform", transform: X }); +} +var aJ = O("ZodOptional", (X, Q) => { + AQ.init(X, Q), z0.init(X, Q), X.unwrap = () => X._zod.def.innerType; +}); +function v(X) { + return new aJ({ type: "optional", innerType: X }); +} +var Lq = O("ZodNullable", (X, Q) => { + wQ.init(X, Q), z0.init(X, Q), X.unwrap = () => X._zod.def.innerType; +}); +function dJ(X) { + return new Lq({ type: "nullable", innerType: X }); +} +var qq = O("ZodDefault", (X, Q) => { + MQ.init(X, Q), z0.init(X, Q), X.unwrap = () => X._zod.def.innerType, X.removeDefault = X.unwrap; +}); +function Fq(X, Q) { + return new qq({ type: "default", innerType: X, get defaultValue() { + return typeof Q === "function" ? Q() : Q; + } }); +} +var Nq = O("ZodPrefault", (X, Q) => { + jQ.init(X, Q), z0.init(X, Q), X.unwrap = () => X._zod.def.innerType; +}); +function Oq(X, Q) { + return new Nq({ type: "prefault", innerType: X, get defaultValue() { + return typeof Q === "function" ? Q() : Q; + } }); +} +var sJ = O("ZodNonOptional", (X, Q) => { + RQ.init(X, Q), z0.init(X, Q), X.unwrap = () => X._zod.def.innerType; +}); +function Dq(X, Q) { + return new sJ({ type: "nonoptional", innerType: X, ...i.normalizeParams(Q) }); +} +var Aq = O("ZodCatch", (X, Q) => { + EQ.init(X, Q), z0.init(X, Q), X.unwrap = () => X._zod.def.innerType, X.removeCatch = X.unwrap; +}); +function wq(X, Q) { + return new Aq({ type: "catch", innerType: X, catchValue: typeof Q === "function" ? Q : () => Q }); +} +var Mq = O("ZodPipe", (X, Q) => { + IQ.init(X, Q), z0.init(X, Q), X.in = Q.in, X.out = Q.out; +}); +function R$(X, Q) { + return new Mq({ type: "pipe", in: X, out: Q }); +} +var jq = O("ZodReadonly", (X, Q) => { + bQ.init(X, Q), z0.init(X, Q); +}); +function Rq(X) { + return new jq({ type: "readonly", innerType: X }); +} +var eJ = O("ZodCustom", (X, Q) => { + PQ.init(X, Q), z0.init(X, Q); +}); +function Eq(X, Q) { + let $ = new w0({ check: "custom", ...i.normalizeParams(Q) }); + return $._zod.check = X, $; +} +function X5(X, Q) { + return L$(eJ, X != null ? X : (() => true), Q); +} +function Iq(X, Q = {}) { + return q$(eJ, X, Q); +} +function bq(X, Q) { + let $ = Eq((Y) => { + return Y.addIssue = (W) => { + var _a3, _b, _c, _d; + if (typeof W === "string") Y.issues.push(i.issue(W, Y.value, $._zod.def)); + else { + let J = W; + if (J.fatal) J.continue = false; + (_a3 = J.code) != null ? _a3 : J.code = "custom", (_b = J.input) != null ? _b : J.input = Y.value, (_c = J.inst) != null ? _c : J.inst = $, (_d = J.continue) != null ? _d : J.continue = !$._zod.def.abort, Y.issues.push(i.issue(J)); + } + }, X(Y.value, Y); + }, Q); + return $; +} +function b$(X, Q) { + return R$(tJ(X), Q); +} +u0(SQ()); +var K1 = "io.modelcontextprotocol/related-task"; +var r4 = "2.0"; +var z1 = X5((X) => X !== null && (typeof X === "object" || typeof X === "function")); +var $5 = J0([D(), Q0().int()]); +var Y5 = D(); +var Pq = c0({ ttl: J0([Q0(), E$()]).optional(), pollInterval: Q0().optional() }); +var S$ = c0({ taskId: D() }); +var Sq = c0({ progressToken: $5.optional(), [K1]: S$.optional() }); +var _0 = c0({ task: Pq.optional(), _meta: Sq.optional() }); +var R0 = I({ method: D(), params: _0.optional() }); +var W6 = c0({ _meta: I({ [K1]: v(S$) }).passthrough().optional() }); +var p0 = I({ method: D(), params: W6.optional() }); +var b0 = c0({ _meta: c0({ [K1]: S$.optional() }).optional() }); +var o4 = J0([D(), Q0().int()]); +var W5 = I({ jsonrpc: T(r4), id: o4, ...R0.shape }).strict(); +var J5 = I({ jsonrpc: T(r4), ...p0.shape }).strict(); +var H5 = I({ jsonrpc: T(r4), id: o4, result: b0 }).strict(); +var x; +(function(X) { + X[X.ConnectionClosed = -32e3] = "ConnectionClosed", X[X.RequestTimeout = -32001] = "RequestTimeout", X[X.ParseError = -32700] = "ParseError", X[X.InvalidRequest = -32600] = "InvalidRequest", X[X.MethodNotFound = -32601] = "MethodNotFound", X[X.InvalidParams = -32602] = "InvalidParams", X[X.InternalError = -32603] = "InternalError", X[X.UrlElicitationRequired = -32042] = "UrlElicitationRequired"; +})(x || (x = {})); +var B5 = I({ jsonrpc: T(r4), id: o4, error: I({ code: Q0().int(), message: D(), data: v(N0()) }) }).strict(); +var zZ = J0([W5, J5, H5, B5]); +var t4 = b0.strict(); +var Zq = W6.extend({ requestId: o4, reason: D().optional() }); +var a4 = p0.extend({ method: T("notifications/cancelled"), params: Zq }); +var Cq = I({ src: D(), mimeType: D().optional(), sizes: r(D()).optional() }); +var kX = I({ icons: r(Cq).optional() }); +var _6 = I({ name: D(), title: D().optional() }); +var K5 = _6.extend({ ..._6.shape, ...kX.shape, version: D(), websiteUrl: D().optional() }); +var kq = i4(I({ applyDefaults: M0().optional() }), O0(D(), N0())); +var vq = b$((X) => { + if (X && typeof X === "object" && !Array.isArray(X)) { + if (Object.keys(X).length === 0) return { form: {} }; + } + return X; +}, i4(I({ form: kq.optional(), url: z1.optional() }), O0(D(), N0()).optional())); +var Tq = I({ list: v(I({}).passthrough()), cancel: v(I({}).passthrough()), requests: v(I({ sampling: v(I({ createMessage: v(I({}).passthrough()) }).passthrough()), elicitation: v(I({ create: v(I({}).passthrough()) }).passthrough()) }).passthrough()) }).passthrough(); +var _q = I({ list: v(I({}).passthrough()), cancel: v(I({}).passthrough()), requests: v(I({ tools: v(I({ call: v(I({}).passthrough()) }).passthrough()) }).passthrough()) }).passthrough(); +var xq = I({ experimental: O0(D(), z1).optional(), sampling: I({ context: z1.optional(), tools: z1.optional() }).optional(), elicitation: vq.optional(), roots: I({ listChanged: M0().optional() }).optional(), tasks: v(Tq) }); +var yq = _0.extend({ protocolVersion: D(), capabilities: xq, clientInfo: K5 }); +var C$ = R0.extend({ method: T("initialize"), params: yq }); +var gq = I({ experimental: O0(D(), z1).optional(), logging: z1.optional(), completions: z1.optional(), prompts: v(I({ listChanged: v(M0()) })), resources: I({ subscribe: M0().optional(), listChanged: M0().optional() }).optional(), tools: I({ listChanged: M0().optional() }).optional(), tasks: v(_q) }).passthrough(); +var hq = b0.extend({ protocolVersion: D(), capabilities: gq, serverInfo: K5, instructions: D().optional() }); +var k$ = p0.extend({ method: T("notifications/initialized") }); +var s4 = R0.extend({ method: T("ping") }); +var fq = I({ progress: Q0(), total: v(Q0()), message: v(D()) }); +var uq = I({ ...W6.shape, ...fq.shape, progressToken: $5 }); +var e4 = p0.extend({ method: T("notifications/progress"), params: uq }); +var lq = _0.extend({ cursor: Y5.optional() }); +var vX = R0.extend({ params: lq.optional() }); +var TX = b0.extend({ nextCursor: v(Y5) }); +var _X = I({ taskId: D(), status: j0(["working", "input_required", "completed", "failed", "cancelled"]), ttl: J0([Q0(), E$()]), createdAt: D(), lastUpdatedAt: D(), pollInterval: v(Q0()), statusMessage: v(D()) }); +var x6 = b0.extend({ task: _X }); +var mq = W6.merge(_X); +var xX = p0.extend({ method: T("notifications/tasks/status"), params: mq }); +var X9 = R0.extend({ method: T("tasks/get"), params: _0.extend({ taskId: D() }) }); +var Q9 = b0.merge(_X); +var $9 = R0.extend({ method: T("tasks/result"), params: _0.extend({ taskId: D() }) }); +var Y9 = vX.extend({ method: T("tasks/list") }); +var W9 = TX.extend({ tasks: r(_X) }); +var U5 = R0.extend({ method: T("tasks/cancel"), params: _0.extend({ taskId: D() }) }); +var V5 = b0.merge(_X); +var L5 = I({ uri: D(), mimeType: v(D()), _meta: O0(D(), N0()).optional() }); +var q5 = L5.extend({ text: D() }); +var v$ = D().refine((X) => { + try { + return atob(X), true; + } catch (Q) { + return false; + } +}, { message: "Invalid Base64 string" }); +var F5 = L5.extend({ blob: v$ }); +var y6 = I({ audience: r(j0(["user", "assistant"])).optional(), priority: Q0().min(0).max(1).optional(), lastModified: SX.datetime({ offset: true }).optional() }); +var N5 = I({ ..._6.shape, ...kX.shape, uri: D(), description: v(D()), mimeType: v(D()), annotations: y6.optional(), _meta: v(c0({})) }); +var cq = I({ ..._6.shape, ...kX.shape, uriTemplate: D(), description: v(D()), mimeType: v(D()), annotations: y6.optional(), _meta: v(c0({})) }); +var J9 = vX.extend({ method: T("resources/list") }); +var pq = TX.extend({ resources: r(N5) }); +var G9 = vX.extend({ method: T("resources/templates/list") }); +var dq = TX.extend({ resourceTemplates: r(cq) }); +var T$ = _0.extend({ uri: D() }); +var iq = T$; +var H9 = R0.extend({ method: T("resources/read"), params: iq }); +var nq = b0.extend({ contents: r(J0([q5, F5])) }); +var rq = p0.extend({ method: T("notifications/resources/list_changed") }); +var oq = T$; +var tq = R0.extend({ method: T("resources/subscribe"), params: oq }); +var aq = T$; +var sq = R0.extend({ method: T("resources/unsubscribe"), params: aq }); +var eq = W6.extend({ uri: D() }); +var XF = p0.extend({ method: T("notifications/resources/updated"), params: eq }); +var QF = I({ name: D(), description: v(D()), required: v(M0()) }); +var $F = I({ ..._6.shape, ...kX.shape, description: v(D()), arguments: v(r(QF)), _meta: v(c0({})) }); +var B9 = vX.extend({ method: T("prompts/list") }); +var YF = TX.extend({ prompts: r($F) }); +var WF = _0.extend({ name: D(), arguments: O0(D(), D()).optional() }); +var z9 = R0.extend({ method: T("prompts/get"), params: WF }); +var _$ = I({ type: T("text"), text: D(), annotations: y6.optional(), _meta: O0(D(), N0()).optional() }); +var x$ = I({ type: T("image"), data: v$, mimeType: D(), annotations: y6.optional(), _meta: O0(D(), N0()).optional() }); +var y$ = I({ type: T("audio"), data: v$, mimeType: D(), annotations: y6.optional(), _meta: O0(D(), N0()).optional() }); +var JF = I({ type: T("tool_use"), name: D(), id: D(), input: I({}).passthrough(), _meta: v(I({}).passthrough()) }).passthrough(); +var GF = I({ type: T("resource"), resource: J0([q5, F5]), annotations: y6.optional(), _meta: O0(D(), N0()).optional() }); +var HF = N5.extend({ type: T("resource_link") }); +var g$ = J0([_$, x$, y$, HF, GF]); +var BF = I({ role: j0(["user", "assistant"]), content: g$ }); +var zF = b0.extend({ description: v(D()), messages: r(BF) }); +var KF = p0.extend({ method: T("notifications/prompts/list_changed") }); +var UF = I({ title: D().optional(), readOnlyHint: M0().optional(), destructiveHint: M0().optional(), idempotentHint: M0().optional(), openWorldHint: M0().optional() }); +var VF = I({ taskSupport: j0(["required", "optional", "forbidden"]).optional() }); +var O5 = I({ ..._6.shape, ...kX.shape, description: D().optional(), inputSchema: I({ type: T("object"), properties: O0(D(), z1).optional(), required: r(D()).optional() }).catchall(N0()), outputSchema: I({ type: T("object"), properties: O0(D(), z1).optional(), required: r(D()).optional() }).catchall(N0()).optional(), annotations: v(UF), execution: v(VF), _meta: O0(D(), N0()).optional() }); +var K9 = vX.extend({ method: T("tools/list") }); +var LF = TX.extend({ tools: r(O5) }); +var U9 = b0.extend({ content: r(g$).default([]), structuredContent: O0(D(), N0()).optional(), isError: v(M0()) }); +var KZ = U9.or(b0.extend({ toolResult: N0() })); +var qF = _0.extend({ name: D(), arguments: v(O0(D(), N0())) }); +var g6 = R0.extend({ method: T("tools/call"), params: qF }); +var FF = p0.extend({ method: T("notifications/tools/list_changed") }); +var yX = j0(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); +var NF = _0.extend({ level: yX }); +var h$ = R0.extend({ method: T("logging/setLevel"), params: NF }); +var OF = W6.extend({ level: yX, logger: D().optional(), data: N0() }); +var DF = p0.extend({ method: T("notifications/message"), params: OF }); +var AF = I({ name: D().optional() }); +var wF = I({ hints: v(r(AF)), costPriority: v(Q0().min(0).max(1)), speedPriority: v(Q0().min(0).max(1)), intelligencePriority: v(Q0().min(0).max(1)) }); +var MF = I({ mode: v(j0(["auto", "required", "none"])) }); +var jF = I({ type: T("tool_result"), toolUseId: D().describe("The unique identifier for the corresponding tool call."), content: r(g$).default([]), structuredContent: I({}).passthrough().optional(), isError: v(M0()), _meta: v(I({}).passthrough()) }).passthrough(); +var RF = I$("type", [_$, x$, y$]); +var n4 = I$("type", [_$, x$, y$, JF, jF]); +var EF = I({ role: j0(["user", "assistant"]), content: J0([n4, r(n4)]), _meta: v(I({}).passthrough()) }).passthrough(); +var IF = _0.extend({ messages: r(EF), modelPreferences: wF.optional(), systemPrompt: D().optional(), includeContext: j0(["none", "thisServer", "allServers"]).optional(), temperature: Q0().optional(), maxTokens: Q0().int(), stopSequences: r(D()).optional(), metadata: z1.optional(), tools: v(r(O5)), toolChoice: v(MF) }); +var bF = R0.extend({ method: T("sampling/createMessage"), params: IF }); +var f$ = b0.extend({ model: D(), stopReason: v(j0(["endTurn", "stopSequence", "maxTokens"]).or(D())), role: j0(["user", "assistant"]), content: RF }); +var u$ = b0.extend({ model: D(), stopReason: v(j0(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(D())), role: j0(["user", "assistant"]), content: J0([n4, r(n4)]) }); +var PF = I({ type: T("boolean"), title: D().optional(), description: D().optional(), default: M0().optional() }); +var SF = I({ type: T("string"), title: D().optional(), description: D().optional(), minLength: Q0().optional(), maxLength: Q0().optional(), format: j0(["email", "uri", "date", "date-time"]).optional(), default: D().optional() }); +var ZF = I({ type: j0(["number", "integer"]), title: D().optional(), description: D().optional(), minimum: Q0().optional(), maximum: Q0().optional(), default: Q0().optional() }); +var CF = I({ type: T("string"), title: D().optional(), description: D().optional(), enum: r(D()), default: D().optional() }); +var kF = I({ type: T("string"), title: D().optional(), description: D().optional(), oneOf: r(I({ const: D(), title: D() })), default: D().optional() }); +var vF = I({ type: T("string"), title: D().optional(), description: D().optional(), enum: r(D()), enumNames: r(D()).optional(), default: D().optional() }); +var TF = J0([CF, kF]); +var _F = I({ type: T("array"), title: D().optional(), description: D().optional(), minItems: Q0().optional(), maxItems: Q0().optional(), items: I({ type: T("string"), enum: r(D()) }), default: r(D()).optional() }); +var xF = I({ type: T("array"), title: D().optional(), description: D().optional(), minItems: Q0().optional(), maxItems: Q0().optional(), items: I({ anyOf: r(I({ const: D(), title: D() })) }), default: r(D()).optional() }); +var yF = J0([_F, xF]); +var gF = J0([vF, TF, yF]); +var hF = J0([gF, PF, SF, ZF]); +var fF = _0.extend({ mode: T("form").optional(), message: D(), requestedSchema: I({ type: T("object"), properties: O0(D(), hF), required: r(D()).optional() }) }); +var uF = _0.extend({ mode: T("url"), message: D(), elicitationId: D(), url: D().url() }); +var lF = J0([fF, uF]); +var mF = R0.extend({ method: T("elicitation/create"), params: lF }); +var cF = W6.extend({ elicitationId: D() }); +var pF = p0.extend({ method: T("notifications/elicitation/complete"), params: cF }); +var V9 = b0.extend({ action: j0(["accept", "decline", "cancel"]), content: b$((X) => X === null ? void 0 : X, O0(D(), J0([D(), Q0(), M0(), r(D())])).optional()) }); +var dF = I({ type: T("ref/resource"), uri: D() }); +var iF = I({ type: T("ref/prompt"), name: D() }); +var nF = _0.extend({ ref: J0([iF, dF]), argument: I({ name: D(), value: D() }), context: I({ arguments: O0(D(), D()).optional() }).optional() }); +var L9 = R0.extend({ method: T("completion/complete"), params: nF }); +var rF = b0.extend({ completion: c0({ values: r(D()).max(100), total: v(Q0().int()), hasMore: v(M0()) }) }); +var oF = I({ uri: D().startsWith("file://"), name: D().optional(), _meta: O0(D(), N0()).optional() }); +var tF = R0.extend({ method: T("roots/list") }); +var l$ = b0.extend({ roots: r(oF) }); +var aF = p0.extend({ method: T("notifications/roots/list_changed") }); +var UZ = J0([s4, C$, L9, h$, z9, B9, J9, G9, H9, tq, sq, g6, K9, X9, $9, Y9]); +var VZ = J0([a4, e4, k$, aF, xX]); +var LZ = J0([t4, f$, u$, V9, l$, Q9, W9, x6]); +var qZ = J0([s4, bF, mF, tF, X9, $9, Y9]); +var FZ = J0([a4, e4, DF, XF, rq, FF, KF, xX, pF]); +var NZ = J0([t4, hq, rF, zF, YF, pq, dq, nq, U9, LF, Q9, W9, x6]); +var XN = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +var gz = K7(cY(), 1); +var hz = K7(yz(), 1); +var lz; +(function(X) { + X.Completable = "McpCompletable"; +})(lz || (lz = {})); +function u_({ prompt: X, options: Q }) { + let { systemPrompt: $, settingSources: Y, sandbox: W, ...J } = Q != null ? Q : {}, G, H; + if ($ === void 0) G = ""; + else if (typeof $ === "string") G = $; + else if ($.type === "preset") H = $.append; + let B = J.pathToClaudeCodeExecutable; + if (!B) { + let q6 = (0, import_url.fileURLToPath)(import_meta.url), F6 = (0, import_path2.join)(q6, ".."); + B = (0, import_path2.join)(F6, "cli.js"); + } + process.env.CLAUDE_AGENT_SDK_VERSION = "0.2.17"; + let { abortController: z2 = N6(), additionalDirectories: K = [], agent: V, agents: L, allowedTools: U = [], betas: F, canUseTool: q, continue: N, cwd: A, disallowedTools: M = [], tools: R, env: S, executable: C = j6() ? "bun" : "node", executableArgs: K0 = [], extraArgs: U0 = {}, fallbackModel: s, enableFileCheckpointing: D0, forkSession: q0, hooks: W1, includePartialMessages: P1, persistSession: U6, maxThinkingTokens: d, maxTurns: Q8, maxBudgetUsd: o6, mcpServers: V6, model: t6, outputFormat: a6, permissionMode: B4 = "default", allowDangerouslySkipPermissions: S0 = false, permissionPromptToolName: S1, plugins: s6, resume: oz, resumeSessionAt: tz, stderr: az, strictMcpConfig: sz } = J, G7 = (a6 == null ? void 0 : a6.type) === "json_schema" ? a6.schema : void 0, L6 = S; + if (!L6) L6 = { ...process.env }; + if (!L6.CLAUDE_CODE_ENTRYPOINT) L6.CLAUDE_CODE_ENTRYPOINT = "sdk-ts"; + if (D0) L6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING = "true"; + if (!B) throw Error("pathToClaudeCodeExecutable is required"); + let $8 = {}, H7 = /* @__PURE__ */ new Map(); + if (V6) for (let [q6, F6] of Object.entries(V6)) if (F6.type === "sdk" && "instance" in F6) H7.set(q6, F6.instance), $8[q6] = { type: "sdk", name: q6 }; + else $8[q6] = F6; + let ez = typeof X === "string", B7 = new XX({ abortController: z2, additionalDirectories: K, agent: V, betas: F, cwd: A, executable: C, executableArgs: K0, extraArgs: U0, pathToClaudeCodeExecutable: B, env: L6, forkSession: q0, stderr: az, maxThinkingTokens: d, maxTurns: Q8, maxBudgetUsd: o6, model: t6, fallbackModel: s, jsonSchema: G7, permissionMode: B4, allowDangerouslySkipPermissions: S0, permissionPromptToolName: S1, continueConversation: N, resume: oz, resumeSessionAt: tz, settingSources: Y != null ? Y : [], allowedTools: U, disallowedTools: M, tools: R, mcpServers: $8, strictMcpConfig: sz, canUseTool: !!q, hooks: !!W1, includePartialMessages: P1, persistSession: U6, plugins: s6, sandbox: W, spawnClaudeCodeProcess: J.spawnClaudeCodeProcess }), z7 = new $X(B7, ez, q, W1, z2, H7, G7, { systemPrompt: G, appendSystemPrompt: H, agents: L }); + if (typeof X === "string") B7.write(Z0({ type: "user", session_id: "", message: { role: "user", content: [{ type: "text", text: X }] }, parent_tool_use_id: null }) + ` +`); + else z7.streamInput(X); + return z7; +} + +// src/utils/context.ts +var CURRENT_NOTE_PREFIX_REGEX = /^\n[\s\S]*?<\/current_note>\n\n/; +var CURRENT_NOTE_SUFFIX_REGEX = /\n\n\n[\s\S]*?<\/current_note>$/; +var XML_CONTEXT_PATTERN = /\n\n<(?:current_note|editor_selection|editor_cursor|context_files)[\s>]/; +function formatCurrentNote(notePath) { + return ` +${notePath} +`; +} +function appendCurrentNote(prompt, notePath) { + return `${prompt} + +${formatCurrentNote(notePath)}`; +} +function stripCurrentNoteContext(prompt) { + const strippedPrefix = prompt.replace(CURRENT_NOTE_PREFIX_REGEX, ""); + if (strippedPrefix !== prompt) { + return strippedPrefix; + } + return prompt.replace(CURRENT_NOTE_SUFFIX_REGEX, ""); +} +function extractContentBeforeXmlContext(text) { + if (!text) return void 0; + const queryMatch = text.match(/\n?([\s\S]*?)\n?<\/query>/); + if (queryMatch) { + return queryMatch[1].trim(); + } + const xmlMatch = text.match(XML_CONTEXT_PATTERN); + if ((xmlMatch == null ? void 0 : xmlMatch.index) !== void 0) { + return text.substring(0, xmlMatch.index).trim(); + } + return void 0; +} +function extractUserQuery(prompt) { + if (!prompt) return ""; + const extracted = extractContentBeforeXmlContext(prompt); + if (extracted !== void 0) { + return extracted; + } + return prompt.replace(/[\s\S]*?<\/current_note>\s*/g, "").replace(/\s*/g, "").replace(/\s*/g, "").replace(/[\s\S]*?<\/context_files>\s*/g, "").trim(); +} +function formatContextFilesLine(files) { + return ` +${files.join(", ")} +`; +} +function appendContextFiles(prompt, files) { + return `${prompt} + +${formatContextFilesLine(files)}`; +} + +// src/utils/session.ts +var SESSION_ERROR_PATTERNS = [ + "session expired", + "session not found", + "invalid session", + "session invalid", + "process exited with code" +]; +var SESSION_ERROR_COMPOUND_PATTERNS = [ + { includes: ["session", "expired"] }, + { includes: ["resume", "failed"] }, + { includes: ["resume", "error"] } +]; +function isSessionExpiredError(error48) { + const msg = error48 instanceof Error ? error48.message.toLowerCase() : ""; + for (const pattern of SESSION_ERROR_PATTERNS) { + if (msg.includes(pattern)) { + return true; + } + } + for (const { includes } of SESSION_ERROR_COMPOUND_PATTERNS) { + if (includes.every((part) => msg.includes(part))) { + return true; + } + } + return false; +} +function formatToolInput(input, maxLength = 200) { + if (!input || Object.keys(input).length === 0) return ""; + try { + const parts = []; + for (const [key, value] of Object.entries(input)) { + if (value === void 0 || value === null) continue; + let valueStr; + if (typeof value === "string") { + valueStr = value.length > 100 ? `${value.slice(0, 100)}...` : value; + } else if (typeof value === "object") { + valueStr = "[object]"; + } else { + valueStr = String(value); + } + parts.push(`${key}=${valueStr}`); + } + const result = parts.join(", "); + return result.length > maxLength ? `${result.slice(0, maxLength)}...` : result; + } catch (e2) { + return "[input formatting error]"; + } +} +function formatToolCallForContext(toolCall, maxErrorLength = 500) { + var _a3; + const status = (_a3 = toolCall.status) != null ? _a3 : "completed"; + const isFailed = status === "error" || status === "blocked"; + const inputStr = formatToolInput(toolCall.input); + const inputPart = inputStr ? ` input: ${inputStr}` : ""; + if (!isFailed) { + return `[Tool ${toolCall.name}${inputPart} status=${status}]`; + } + const hasResult = typeof toolCall.result === "string" && toolCall.result.trim().length > 0; + if (!hasResult) { + return `[Tool ${toolCall.name}${inputPart} status=${status}]`; + } + const errorMsg = truncateToolResult(toolCall.result, maxErrorLength); + return `[Tool ${toolCall.name}${inputPart} status=${status}] error: ${errorMsg}`; +} +function truncateToolResult(result, maxLength = 500) { + if (result.length > maxLength) { + return `${result.slice(0, maxLength)}... (truncated)`; + } + return result; +} +function formatContextLine(message) { + if (!message.currentNote) { + return null; + } + return formatCurrentNote(message.currentNote); +} +function formatThinkingBlocks(message) { + if (!message.contentBlocks) return []; + const thinkingBlocks = message.contentBlocks.filter( + (block) => block.type === "thinking" + ); + if (thinkingBlocks.length === 0) return []; + const totalDuration = thinkingBlocks.reduce( + (sum, block) => { + var _a3; + return sum + ((_a3 = block.durationSeconds) != null ? _a3 : 0); + }, + 0 + ); + const durationPart = totalDuration > 0 ? `, ${totalDuration.toFixed(1)}s total` : ""; + return [`[Thinking: ${thinkingBlocks.length} block(s)${durationPart}]`]; +} +function buildContextFromHistory(messages) { + var _a3, _b, _c; + const parts = []; + for (const message of messages) { + if (message.role !== "user" && message.role !== "assistant") { + continue; + } + if (message.isInterrupt) { + continue; + } + if (message.role === "assistant") { + const hasContent = message.content && message.content.trim().length > 0; + const hasToolCalls = message.toolCalls && message.toolCalls.length > 0; + const hasThinking = (_a3 = message.contentBlocks) == null ? void 0 : _a3.some((b3) => b3.type === "thinking"); + if (!hasContent && !hasToolCalls && !hasThinking) { + continue; + } + } + const role = message.role === "user" ? "User" : "Assistant"; + const lines = []; + const content = (_b = message.content) == null ? void 0 : _b.trim(); + const contextLine = formatContextLine(message); + const userPayload = contextLine ? content ? `${contextLine} + +${content}` : contextLine : content; + lines.push(userPayload ? `${role}: ${userPayload}` : `${role}:`); + if (message.role === "assistant") { + const thinkingLines = formatThinkingBlocks(message); + if (thinkingLines.length > 0) { + lines.push(...thinkingLines); + } + } + if (message.role === "assistant" && ((_c = message.toolCalls) == null ? void 0 : _c.length)) { + const toolLines = message.toolCalls.map((tc) => formatToolCallForContext(tc)).filter(Boolean); + if (toolLines.length > 0) { + lines.push(...toolLines); + } + } + parts.push(lines.join("\n")); + } + return parts.join("\n\n"); +} +function getLastUserMessage(messages) { + for (let i2 = messages.length - 1; i2 >= 0; i2--) { + if (messages[i2].role === "user") { + return messages[i2]; + } + } + return void 0; +} +function buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory) { + var _a3, _b; + if (!historyContext) return prompt; + const lastUserMessage = getLastUserMessage(conversationHistory); + const lastUserQuery = (_b = lastUserMessage == null ? void 0 : lastUserMessage.displayContent) != null ? _b : extractUserQuery((_a3 = lastUserMessage == null ? void 0 : lastUserMessage.content) != null ? _a3 : ""); + const currentUserQuery = extractUserQuery(actualPrompt); + const shouldAppendPrompt = !lastUserMessage || lastUserQuery.trim() !== currentUserQuery.trim(); + return shouldAppendPrompt ? `${historyContext} + +User: ${prompt}` : historyContext; +} + +// src/core/hooks/SecurityHooks.ts +var import_obsidian2 = require("obsidian"); + +// src/core/security/BashPathValidator.ts +var path5 = __toESM(require("path")); +function tokenizeBashCommand(command) { + var _a3; + const tokens = []; + const tokenRegex = /(['"`])(.*?)\1|[^\s]+/g; + let match; + while ((match = tokenRegex.exec(command)) !== null) { + const token = (_a3 = match[2]) != null ? _a3 : match[0]; + const cleaned = token.trim(); + if (!cleaned) continue; + tokens.push(cleaned); + } + return tokens; +} +function splitBashTokensIntoSegments(tokens) { + const separators = /* @__PURE__ */ new Set(["&&", "||", ";", "|"]); + const segments = []; + let current = []; + for (const token of tokens) { + if (separators.has(token)) { + if (current.length > 0) { + segments.push(current); + current = []; + } + continue; + } + current.push(token); + } + if (current.length > 0) { + segments.push(current); + } + return segments; +} +function getBashSegmentCommandName(segment) { + const wrappers = /* @__PURE__ */ new Set(["command", "env", "sudo"]); + let cmdIndex = 0; + while (cmdIndex < segment.length) { + const token = segment[cmdIndex]; + if (wrappers.has(token)) { + cmdIndex += 1; + continue; + } + if (!token.startsWith("-") && token.includes("=")) { + cmdIndex += 1; + continue; + } + break; + } + const rawCmd = segment[cmdIndex] || ""; + const cmdName = path5.basename(rawCmd); + return { cmdName, cmdIndex }; +} +var OUTPUT_REDIRECT_OPS = /* @__PURE__ */ new Set([">", ">>", "1>", "1>>", "2>", "2>>", "&>", "&>>", ">|"]); +var INPUT_REDIRECT_OPS = /* @__PURE__ */ new Set(["<", "<<", "0<", "0<<"]); +var OUTPUT_OPTION_FLAGS = /* @__PURE__ */ new Set(["-o", "--output", "--out", "--outfile", "--output-file"]); +function isBashOutputRedirectOperator(token) { + return OUTPUT_REDIRECT_OPS.has(token); +} +function isBashInputRedirectOperator(token) { + return INPUT_REDIRECT_OPS.has(token); +} +function isBashOutputOptionExpectingValue(token) { + return OUTPUT_OPTION_FLAGS.has(token); +} +function cleanPathToken(raw) { + let token = raw.trim(); + if (!token) return null; + if (token.startsWith('"') && token.endsWith('"') || token.startsWith("'") && token.endsWith("'") || token.startsWith("`") && token.endsWith("`")) { + token = token.slice(1, -1).trim(); + } + while (token.startsWith("(") || token.startsWith("[") || token.startsWith("{")) { + token = token.slice(1).trim(); + } + while (token.endsWith(")") || token.endsWith("]") || token.endsWith("}") || token.endsWith(";") || token.endsWith(",")) { + token = token.slice(0, -1).trim(); + } + if (!token) return null; + if (token.startsWith('"') && token.endsWith('"') || token.startsWith("'") && token.endsWith("'") || token.startsWith("`") && token.endsWith("`")) { + token = token.slice(1, -1).trim(); + } + if (!token) return null; + if (token === "." || token === "/" || token === "\\" || token === "--") return null; + return token; +} +function isPathLikeToken(token) { + const cleaned = token.trim(); + if (!cleaned) return false; + if (cleaned === "." || cleaned === "/" || cleaned === "\\" || cleaned === "--") return false; + const isWindows2 = process.platform === "win32"; + return ( + // Home directory paths (Unix and Windows style) + cleaned === "~" || cleaned.startsWith("~/") || isWindows2 && cleaned.startsWith("~\\") || // Relative paths + cleaned.startsWith("./") || cleaned.startsWith("../") || cleaned === ".." || isWindows2 && (cleaned.startsWith(".\\") || cleaned.startsWith("..\\")) || // Absolute paths (Unix) + cleaned.startsWith("/") || // Absolute paths (Windows drive letters) + isWindows2 && /^[A-Za-z]:[\\/]/.test(cleaned) || // Absolute paths (Windows UNC) + isWindows2 && (cleaned.startsWith("\\\\") || cleaned.startsWith("//")) || // Contains path separators + cleaned.includes("/") || isWindows2 && cleaned.includes("\\") + ); +} +function checkBashPathAccess(candidate, access, context) { + const cleaned = cleanPathToken(candidate); + if (!cleaned) return null; + const accessType = context.getPathAccessType(cleaned); + if (accessType === "vault" || accessType === "readwrite") { + return null; + } + if (accessType === "context") { + return null; + } + if (accessType === "export") { + return access === "write" ? null : { type: "export_path_read", path: cleaned }; + } + return { type: "outside_vault", path: cleaned }; +} +function findBashPathViolationInSegment(segment, context) { + if (segment.length === 0) return null; + const { cmdName, cmdIndex } = getBashSegmentCommandName(segment); + const destinationCommands = /* @__PURE__ */ new Set(["cp", "mv", "rsync"]); + let destinationTokenIndex = null; + if (destinationCommands.has(cmdName)) { + const pathArgIndices = []; + let seenDoubleDash = false; + for (let i2 = cmdIndex + 1; i2 < segment.length; i2 += 1) { + const token = segment[i2]; + if (!seenDoubleDash && token === "--") { + seenDoubleDash = true; + continue; + } + if (!seenDoubleDash && token.startsWith("-")) { + continue; + } + if (isPathLikeToken(token)) { + pathArgIndices.push(i2); + } + } + if (pathArgIndices.length > 0) { + destinationTokenIndex = pathArgIndices[pathArgIndices.length - 1]; + } + } + let expectWriteNext = false; + for (let i2 = 0; i2 < segment.length; i2 += 1) { + const token = segment[i2]; + if (isBashOutputRedirectOperator(token)) { + expectWriteNext = true; + continue; + } + if (isBashInputRedirectOperator(token)) { + expectWriteNext = false; + continue; + } + if (isBashOutputOptionExpectingValue(token)) { + expectWriteNext = true; + continue; + } + const embeddedOutputRedirect = token.match(/^(?:&>>|&>|\d*>>|\d*>\||\d*>|>>|>\||>)(.+)$/); + if (embeddedOutputRedirect) { + const violation2 = checkBashPathAccess(embeddedOutputRedirect[1], "write", context); + if (violation2) return violation2; + continue; + } + const embeddedInputRedirect = token.match(/^(?:\d*<<|\d*<|<<|<)(.+)$/); + if (embeddedInputRedirect) { + const violation2 = checkBashPathAccess(embeddedInputRedirect[1], "read", context); + if (violation2) return violation2; + continue; + } + const embeddedLongOutput = token.match(/^--(?:output|out|outfile|output-file)=(.+)$/); + if (embeddedLongOutput) { + const violation2 = checkBashPathAccess(embeddedLongOutput[1], "write", context); + if (violation2) return violation2; + continue; + } + const embeddedShortOutput = token.match(/^-o(.+)$/); + if (embeddedShortOutput) { + const violation2 = checkBashPathAccess(embeddedShortOutput[1], "write", context); + if (violation2) return violation2; + continue; + } + const eqIndex = token.indexOf("="); + if (eqIndex > 0) { + const key = token.slice(0, eqIndex); + const value = token.slice(eqIndex + 1); + if (key.startsWith("-") && isPathLikeToken(value)) { + const violation2 = checkBashPathAccess(value, "read", context); + if (violation2) return violation2; + } + } + if (!isPathLikeToken(token)) { + expectWriteNext = false; + continue; + } + const access = i2 === destinationTokenIndex || expectWriteNext ? "write" : "read"; + const violation = checkBashPathAccess(token, access, context); + if (violation) return violation; + expectWriteNext = false; + } + return null; +} +function findBashCommandPathViolation(command, context) { + if (!command) return null; + const tokens = tokenizeBashCommand(command); + const segments = splitBashTokensIntoSegments(tokens); + for (const segment of segments) { + const violation = findBashPathViolationInSegment(segment, context); + if (violation) { + return violation; + } + } + return null; +} + +// src/core/security/BlocklistChecker.ts +function isCommandBlocked(command, patterns, enableBlocklist) { + if (!enableBlocklist) { + return false; + } + return patterns.some((pattern) => { + try { + return new RegExp(pattern, "i").test(command); + } catch (e2) { + return command.toLowerCase().includes(pattern.toLowerCase()); + } + }); +} + +// src/core/tools/toolNames.ts +var TOOL_AGENT_OUTPUT = "TaskOutput"; +var TOOL_BASH = "Bash"; +var TOOL_BASH_OUTPUT = "BashOutput"; +var TOOL_EDIT = "Edit"; +var TOOL_GLOB = "Glob"; +var TOOL_GREP = "Grep"; +var TOOL_KILL_SHELL = "KillShell"; +var TOOL_LS = "LS"; +var TOOL_LIST_MCP_RESOURCES = "ListMcpResources"; +var TOOL_MCP = "Mcp"; +var TOOL_NOTEBOOK_EDIT = "NotebookEdit"; +var TOOL_READ = "Read"; +var TOOL_READ_MCP_RESOURCE = "ReadMcpResource"; +var TOOL_SKILL = "Skill"; +var TOOL_TASK = "Task"; +var TOOL_TODO_WRITE = "TodoWrite"; +var TOOL_WEB_FETCH = "WebFetch"; +var TOOL_WEB_SEARCH = "WebSearch"; +var TOOL_WRITE = "Write"; +var EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT, TOOL_NOTEBOOK_EDIT]; +var WRITE_EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT]; +var FILE_TOOLS = [ + TOOL_READ, + TOOL_WRITE, + TOOL_EDIT, + TOOL_GLOB, + TOOL_GREP, + TOOL_LS, + TOOL_NOTEBOOK_EDIT, + TOOL_BASH +]; +var READ_ONLY_TOOLS = [ + TOOL_READ, + TOOL_GREP, + TOOL_GLOB, + TOOL_LS, + TOOL_WEB_SEARCH, + TOOL_WEB_FETCH +]; +function isEditTool(toolName) { + return EDIT_TOOLS.includes(toolName); +} +function isWriteEditTool(toolName) { + return WRITE_EDIT_TOOLS.includes(toolName); +} +function isFileTool(toolName) { + return FILE_TOOLS.includes(toolName); +} +function isReadOnlyTool(toolName) { + return READ_ONLY_TOOLS.includes(toolName); +} + +// src/core/tools/toolInput.ts +function getPathFromToolInput(toolName, toolInput) { + switch (toolName) { + case TOOL_READ: + case TOOL_WRITE: + case TOOL_EDIT: + case TOOL_NOTEBOOK_EDIT: + return toolInput.file_path || toolInput.notebook_path || null; + case TOOL_GLOB: + return toolInput.path || toolInput.pattern || null; + case TOOL_GREP: + return toolInput.path || null; + case TOOL_LS: + return toolInput.path || null; + default: + return null; + } +} + +// src/core/hooks/SecurityHooks.ts +function createBlocklistHook(getContext) { + return { + matcher: TOOL_BASH, + hooks: [ + async (hookInput) => { + var _a3; + const input = hookInput; + const command = ((_a3 = input.tool_input) == null ? void 0 : _a3.command) || ""; + const context = getContext(); + const bashToolCommands = getBashToolBlockedCommands(context.blockedCommands); + if (isCommandBlocked(command, bashToolCommands, context.enableBlocklist)) { + new import_obsidian2.Notice("Command blocked by security policy"); + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `Command blocked by blocklist: ${command}` + } + }; + } + return { continue: true }; + } + ] + }; +} +function createVaultRestrictionHook(context) { + return { + hooks: [ + async (hookInput) => { + var _a3; + const input = hookInput; + const toolName = input.tool_name; + if (toolName === TOOL_BASH) { + const command = ((_a3 = input.tool_input) == null ? void 0 : _a3.command) || ""; + const pathCheckContext = { + getPathAccessType: (p2) => context.getPathAccessType(p2) + }; + const violation = findBashCommandPathViolation(command, pathCheckContext); + if (violation) { + const reason = violation.type === "export_path_read" ? `Access denied: Command path "${violation.path}" is in an allowed export directory, but export paths are write-only.` : `Access denied: Command path "${violation.path}" is outside the vault. Agent is restricted to vault directory only.`; + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: reason + } + }; + } + return { continue: true }; + } + if (!isFileTool(toolName)) { + return { continue: true }; + } + const filePath = getPathFromToolInput(toolName, input.tool_input); + if (filePath) { + const accessType = context.getPathAccessType(filePath); + if (accessType === "vault" || accessType === "readwrite" || accessType === "context") { + return { continue: true }; + } + if (isEditTool(toolName) && accessType === "export") { + return { continue: true }; + } + if (!isEditTool(toolName) && accessType === "export") { + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `Access denied: Path "${filePath}" is in an allowed export directory, but export paths are write-only.` + } + }; + } + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `Access denied: Path "${filePath}" is outside the vault. Agent is restricted to vault directory only.` + } + }; + } + return { continue: true }; + } + ] + }; +} + +// src/core/sdk/transformSDKMessage.ts +function* transformSDKMessage(message, options) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o; + const parentToolUseId = message.type === "result" ? null : (_a3 = message.parent_tool_use_id) != null ? _a3 : null; + switch (message.type) { + case "system": + if (message.subtype === "init" && message.session_id) { + yield { + type: "session_init", + sessionId: message.session_id, + agents: message.agents + }; + } else if (message.subtype === "compact_boundary") { + yield { type: "compact_boundary" }; + } + break; + case "assistant": { + if (((_b = message.message) == null ? void 0 : _b.content) && Array.isArray(message.message.content)) { + for (const block of message.message.content) { + if (block.type === "thinking" && block.thinking) { + yield { type: "thinking", content: block.thinking, parentToolUseId }; + } else if (block.type === "text" && block.text) { + yield { type: "text", content: block.text, parentToolUseId }; + } else if (block.type === "tool_use") { + yield { + type: "tool_use", + id: block.id || `tool-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`, + name: block.name || "unknown", + input: block.input || {}, + parentToolUseId + }; + } + } + } + const apiMessage = message.message; + if (parentToolUseId === null && (apiMessage == null ? void 0 : apiMessage.usage)) { + const usage = apiMessage.usage; + const inputTokens = (_c = usage.input_tokens) != null ? _c : 0; + const cacheCreationInputTokens = (_d = usage.cache_creation_input_tokens) != null ? _d : 0; + const cacheReadInputTokens = (_e = usage.cache_read_input_tokens) != null ? _e : 0; + const contextTokens = inputTokens + cacheCreationInputTokens + cacheReadInputTokens; + const model = (_f = options == null ? void 0 : options.intendedModel) != null ? _f : "sonnet"; + const contextWindow = getContextWindowSize(model, (_g = options == null ? void 0 : options.is1MEnabled) != null ? _g : false, options == null ? void 0 : options.customContextLimits); + const percentage = Math.min(100, Math.max(0, Math.round(contextTokens / contextWindow * 100))); + const usageInfo = { + model, + inputTokens, + cacheCreationInputTokens, + cacheReadInputTokens, + contextWindow, + contextTokens, + percentage + }; + yield { type: "usage", usage: usageInfo }; + } + break; + } + case "user": + if (message._blocked && message._blockReason) { + yield { + type: "blocked", + content: message._blockReason + }; + break; + } + if (message.tool_use_result !== void 0 && message.parent_tool_use_id) { + yield { + type: "tool_result", + id: message.parent_tool_use_id, + content: typeof message.tool_use_result === "string" ? message.tool_use_result : JSON.stringify(message.tool_use_result, null, 2), + isError: false, + parentToolUseId, + toolUseResult: (_h = message.tool_use_result) != null ? _h : void 0 + }; + } + if (((_i = message.message) == null ? void 0 : _i.content) && Array.isArray(message.message.content)) { + for (const block of message.message.content) { + if (block.type === "tool_result") { + yield { + type: "tool_result", + id: block.tool_use_id || message.parent_tool_use_id || "", + content: typeof block.content === "string" ? block.content : JSON.stringify(block.content, null, 2), + isError: block.is_error || false, + parentToolUseId, + toolUseResult: (_j = message.tool_use_result) != null ? _j : void 0 + }; + } + } + } + break; + case "stream_event": { + const event = message.event; + if ((event == null ? void 0 : event.type) === "content_block_start" && ((_k = event.content_block) == null ? void 0 : _k.type) === "tool_use") { + yield { + type: "tool_use", + id: event.content_block.id || `tool-${Date.now()}`, + name: event.content_block.name || "unknown", + input: event.content_block.input || {}, + parentToolUseId + }; + } else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_l = event.content_block) == null ? void 0 : _l.type) === "thinking") { + if (event.content_block.thinking) { + yield { type: "thinking", content: event.content_block.thinking, parentToolUseId }; + } + } else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_m = event.content_block) == null ? void 0 : _m.type) === "text") { + if (event.content_block.text) { + yield { type: "text", content: event.content_block.text, parentToolUseId }; + } + } else if ((event == null ? void 0 : event.type) === "content_block_delta") { + if (((_n = event.delta) == null ? void 0 : _n.type) === "thinking_delta" && event.delta.thinking) { + yield { type: "thinking", content: event.delta.thinking, parentToolUseId }; + } else if (((_o = event.delta) == null ? void 0 : _o.type) === "text_delta" && event.delta.text) { + yield { type: "text", content: event.delta.text, parentToolUseId }; + } + } + break; + } + case "result": + break; + case "error": + if (message.error) { + yield { type: "error", content: message.error }; + } + break; + } +} + +// src/core/sdk/typeGuards.ts +function isSessionInitEvent(event) { + return event.type === "session_init"; +} +function isStreamChunk(event) { + return event.type !== "session_init"; +} + +// src/core/security/ApprovalManager.ts +function getActionPattern(toolName, input) { + switch (toolName) { + case TOOL_BASH: + return typeof input.command === "string" ? input.command.trim() : ""; + case TOOL_READ: + case TOOL_WRITE: + case TOOL_EDIT: + return typeof input.file_path === "string" && input.file_path ? input.file_path : "*"; + case TOOL_NOTEBOOK_EDIT: + if (typeof input.notebook_path === "string" && input.notebook_path) { + return input.notebook_path; + } + return typeof input.file_path === "string" && input.file_path ? input.file_path : "*"; + case TOOL_GLOB: + return typeof input.pattern === "string" && input.pattern ? input.pattern : "*"; + case TOOL_GREP: + return typeof input.pattern === "string" && input.pattern ? input.pattern : "*"; + default: + return JSON.stringify(input); + } +} +function getActionDescription(toolName, input) { + const pattern = getActionPattern(toolName, input); + switch (toolName) { + case TOOL_BASH: + return `Run command: ${pattern}`; + case TOOL_READ: + return `Read file: ${pattern}`; + case TOOL_WRITE: + return `Write to file: ${pattern}`; + case TOOL_EDIT: + return `Edit file: ${pattern}`; + case TOOL_GLOB: + return `Search files matching: ${pattern}`; + case TOOL_GREP: + return `Search content matching: ${pattern}`; + default: + return `${toolName}: ${pattern}`; + } +} +function buildPermissionUpdates(toolName, input, decision, suggestions) { + const destination = decision === "allow-always" ? "projectSettings" : "session"; + const processed = []; + let hasRuleUpdate = false; + if (suggestions) { + for (const s of suggestions) { + if (s.type === "addRules" || s.type === "replaceRules") { + hasRuleUpdate = true; + processed.push({ ...s, behavior: "allow", destination }); + } else { + processed.push(s); + } + } + } + if (!hasRuleUpdate) { + const pattern = getActionPattern(toolName, input); + const ruleValue = { toolName }; + if (pattern && pattern !== "*" && !pattern.startsWith("{")) { + ruleValue.ruleContent = pattern; + } + processed.unshift({ + type: "addRules", + behavior: "allow", + rules: [ruleValue], + destination + }); + } + return processed; +} + +// src/core/agent/types.ts +var MESSAGE_CHANNEL_CONFIG = { + MAX_QUEUED_MESSAGES: 8, + // Memory protection from rapid user input + MAX_MERGED_CHARS: 12e3 + // ~3k tokens — batch size under context limits +}; +function createResponseHandler(options) { + let _sawStreamText = false; + let _sawAnyChunk = false; + return { + id: options.id, + onChunk: options.onChunk, + onDone: options.onDone, + onError: options.onError, + get sawStreamText() { + return _sawStreamText; + }, + get sawAnyChunk() { + return _sawAnyChunk; + }, + markStreamTextSeen() { + _sawStreamText = true; + }, + resetStreamText() { + _sawStreamText = false; + }, + markChunkSeen() { + _sawAnyChunk = true; + } + }; +} +var UNSUPPORTED_SDK_TOOLS = [ + "AskUserQuestion", + "EnterPlanMode", + "ExitPlanMode" +]; +var DISABLED_BUILTIN_SUBAGENTS = [ + "Task(statusline-setup)" +]; +function isTurnCompleteMessage(message) { + const messageType = message.type; + return messageType === "result" || messageType === "error"; +} +function computeSystemPromptKey(settings11) { + const parts = [ + settings11.mediaFolder || "", + settings11.customPrompt || "", + (settings11.allowedExportPaths || []).sort().join("|"), + settings11.vaultPath || "", + (settings11.userName || "").trim() + // Note: hasEditorContext is per-message, not tracked here + ]; + return parts.join("::"); +} + +// src/core/agent/MessageChannel.ts +var MessageChannel = class { + constructor(onWarning = () => { + }) { + this.queue = []; + this.turnActive = false; + this.closed = false; + this.resolveNext = null; + this.currentSessionId = null; + this.onWarning = onWarning; + } + setSessionId(sessionId) { + this.currentSessionId = sessionId; + } + isTurnActive() { + return this.turnActive; + } + isClosed() { + return this.closed; + } + /** + * Enqueue a message. If a turn is active: + * - Text-only: merge with queued text (up to MAX_MERGED_CHARS) + * - With attachments: replace any existing queued attachment (one at a time) + */ + enqueue(message) { + if (this.closed) { + throw new Error("MessageChannel is closed"); + } + const hasAttachments = this.messageHasAttachments(message); + if (!this.turnActive) { + if (this.resolveNext) { + this.turnActive = true; + const resolve4 = this.resolveNext; + this.resolveNext = null; + resolve4({ value: message, done: false }); + } else { + if (this.queue.length >= MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES) { + this.onWarning(`[MessageChannel] Queue full (${MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES}), dropping newest`); + return; + } + if (hasAttachments) { + this.queue.push({ type: "attachment", message }); + } else { + this.queue.push({ type: "text", content: this.extractTextContent(message) }); + } + } + return; + } + if (hasAttachments) { + const existingIdx = this.queue.findIndex((m) => m.type === "attachment"); + if (existingIdx >= 0) { + this.queue[existingIdx] = { type: "attachment", message }; + this.onWarning("[MessageChannel] Attachment message replaced (only one can be queued)"); + } else { + this.queue.push({ type: "attachment", message }); + } + return; + } + const textContent = this.extractTextContent(message); + const existingTextIdx = this.queue.findIndex((m) => m.type === "text"); + if (existingTextIdx >= 0) { + const existing = this.queue[existingTextIdx]; + const mergedContent = existing.content + "\n\n" + textContent; + if (mergedContent.length > MESSAGE_CHANNEL_CONFIG.MAX_MERGED_CHARS) { + this.onWarning(`[MessageChannel] Merged content exceeds ${MESSAGE_CHANNEL_CONFIG.MAX_MERGED_CHARS} chars, dropping newest`); + return; + } + existing.content = mergedContent; + } else { + if (this.queue.length >= MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES) { + this.onWarning(`[MessageChannel] Queue full (${MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES}), dropping newest`); + return; + } + this.queue.push({ type: "text", content: textContent }); + } + } + onTurnComplete() { + this.turnActive = false; + if (this.queue.length > 0 && this.resolveNext) { + const pending = this.queue.shift(); + this.turnActive = true; + const resolve4 = this.resolveNext; + this.resolveNext = null; + resolve4({ value: this.pendingToMessage(pending), done: false }); + } + } + close() { + this.closed = true; + this.queue = []; + if (this.resolveNext) { + const resolve4 = this.resolveNext; + this.resolveNext = null; + resolve4({ value: void 0, done: true }); + } + } + reset() { + this.queue = []; + this.turnActive = false; + this.closed = false; + this.resolveNext = null; + } + getQueueLength() { + return this.queue.length; + } + [Symbol.asyncIterator]() { + return { + next: () => { + if (this.closed) { + return Promise.resolve({ value: void 0, done: true }); + } + if (this.queue.length > 0 && !this.turnActive) { + const pending = this.queue.shift(); + this.turnActive = true; + return Promise.resolve({ value: this.pendingToMessage(pending), done: false }); + } + return new Promise((resolve4) => { + this.resolveNext = resolve4; + }); + } + }; + } + messageHasAttachments(message) { + var _a3; + if (!((_a3 = message.message) == null ? void 0 : _a3.content)) return false; + if (typeof message.message.content === "string") return false; + return message.message.content.some((block) => block.type === "image"); + } + extractTextContent(message) { + var _a3; + if (!((_a3 = message.message) == null ? void 0 : _a3.content)) return ""; + if (typeof message.message.content === "string") return message.message.content; + return message.message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n\n"); + } + pendingToMessage(pending) { + if (pending.type === "attachment") { + return pending.message; + } + return { + type: "user", + message: { + role: "user", + content: pending.content + }, + parent_tool_use_id: null, + session_id: this.currentSessionId || "" + }; + } +}; + +// src/utils/date.ts +function getTodayDate() { + const now = /* @__PURE__ */ new Date(); + const readable = now.toLocaleDateString("en-US", { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric" + }); + const iso = now.toISOString().split("T")[0]; + return `${readable} (${iso})`; +} +function formatDurationMmSs(seconds) { + if (!Number.isFinite(seconds) || seconds < 0) { + return "0s"; + } + const mins = Math.floor(seconds / 60); + const secs = seconds % 60; + if (mins === 0) { + return `${secs}s`; + } + return `${mins}m ${secs}s`; +} + +// src/core/prompts/mainAgent.ts +function getBaseSystemPrompt(vaultPath, userName) { + const vaultInfo = vaultPath ? ` + +Vault absolute path: ${vaultPath}` : ""; + const trimmedUserName = userName == null ? void 0 : userName.trim(); + const userContext = trimmedUserName ? `## User Context + +You are collaborating with **${trimmedUserName}**. + +` : ""; + return `${userContext}## Time Context + +- **Current Date**: ${getTodayDate()} +- **Knowledge Status**: You possess extensive internal knowledge up to your training cutoff. You do not know the exact date of your cutoff, but you must assume that your internal weights are static and "past," while the Current Date is "present." + +## Identity & Role + +You are **Claudian**, an expert AI assistant specialized in Obsidian vault management, knowledge organization, and code analysis. You operate directly inside the user's Obsidian vault. + +**Core Principles:** +1. **Obsidian Native**: You understand Markdown, YAML frontmatter, Wiki-links, and the "second brain" philosophy. +2. **Safety First**: You never overwrite data without understanding context. You always use relative paths. +3. **Proactive Thinking**: You do not just execute; you *plan* and *verify*. You anticipate potential issues (like broken links or missing files). +4. **Clarity**: Your changes are precise, minimizing "noise" in the user's notes or code. + +The current working directory is the user's vault root.${vaultInfo} + +## Path Rules (MUST FOLLOW) + +| Location | Access | Path Format | Example | +|----------|--------|-------------|---------| +| **Vault** | Read/Write | Relative from vault root | \`notes/my-note.md\`, \`.\` | +| **Export paths** | Write-only | \`~\` or absolute | \`~/Desktop/output.docx\` | +| **External contexts** | Full access | Absolute path | \`/Users/me/Workspace/file.ts\` | + +**Vault files** (default): +- \u2713 Correct: \`notes/my-note.md\`, \`my-note.md\`, \`folder/subfolder/file.md\`, \`.\` +- \u2717 WRONG: \`/notes/my-note.md\`, \`${vaultPath || "/absolute/path"}/file.md\` +- A leading slash or absolute path will FAIL for vault operations. + +**Path specificity**: When paths overlap, the **more specific path wins**: +- If \`~/Desktop\` is export (write-only) and \`~/Desktop/Workspace\` is external context (full access) +- \u2192 Files in \`~/Desktop/Workspace\` have full read/write access +- \u2192 Files directly in \`~/Desktop\` remain write-only + +## User Message Format + +User messages have the query first, followed by optional XML context tags: + +\`\`\` +User's question or request here + + +path/to/note.md + + + +selected text content + +\`\`\` + +- The user's query/instruction always comes first in the message. +- \`\`: The note the user is currently viewing/focused on. Read this to understand context. +- \`\`: Text currently selected in the editor, with file path and line numbers. +- \`@filename.md\`: Files mentioned with @ in the query. Read these files when referenced. + +## Obsidian Context + +- **Structure**: Files are Markdown (.md). Folders organize content. +- **Frontmatter**: YAML at the top of files (metadata). Respect existing fields. +- **Links**: Internal Wiki-links \`[[note-name]]\` or \`[[folder/note-name]]\`. External links \`[text](url)\`. + - When reading a note with wikilinks, consider reading linked notes\u2014they often contain related context that helps understand the current note. +- **Tags**: #tag-name for categorization. +- **Dataview**: You may encounter Dataview queries (in \`\`\`dataview\`\`\` blocks). Do not break them unless asked. +- **Vault Config**: \`.obsidian/\` contains internal config. Touch only if you know what you are doing. + +**File References in Responses:** +When mentioning vault files in your responses, use wikilink format so users can click to open them: +- \u2713 Use: \`[[folder/note.md]]\` or \`[[note]]\` +- \u2717 Avoid: plain paths like \`folder/note.md\` (not clickable) + +**Image embeds:** Use \`![[image.png]]\` to display images directly in chat. Images render visually, making it easy to show diagrams, screenshots, or visual content you're discussing. + +Examples: +- "I found your notes in [[30.areas/finance/Investment lessons/2024.Current trading lessons.md]]" +- "See [[daily notes/2024-01-15]] for more details" +- "Here's the diagram: ![[attachments/architecture.png]]" + +## Tool Usage Guidelines + +Standard tools (Read, Write, Edit, Glob, Grep, LS, Bash, WebSearch, WebFetch, Skills) work as expected. + +**Thinking Process:** +Before taking action, explicitly THINK about: +1. **Context**: Do I have enough information? (Use Read/Search if not). +2. **Impact**: What will this change affect? (Links, other files). +3. **Plan**: What are the steps? (Use TodoWrite for >2 steps). + +**Tool-Specific Rules:** +- **Read**: + - Always Read a file before Editing it. + - Read can view images (PNG, JPG, GIF, WebP) for visual analysis. +- **Edit**: + - Requires **EXACT** \`old_string\` match including whitespace/indentation. + - If Edit fails, Read the file again to check the current content. +- **Bash**: + - Runs with vault as working directory. + - **Prefer** Read/Write/Edit over shell commands for file operations (safer). + - **Stdout-capable tools** (pandoc, jq, imagemagick): Prefer piping output directly instead of creating temporary files when the result will be used immediately. + - Use BashOutput/KillShell to manage background processes. +- **LS**: Uses "." for vault root. +- **WebFetch**: For text/HTML/PDF only. Avoid binaries. + +### WebSearch + +Use WebSearch strictly according to the following logic: + +1. **Static/Historical**: Rely on internal knowledge for established facts, history, or older code libraries. Use WebSearch to confirm or expand on your knowledge. +2. **Dynamic/Recent**: **MUST** search for: + - "Latest" news, versions, docs. + - Events in the current/previous year. + - Volatile data (prices, weather). +3. **Date Awareness**: If user says "yesterday", calculate the date relative to **Current Date**. +4. **Ambiguity**: If unsure whether knowledge is outdated, SEARCH. + +### Task (Subagents) + +Spawn subagents for complex multi-step tasks. Parameters: \`prompt\`, \`description\`, \`subagent_type\`, \`run_in_background\`. + +**CRITICAL - Subagent Path Rules:** +- Subagents inherit the vault as their working directory. +- Reference files using **RELATIVE** paths. +- NEVER use absolute paths in subagent prompts. + +**When to use:** +- Parallelizable work (main + subagent or multiple subagents) +- Preserve main agent's context window +- Offload contained tasks while continuing other work + +**IMPORTANT:** Always explicitly set \`run_in_background\` - never omit it: +- \`run_in_background=false\` for sync (inline) tasks +- \`run_in_background=true\` for async (background) tasks + +**Sync Mode (\`run_in_background=false\`)**: +- Runs inline, result returned directly. +- **DEFAULT** to this unless explicitly asked or the task is very long-running. + +**Async Mode (\`run_in_background=true\`)**: +- Use ONLY when explicitly requested or task is clearly long-running. +- Returns \`task_id\` and \`output_file\` path immediately. +- System sends \`\` with result when complete. +- Full transcript persists in \`output_file\`. + +**Retrieving async results (three options):** +- Wait for \`\` (automatic, includes result) +- Use \`TaskOutput task_id="..." block=true\` (blocking) or \`block=false\` (polling) +- Read \`output_file\` directly with Read tool + +**Async workflow:** +1. Launch: \`Task prompt="..." run_in_background=true\` \u2192 get \`task_id\` and \`output_file\` +2. Continue working on other tasks (if any) +3. If no other work: use \`TaskOutput task_id="..." block=true\` to wait for completion +4. Report result to user + +**Critical:** Never end response without retrieving async task results. When idle, MUST actively wait with \`TaskOutput block=true\` rather than waiting passively. + +### TodoWrite + +Track task progress. Parameter: \`todos\` (array of {content, status, activeForm}). +- Statuses: \`pending\`, \`in_progress\`, \`completed\` +- \`content\`: imperative ("Fix the bug") +- \`activeForm\`: present continuous ("Fixing the bug") + +**Use for:** Tasks with 2+ steps, multi-file changes, complex operations. +Use proactively for any task meeting these criteria to keep progress visible. + +**Workflow:** +1. **Plan**: Create the todo list at the start. +2. **Execute**: Mark \`in_progress\` -> do work -> Mark \`completed\`. +3. **Update**: If new tasks arise, add them. + +**Example:** User asks "refactor auth and add tests" +\`\`\` +[ + {content: "Analyze auth module", status: "in_progress", activeForm: "Analyzing auth module"}, + {content: "Refactor auth code", status: "pending", activeForm: "Refactoring auth code"}, + {content: "Add unit tests", status: "pending", activeForm: "Adding unit tests"} +] +\`\`\` + +### Skills + +Reusable capability modules. Use the \`Skill\` tool to invoke them when their description matches the user's need. + +## Editor Selection + +User messages may include an \`\` tag showing text the user selected: + +\`\`\`xml + +selected text here +possibly multiple lines + +\`\`\` + +**When present:** The user selected this text before sending their message. Use this context to understand what they're referring to.`; +} +function getImageInstructions(mediaFolder) { + const folder = mediaFolder.trim(); + const mediaPath = folder ? "./" + folder : "."; + const examplePath = folder ? folder + "/" : ""; + return ` + +## Embedded Images in Notes + +**Proactive image reading**: When reading a note with embedded images, read them alongside text for full context. Images often contain critical information (diagrams, screenshots, charts). + +**Local images** (\`![[image.jpg]]\`): +- Located in media folder: \`${mediaPath}\` +- Read with: \`Read file_path="${examplePath}image.jpg"\` +- Formats: PNG, JPG/JPEG, GIF, WebP + +**External images** (\`![alt](url)\`): +- WebFetch does NOT support images +- Download to media folder \u2192 Read \u2192 Replace URL with wiki-link: + +\`\`\`bash +# Download to media folder with descriptive name +mkdir -p ${mediaPath} +img_name="downloaded_\\$(date +%s).png" +curl -sfo "${examplePath}$img_name" 'URL' +\`\`\` + +Then read with \`Read file_path="${examplePath}$img_name"\`, and replace the markdown link \`![alt](url)\` with \`![[${examplePath}$img_name]]\` in the note. + +**Benefits**: Image becomes a permanent vault asset, works offline, and uses Obsidian's native embed syntax.`; +} +function getExportInstructions(allowedExportPaths) { + if (allowedExportPaths.length === 0) { + return ""; + } + const uniquePaths = Array.from(new Set(allowedExportPaths.map((p2) => p2.trim()).filter(Boolean))); + if (uniquePaths.length === 0) { + return ""; + } + const formattedPaths = uniquePaths.map((p2) => `- ${p2}`).join("\n"); + return ` + +## Allowed Export Paths + +Write-only destinations outside the vault: + +${formattedPaths} + +Examples: +\`\`\`bash +pandoc ./note.md -o ~/Desktop/note.docx # Direct export +pandoc ./note.md | head -100 # Pipe to stdout (no temp file) +cp ./note.md ~/Desktop/note.md +\`\`\``; +} +function buildSystemPrompt(settings11 = {}) { + var _a3; + let prompt = getBaseSystemPrompt(settings11.vaultPath, settings11.userName); + prompt += getImageInstructions(settings11.mediaFolder || ""); + prompt += getExportInstructions(settings11.allowedExportPaths || []); + if ((_a3 = settings11.customPrompt) == null ? void 0 : _a3.trim()) { + prompt += "\n\n## Custom Instructions\n\n" + settings11.customPrompt.trim(); + } + return prompt; +} + +// src/core/agent/customSpawn.ts +var import_child_process2 = require("child_process"); +function createCustomSpawnFunction(enhancedPath) { + return (options) => { + let { command } = options; + const { args, cwd, env, signal } = options; + const shouldPipeStderr = !!(env == null ? void 0 : env.DEBUG_CLAUDE_AGENT_SDK); + if (command === "node") { + const nodeFullPath = findNodeExecutable(enhancedPath); + if (nodeFullPath) { + command = nodeFullPath; + } + } + const child = (0, import_child_process2.spawn)(command, args, { + cwd, + env, + signal, + stdio: ["pipe", "pipe", shouldPipeStderr ? "pipe" : "ignore"], + windowsHide: true + }); + if (shouldPipeStderr && child.stderr && typeof child.stderr.on === "function") { + child.stderr.on("data", () => { + }); + } + if (!child.stdin || !child.stdout) { + throw new Error("Failed to create process streams"); + } + return child; + }; +} + +// src/core/agent/QueryOptionsBuilder.ts +var QueryOptionsBuilder = class _QueryOptionsBuilder { + /** + * Some changes (model, thinking tokens) can be updated dynamically; others require restart. + */ + static needsRestart(currentConfig, newConfig) { + if (!currentConfig) return true; + if (currentConfig.systemPromptKey !== newConfig.systemPromptKey) return true; + if (currentConfig.disallowedToolsKey !== newConfig.disallowedToolsKey) return true; + if (currentConfig.pluginsKey !== newConfig.pluginsKey) return true; + if (currentConfig.settingSources !== newConfig.settingSources) return true; + if (currentConfig.claudeCliPath !== newConfig.claudeCliPath) return true; + if (currentConfig.show1MModel !== newConfig.show1MModel) return true; + if (currentConfig.enableChrome !== newConfig.enableChrome) return true; + if (_QueryOptionsBuilder.pathsChanged(currentConfig.allowedExportPaths, newConfig.allowedExportPaths)) { + return true; + } + if (_QueryOptionsBuilder.pathsChanged(currentConfig.externalContextPaths, newConfig.externalContextPaths)) { + return true; + } + return false; + } + /** Builds configuration snapshot for restart detection. */ + static buildPersistentQueryConfig(ctx, externalContextPaths) { + var _a3; + const systemPromptSettings = { + mediaFolder: ctx.settings.mediaFolder, + customPrompt: ctx.settings.systemPrompt, + allowedExportPaths: ctx.settings.allowedExportPaths, + vaultPath: ctx.vaultPath, + userName: ctx.settings.userName + }; + const budgetSetting = ctx.settings.thinkingBudget; + const budgetConfig = THINKING_BUDGETS.find((b3) => b3.value === budgetSetting); + const thinkingTokens = (_a3 = budgetConfig == null ? void 0 : budgetConfig.tokens) != null ? _a3 : null; + const allDisallowedTools = ctx.mcpManager.getAllDisallowedMcpTools(); + const disallowedToolsKey = allDisallowedTools.join("|"); + const pluginsKey = ctx.pluginManager.getPluginsKey(); + return { + model: ctx.settings.model, + thinkingTokens: thinkingTokens && thinkingTokens > 0 ? thinkingTokens : null, + permissionMode: ctx.settings.permissionMode, + systemPromptKey: computeSystemPromptKey(systemPromptSettings), + disallowedToolsKey, + mcpServersKey: "", + // Dynamic via setMcpServers, not tracked for restart + pluginsKey, + externalContextPaths: externalContextPaths || [], + allowedExportPaths: ctx.settings.allowedExportPaths, + settingSources: ctx.settings.loadUserClaudeSettings ? "user,project" : "project", + claudeCliPath: ctx.cliPath, + show1MModel: ctx.settings.show1MModel, + enableChrome: ctx.settings.enableChrome + }; + } + /** Builds SDK options for the persistent query. */ + static buildPersistentQueryOptions(ctx) { + const permissionMode = ctx.settings.permissionMode; + const resolved = resolveModelWithBetas(ctx.settings.model, ctx.settings.show1MModel); + const systemPrompt = buildSystemPrompt({ + mediaFolder: ctx.settings.mediaFolder, + customPrompt: ctx.settings.systemPrompt, + allowedExportPaths: ctx.settings.allowedExportPaths, + vaultPath: ctx.vaultPath, + userName: ctx.settings.userName + }); + const options = { + cwd: ctx.vaultPath, + systemPrompt, + model: resolved.model, + abortController: ctx.abortController, + pathToClaudeCodeExecutable: ctx.cliPath, + settingSources: ctx.settings.loadUserClaudeSettings ? ["user", "project"] : ["project"], + env: { + ...process.env, + ...ctx.customEnv, + PATH: ctx.enhancedPath + }, + includePartialMessages: true + }; + if (resolved.betas) { + options.betas = resolved.betas; + } + _QueryOptionsBuilder.applyExtraArgs(options, ctx.settings); + options.disallowedTools = [ + ...ctx.mcpManager.getAllDisallowedMcpTools(), + ...UNSUPPORTED_SDK_TOOLS, + ...DISABLED_BUILTIN_SUBAGENTS + ]; + _QueryOptionsBuilder.applyPermissionMode(options, permissionMode, ctx.canUseTool); + _QueryOptionsBuilder.applyThinkingBudget(options, ctx.settings.thinkingBudget); + options.hooks = ctx.hooks; + if (ctx.resumeSessionId) { + options.resume = ctx.resumeSessionId; + } + if (ctx.externalContextPaths && ctx.externalContextPaths.length > 0) { + options.additionalDirectories = ctx.externalContextPaths; + } + options.spawnClaudeCodeProcess = createCustomSpawnFunction(ctx.enhancedPath); + return options; + } + /** Builds SDK options for a cold-start query. */ + static buildColdStartQueryOptions(ctx) { + var _a3; + const permissionMode = ctx.settings.permissionMode; + const selectedModel = (_a3 = ctx.modelOverride) != null ? _a3 : ctx.settings.model; + const resolved = resolveModelWithBetas(selectedModel, ctx.settings.show1MModel); + const systemPrompt = buildSystemPrompt({ + mediaFolder: ctx.settings.mediaFolder, + customPrompt: ctx.settings.systemPrompt, + allowedExportPaths: ctx.settings.allowedExportPaths, + vaultPath: ctx.vaultPath, + userName: ctx.settings.userName + }); + const options = { + cwd: ctx.vaultPath, + systemPrompt, + model: resolved.model, + abortController: ctx.abortController, + pathToClaudeCodeExecutable: ctx.cliPath, + // User settings may contain permission rules that bypass Claudian's permission system + settingSources: ctx.settings.loadUserClaudeSettings ? ["user", "project"] : ["project"], + env: { + ...process.env, + ...ctx.customEnv, + PATH: ctx.enhancedPath + }, + includePartialMessages: true + }; + if (resolved.betas) { + options.betas = resolved.betas; + } + _QueryOptionsBuilder.applyExtraArgs(options, ctx.settings); + const mcpMentions = ctx.mcpMentions || /* @__PURE__ */ new Set(); + const uiEnabledServers = ctx.enabledMcpServers || /* @__PURE__ */ new Set(); + const combinedMentions = /* @__PURE__ */ new Set([...mcpMentions, ...uiEnabledServers]); + const mcpServers = ctx.mcpManager.getActiveServers(combinedMentions); + if (Object.keys(mcpServers).length > 0) { + options.mcpServers = mcpServers; + } + const disallowedMcpTools = ctx.mcpManager.getDisallowedMcpTools(combinedMentions); + options.disallowedTools = [ + ...disallowedMcpTools, + ...UNSUPPORTED_SDK_TOOLS, + ...DISABLED_BUILTIN_SUBAGENTS + ]; + _QueryOptionsBuilder.applyPermissionMode(options, permissionMode, ctx.canUseTool); + options.hooks = ctx.hooks; + _QueryOptionsBuilder.applyThinkingBudget(options, ctx.settings.thinkingBudget); + if (ctx.allowedTools !== void 0 && ctx.allowedTools.length > 0) { + options.tools = ctx.allowedTools; + } + if (ctx.sessionId) { + options.resume = ctx.sessionId; + } + if (ctx.externalContextPaths && ctx.externalContextPaths.length > 0) { + options.additionalDirectories = ctx.externalContextPaths; + } + options.spawnClaudeCodeProcess = createCustomSpawnFunction(ctx.enhancedPath); + return options; + } + /** + * Always sets allowDangerouslySkipPermissions: true to enable dynamic + * switching between permission modes without requiring a process restart. + */ + static applyPermissionMode(options, permissionMode, canUseTool) { + options.allowDangerouslySkipPermissions = true; + if (permissionMode === "yolo") { + options.permissionMode = "bypassPermissions"; + } else { + options.permissionMode = "acceptEdits"; + if (canUseTool) { + options.canUseTool = canUseTool; + } + } + } + static applyExtraArgs(options, settings11) { + if (settings11.enableChrome) { + options.extraArgs = { ...options.extraArgs, chrome: null }; + } + } + static applyThinkingBudget(options, budgetSetting) { + const budgetConfig = THINKING_BUDGETS.find((b3) => b3.value === budgetSetting); + if (budgetConfig && budgetConfig.tokens > 0) { + options.maxThinkingTokens = budgetConfig.tokens; + } + } + static pathsChanged(a, b3) { + const aKey = [...a || []].sort().join("|"); + const bKey = [...b3 || []].sort().join("|"); + return aKey !== bKey; + } +}; + +// src/core/agent/SessionManager.ts +var SessionManager = class { + constructor() { + this.state = { + sessionId: null, + sessionModel: null, + pendingSessionModel: null, + wasInterrupted: false, + needsHistoryRebuild: false, + sessionInvalidated: false + }; + } + getSessionId() { + return this.state.sessionId; + } + setSessionId(id, defaultModel) { + this.state.sessionId = id; + this.state.sessionModel = id ? defaultModel != null ? defaultModel : null : null; + this.state.needsHistoryRebuild = false; + this.state.sessionInvalidated = false; + } + wasInterrupted() { + return this.state.wasInterrupted; + } + markInterrupted() { + this.state.wasInterrupted = true; + } + clearInterrupted() { + this.state.wasInterrupted = false; + } + setPendingModel(model) { + this.state.pendingSessionModel = model; + } + clearPendingModel() { + this.state.pendingSessionModel = null; + } + /** + * Captures a session ID from SDK response. + * Detects mismatch if we had a different session ID before (context lost). + */ + captureSession(sessionId) { + const hadSession = this.state.sessionId !== null; + const isDifferent = this.state.sessionId !== sessionId; + if (hadSession && isDifferent) { + this.state.needsHistoryRebuild = true; + } + this.state.sessionId = sessionId; + this.state.sessionModel = this.state.pendingSessionModel; + this.state.pendingSessionModel = null; + this.state.sessionInvalidated = false; + } + needsHistoryRebuild() { + return this.state.needsHistoryRebuild; + } + clearHistoryRebuild() { + this.state.needsHistoryRebuild = false; + } + invalidateSession() { + this.state.sessionId = null; + this.state.sessionModel = null; + this.state.sessionInvalidated = true; + } + /** Consume the invalidation flag (returns true once). */ + consumeInvalidation() { + const wasInvalidated = this.state.sessionInvalidated; + this.state.sessionInvalidated = false; + return wasInvalidated; + } + reset() { + this.state = { + sessionId: null, + sessionModel: null, + pendingSessionModel: null, + wasInterrupted: false, + needsHistoryRebuild: false, + sessionInvalidated: false + }; + } +}; + +// src/core/agent/ClaudianService.ts +var ClaudianService = class { + // Prevent consumer error restarts during cold-start + constructor(plugin, mcpManager) { + this.abortController = null; + this.approvalCallback = null; + this.approvalDismisser = null; + this.vaultPath = null; + this.currentExternalContextPaths = []; + this.readyStateListeners = /* @__PURE__ */ new Set(); + // Modular components + this.sessionManager = new SessionManager(); + this.persistentQuery = null; + this.messageChannel = null; + this.queryAbortController = null; + this.responseHandlers = []; + this.responseConsumerRunning = false; + this.shuttingDown = false; + // Tracked configuration for detecting changes that require restart + this.currentConfig = null; + // Current allowed tools for canUseTool enforcement (null = no restriction) + this.currentAllowedTools = null; + // Last sent message for crash recovery (Phase 1.3) + this.lastSentMessage = null; + this.lastSentQueryOptions = null; + this.crashRecoveryAttempted = false; + this.coldStartInProgress = false; + this.plugin = plugin; + this.mcpManager = mcpManager; + } + onReadyStateChange(listener) { + this.readyStateListeners.add(listener); + try { + listener(this.isReady()); + } catch (e2) { + } + return () => { + this.readyStateListeners.delete(listener); + }; + } + notifyReadyStateChange() { + if (this.readyStateListeners.size === 0) { + return; + } + const isReady = this.isReady(); + for (const listener of this.readyStateListeners) { + try { + listener(isReady); + } catch (e2) { + } + } + } + async reloadMcpServers() { + await this.mcpManager.loadServers(); + } + /** + * Ensures the persistent query is running with current configuration. + * Unified API that replaces preWarm() and restartPersistentQuery(). + * + * Behavior: + * - If not running → start (if paths available) + * - If running and force=true → close and restart + * - If running and config changed → close and restart + * - If running and config unchanged → no-op + * + * Note: When restart is needed, the query is closed BEFORE checking if we can + * start a new one. This ensures fallback to cold-start if CLI becomes unavailable. + * + * @returns true if the query was (re)started, false otherwise + */ + async ensureReady(options) { + var _a3, _b, _c; + const vaultPath = getVaultPath(this.plugin.app); + if (options && options.externalContextPaths !== void 0) { + this.currentExternalContextPaths = options.externalContextPaths; + } + const effectiveSessionId = (_b = (_a3 = options == null ? void 0 : options.sessionId) != null ? _a3 : this.sessionManager.getSessionId()) != null ? _b : void 0; + const externalContextPaths = (_c = options == null ? void 0 : options.externalContextPaths) != null ? _c : this.currentExternalContextPaths; + if (!this.persistentQuery) { + if (!vaultPath) return false; + const cliPath2 = this.plugin.getResolvedClaudeCliPath(); + if (!cliPath2) return false; + await this.startPersistentQuery(vaultPath, cliPath2, effectiveSessionId, externalContextPaths); + return true; + } + if (options == null ? void 0 : options.force) { + this.closePersistentQuery("forced restart", { preserveHandlers: options.preserveHandlers }); + if (!vaultPath) return false; + const cliPath2 = this.plugin.getResolvedClaudeCliPath(); + if (!cliPath2) return false; + await this.startPersistentQuery(vaultPath, cliPath2, effectiveSessionId, externalContextPaths); + return true; + } + if (!vaultPath) return false; + const cliPath = this.plugin.getResolvedClaudeCliPath(); + if (!cliPath) return false; + const newConfig = this.buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths); + if (this.needsRestart(newConfig)) { + this.closePersistentQuery("config changed", { preserveHandlers: options == null ? void 0 : options.preserveHandlers }); + const cliPathAfterClose = this.plugin.getResolvedClaudeCliPath(); + if (cliPathAfterClose) { + await this.startPersistentQuery(vaultPath, cliPathAfterClose, effectiveSessionId, externalContextPaths); + return true; + } + return false; + } + return false; + } + /** + * Starts the persistent query for the active chat conversation. + */ + async startPersistentQuery(vaultPath, cliPath, resumeSessionId, externalContextPaths) { + if (this.persistentQuery) { + return; + } + this.shuttingDown = false; + this.vaultPath = vaultPath; + this.messageChannel = new MessageChannel(); + if (resumeSessionId) { + this.messageChannel.setSessionId(resumeSessionId); + this.sessionManager.setSessionId(resumeSessionId, this.plugin.settings.model); + } + this.queryAbortController = new AbortController(); + const config2 = this.buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths); + this.currentConfig = config2; + const options = await this.buildPersistentQueryOptions( + vaultPath, + cliPath, + resumeSessionId, + externalContextPaths + ); + this.persistentQuery = u_({ + prompt: this.messageChannel, + options + }); + this.attachPersistentQueryStdinErrorHandler(this.persistentQuery); + this.startResponseConsumer(); + this.notifyReadyStateChange(); + } + attachPersistentQueryStdinErrorHandler(query) { + var _a3; + const stdin = (_a3 = query.transport) == null ? void 0 : _a3.processStdin; + if (!stdin || typeof stdin.on !== "function" || typeof stdin.once !== "function") { + return; + } + const handler = (error48) => { + if (this.shuttingDown || this.isPipeError(error48)) { + return; + } + this.closePersistentQuery("stdin error"); + }; + stdin.on("error", handler); + stdin.once("close", () => { + stdin.removeListener("error", handler); + }); + } + isPipeError(error48) { + if (!error48 || typeof error48 !== "object") return false; + const e2 = error48; + return e2.code === "EPIPE" || typeof e2.message === "string" && e2.message.includes("EPIPE"); + } + /** + * Closes the persistent query and cleans up resources. + */ + closePersistentQuery(_reason, options) { + var _a3, _b, _c; + if (!this.persistentQuery) { + return; + } + const preserveHandlers = (_a3 = options == null ? void 0 : options.preserveHandlers) != null ? _a3 : false; + this.shuttingDown = true; + (_b = this.messageChannel) == null ? void 0 : _b.close(); + void this.persistentQuery.interrupt().catch(() => { + }); + (_c = this.queryAbortController) == null ? void 0 : _c.abort(); + if (!preserveHandlers) { + for (const handler of this.responseHandlers) { + handler.onDone(); + } + } + this.persistentQuery = null; + this.messageChannel = null; + this.queryAbortController = null; + this.responseConsumerRunning = false; + this.currentConfig = null; + if (!preserveHandlers) { + this.responseHandlers = []; + this.currentAllowedTools = null; + } + this.shuttingDown = false; + this.notifyReadyStateChange(); + } + /** + * Checks if the persistent query needs to be restarted based on configuration changes. + */ + needsRestart(newConfig) { + return QueryOptionsBuilder.needsRestart(this.currentConfig, newConfig); + } + /** + * Builds configuration object for tracking changes. + */ + buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths) { + return QueryOptionsBuilder.buildPersistentQueryConfig( + this.buildQueryOptionsContext(vaultPath, cliPath), + externalContextPaths + ); + } + /** + * Builds the base query options context from current state. + */ + buildQueryOptionsContext(vaultPath, cliPath) { + const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables()); + const enhancedPath = getEnhancedPath(customEnv.PATH, cliPath); + return { + vaultPath, + cliPath, + settings: this.plugin.settings, + customEnv, + enhancedPath, + mcpManager: this.mcpManager, + pluginManager: this.plugin.pluginManager + }; + } + /** + * Builds SDK options for the persistent query. + */ + buildPersistentQueryOptions(vaultPath, cliPath, resumeSessionId, externalContextPaths) { + var _a3; + const baseContext = this.buildQueryOptionsContext(vaultPath, cliPath); + const hooks = this.buildHooks(); + const permissionMode = this.plugin.settings.permissionMode; + const ctx = { + ...baseContext, + abortController: (_a3 = this.queryAbortController) != null ? _a3 : void 0, + resumeSessionId, + canUseTool: permissionMode !== "yolo" ? this.createApprovalCallback() : void 0, + hooks, + externalContextPaths + }; + return QueryOptionsBuilder.buildPersistentQueryOptions(ctx); + } + /** + * Builds the hooks for SDK options. + * Hooks need access to `this` for dynamic settings, so they're built here. + * + * @param externalContextPaths - Optional external context paths for cold-start queries. + * If not provided, the closure reads this.currentExternalContextPaths at execution + * time (for persistent queries where the value may change dynamically). + */ + buildHooks(externalContextPaths) { + const blocklistHook = createBlocklistHook(() => ({ + blockedCommands: this.plugin.settings.blockedCommands, + enableBlocklist: this.plugin.settings.enableBlocklist + })); + const vaultRestrictionHook = createVaultRestrictionHook({ + getPathAccessType: (p2) => { + if (!this.vaultPath) return "vault"; + const paths = externalContextPaths != null ? externalContextPaths : this.currentExternalContextPaths; + return getPathAccessType( + p2, + paths, + this.plugin.settings.allowedExportPaths, + this.vaultPath + ); + } + }); + return { + PreToolUse: [blocklistHook, vaultRestrictionHook] + }; + } + /** + * Starts the background consumer loop that routes chunks to handlers. + */ + startResponseConsumer() { + if (this.responseConsumerRunning) { + return; + } + this.responseConsumerRunning = true; + const queryForThisConsumer = this.persistentQuery; + void (async () => { + var _a3; + if (!this.persistentQuery) return; + try { + for await (const message of this.persistentQuery) { + if (this.shuttingDown) break; + await this.routeMessage(message); + } + } catch (error48) { + if (this.persistentQuery !== queryForThisConsumer && this.persistentQuery !== null) { + return; + } + if (!this.shuttingDown && !this.coldStartInProgress) { + const handler = this.responseHandlers[this.responseHandlers.length - 1]; + const errorInstance = error48 instanceof Error ? error48 : new Error(String(error48)); + const messageToReplay = this.lastSentMessage; + if (!this.crashRecoveryAttempted && messageToReplay && handler && !handler.sawAnyChunk) { + this.crashRecoveryAttempted = true; + try { + await this.ensureReady({ force: true, preserveHandlers: true }); + if (!this.messageChannel) { + throw new Error("Persistent query restart did not create message channel"); + } + await this.applyDynamicUpdates((_a3 = this.lastSentQueryOptions) != null ? _a3 : void 0, { preserveHandlers: true }); + this.messageChannel.enqueue(messageToReplay); + return; + } catch (restartError) { + if (isSessionExpiredError(restartError)) { + this.sessionManager.invalidateSession(); + } + handler.onError(errorInstance); + return; + } + } + if (handler) { + handler.onError(errorInstance); + } + if (!this.crashRecoveryAttempted) { + this.crashRecoveryAttempted = true; + try { + await this.ensureReady({ force: true }); + } catch (restartError) { + if (isSessionExpiredError(restartError)) { + this.sessionManager.invalidateSession(); + } + } + } + } + } finally { + if (this.persistentQuery === queryForThisConsumer || this.persistentQuery === null) { + this.responseConsumerRunning = false; + } + } + })(); + } + /** @param modelOverride - Optional model override for cold-start queries */ + getTransformOptions(modelOverride) { + var _a3; + return { + intendedModel: modelOverride != null ? modelOverride : this.plugin.settings.model, + is1MEnabled: (_a3 = this.plugin.settings.show1MModel) != null ? _a3 : false, + customContextLimits: this.plugin.settings.customContextLimits + }; + } + /** + * Routes an SDK message to the active response handler. + * + * Design: Only one handler exists at a time because MessageChannel enforces + * single-turn processing. When a turn is active, new messages are queued/merged. + * The next message only dequeues after onTurnComplete(), which calls onDone() + * on the current handler. A new handler is registered only when the next query starts. + */ + async routeMessage(message) { + var _a3, _b; + const handler = this.responseHandlers[this.responseHandlers.length - 1]; + if (handler && this.isStreamTextEvent(message)) { + handler.markStreamTextSeen(); + } + for (const event of transformSDKMessage(message, this.getTransformOptions())) { + if (isSessionInitEvent(event)) { + this.sessionManager.captureSession(event.sessionId); + (_a3 = this.messageChannel) == null ? void 0 : _a3.setSessionId(event.sessionId); + if (event.agents) { + try { + this.plugin.agentManager.setBuiltinAgentNames(event.agents); + } catch (e2) { + } + } + } else if (isStreamChunk(event)) { + if (message.type === "assistant" && (handler == null ? void 0 : handler.sawStreamText) && event.type === "text") { + continue; + } + if (handler) { + if (event.type === "usage") { + handler.onChunk({ ...event, sessionId: this.sessionManager.getSessionId() }); + } else { + handler.onChunk(event); + } + } + } + } + if (isTurnCompleteMessage(message)) { + (_b = this.messageChannel) == null ? void 0 : _b.onTurnComplete(); + if (handler) { + handler.resetStreamText(); + handler.onDone(); + } + } + } + registerResponseHandler(handler) { + this.responseHandlers.push(handler); + } + unregisterResponseHandler(handlerId) { + const idx = this.responseHandlers.findIndex((h) => h.id === handlerId); + if (idx >= 0) { + this.responseHandlers.splice(idx, 1); + } + } + isPersistentQueryActive() { + return this.persistentQuery !== null && !this.shuttingDown; + } + /** + * Sends a query to Claude and streams the response. + * + * Query selection: + * - Persistent query: default chat conversation + * - Cold-start query: only when forceColdStart is set + */ + async *query(prompt, images, conversationHistory, queryOptions) { + var _a3; + const vaultPath = getVaultPath(this.plugin.app); + if (!vaultPath) { + yield { type: "error", content: "Could not determine vault path" }; + return; + } + const resolvedClaudePath = this.plugin.getResolvedClaudeCliPath(); + if (!resolvedClaudePath) { + yield { type: "error", content: "Claude CLI not found. Please install Claude Code CLI." }; + return; + } + const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables()); + const enhancedPath = getEnhancedPath(customEnv.PATH, resolvedClaudePath); + const missingNodeError = getMissingNodeError(resolvedClaudePath, enhancedPath); + if (missingNodeError) { + yield { type: "error", content: missingNodeError }; + return; + } + let promptToSend = prompt; + let forceColdStart = false; + if (this.sessionManager.wasInterrupted()) { + this.sessionManager.clearInterrupted(); + } + if (this.sessionManager.needsHistoryRebuild() && conversationHistory && conversationHistory.length > 0) { + const historyContext = buildContextFromHistory(conversationHistory); + const actualPrompt = stripCurrentNoteContext(prompt); + promptToSend = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory); + this.sessionManager.clearHistoryRebuild(); + } + const noSessionButHasHistory = !this.sessionManager.getSessionId() && conversationHistory && conversationHistory.length > 0; + if (noSessionButHasHistory) { + const historyContext = buildContextFromHistory(conversationHistory); + const actualPrompt = stripCurrentNoteContext(prompt); + promptToSend = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory); + forceColdStart = true; + } + const effectiveQueryOptions = forceColdStart ? { ...queryOptions, forceColdStart: true } : queryOptions; + if (forceColdStart) { + this.coldStartInProgress = true; + this.closePersistentQuery("session invalidated"); + } + const shouldUsePersistent = !(effectiveQueryOptions == null ? void 0 : effectiveQueryOptions.forceColdStart); + if (shouldUsePersistent) { + if (!this.persistentQuery && !this.shuttingDown) { + await this.startPersistentQuery( + vaultPath, + resolvedClaudePath, + (_a3 = this.sessionManager.getSessionId()) != null ? _a3 : void 0 + ); + } + if (this.persistentQuery && !this.shuttingDown) { + try { + yield* this.queryViaPersistent(promptToSend, images, vaultPath, resolvedClaudePath, effectiveQueryOptions); + return; + } catch (error48) { + if (isSessionExpiredError(error48) && conversationHistory && conversationHistory.length > 0) { + this.sessionManager.invalidateSession(); + const retryRequest = this.buildHistoryRebuildRequest(prompt, conversationHistory); + this.coldStartInProgress = true; + this.abortController = new AbortController(); + try { + yield* this.queryViaSDK( + retryRequest.prompt, + vaultPath, + resolvedClaudePath, + // Use current message's images, fallback to history images + images != null ? images : retryRequest.images, + effectiveQueryOptions + ); + } catch (retryError) { + const msg = retryError instanceof Error ? retryError.message : "Unknown error"; + yield { type: "error", content: msg }; + } finally { + this.coldStartInProgress = false; + this.abortController = null; + } + return; + } + throw error48; + } + } + } + this.coldStartInProgress = true; + this.abortController = new AbortController(); + try { + yield* this.queryViaSDK(promptToSend, vaultPath, resolvedClaudePath, images, effectiveQueryOptions); + } catch (error48) { + if (isSessionExpiredError(error48) && conversationHistory && conversationHistory.length > 0) { + this.sessionManager.invalidateSession(); + const retryRequest = this.buildHistoryRebuildRequest(prompt, conversationHistory); + try { + yield* this.queryViaSDK( + retryRequest.prompt, + vaultPath, + resolvedClaudePath, + // Use current message's images, fallback to history images + images != null ? images : retryRequest.images, + effectiveQueryOptions + ); + } catch (retryError) { + const msg2 = retryError instanceof Error ? retryError.message : "Unknown error"; + yield { type: "error", content: msg2 }; + } + return; + } + const msg = error48 instanceof Error ? error48.message : "Unknown error"; + yield { type: "error", content: msg }; + } finally { + this.coldStartInProgress = false; + this.abortController = null; + } + } + buildHistoryRebuildRequest(prompt, conversationHistory) { + const historyContext = buildContextFromHistory(conversationHistory); + const actualPrompt = stripCurrentNoteContext(prompt); + const fullPrompt = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory); + const lastUserMessage = getLastUserMessage(conversationHistory); + return { + prompt: fullPrompt, + images: lastUserMessage == null ? void 0 : lastUserMessage.images + }; + } + /** + * Query via persistent query (Phase 1.5). + * Uses the message channel to send messages without cold-start latency. + */ + async *queryViaPersistent(prompt, images, vaultPath, cliPath, queryOptions) { + if (!this.persistentQuery || !this.messageChannel) { + yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions); + return; + } + if ((queryOptions == null ? void 0 : queryOptions.allowedTools) !== void 0) { + this.currentAllowedTools = queryOptions.allowedTools.length > 0 ? [...queryOptions.allowedTools, TOOL_SKILL] : []; + } else { + this.currentAllowedTools = null; + } + const savedAllowedTools = this.currentAllowedTools; + await this.applyDynamicUpdates(queryOptions); + this.currentAllowedTools = savedAllowedTools; + if (!this.persistentQuery || !this.messageChannel) { + yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions); + return; + } + if (!this.responseConsumerRunning) { + yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions); + return; + } + const message = this.buildSDKUserMessage(prompt, images); + const state = { + chunks: [], + resolveChunk: null, + done: false, + error: null + }; + const handlerId = `handler-${Date.now()}-${Math.random().toString(36).slice(2)}`; + const handler = createResponseHandler({ + id: handlerId, + onChunk: (chunk) => { + handler.markChunkSeen(); + if (state.resolveChunk) { + state.resolveChunk(chunk); + state.resolveChunk = null; + } else { + state.chunks.push(chunk); + } + }, + onDone: () => { + state.done = true; + if (state.resolveChunk) { + state.resolveChunk(null); + state.resolveChunk = null; + } + }, + onError: (err) => { + state.error = err; + state.done = true; + if (state.resolveChunk) { + state.resolveChunk(null); + state.resolveChunk = null; + } + } + }); + this.registerResponseHandler(handler); + try { + this.lastSentMessage = message; + this.lastSentQueryOptions = queryOptions != null ? queryOptions : null; + this.crashRecoveryAttempted = false; + try { + this.messageChannel.enqueue(message); + } catch (error48) { + if (error48 instanceof Error && error48.message.includes("closed")) { + yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions); + return; + } + throw error48; + } + while (!state.done) { + if (state.chunks.length > 0) { + yield state.chunks.shift(); + } else { + const chunk = await new Promise((resolve4) => { + state.resolveChunk = resolve4; + }); + if (chunk) { + yield chunk; + } + } + } + while (state.chunks.length > 0) { + yield state.chunks.shift(); + } + if (state.error) { + if (isSessionExpiredError(state.error)) { + throw state.error; + } + yield { type: "error", content: state.error.message }; + } + this.lastSentMessage = null; + this.lastSentQueryOptions = null; + yield { type: "done" }; + } finally { + this.unregisterResponseHandler(handlerId); + this.currentAllowedTools = null; + } + } + buildSDKUserMessage(prompt, images) { + const sessionId = this.sessionManager.getSessionId() || ""; + if (!images || images.length === 0) { + return { + type: "user", + message: { + role: "user", + content: prompt + }, + parent_tool_use_id: null, + session_id: sessionId + }; + } + const content = []; + for (const image of images) { + content.push({ + type: "image", + source: { + type: "base64", + media_type: image.mediaType, + data: image.data + } + }); + } + if (prompt.trim()) { + content.push({ + type: "text", + text: prompt + }); + } + return { + type: "user", + message: { + role: "user", + content + }, + parent_tool_use_id: null, + session_id: sessionId + }; + } + /** + * Apply dynamic updates to the persistent query before sending a message (Phase 1.6). + */ + async applyDynamicUpdates(queryOptions, restartOptions, allowRestart = true) { + var _a3, _b, _c; + if (!this.persistentQuery) return; + if (!this.vaultPath) { + return; + } + const cliPath = this.plugin.getResolvedClaudeCliPath(); + if (!cliPath) { + return; + } + const selectedModel = (queryOptions == null ? void 0 : queryOptions.model) || this.plugin.settings.model; + const permissionMode = this.plugin.settings.permissionMode; + const budgetSetting = this.plugin.settings.thinkingBudget; + const budgetConfig = THINKING_BUDGETS.find((b3) => b3.value === budgetSetting); + const thinkingTokens = (_a3 = budgetConfig == null ? void 0 : budgetConfig.tokens) != null ? _a3 : null; + const show1MModel = this.plugin.settings.show1MModel; + if (this.currentConfig && selectedModel !== this.currentConfig.model) { + const resolved = resolveModelWithBetas(selectedModel, show1MModel); + try { + await this.persistentQuery.setModel(resolved.model); + this.currentConfig.model = selectedModel; + } catch (e2) { + } + } + const currentThinking = (_c = (_b = this.currentConfig) == null ? void 0 : _b.thinkingTokens) != null ? _c : null; + if (thinkingTokens !== currentThinking) { + try { + await this.persistentQuery.setMaxThinkingTokens(thinkingTokens); + if (this.currentConfig) { + this.currentConfig.thinkingTokens = thinkingTokens; + } + } catch (e2) { + } + } + if (this.currentConfig && permissionMode !== this.currentConfig.permissionMode) { + const sdkMode = permissionMode === "yolo" ? "bypassPermissions" : "acceptEdits"; + try { + await this.persistentQuery.setPermissionMode(sdkMode); + this.currentConfig.permissionMode = permissionMode; + } catch (e2) { + } + } + const mcpMentions = (queryOptions == null ? void 0 : queryOptions.mcpMentions) || /* @__PURE__ */ new Set(); + const uiEnabledServers = (queryOptions == null ? void 0 : queryOptions.enabledMcpServers) || /* @__PURE__ */ new Set(); + const combinedMentions = /* @__PURE__ */ new Set([...mcpMentions, ...uiEnabledServers]); + const mcpServers = this.mcpManager.getActiveServers(combinedMentions); + const mcpServersKey = JSON.stringify(mcpServers); + if (this.currentConfig && mcpServersKey !== this.currentConfig.mcpServersKey) { + const serverConfigs = {}; + for (const [name, config2] of Object.entries(mcpServers)) { + serverConfigs[name] = config2; + } + try { + await this.persistentQuery.setMcpServers(serverConfigs); + this.currentConfig.mcpServersKey = mcpServersKey; + } catch (e2) { + } + } + const newExternalContextPaths = (queryOptions == null ? void 0 : queryOptions.externalContextPaths) || []; + this.currentExternalContextPaths = newExternalContextPaths; + if (!allowRestart) { + return; + } + const newConfig = this.buildPersistentQueryConfig(this.vaultPath, cliPath, newExternalContextPaths); + if (!this.needsRestart(newConfig)) { + return; + } + const restarted = await this.ensureReady({ + externalContextPaths: newExternalContextPaths, + preserveHandlers: restartOptions == null ? void 0 : restartOptions.preserveHandlers, + force: true + }); + if (restarted && this.persistentQuery) { + await this.applyDynamicUpdates(queryOptions, restartOptions, false); + } + } + isStreamTextEvent(message) { + var _a3, _b; + if (message.type !== "stream_event") return false; + const event = message.event; + if (!event) return false; + if (event.type === "content_block_start") { + return ((_a3 = event.content_block) == null ? void 0 : _a3.type) === "text"; + } + if (event.type === "content_block_delta") { + return ((_b = event.delta) == null ? void 0 : _b.type) === "text_delta"; + } + return false; + } + buildPromptWithImages(prompt, images) { + if (!images || images.length === 0) { + return prompt; + } + const content = []; + for (const image of images) { + content.push({ + type: "image", + source: { + type: "base64", + media_type: image.mediaType, + data: image.data + } + }); + } + if (prompt.trim()) { + content.push({ + type: "text", + text: prompt + }); + } + async function* messageGenerator() { + yield { + type: "user", + message: { + role: "user", + content + } + }; + } + return messageGenerator(); + } + async *queryViaSDK(prompt, cwd, cliPath, images, queryOptions) { + var _a3, _b, _c; + const selectedModel = (queryOptions == null ? void 0 : queryOptions.model) || this.plugin.settings.model; + const permissionMode = this.plugin.settings.permissionMode; + this.sessionManager.setPendingModel(selectedModel); + this.vaultPath = cwd; + const queryPrompt = this.buildPromptWithImages(prompt, images); + const baseContext = this.buildQueryOptionsContext(cwd, cliPath); + const externalContextPaths = (queryOptions == null ? void 0 : queryOptions.externalContextPaths) || []; + const hooks = this.buildHooks(externalContextPaths); + const hasEditorContext = prompt.includes(" 0) { + const toolSet = /* @__PURE__ */ new Set([...queryOptions.allowedTools, TOOL_SKILL]); + allowedTools = [...toolSet]; + } + const ctx = { + ...baseContext, + abortController: (_a3 = this.abortController) != null ? _a3 : void 0, + sessionId: (_b = this.sessionManager.getSessionId()) != null ? _b : void 0, + modelOverride: queryOptions == null ? void 0 : queryOptions.model, + canUseTool: permissionMode !== "yolo" ? this.createApprovalCallback() : void 0, + hooks, + mcpMentions: queryOptions == null ? void 0 : queryOptions.mcpMentions, + enabledMcpServers: queryOptions == null ? void 0 : queryOptions.enabledMcpServers, + allowedTools, + hasEditorContext, + externalContextPaths + }; + const options = QueryOptionsBuilder.buildColdStartQueryOptions(ctx); + let sawStreamText = false; + try { + const response = u_({ prompt: queryPrompt, options }); + let streamSessionId = this.sessionManager.getSessionId(); + for await (const message of response) { + if (this.isStreamTextEvent(message)) { + sawStreamText = true; + } + if ((_c = this.abortController) == null ? void 0 : _c.signal.aborted) { + await response.interrupt(); + break; + } + for (const event of transformSDKMessage(message, this.getTransformOptions(selectedModel))) { + if (isSessionInitEvent(event)) { + this.sessionManager.captureSession(event.sessionId); + streamSessionId = event.sessionId; + } else if (isStreamChunk(event)) { + if (message.type === "assistant" && sawStreamText && event.type === "text") { + continue; + } + if (event.type === "usage") { + yield { ...event, sessionId: streamSessionId }; + } else { + yield event; + } + } + } + if (message.type === "result") { + sawStreamText = false; + } + } + } catch (error48) { + if (isSessionExpiredError(error48)) { + throw error48; + } + const msg = error48 instanceof Error ? error48.message : "Unknown error"; + yield { type: "error", content: msg }; + } finally { + this.sessionManager.clearPendingModel(); + this.currentAllowedTools = null; + } + yield { type: "done" }; + } + cancel() { + var _a3; + (_a3 = this.approvalDismisser) == null ? void 0 : _a3.call(this); + if (this.abortController) { + this.abortController.abort(); + this.sessionManager.markInterrupted(); + } + if (this.persistentQuery && !this.shuttingDown) { + void this.persistentQuery.interrupt().catch(() => { + }); + } + } + /** + * Reset the conversation session. + * Closes the persistent query since session is changing. + */ + resetSession() { + this.closePersistentQuery("session reset"); + this.crashRecoveryAttempted = false; + this.sessionManager.reset(); + } + getSessionId() { + return this.sessionManager.getSessionId(); + } + /** Consume session invalidation flag for persistence updates. */ + consumeSessionInvalidation() { + return this.sessionManager.consumeInvalidation(); + } + /** + * Check if the service is ready (persistent query is active). + * Used to determine if SDK skills are available. + */ + isReady() { + return this.isPersistentQueryActive(); + } + /** + * Get supported commands (SDK skills) from the persistent query. + * Returns an empty array if the query is not ready. + */ + async getSupportedCommands() { + if (!this.persistentQuery) { + return []; + } + try { + const sdkCommands = await this.persistentQuery.supportedCommands(); + return sdkCommands.map((cmd) => ({ + id: `sdk:${cmd.name}`, + name: cmd.name, + description: cmd.description, + argumentHint: cmd.argumentHint, + content: "", + // SDK skills don't need content - they're handled by the SDK + source: "sdk" + })); + } catch (e2) { + return []; + } + } + /** + * Set the session ID (for restoring from saved conversation). + * Closes persistent query synchronously if session is changing, then ensures query is ready. + * + * @param id - Session ID to restore, or null for new session + * @param externalContextPaths - External context paths for the session (prevents stale contexts) + */ + setSessionId(id, externalContextPaths) { + const currentId = this.sessionManager.getSessionId(); + const sessionChanged = currentId !== id; + if (sessionChanged) { + this.closePersistentQuery("session switch"); + this.crashRecoveryAttempted = false; + } + this.sessionManager.setSessionId(id, this.plugin.settings.model); + this.ensureReady({ + sessionId: id != null ? id : void 0, + externalContextPaths + }).catch(() => { + }); + } + /** + * Cleanup resources (Phase 5). + * Called on plugin unload to close persistent query and abort any cold-start query. + */ + cleanup() { + this.closePersistentQuery("plugin cleanup"); + this.cancel(); + this.resetSession(); + } + setApprovalCallback(callback) { + this.approvalCallback = callback; + } + setApprovalDismisser(dismisser) { + this.approvalDismisser = dismisser; + } + createApprovalCallback() { + return async (toolName, input, options) => { + if (this.currentAllowedTools !== null) { + if (!this.currentAllowedTools.includes(toolName) && toolName !== TOOL_SKILL) { + const allowedList = this.currentAllowedTools.length > 0 ? ` Allowed tools: ${this.currentAllowedTools.join(", ")}.` : " No tools are allowed for this query type."; + return { + behavior: "deny", + message: `Tool "${toolName}" is not allowed for this query.${allowedList}` + }; + } + } + if (!this.approvalCallback) { + return { behavior: "deny", message: "No approval handler available." }; + } + try { + const { decisionReason, blockedPath, agentID } = options; + const description = getActionDescription(toolName, input); + const decision = await this.approvalCallback( + toolName, + input, + description, + { decisionReason, blockedPath, agentID } + ); + if (decision === "cancel") { + return { behavior: "deny", message: "User interrupted.", interrupt: true }; + } + if (decision === "allow" || decision === "allow-always") { + const updatedPermissions = buildPermissionUpdates( + toolName, + input, + decision, + options.suggestions + ); + return { behavior: "allow", updatedInput: input, updatedPermissions }; + } + return { behavior: "deny", message: "User denied this action.", interrupt: false }; + } catch (error48) { + return { + behavior: "deny", + message: `Approval request failed: ${error48 instanceof Error ? error48.message : "Unknown error"}`, + interrupt: false + }; + } + }; + } +}; + +// src/core/commands/builtInCommands.ts +var BUILT_IN_COMMANDS = [ + { + name: "clear", + aliases: ["new"], + description: "Start a new conversation", + action: "clear" + }, + { + name: "add-dir", + description: "Add external context directory", + action: "add-dir", + hasArgs: true, + argumentHint: "path/to/directory" + } +]; +var commandMap = /* @__PURE__ */ new Map(); +for (const cmd of BUILT_IN_COMMANDS) { + commandMap.set(cmd.name.toLowerCase(), cmd); + if (cmd.aliases) { + for (const alias of cmd.aliases) { + commandMap.set(alias.toLowerCase(), cmd); + } + } +} +function detectBuiltInCommand(input) { + const trimmed = input.trim(); + if (!trimmed.startsWith("/")) return null; + const match = trimmed.match(/^\/([a-zA-Z0-9_-]+)(?:\s(.*))?$/); + if (!match) return null; + const cmdName = match[1].toLowerCase(); + const command = commandMap.get(cmdName); + if (!command) return null; + const args = (match[2] || "").trim(); + return { command, args }; +} +function getBuiltInCommandsForDropdown() { + return BUILT_IN_COMMANDS.map((cmd) => ({ + id: `builtin:${cmd.name}`, + name: cmd.name, + description: cmd.description, + content: "", + // Built-in commands don't have prompt content + argumentHint: cmd.argumentHint + })); +} + +// src/shared/components/SlashCommandDropdown.ts +var FILTERED_SDK_COMMANDS = /* @__PURE__ */ new Set([ + "context", + "cost", + "init", + "keybindings-help", + "release-notes", + "security-review" +]); +var SlashCommandDropdown = class { + constructor(containerEl, inputEl, callbacks, options = {}) { + this.dropdownEl = null; + this.slashStartIndex = -1; + this.selectedIndex = 0; + this.filteredCommands = []; + // SDK skills cache + this.cachedSdkSkills = []; + this.sdkSkillsFetched = false; + // Race condition guard for async dropdown rendering + this.requestId = 0; + var _a3, _b; + this.containerEl = containerEl; + this.inputEl = inputEl; + this.callbacks = callbacks; + this.isFixed = (_a3 = options.fixed) != null ? _a3 : false; + this.hiddenCommands = (_b = options.hiddenCommands) != null ? _b : /* @__PURE__ */ new Set(); + this.onInput = () => this.handleInputChange(); + this.inputEl.addEventListener("input", this.onInput); + } + setHiddenCommands(commands) { + this.hiddenCommands = commands; + } + handleInputChange() { + const text = this.getInputValue(); + const cursorPos = this.getCursorPosition(); + const textBeforeCursor = text.substring(0, cursorPos); + if (text.charAt(0) !== "/") { + this.hide(); + return; + } + const slashIndex = 0; + const searchText = textBeforeCursor.substring(slashIndex + 1); + if (/\s/.test(searchText)) { + this.hide(); + return; + } + this.slashStartIndex = slashIndex; + this.showDropdown(searchText); + } + handleKeydown(e2) { + if (!this.isVisible()) return false; + switch (e2.key) { + case "ArrowDown": + e2.preventDefault(); + this.navigate(1); + return true; + case "ArrowUp": + e2.preventDefault(); + this.navigate(-1); + return true; + case "Enter": + case "Tab": + if (this.filteredCommands.length > 0) { + e2.preventDefault(); + this.selectItem(); + return true; + } + return false; + case "Escape": + e2.preventDefault(); + this.hide(); + return true; + } + return false; + } + isVisible() { + var _a3, _b; + return (_b = (_a3 = this.dropdownEl) == null ? void 0 : _a3.hasClass("visible")) != null ? _b : false; + } + hide() { + if (this.dropdownEl) { + this.dropdownEl.removeClass("visible"); + } + this.slashStartIndex = -1; + this.callbacks.onHide(); + } + destroy() { + this.inputEl.removeEventListener("input", this.onInput); + if (this.dropdownEl) { + this.dropdownEl.remove(); + this.dropdownEl = null; + } + } + /** + * Resets the SDK skills cache. + * Call this when switching conversations or creating a new chat. + */ + resetSdkSkillsCache() { + this.cachedSdkSkills = []; + this.sdkSkillsFetched = false; + this.requestId = 0; + } + getInputValue() { + return this.inputEl.value; + } + getCursorPosition() { + return this.inputEl.selectionStart || 0; + } + setInputValue(value) { + this.inputEl.value = value; + } + setCursorPosition(pos) { + this.inputEl.selectionStart = pos; + this.inputEl.selectionEnd = pos; + } + async showDropdown(searchText) { + const currentRequest = ++this.requestId; + const builtInCommands = getBuiltInCommandsForDropdown(); + const searchLower = searchText.toLowerCase(); + if (!this.sdkSkillsFetched && this.callbacks.getSdkCommands) { + try { + const sdkCommands = await this.callbacks.getSdkCommands(); + if (currentRequest !== this.requestId) return; + if (sdkCommands.length > 0) { + this.cachedSdkSkills = sdkCommands; + this.sdkSkillsFetched = true; + } + } catch (e2) { + if (currentRequest !== this.requestId) return; + } + } + const allCommands = this.buildCommandList(builtInCommands); + this.filteredCommands = allCommands.filter( + (cmd) => { + var _a3; + return cmd.name.toLowerCase().includes(searchLower) || ((_a3 = cmd.description) == null ? void 0 : _a3.toLowerCase().includes(searchLower)); + } + ).sort((a, b3) => a.name.localeCompare(b3.name)); + if (currentRequest !== this.requestId) return; + if (searchText.length > 0 && this.filteredCommands.length === 0) { + this.hide(); + return; + } + this.selectedIndex = 0; + this.render(); + } + /** + * Builds the merged command list from built-in and SDK commands. + * Built-in commands have highest priority and are not subject to hiding. + * SDK commands are deduplicated, filtered, and respect user hiding. + */ + buildCommandList(builtInCommands) { + const seenNames = /* @__PURE__ */ new Set(); + const allCommands = []; + for (const cmd of builtInCommands) { + const nameLower = cmd.name.toLowerCase(); + if (!seenNames.has(nameLower)) { + seenNames.add(nameLower); + allCommands.push(cmd); + } + } + for (const cmd of this.cachedSdkSkills) { + const nameLower = cmd.name.toLowerCase(); + if (FILTERED_SDK_COMMANDS.has(nameLower) || seenNames.has(nameLower) || this.hiddenCommands.has(nameLower)) { + continue; + } + seenNames.add(nameLower); + allCommands.push(cmd); + } + return allCommands; + } + render() { + if (!this.dropdownEl) { + this.dropdownEl = this.createDropdownElement(); + } + this.dropdownEl.empty(); + if (this.filteredCommands.length === 0) { + const emptyEl = this.dropdownEl.createDiv({ cls: "claudian-slash-empty" }); + emptyEl.setText("No matching commands"); + } else { + for (let i2 = 0; i2 < this.filteredCommands.length; i2++) { + const cmd = this.filteredCommands[i2]; + const itemEl = this.dropdownEl.createDiv({ cls: "claudian-slash-item" }); + if (i2 === this.selectedIndex) { + itemEl.addClass("selected"); + } + const nameEl = itemEl.createSpan({ cls: "claudian-slash-name" }); + nameEl.setText(`/${cmd.name}`); + if (cmd.argumentHint) { + const hintEl = itemEl.createSpan({ cls: "claudian-slash-hint" }); + hintEl.setText(`[${cmd.argumentHint}]`); + } + if (cmd.description) { + const descEl = itemEl.createDiv({ cls: "claudian-slash-desc" }); + descEl.setText(cmd.description); + } + itemEl.addEventListener("click", () => { + this.selectedIndex = i2; + this.selectItem(); + }); + itemEl.addEventListener("mouseenter", () => { + this.selectedIndex = i2; + this.updateSelection(); + }); + } + } + this.dropdownEl.addClass("visible"); + if (this.isFixed) { + this.positionFixed(); + } + } + createDropdownElement() { + if (this.isFixed) { + const dropdown = this.containerEl.createDiv({ + cls: "claudian-slash-dropdown claudian-slash-dropdown-fixed" + }); + return dropdown; + } else { + return this.containerEl.createDiv({ cls: "claudian-slash-dropdown" }); + } + } + positionFixed() { + if (!this.dropdownEl || !this.isFixed) return; + const inputRect = this.inputEl.getBoundingClientRect(); + this.dropdownEl.style.position = "fixed"; + this.dropdownEl.style.bottom = `${window.innerHeight - inputRect.top + 4}px`; + this.dropdownEl.style.left = `${inputRect.left}px`; + this.dropdownEl.style.right = "auto"; + this.dropdownEl.style.width = `${Math.max(inputRect.width, 280)}px`; + this.dropdownEl.style.zIndex = "10001"; + } + navigate(direction) { + const maxIndex = this.filteredCommands.length - 1; + this.selectedIndex = Math.max(0, Math.min(maxIndex, this.selectedIndex + direction)); + this.updateSelection(); + } + updateSelection() { + var _a3; + const items = (_a3 = this.dropdownEl) == null ? void 0 : _a3.querySelectorAll(".claudian-slash-item"); + items == null ? void 0 : items.forEach((item, index) => { + if (index === this.selectedIndex) { + item.addClass("selected"); + item.scrollIntoView({ block: "nearest" }); + } else { + item.removeClass("selected"); + } + }); + } + selectItem() { + if (this.filteredCommands.length === 0) return; + const selected = this.filteredCommands[this.selectedIndex]; + if (!selected) return; + const text = this.getInputValue(); + const beforeSlash = text.substring(0, this.slashStartIndex); + const afterCursor = text.substring(this.getCursorPosition()); + const replacement = `/${selected.name} `; + this.setInputValue(beforeSlash + replacement + afterCursor); + this.setCursorPosition(beforeSlash.length + replacement.length); + this.hide(); + this.callbacks.onSelect(selected); + this.inputEl.focus(); + } +}; + +// src/features/chat/controllers/ConversationController.ts +var import_obsidian8 = require("obsidian"); + +// src/features/chat/rendering/MessageRenderer.ts +var import_obsidian7 = require("obsidian"); + +// src/utils/fileLink.ts +var WIKILINK_PATTERN_SOURCE = "(?= 0 ? inner.slice(0, pipeIndex) : inner; +} +function findWikilinks(app, text) { + const pattern = createWikilinkPattern(); + const matches = []; + let match; + while ((match = pattern.exec(text)) !== null) { + const fullMatch = match[0]; + const linkPath = match[1]; + const linkTarget = extractLinkTarget(fullMatch); + if (!fileExistsInVault(app, linkPath)) continue; + const pipeIndex = fullMatch.lastIndexOf("|"); + const displayText = pipeIndex > 0 ? fullMatch.slice(pipeIndex + 1, -2) : linkPath; + matches.push({ index: match.index, fullMatch, linkPath, linkTarget, displayText }); + } + return matches.sort((a, b3) => b3.index - a.index); +} +function fileExistsInVault(app, linkPath) { + const file2 = app.metadataCache.getFirstLinkpathDest(linkPath, ""); + if (file2) { + return true; + } + const directFile = app.vault.getFileByPath(linkPath); + if (directFile) { + return true; + } + if (!linkPath.endsWith(".md")) { + const withExt = app.vault.getFileByPath(linkPath + ".md"); + if (withExt) { + return true; + } + } + return false; +} +function createWikilink(linkTarget, displayText) { + const link = document.createElement("a"); + link.className = "claudian-file-link internal-link"; + link.textContent = displayText; + link.setAttribute("data-href", linkTarget); + link.setAttribute("href", linkTarget); + return link; +} +function registerFileLinkHandler(app, container, component) { + component.registerDomEvent(container, "click", (event) => { + const target = event.target; + const link = target.closest(".claudian-file-link, .internal-link"); + if (link) { + event.preventDefault(); + const linkTarget = link.dataset.href || link.getAttribute("href"); + if (linkTarget) { + void app.workspace.openLinkText(linkTarget, "", "tab"); + } + } + }); +} +function buildFragmentWithLinks(text, matches) { + const fragment = document.createDocumentFragment(); + let currentIndex = text.length; + for (const { index, fullMatch, linkTarget, displayText } of matches) { + const endIndex = index + fullMatch.length; + if (endIndex < currentIndex) { + fragment.insertBefore( + document.createTextNode(text.slice(endIndex, currentIndex)), + fragment.firstChild + ); + } + fragment.insertBefore(createWikilink(linkTarget, displayText), fragment.firstChild); + currentIndex = index; + } + if (currentIndex > 0) { + fragment.insertBefore( + document.createTextNode(text.slice(0, currentIndex)), + fragment.firstChild + ); + } + return fragment; +} +function processTextNode(app, node) { + var _a3; + const text = node.textContent; + if (!text || !text.includes("[[")) return false; + const matches = findWikilinks(app, text); + if (matches.length === 0) return false; + (_a3 = node.parentNode) == null ? void 0 : _a3.replaceChild(buildFragmentWithLinks(text, matches), node); + return true; +} +function processFileLinks(app, container) { + if (!app || !container) return; + container.querySelectorAll("code").forEach((codeEl) => { + var _a3; + if (((_a3 = codeEl.parentElement) == null ? void 0 : _a3.tagName) === "PRE") return; + const text = codeEl.textContent; + if (!text || !text.includes("[[")) return; + const matches = findWikilinks(app, text); + if (matches.length === 0) return; + codeEl.textContent = ""; + codeEl.appendChild(buildFragmentWithLinks(text, matches)); + }); + const walker = document.createTreeWalker( + container, + NodeFilter.SHOW_TEXT, + { + acceptNode(node2) { + const parent = node2.parentElement; + if (!parent) return NodeFilter.FILTER_REJECT; + const tagName = parent.tagName.toUpperCase(); + if (tagName === "PRE" || tagName === "CODE" || tagName === "A") { + return NodeFilter.FILTER_REJECT; + } + if (parent.closest("pre, code, a, .claudian-file-link, .internal-link")) { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; + } + } + ); + const textNodes = []; + let node; + while (node = walker.nextNode()) { + textNodes.push(node); + } + for (const textNode of textNodes) { + processTextNode(app, textNode); + } +} + +// src/utils/imageEmbed.ts +var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([ + "png", + "jpg", + "jpeg", + "gif", + "webp", + "svg", + "bmp", + "ico" +]); +var IMAGE_EMBED_PATTERN = /!\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g; +function isImagePath(path10) { + var _a3; + const ext = (_a3 = path10.split(".").pop()) == null ? void 0 : _a3.toLowerCase(); + return ext ? IMAGE_EXTENSIONS.has(ext) : false; +} +function resolveImageFile(app, imagePath, mediaFolder) { + let file2 = app.vault.getFileByPath(imagePath); + if (file2) return file2; + if (mediaFolder) { + const withFolder = `${mediaFolder}/${imagePath}`; + file2 = app.vault.getFileByPath(withFolder); + if (file2) return file2; + } + const resolved = app.metadataCache.getFirstLinkpathDest(imagePath, ""); + if (resolved) return resolved; + return null; +} +function escapeHtml(str) { + return str.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +} +function buildStyleAttribute(altText) { + if (!altText) return ""; + const dimMatch = altText.match(/^(\d+)(?:x(\d+))?$/); + if (!dimMatch) return ""; + const width = dimMatch[1]; + const height = dimMatch[2]; + if (height) { + return ` style="width: ${width}px; height: ${height}px;"`; + } + return ` style="width: ${width}px;"`; +} +function createImageHtml(app, file2, altText) { + const src = app.vault.getResourcePath(file2); + const alt = escapeHtml(altText || file2.basename); + const style = buildStyleAttribute(altText); + return `${alt}`; +} +function createFallbackHtml(wikilink) { + return `${escapeHtml(wikilink)}`; +} +function replaceImageEmbedsWithHtml(markdown, app, mediaFolder = "") { + if (!(app == null ? void 0 : app.vault) || !(app == null ? void 0 : app.metadataCache)) { + return markdown; + } + IMAGE_EMBED_PATTERN.lastIndex = 0; + return markdown.replace( + IMAGE_EMBED_PATTERN, + (match, imagePath, altText) => { + try { + if (!isImagePath(imagePath)) { + return match; + } + const file2 = resolveImageFile(app, imagePath, mediaFolder); + if (!file2) { + return createFallbackHtml(match); + } + return createImageHtml(app, file2, altText); + } catch (e2) { + return createFallbackHtml(match); + } + } + ); +} + +// src/features/chat/rendering/SubagentRenderer.ts +var import_obsidian5 = require("obsidian"); + +// src/core/tools/todo.ts +function isValidTodoItem(item) { + if (typeof item !== "object" || item === null) return false; + const record2 = item; + return typeof record2.content === "string" && record2.content.length > 0 && typeof record2.activeForm === "string" && record2.activeForm.length > 0 && typeof record2.status === "string" && ["pending", "in_progress", "completed"].includes(record2.status); +} +function parseTodoInput(input) { + if (!input.todos || !Array.isArray(input.todos)) { + return null; + } + const validTodos = []; + for (const item of input.todos) { + if (isValidTodoItem(item)) { + validTodos.push(item); + } + } + return validTodos.length > 0 ? validTodos : null; +} + +// src/core/tools/toolIcons.ts +var TOOL_ICONS = { + [TOOL_READ]: "file-text", + [TOOL_WRITE]: "file-plus", + [TOOL_EDIT]: "file-pen", + [TOOL_NOTEBOOK_EDIT]: "file-pen", + [TOOL_BASH]: "terminal", + [TOOL_BASH_OUTPUT]: "terminal", + [TOOL_KILL_SHELL]: "terminal", + [TOOL_GLOB]: "folder-search", + [TOOL_GREP]: "search", + [TOOL_LS]: "list", + [TOOL_TODO_WRITE]: "list-checks", + [TOOL_TASK]: "bot", + [TOOL_LIST_MCP_RESOURCES]: "list", + [TOOL_READ_MCP_RESOURCE]: "file-text", + [TOOL_MCP]: "wrench", + [TOOL_WEB_SEARCH]: "globe", + [TOOL_WEB_FETCH]: "download", + [TOOL_AGENT_OUTPUT]: "bot", + [TOOL_SKILL]: "zap" +}; +var MCP_ICON_MARKER = "__mcp_icon__"; +function getToolIcon(toolName) { + if (toolName.startsWith("mcp__")) { + return MCP_ICON_MARKER; + } + return TOOL_ICONS[toolName] || "wrench"; +} + +// src/features/chat/rendering/collapsible.ts +function setupCollapsible(wrapperEl, headerEl, contentEl, state, options = {}) { + const { initiallyExpanded = false, onToggle, baseAriaLabel } = options; + const updateAriaLabel = (isExpanded) => { + if (baseAriaLabel) { + const action = isExpanded ? "click to collapse" : "click to expand"; + headerEl.setAttribute("aria-label", `${baseAriaLabel} - ${action}`); + } + }; + state.isExpanded = initiallyExpanded; + if (initiallyExpanded) { + wrapperEl.addClass("expanded"); + contentEl.style.display = "block"; + headerEl.setAttribute("aria-expanded", "true"); + } else { + contentEl.style.display = "none"; + headerEl.setAttribute("aria-expanded", "false"); + } + updateAriaLabel(initiallyExpanded); + const toggleExpand = () => { + state.isExpanded = !state.isExpanded; + if (state.isExpanded) { + wrapperEl.addClass("expanded"); + contentEl.style.display = "block"; + headerEl.setAttribute("aria-expanded", "true"); + } else { + wrapperEl.removeClass("expanded"); + contentEl.style.display = "none"; + headerEl.setAttribute("aria-expanded", "false"); + } + updateAriaLabel(state.isExpanded); + onToggle == null ? void 0 : onToggle(state.isExpanded); + }; + headerEl.addEventListener("click", toggleExpand); + headerEl.addEventListener("keydown", (e2) => { + if (e2.key === "Enter" || e2.key === " ") { + e2.preventDefault(); + toggleExpand(); + } + }); +} +function collapseElement(wrapperEl, headerEl, contentEl, state) { + state.isExpanded = false; + wrapperEl.removeClass("expanded"); + contentEl.style.display = "none"; + headerEl.setAttribute("aria-expanded", "false"); +} + +// src/features/chat/rendering/ToolCallRenderer.ts +var import_obsidian4 = require("obsidian"); + +// src/shared/icons.ts +var MCP_ICON_SVG = `MCP`; +var CHECK_ICON_SVG = ``; + +// src/features/chat/rendering/todoUtils.ts +var import_obsidian3 = require("obsidian"); +function getTodoStatusIcon(status) { + return status === "completed" ? "check" : "dot"; +} +function getTodoDisplayText(todo) { + return todo.status === "in_progress" ? todo.activeForm : todo.content; +} +function renderTodoItems(container, todos) { + container.empty(); + for (const todo of todos) { + const item = container.createDiv({ cls: `claudian-todo-item claudian-todo-${todo.status}` }); + const icon = item.createSpan({ cls: "claudian-todo-status-icon" }); + icon.setAttribute("aria-hidden", "true"); + (0, import_obsidian3.setIcon)(icon, getTodoStatusIcon(todo.status)); + const text = item.createSpan({ cls: "claudian-todo-text" }); + text.setText(getTodoDisplayText(todo)); + } +} + +// src/features/chat/rendering/ToolCallRenderer.ts +function setToolIcon(el, name) { + const icon = getToolIcon(name); + if (icon === MCP_ICON_MARKER) { + el.innerHTML = MCP_ICON_SVG; + } else { + (0, import_obsidian4.setIcon)(el, icon); + } +} +function getToolLabel(name, input) { + switch (name) { + case TOOL_READ: + return `Read: ${shortenPath(input.file_path) || "file"}`; + case TOOL_WRITE: + return `Write: ${shortenPath(input.file_path) || "file"}`; + case TOOL_EDIT: + return `Edit: ${shortenPath(input.file_path) || "file"}`; + case TOOL_BASH: { + const cmd = input.command || "command"; + return `Bash: ${cmd.length > 40 ? cmd.substring(0, 40) + "..." : cmd}`; + } + case TOOL_GLOB: + return `Glob: ${input.pattern || "files"}`; + case TOOL_GREP: + return `Grep: ${input.pattern || "pattern"}`; + case TOOL_WEB_SEARCH: { + const query = input.query || "search"; + return `WebSearch: ${query.length > 40 ? query.substring(0, 40) + "..." : query}`; + } + case TOOL_WEB_FETCH: { + const url2 = input.url || "url"; + return `WebFetch: ${url2.length > 40 ? url2.substring(0, 40) + "..." : url2}`; + } + case TOOL_LS: + return `LS: ${shortenPath(input.path) || "."}`; + case TOOL_TODO_WRITE: { + const todos = input.todos; + if (todos && Array.isArray(todos)) { + const completed = todos.filter((t2) => t2.status === "completed").length; + return `Tasks (${completed}/${todos.length})`; + } + return "Tasks"; + } + case TOOL_SKILL: { + const skillName = input.skill || "skill"; + return `Skill: ${skillName}`; + } + default: + return name; + } +} +function shortenPath(filePath) { + if (!filePath) return ""; + const normalized = filePath.replace(/\\/g, "/"); + const parts = normalized.split("/"); + if (parts.length <= 3) return normalized; + return ".../" + parts.slice(-2).join("/"); +} +function parseWebSearchResult(result) { + const linksMatch = result.match(/Links:\s*(\[[\s\S]*\])/); + if (!linksMatch) return null; + try { + const links = JSON.parse(linksMatch[1]); + if (!Array.isArray(links) || links.length === 0) return null; + return links; + } catch (e2) { + return null; + } +} +function renderWebSearchResult(container, result, maxItems = 3) { + const links = parseWebSearchResult(result); + if (!links) return false; + container.empty(); + const displayItems = links.slice(0, maxItems); + displayItems.forEach((link) => { + const item = container.createSpan({ cls: "claudian-tool-result-bullet" }); + item.setText(`\u2022 ${link.title}`); + }); + if (links.length > maxItems) { + const more = container.createSpan({ cls: "claudian-tool-result-item" }); + more.setText(`${links.length - maxItems} more results`); + } + return true; +} +function renderReadResult(container, result) { + container.empty(); + const lines = result.split(/\r?\n/).filter((line) => line.trim() !== ""); + const item = container.createSpan({ cls: "claudian-tool-result-item" }); + item.setText(`${lines.length} lines read`); +} +function getTodos(input) { + const todos = input.todos; + if (!todos || !Array.isArray(todos)) return void 0; + return todos; +} +function getCurrentTask(input) { + const todos = getTodos(input); + if (!todos) return void 0; + return todos.find((t2) => t2.status === "in_progress"); +} +function areAllTodosCompleted(input) { + const todos = getTodos(input); + if (!todos || todos.length === 0) return false; + return todos.every((t2) => t2.status === "completed"); +} +function resetStatusElement(statusEl, statusClass, ariaLabel) { + statusEl.className = "claudian-tool-status"; + statusEl.empty(); + statusEl.addClass(statusClass); + statusEl.setAttribute("aria-label", ariaLabel); +} +var STATUS_ICONS = { + completed: "check", + error: "x", + blocked: "shield-off" +}; +function setTodoWriteStatus(statusEl, input) { + const isComplete = areAllTodosCompleted(input); + const status = isComplete ? "completed" : "running"; + const ariaLabel = isComplete ? "Status: completed" : "Status: in progress"; + resetStatusElement(statusEl, `status-${status}`, ariaLabel); + if (isComplete) (0, import_obsidian4.setIcon)(statusEl, "check"); +} +function setToolStatus(statusEl, status) { + resetStatusElement(statusEl, `status-${status}`, `Status: ${status}`); + const icon = STATUS_ICONS[status]; + if (icon) (0, import_obsidian4.setIcon)(statusEl, icon); +} +function renderToolResultContent(container, toolName, result) { + if (!result) { + container.setText("No result"); + return; + } + if (toolName === TOOL_WEB_SEARCH) { + if (!renderWebSearchResult(container, result, 3)) { + renderResultLines(container, result, 3); + } + } else if (toolName === TOOL_READ) { + renderReadResult(container, result); + } else { + renderResultLines(container, result, 3); + } +} +function createCurrentTaskPreview(header, input) { + const currentTaskEl = header.createSpan({ cls: "claudian-tool-current" }); + const currentTask = getCurrentTask(input); + if (currentTask) { + currentTaskEl.setText(currentTask.activeForm); + } + return currentTaskEl; +} +function createTodoToggleHandler(currentTaskEl, statusEl, onExpandChange) { + return (expanded) => { + if (onExpandChange) onExpandChange(expanded); + if (currentTaskEl) { + currentTaskEl.style.display = expanded ? "none" : ""; + } + if (statusEl) { + statusEl.style.display = expanded ? "none" : ""; + } + }; +} +function renderTodoWriteResult(container, input) { + container.empty(); + container.addClass("claudian-todo-panel-content"); + container.addClass("claudian-todo-list-container"); + const todos = input.todos; + if (!todos || !Array.isArray(todos)) { + const item = container.createSpan({ cls: "claudian-tool-result-item" }); + item.setText("Tasks updated"); + return; + } + renderTodoItems(container, todos); +} +function renderResultLines(container, result, maxLines = 3) { + container.empty(); + const lines = result.split(/\r?\n/); + const displayLines = lines.slice(0, maxLines); + displayLines.forEach((line) => { + const stripped = line.replace(/^\s*\d+→/, ""); + const item = container.createSpan({ cls: "claudian-tool-result-item" }); + item.setText(stripped); + }); + if (lines.length > maxLines) { + const more = container.createSpan({ cls: "claudian-tool-result-item" }); + more.setText(`${lines.length - maxLines} more lines`); + } +} +function isBlockedToolResult(content, isError) { + const lower = content.toLowerCase(); + if (lower.includes("blocked by blocklist")) return true; + if (lower.includes("outside the vault")) return true; + if (lower.includes("access denied")) return true; + if (lower.includes("user denied")) return true; + if (lower.includes("approval")) return true; + if (isError && lower.includes("deny")) return true; + return false; +} +function createToolElementStructure(parentEl, toolCall) { + const toolEl = parentEl.createDiv({ cls: "claudian-tool-call" }); + const header = toolEl.createDiv({ cls: "claudian-tool-header" }); + header.setAttribute("tabindex", "0"); + header.setAttribute("role", "button"); + const iconEl = header.createSpan({ cls: "claudian-tool-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + setToolIcon(iconEl, toolCall.name); + const labelEl = header.createSpan({ cls: "claudian-tool-label" }); + labelEl.setText(getToolLabel(toolCall.name, toolCall.input)); + const currentTaskEl = toolCall.name === TOOL_TODO_WRITE ? createCurrentTaskPreview(header, toolCall.input) : null; + const statusEl = header.createSpan({ cls: "claudian-tool-status" }); + const content = toolEl.createDiv({ cls: "claudian-tool-content" }); + return { toolEl, header, labelEl, statusEl, content, currentTaskEl }; +} +function renderToolContent(content, toolCall, initialText) { + if (toolCall.name === TOOL_TODO_WRITE) { + content.addClass("claudian-tool-content-todo"); + renderTodoWriteResult(content, toolCall.input); + } else { + const resultRow = content.createDiv({ cls: "claudian-tool-result-row" }); + const resultText = resultRow.createSpan({ cls: "claudian-tool-result-text" }); + if (initialText) { + resultText.setText(initialText); + } else { + renderToolResultContent(resultText, toolCall.name, toolCall.result); + } + } +} +function renderToolCall(parentEl, toolCall, toolCallElements) { + const { toolEl, header, statusEl, content, currentTaskEl } = createToolElementStructure(parentEl, toolCall); + toolEl.dataset.toolId = toolCall.id; + toolCallElements.set(toolCall.id, toolEl); + statusEl.addClass(`status-${toolCall.status}`); + statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`); + renderToolContent(content, toolCall, "Running..."); + const state = { isExpanded: false }; + toolCall.isExpanded = false; + const todoStatusEl = toolCall.name === TOOL_TODO_WRITE ? statusEl : null; + setupCollapsible(toolEl, header, content, state, { + initiallyExpanded: false, + onToggle: createTodoToggleHandler(currentTaskEl, todoStatusEl, (expanded) => { + toolCall.isExpanded = expanded; + }), + baseAriaLabel: getToolLabel(toolCall.name, toolCall.input) + }); + return toolEl; +} +function updateToolCallResult(toolId, toolCall, toolCallElements) { + const toolEl = toolCallElements.get(toolId); + if (!toolEl) return; + if (toolCall.name === TOOL_TODO_WRITE) { + const statusEl2 = toolEl.querySelector(".claudian-tool-status"); + if (statusEl2) { + setTodoWriteStatus(statusEl2, toolCall.input); + } + const content = toolEl.querySelector(".claudian-tool-content"); + if (content) { + renderTodoWriteResult(content, toolCall.input); + } + const labelEl = toolEl.querySelector(".claudian-tool-label"); + if (labelEl) { + labelEl.setText(getToolLabel(toolCall.name, toolCall.input)); + } + const currentTaskEl = toolEl.querySelector(".claudian-tool-current"); + if (currentTaskEl) { + const currentTask = getCurrentTask(toolCall.input); + currentTaskEl.setText(currentTask ? currentTask.activeForm : ""); + } + return; + } + const statusEl = toolEl.querySelector(".claudian-tool-status"); + if (statusEl) { + setToolStatus(statusEl, toolCall.status); + } + const resultText = toolEl.querySelector(".claudian-tool-result-text"); + if (resultText) { + renderToolResultContent(resultText, toolCall.name, toolCall.result); + } +} +function renderStoredToolCall(parentEl, toolCall) { + const { toolEl, header, statusEl, content, currentTaskEl } = createToolElementStructure(parentEl, toolCall); + if (toolCall.name === TOOL_TODO_WRITE) { + setTodoWriteStatus(statusEl, toolCall.input); + } else { + setToolStatus(statusEl, toolCall.status); + } + renderToolContent(content, toolCall); + const state = { isExpanded: false }; + const todoStatusEl = toolCall.name === TOOL_TODO_WRITE ? statusEl : null; + setupCollapsible(toolEl, header, content, state, { + initiallyExpanded: false, + onToggle: createTodoToggleHandler(currentTaskEl, todoStatusEl), + baseAriaLabel: getToolLabel(toolCall.name, toolCall.input) + }); + return toolEl; +} + +// src/features/chat/rendering/SubagentRenderer.ts +function extractTaskDescription(input) { + return input.description || "Subagent task"; +} +function truncateDescription(description, maxLength = 40) { + if (description.length <= maxLength) return description; + return description.substring(0, maxLength) + "..."; +} +function truncateResult(result) { + const lines = result.split(/\r?\n/).filter((line) => line.trim()); + if (lines.length <= 2) { + return lines.join("\n"); + } + return lines.slice(0, 2).join("\n") + "..."; +} +function createStatusRow(parentEl, text, options) { + const rowEl = parentEl.createDiv({ cls: "claudian-subagent-done" }); + if (options == null ? void 0 : options.rowClass) rowEl.addClass(options.rowClass); + const textEl = rowEl.createDiv({ cls: "claudian-subagent-done-text" }); + if (options == null ? void 0 : options.textClass) textEl.addClass(options.textClass); + textEl.setText(text); + return rowEl; +} +function createSubagentBlock(parentEl, taskToolId, taskInput) { + const description = extractTaskDescription(taskInput); + const info = { + id: taskToolId, + description, + status: "running", + toolCalls: [], + isExpanded: false + // Collapsed by default + }; + const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); + wrapperEl.dataset.subagentId = taskToolId; + const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); + headerEl.setAttribute("tabindex", "0"); + headerEl.setAttribute("role", "button"); + headerEl.setAttribute("aria-expanded", "false"); + headerEl.setAttribute("aria-label", `Subagent task: ${truncateDescription(description)} - click to expand`); + const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + (0, import_obsidian5.setIcon)(iconEl, getToolIcon(TOOL_TASK)); + const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); + labelEl.setText(truncateDescription(description)); + const countEl = headerEl.createDiv({ cls: "claudian-subagent-count" }); + countEl.setText("0 tool uses"); + const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" }); + statusEl.setAttribute("aria-label", "Status: running"); + const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); + setupCollapsible(wrapperEl, headerEl, contentEl, info); + return { + wrapperEl, + contentEl, + headerEl, + labelEl, + countEl, + statusEl, + info, + currentToolEl: null, + currentResultEl: null + }; +} +function addSubagentToolCall(state, toolCall) { + state.info.toolCalls.push(toolCall); + const toolCount = state.info.toolCalls.length; + state.countEl.setText(`${toolCount} tool uses`); + state.contentEl.empty(); + state.currentResultEl = null; + const itemEl = state.contentEl.createDiv({ + cls: `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}` + }); + itemEl.dataset.toolId = toolCall.id; + state.currentToolEl = itemEl; + const toolRowEl = itemEl.createDiv({ cls: "claudian-subagent-tool-row" }); + const labelEl = toolRowEl.createDiv({ cls: "claudian-subagent-tool-text" }); + labelEl.setText(getToolLabel(toolCall.name, toolCall.input)); +} +function updateSubagentToolResult(state, toolId, toolCall) { + const idx = state.info.toolCalls.findIndex((tc) => tc.id === toolId); + if (idx !== -1) { + state.info.toolCalls[idx] = toolCall; + } + if (state.currentToolEl && state.currentToolEl.dataset.toolId === toolId) { + state.currentToolEl.className = `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}`; + if (toolCall.result) { + if (!state.currentResultEl) { + state.currentResultEl = state.currentToolEl.createDiv({ cls: "claudian-subagent-tool-result" }); + const bulletEl = state.currentResultEl.createDiv({ cls: "claudian-subagent-bullet" }); + bulletEl.setText("\u2022"); + const textEl = state.currentResultEl.createDiv({ cls: "claudian-subagent-result-text" }); + textEl.setText(truncateResult(toolCall.result)); + } else { + const textEl = state.currentResultEl.querySelector(".claudian-subagent-result-text"); + if (textEl) { + textEl.setText(truncateResult(toolCall.result)); + } + } + } + } +} +function finalizeSubagentBlock(state, result, isError) { + state.info.status = isError ? "error" : "completed"; + state.info.result = result; + state.labelEl.setText(truncateDescription(state.info.description)); + const toolCount = state.info.toolCalls.length; + state.countEl.setText(`${toolCount} tool uses`); + state.statusEl.className = "claudian-subagent-status"; + state.statusEl.addClass(`status-${state.info.status}`); + state.statusEl.empty(); + if (state.info.status === "completed") { + (0, import_obsidian5.setIcon)(state.statusEl, "check"); + } else { + (0, import_obsidian5.setIcon)(state.statusEl, "x"); + } + if (state.info.status === "completed") { + state.wrapperEl.addClass("done"); + } else if (state.info.status === "error") { + state.wrapperEl.addClass("error"); + } + state.contentEl.empty(); + state.currentToolEl = null; + state.currentResultEl = null; + createStatusRow(state.contentEl, isError ? "ERROR" : "DONE"); +} +function renderStoredSubagent(parentEl, subagent) { + const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); + if (subagent.status === "completed") { + wrapperEl.addClass("done"); + } else if (subagent.status === "error") { + wrapperEl.addClass("error"); + } + wrapperEl.dataset.subagentId = subagent.id; + const toolCount = subagent.toolCalls.length; + const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); + headerEl.setAttribute("tabindex", "0"); + headerEl.setAttribute("role", "button"); + headerEl.setAttribute("aria-label", `Subagent task: ${truncateDescription(subagent.description)} - ${toolCount} tool uses - Status: ${subagent.status}`); + const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + (0, import_obsidian5.setIcon)(iconEl, getToolIcon(TOOL_TASK)); + const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); + labelEl.setText(truncateDescription(subagent.description)); + const countEl = headerEl.createDiv({ cls: "claudian-subagent-count" }); + countEl.setText(`${toolCount} tool uses`); + const statusEl = headerEl.createDiv({ cls: `claudian-subagent-status status-${subagent.status}` }); + statusEl.setAttribute("aria-label", `Status: ${subagent.status}`); + if (subagent.status === "completed") { + (0, import_obsidian5.setIcon)(statusEl, "check"); + } else if (subagent.status === "error") { + (0, import_obsidian5.setIcon)(statusEl, "x"); + } + const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); + if (subagent.status === "completed" || subagent.status === "error") { + createStatusRow(contentEl, subagent.status === "error" ? "ERROR" : "DONE"); + } else { + const lastTool = subagent.toolCalls[subagent.toolCalls.length - 1]; + if (lastTool) { + const itemEl = contentEl.createDiv({ + cls: `claudian-subagent-tool-item claudian-subagent-tool-${lastTool.status}` + }); + const toolRowEl = itemEl.createDiv({ cls: "claudian-subagent-tool-row" }); + const toolLabelEl = toolRowEl.createDiv({ cls: "claudian-subagent-tool-text" }); + toolLabelEl.setText(getToolLabel(lastTool.name, lastTool.input)); + if (lastTool.result) { + const resultEl = itemEl.createDiv({ cls: "claudian-subagent-tool-result" }); + const bulletEl = resultEl.createDiv({ cls: "claudian-subagent-bullet" }); + bulletEl.setText("\u2022"); + const textEl = resultEl.createDiv({ cls: "claudian-subagent-result-text" }); + textEl.setText(truncateResult(lastTool.result)); + } + } + } + const state = { isExpanded: false }; + setupCollapsible(wrapperEl, headerEl, contentEl, state); + return wrapperEl; +} +function setAsyncWrapperStatus(wrapperEl, status) { + const classes = ["pending", "running", "awaiting", "completed", "error", "orphaned", "async"]; + classes.forEach((cls) => wrapperEl.removeClass(cls)); + wrapperEl.addClass("async"); + wrapperEl.addClass(status); +} +function getAsyncDisplayStatus(asyncStatus) { + switch (asyncStatus) { + case "completed": + return "completed"; + case "error": + return "error"; + case "orphaned": + return "orphaned"; + default: + return "running"; + } +} +function getAsyncStatusText(asyncStatus) { + switch (asyncStatus) { + case "pending": + return "Initializing"; + case "completed": + return ""; + // Just show tick icon, no text + case "error": + return "Error"; + case "orphaned": + return "Orphaned"; + default: + return "Running in background"; + } +} +function getAsyncStatusAriaLabel(asyncStatus) { + switch (asyncStatus) { + case "pending": + return "Initializing"; + case "completed": + return "Completed"; + case "error": + return "Error"; + case "orphaned": + return "Orphaned"; + default: + return "Running in background"; + } +} +function updateAsyncLabel(state) { + state.labelEl.setText(truncateDescription(state.info.description)); +} +function truncatePrompt(prompt, maxLength = 200) { + if (!prompt) return ""; + if (prompt.length <= maxLength) return prompt; + return prompt.substring(0, maxLength) + "..."; +} +function createAsyncSubagentBlock(parentEl, taskToolId, taskInput) { + const description = taskInput.description || "Background task"; + const prompt = taskInput.prompt || ""; + const info = { + id: taskToolId, + description, + prompt, + mode: "async", + status: "running", + toolCalls: [], + isExpanded: false, + asyncStatus: "pending" + }; + const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); + setAsyncWrapperStatus(wrapperEl, "pending"); + wrapperEl.dataset.asyncSubagentId = taskToolId; + const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); + headerEl.setAttribute("tabindex", "0"); + headerEl.setAttribute("role", "button"); + headerEl.setAttribute("aria-expanded", "false"); + headerEl.setAttribute("aria-label", `Background task: ${description} - click to expand`); + const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + (0, import_obsidian5.setIcon)(iconEl, getToolIcon(TOOL_TASK)); + const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); + labelEl.setText(truncateDescription(description)); + const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" }); + statusTextEl.setText("Initializing"); + const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" }); + statusEl.setAttribute("aria-label", "Status: running"); + const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); + createStatusRow(contentEl, truncatePrompt(prompt) || "Background task", { textClass: "claudian-async-prompt" }); + setupCollapsible(wrapperEl, headerEl, contentEl, info); + return { + wrapperEl, + contentEl, + headerEl, + labelEl, + statusTextEl, + statusEl, + info + }; +} +function updateAsyncSubagentRunning(state, agentId) { + state.info.asyncStatus = "running"; + state.info.agentId = agentId; + setAsyncWrapperStatus(state.wrapperEl, "running"); + updateAsyncLabel(state); + state.statusTextEl.setText("Running in background"); + state.contentEl.empty(); + createStatusRow(state.contentEl, truncatePrompt(state.info.prompt || "") || "Background task", { textClass: "claudian-async-prompt" }); +} +function finalizeAsyncSubagent(state, result, isError) { + state.info.asyncStatus = isError ? "error" : "completed"; + state.info.status = isError ? "error" : "completed"; + state.info.result = result; + setAsyncWrapperStatus(state.wrapperEl, isError ? "error" : "completed"); + updateAsyncLabel(state); + state.statusTextEl.setText(isError ? "Error" : ""); + state.statusEl.className = "claudian-subagent-status"; + state.statusEl.addClass(`status-${isError ? "error" : "completed"}`); + state.statusEl.empty(); + if (isError) { + (0, import_obsidian5.setIcon)(state.statusEl, "x"); + } else { + (0, import_obsidian5.setIcon)(state.statusEl, "check"); + } + if (isError) { + state.wrapperEl.addClass("error"); + } else { + state.wrapperEl.addClass("done"); + } + state.contentEl.empty(); + let displayText; + if (isError && result) { + const truncated = result.length > 80 ? result.substring(0, 80) + "..." : result; + displayText = `ERROR: ${truncated}`; + } else { + displayText = isError ? "ERROR" : "DONE"; + } + createStatusRow(state.contentEl, displayText); +} +function markAsyncSubagentOrphaned(state) { + state.info.asyncStatus = "orphaned"; + state.info.status = "error"; + state.info.result = "Conversation ended before task completed"; + setAsyncWrapperStatus(state.wrapperEl, "orphaned"); + updateAsyncLabel(state); + state.statusTextEl.setText("Orphaned"); + state.statusEl.className = "claudian-subagent-status status-error"; + state.statusEl.empty(); + (0, import_obsidian5.setIcon)(state.statusEl, "alert-circle"); + state.wrapperEl.addClass("error"); + state.wrapperEl.addClass("orphaned"); + state.contentEl.empty(); + createStatusRow(state.contentEl, "\u26A0\uFE0F Task orphaned", { rowClass: "claudian-async-orphaned" }); +} +function renderStoredAsyncSubagent(parentEl, subagent) { + const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); + const displayStatus = getAsyncDisplayStatus(subagent.asyncStatus); + setAsyncWrapperStatus(wrapperEl, displayStatus); + if (displayStatus === "completed") { + wrapperEl.addClass("done"); + } else if (displayStatus === "error" || displayStatus === "orphaned") { + wrapperEl.addClass("error"); + } + wrapperEl.dataset.asyncSubagentId = subagent.id; + const statusText = getAsyncStatusText(subagent.asyncStatus); + const statusAriaLabel = getAsyncStatusAriaLabel(subagent.asyncStatus); + const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); + headerEl.setAttribute("tabindex", "0"); + headerEl.setAttribute("role", "button"); + headerEl.setAttribute("aria-expanded", "false"); + headerEl.setAttribute("aria-label", `Background task: ${subagent.description} - ${statusAriaLabel} - click to expand`); + const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + (0, import_obsidian5.setIcon)(iconEl, getToolIcon(TOOL_TASK)); + const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); + labelEl.setText(truncateDescription(subagent.description)); + const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" }); + statusTextEl.setText(statusText); + let statusIconClass; + switch (displayStatus) { + case "error": + case "orphaned": + statusIconClass = "status-error"; + break; + case "completed": + statusIconClass = "status-completed"; + break; + default: + statusIconClass = "status-running"; + } + const statusEl = headerEl.createDiv({ cls: `claudian-subagent-status ${statusIconClass}` }); + statusEl.setAttribute("aria-label", `Status: ${statusAriaLabel}`); + switch (displayStatus) { + case "completed": + (0, import_obsidian5.setIcon)(statusEl, "check"); + break; + case "error": + (0, import_obsidian5.setIcon)(statusEl, "x"); + break; + case "orphaned": + (0, import_obsidian5.setIcon)(statusEl, "alert-circle"); + break; + } + const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); + switch (displayStatus) { + case "completed": + createStatusRow(contentEl, "DONE"); + break; + case "error": + createStatusRow(contentEl, "ERROR"); + break; + case "orphaned": + createStatusRow(contentEl, "\u26A0\uFE0F Task orphaned"); + break; + default: + createStatusRow(contentEl, truncatePrompt(subagent.prompt || "") || "Background task", { textClass: "claudian-async-prompt" }); + } + const state = { isExpanded: false }; + setupCollapsible(wrapperEl, headerEl, contentEl, state); + return wrapperEl; +} + +// src/features/chat/rendering/ThinkingBlockRenderer.ts +function createThinkingBlock(parentEl, renderContent) { + const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" }); + const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" }); + header.setAttribute("tabindex", "0"); + header.setAttribute("role", "button"); + header.setAttribute("aria-expanded", "false"); + header.setAttribute("aria-label", "Extended thinking - click to expand"); + const labelEl = header.createSpan({ cls: "claudian-thinking-label" }); + const startTime = Date.now(); + labelEl.setText("Thinking 0s..."); + const timerInterval = setInterval(() => { + const elapsed = Math.floor((Date.now() - startTime) / 1e3); + labelEl.setText(`Thinking ${elapsed}s...`); + }, 1e3); + const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" }); + const state = { + wrapperEl, + contentEl, + labelEl, + content: "", + startTime, + timerInterval, + isExpanded: false + }; + setupCollapsible(wrapperEl, header, contentEl, state); + return state; +} +async function appendThinkingContent(state, content, renderContent) { + state.content += content; + await renderContent(state.contentEl, state.content); +} +function finalizeThinkingBlock(state) { + if (state.timerInterval) { + clearInterval(state.timerInterval); + state.timerInterval = null; + } + const durationSeconds = Math.floor((Date.now() - state.startTime) / 1e3); + state.labelEl.setText(`Thought for ${durationSeconds}s`); + const header = state.wrapperEl.querySelector(".claudian-thinking-header"); + if (header) { + collapseElement(state.wrapperEl, header, state.contentEl, state); + } + return durationSeconds; +} +function cleanupThinkingBlock(state) { + if (state == null ? void 0 : state.timerInterval) { + clearInterval(state.timerInterval); + } +} +function renderStoredThinkingBlock(parentEl, content, durationSeconds, renderContent) { + const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" }); + const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" }); + header.setAttribute("tabindex", "0"); + header.setAttribute("role", "button"); + header.setAttribute("aria-label", "Extended thinking - click to expand"); + const labelEl = header.createSpan({ cls: "claudian-thinking-label" }); + const labelText = durationSeconds !== void 0 ? `Thought for ${durationSeconds}s` : "Thought"; + labelEl.setText(labelText); + const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" }); + renderContent(contentEl, content); + const state = { isExpanded: false }; + setupCollapsible(wrapperEl, header, contentEl, state); + return wrapperEl; +} + +// src/features/chat/rendering/WriteEditRenderer.ts +var import_obsidian6 = require("obsidian"); + +// src/features/chat/rendering/DiffRenderer.ts +function splitIntoHunks(diffLines, contextLines = 3) { + if (diffLines.length === 0) return []; + const changedIndices = []; + for (let i2 = 0; i2 < diffLines.length; i2++) { + if (diffLines[i2].type !== "equal") { + changedIndices.push(i2); + } + } + if (changedIndices.length === 0) return []; + const ranges = []; + for (const idx of changedIndices) { + const start = Math.max(0, idx - contextLines); + const end = Math.min(diffLines.length - 1, idx + contextLines); + if (ranges.length > 0 && start <= ranges[ranges.length - 1].end + 1) { + ranges[ranges.length - 1].end = end; + } else { + ranges.push({ start, end }); + } + } + const hunks = []; + for (const range of ranges) { + const lines = diffLines.slice(range.start, range.end + 1); + let oldStart = 1; + let newStart = 1; + for (let i2 = 0; i2 < range.start; i2++) { + const line = diffLines[i2]; + if (line.type === "equal" || line.type === "delete") oldStart++; + if (line.type === "equal" || line.type === "insert") newStart++; + } + hunks.push({ lines, oldStart, newStart }); + } + return hunks; +} +var NEW_FILE_DISPLAY_CAP = 20; +function renderDiffContent(containerEl, diffLines, contextLines = 3) { + containerEl.empty(); + const allInserts = diffLines.length > 0 && diffLines.every((l3) => l3.type === "insert"); + if (allInserts && diffLines.length > NEW_FILE_DISPLAY_CAP) { + const hunkEl = containerEl.createDiv({ cls: "claudian-diff-hunk" }); + for (const line of diffLines.slice(0, NEW_FILE_DISPLAY_CAP)) { + const lineEl = hunkEl.createDiv({ cls: "claudian-diff-line claudian-diff-insert" }); + const prefixEl = lineEl.createSpan({ cls: "claudian-diff-prefix" }); + prefixEl.setText("+"); + const contentEl = lineEl.createSpan({ cls: "claudian-diff-text" }); + contentEl.setText(line.text || " "); + } + const remaining = diffLines.length - NEW_FILE_DISPLAY_CAP; + const separator = containerEl.createDiv({ cls: "claudian-diff-separator" }); + separator.setText(`... ${remaining} more lines`); + return; + } + const hunks = splitIntoHunks(diffLines, contextLines); + if (hunks.length === 0) { + const noChanges = containerEl.createDiv({ cls: "claudian-diff-no-changes" }); + noChanges.setText("No changes"); + return; + } + hunks.forEach((hunk, hunkIndex) => { + if (hunkIndex > 0) { + const separator = containerEl.createDiv({ cls: "claudian-diff-separator" }); + separator.setText("..."); + } + const hunkEl = containerEl.createDiv({ cls: "claudian-diff-hunk" }); + for (const line of hunk.lines) { + const lineEl = hunkEl.createDiv({ cls: `claudian-diff-line claudian-diff-${line.type}` }); + const prefix = line.type === "insert" ? "+" : line.type === "delete" ? "-" : " "; + const prefixEl = lineEl.createSpan({ cls: "claudian-diff-prefix" }); + prefixEl.setText(prefix); + const contentEl = lineEl.createSpan({ cls: "claudian-diff-text" }); + contentEl.setText(line.text || " "); + } + }); +} + +// src/features/chat/rendering/WriteEditRenderer.ts +function shortenPath2(filePath, maxLength = 40) { + if (!filePath) return "file"; + const normalized = filePath.replace(/\\/g, "/"); + if (normalized.length <= maxLength) return normalized; + const parts = normalized.split("/"); + if (parts.length <= 2) { + return "..." + normalized.slice(-maxLength + 3); + } + const filename = parts[parts.length - 1]; + const firstDir = parts[0]; + const available = maxLength - firstDir.length - filename.length - 5; + if (available < 0) { + return "..." + filename.slice(-maxLength + 3); + } + return `${firstDir}/.../${filename}`; +} +function renderDiffStats(statsEl, stats) { + if (stats.added > 0) { + const addedEl = statsEl.createSpan({ cls: "added" }); + addedEl.setText(`+${stats.added}`); + } + if (stats.removed > 0) { + if (stats.added > 0) { + statsEl.createSpan({ text: " " }); + } + const removedEl = statsEl.createSpan({ cls: "removed" }); + removedEl.setText(`-${stats.removed}`); + } +} +function createWriteEditBlock(parentEl, toolCall) { + const filePath = toolCall.input.file_path || "file"; + const toolName = toolCall.name; + const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" }); + wrapperEl.dataset.toolId = toolCall.id; + const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" }); + headerEl.setAttribute("tabindex", "0"); + headerEl.setAttribute("role", "button"); + headerEl.setAttribute("aria-label", `${toolName}: ${shortenPath2(filePath)} - click to expand`); + const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + (0, import_obsidian6.setIcon)(iconEl, getToolIcon(toolName)); + const labelEl = headerEl.createDiv({ cls: "claudian-write-edit-label" }); + labelEl.setText(`${toolName}: ${shortenPath2(filePath)}`); + const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" }); + const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status status-running" }); + statusEl.setAttribute("aria-label", "Status: running"); + const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" }); + const loadingRow = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); + const loadingEl = loadingRow.createDiv({ cls: "claudian-write-edit-loading" }); + loadingEl.setText("Writing..."); + const state = { + wrapperEl, + contentEl, + headerEl, + labelEl, + statsEl, + statusEl, + toolCall, + isExpanded: false + }; + setupCollapsible(wrapperEl, headerEl, contentEl, state); + return state; +} +function updateWriteEditWithDiff(state, diffData) { + state.statsEl.empty(); + state.contentEl.empty(); + const { diffLines, stats } = diffData; + state.diffLines = diffLines; + renderDiffStats(state.statsEl, stats); + const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); + const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" }); + renderDiffContent(diffEl, diffLines); +} +function finalizeWriteEditBlock(state, isError) { + state.statusEl.className = "claudian-write-edit-status"; + state.statusEl.empty(); + if (isError) { + state.statusEl.addClass("status-error"); + (0, import_obsidian6.setIcon)(state.statusEl, "x"); + state.statusEl.setAttribute("aria-label", "Status: error"); + if (!state.diffLines) { + state.contentEl.empty(); + const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); + const errorEl = row.createDiv({ cls: "claudian-write-edit-error" }); + errorEl.setText(state.toolCall.result || "Error"); + } + } else if (!state.diffLines) { + state.contentEl.empty(); + const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); + const doneEl = row.createDiv({ cls: "claudian-write-edit-done-text" }); + doneEl.setText("DONE"); + } + if (isError) { + state.wrapperEl.addClass("error"); + } else { + state.wrapperEl.addClass("done"); + } +} +function renderStoredWriteEdit(parentEl, toolCall) { + const filePath = toolCall.input.file_path || "file"; + const toolName = toolCall.name; + const isError = toolCall.status === "error" || toolCall.status === "blocked"; + const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" }); + if (isError) { + wrapperEl.addClass("error"); + } else if (toolCall.status === "completed") { + wrapperEl.addClass("done"); + } + wrapperEl.dataset.toolId = toolCall.id; + const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" }); + headerEl.setAttribute("tabindex", "0"); + headerEl.setAttribute("role", "button"); + const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + (0, import_obsidian6.setIcon)(iconEl, getToolIcon(toolName)); + const labelEl = headerEl.createDiv({ cls: "claudian-write-edit-label" }); + labelEl.setText(`${toolName}: ${shortenPath2(filePath)}`); + const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" }); + if (toolCall.diffData) { + renderDiffStats(statsEl, toolCall.diffData.stats); + } + const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status" }); + if (isError) { + statusEl.addClass("status-error"); + (0, import_obsidian6.setIcon)(statusEl, "x"); + } + const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" }); + const row = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); + if (toolCall.diffData && toolCall.diffData.diffLines.length > 0) { + const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" }); + renderDiffContent(diffEl, toolCall.diffData.diffLines); + } else if (isError && toolCall.result) { + const errorEl = row.createDiv({ cls: "claudian-write-edit-error" }); + errorEl.setText(toolCall.result); + } else { + const doneEl = row.createDiv({ cls: "claudian-write-edit-done-text" }); + doneEl.setText(isError ? "ERROR" : "DONE"); + } + const state = { isExpanded: false }; + setupCollapsible(wrapperEl, headerEl, contentEl, state); + return wrapperEl; +} + +// src/features/chat/rendering/MessageRenderer.ts +var _MessageRenderer = class _MessageRenderer { + constructor(plugin, component, messagesEl) { + this.app = plugin.app; + this.plugin = plugin; + this.component = component; + this.messagesEl = messagesEl; + registerFileLinkHandler(this.app, this.messagesEl, this.component); + } + /** Sets the messages container element. */ + setMessagesEl(el) { + this.messagesEl = el; + } + // ============================================ + // Streaming Message Rendering + // ============================================ + /** + * Adds a new message to the chat during streaming. + * Returns the message element for content updates. + */ + addMessage(msg) { + var _a3, _b; + if (msg.role === "user" && msg.images && msg.images.length > 0) { + this.renderMessageImages(this.messagesEl, msg.images); + } + if (msg.role === "user") { + const textToShow = (_a3 = msg.displayContent) != null ? _a3 : msg.content; + if (!textToShow) { + this.scrollToBottom(); + const lastChild = this.messagesEl.lastElementChild; + return lastChild != null ? lastChild : this.messagesEl; + } + } + const msgEl = this.messagesEl.createDiv({ + cls: `claudian-message claudian-message-${msg.role}` + }); + const contentEl = msgEl.createDiv({ cls: "claudian-message-content" }); + if (msg.role === "user") { + const textToShow = (_b = msg.displayContent) != null ? _b : msg.content; + if (textToShow) { + const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); + void this.renderContent(textEl, textToShow); + } + } + this.scrollToBottom(); + return msgEl; + } + // ============================================ + // Stored Message Rendering (Batch/Replay) + // ============================================ + /** + * Renders all messages for conversation load/switch. + * @param messages Array of messages to render + * @param getGreeting Function to get greeting text + * @returns The newly created welcome element + */ + renderMessages(messages, getGreeting) { + this.messagesEl.empty(); + const newWelcomeEl = this.messagesEl.createDiv({ cls: "claudian-welcome" }); + newWelcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: getGreeting() }); + for (const msg of messages) { + this.renderStoredMessage(msg); + } + this.scrollToBottom(); + return newWelcomeEl; + } + /** + * Renders a persisted message from history. + */ + renderStoredMessage(msg) { + var _a3, _b; + if (msg.isInterrupt) { + this.renderInterruptMessage(); + return; + } + if (msg.isRebuiltContext) { + return; + } + if (msg.role === "user" && msg.images && msg.images.length > 0) { + this.renderMessageImages(this.messagesEl, msg.images); + } + if (msg.role === "user") { + const textToShow = (_a3 = msg.displayContent) != null ? _a3 : msg.content; + if (!textToShow) { + return; + } + } + const msgEl = this.messagesEl.createDiv({ + cls: `claudian-message claudian-message-${msg.role}` + }); + const contentEl = msgEl.createDiv({ cls: "claudian-message-content" }); + if (msg.role === "user") { + const textToShow = (_b = msg.displayContent) != null ? _b : msg.content; + if (textToShow) { + const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); + void this.renderContent(textEl, textToShow); + } + } else if (msg.role === "assistant") { + this.renderAssistantContent(msg, contentEl); + } + } + /** + * Renders an interrupt indicator (stored interrupts from SDK history). + * Uses the same styling as streaming interrupts. + */ + renderInterruptMessage() { + const msgEl = this.messagesEl.createDiv({ cls: "claudian-message claudian-message-assistant" }); + const contentEl = msgEl.createDiv({ cls: "claudian-message-content" }); + const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); + textEl.innerHTML = 'Interrupted \xB7 What should Claudian do instead?'; + } + /** + * Renders assistant message content (content blocks or fallback). + */ + renderAssistantContent(msg, contentEl) { + var _a3, _b, _c; + if (msg.contentBlocks && msg.contentBlocks.length > 0) { + for (const block of msg.contentBlocks) { + if (block.type === "thinking") { + renderStoredThinkingBlock( + contentEl, + block.content, + block.durationSeconds, + (el, md) => this.renderContent(el, md) + ); + } else if (block.type === "text") { + if (!block.content || !block.content.trim()) { + continue; + } + const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); + void this.renderContent(textEl, block.content); + this.addTextCopyButton(textEl, block.content); + } else if (block.type === "tool_use") { + const toolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === block.toolId); + if (toolCall) { + this.renderToolCall(contentEl, toolCall); + } + } else if (block.type === "compact_boundary") { + const boundaryEl = contentEl.createDiv({ cls: "claudian-compact-boundary" }); + boundaryEl.createSpan({ cls: "claudian-compact-boundary-label", text: "Conversation compacted" }); + } else if (block.type === "subagent") { + const subagent = (_b = msg.subagents) == null ? void 0 : _b.find((s) => s.id === block.subagentId); + if (subagent) { + const mode = block.mode || subagent.mode || "sync"; + if (mode === "async") { + renderStoredAsyncSubagent(contentEl, subagent); + } else { + renderStoredSubagent(contentEl, subagent); + } + } + } + } + } else { + if (msg.content) { + const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); + void this.renderContent(textEl, msg.content); + this.addTextCopyButton(textEl, msg.content); + } + if (msg.toolCalls) { + for (const toolCall of msg.toolCalls) { + this.renderToolCall(contentEl, toolCall); + } + } + } + const hasCompactBoundary = (_c = msg.contentBlocks) == null ? void 0 : _c.some((b3) => b3.type === "compact_boundary"); + if (msg.durationSeconds && msg.durationSeconds > 0 && !hasCompactBoundary) { + const flavorWord = msg.durationFlavorWord || "Baked"; + const footerEl = contentEl.createDiv({ cls: "claudian-response-footer" }); + footerEl.createSpan({ + text: `* ${flavorWord} for ${formatDurationMmSs(msg.durationSeconds)}`, + cls: "claudian-baked-duration" + }); + } + } + /** + * Renders a tool call with special handling for Write/Edit and Task (subagent). + * TaskOutput is hidden as it's an internal tool for async subagent communication. + */ + renderToolCall(contentEl, toolCall) { + var _a3; + if (toolCall.name === TOOL_AGENT_OUTPUT) { + return; + } + if (isWriteEditTool(toolCall.name)) { + renderStoredWriteEdit(contentEl, toolCall); + } else if (toolCall.name === TOOL_TASK) { + let status; + switch (toolCall.status) { + case "completed": + status = "completed"; + break; + case "error": + status = "error"; + break; + default: + status = "running"; + } + const subagentInfo = { + id: toolCall.id, + description: ((_a3 = toolCall.input) == null ? void 0 : _a3.description) || "Subagent task", + status, + toolCalls: [], + isExpanded: false, + result: toolCall.result + }; + renderStoredSubagent(contentEl, subagentInfo); + } else { + renderStoredToolCall(contentEl, toolCall); + } + } + // ============================================ + // Image Rendering + // ============================================ + /** + * Renders image attachments above a message. + */ + renderMessageImages(containerEl, images) { + const imagesEl = containerEl.createDiv({ cls: "claudian-message-images" }); + for (const image of images) { + const imageWrapper = imagesEl.createDiv({ cls: "claudian-message-image" }); + const imgEl = imageWrapper.createEl("img", { + attr: { + alt: image.name + } + }); + void this.setImageSrc(imgEl, image); + imgEl.addEventListener("click", () => { + void this.showFullImage(image); + }); + } + } + /** + * Shows full-size image in modal overlay. + */ + showFullImage(image) { + const dataUri = `data:${image.mediaType};base64,${image.data}`; + const overlay = document.body.createDiv({ cls: "claudian-image-modal-overlay" }); + const modal = overlay.createDiv({ cls: "claudian-image-modal" }); + modal.createEl("img", { + attr: { + src: dataUri, + alt: image.name + } + }); + const closeBtn = modal.createDiv({ cls: "claudian-image-modal-close" }); + closeBtn.setText("\xD7"); + const handleEsc = (e2) => { + if (e2.key === "Escape") { + close(); + } + }; + const close = () => { + document.removeEventListener("keydown", handleEsc); + overlay.remove(); + }; + closeBtn.addEventListener("click", close); + overlay.addEventListener("click", (e2) => { + if (e2.target === overlay) close(); + }); + document.addEventListener("keydown", handleEsc); + } + /** + * Sets image src from attachment data. + */ + setImageSrc(imgEl, image) { + const dataUri = `data:${image.mediaType};base64,${image.data}`; + imgEl.setAttribute("src", dataUri); + } + // ============================================ + // Content Rendering + // ============================================ + /** + * Renders markdown content with code block enhancements. + */ + async renderContent(el, markdown) { + el.empty(); + try { + const processedMarkdown = replaceImageEmbedsWithHtml( + markdown, + this.app, + this.plugin.settings.mediaFolder + ); + await import_obsidian7.MarkdownRenderer.renderMarkdown(processedMarkdown, el, "", this.component); + el.querySelectorAll("pre").forEach((pre) => { + var _a3, _b; + if ((_a3 = pre.parentElement) == null ? void 0 : _a3.classList.contains("claudian-code-wrapper")) return; + const wrapper = createEl("div", { cls: "claudian-code-wrapper" }); + (_b = pre.parentElement) == null ? void 0 : _b.insertBefore(wrapper, pre); + wrapper.appendChild(pre); + const code = pre.querySelector('code[class*="language-"]'); + if (code) { + const match = code.className.match(/language-(\w+)/); + if (match) { + wrapper.classList.add("has-language"); + const label = createEl("span", { + cls: "claudian-code-lang-label", + text: match[1] + }); + wrapper.appendChild(label); + label.addEventListener("click", async () => { + try { + await navigator.clipboard.writeText(code.textContent || ""); + label.setText("copied!"); + setTimeout(() => label.setText(match[1]), 1500); + } catch (e2) { + } + }); + } + } + const copyBtn = pre.querySelector(".copy-code-button"); + if (copyBtn) { + wrapper.appendChild(copyBtn); + } + }); + processFileLinks(this.app, el); + } catch (e2) { + el.createDiv({ + cls: "claudian-render-error", + text: "Failed to render message content." + }); + } + } + /** + * Adds a copy button to a text block. + * Button shows clipboard icon on hover, changes to "copied!" on click. + * @param textEl The rendered text element + * @param markdown The original markdown content to copy + */ + addTextCopyButton(textEl, markdown) { + const copyBtn = textEl.createSpan({ cls: "claudian-text-copy-btn" }); + copyBtn.innerHTML = _MessageRenderer.COPY_ICON; + let feedbackTimeout = null; + copyBtn.addEventListener("click", async (e2) => { + e2.stopPropagation(); + try { + await navigator.clipboard.writeText(markdown); + } catch (e3) { + return; + } + if (feedbackTimeout) { + clearTimeout(feedbackTimeout); + } + copyBtn.innerHTML = ""; + copyBtn.setText("copied!"); + copyBtn.classList.add("copied"); + feedbackTimeout = setTimeout(() => { + copyBtn.innerHTML = _MessageRenderer.COPY_ICON; + copyBtn.classList.remove("copied"); + feedbackTimeout = null; + }, 1500); + }); + } + // ============================================ + // Utilities + // ============================================ + /** Scrolls messages container to bottom. */ + scrollToBottom() { + this.messagesEl.scrollTop = this.messagesEl.scrollHeight; + } + /** Scrolls to bottom if already near bottom (within threshold). */ + scrollToBottomIfNeeded(threshold = 100) { + const { scrollTop, scrollHeight, clientHeight } = this.messagesEl; + const isNearBottom = scrollHeight - scrollTop - clientHeight < threshold; + if (isNearBottom) { + requestAnimationFrame(() => { + this.messagesEl.scrollTop = this.messagesEl.scrollHeight; + }); + } + } +}; +// ============================================ +// Copy Button +// ============================================ +/** Clipboard icon SVG for copy button. */ +_MessageRenderer.COPY_ICON = ``; +var MessageRenderer = _MessageRenderer; + +// src/features/chat/controllers/ConversationController.ts +var ConversationController = class { + constructor(deps, callbacks = {}) { + this.deps = deps; + this.callbacks = callbacks; + } + getAgentService() { + var _a3, _b, _c; + return (_c = (_b = (_a3 = this.deps).getAgentService) == null ? void 0 : _b.call(_a3)) != null ? _c : null; + } + // ============================================ + // Conversation Lifecycle + // ============================================ + /** + * Resets to entry point state (New Chat). + * + * Entry point is a blank UI state - no conversation is created until the + * first message is sent. This prevents empty conversations cluttering history. + */ + async createNew(options = {}) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j; + const { plugin, state, subagentManager } = this.deps; + const force = !!options.force; + if (state.isStreaming && !force) return; + if (state.isCreatingConversation) return; + if (state.isSwitchingConversation) return; + state.isCreatingConversation = true; + try { + if (force && state.isStreaming) { + state.cancelRequested = true; + state.bumpStreamGeneration(); + (_a3 = this.getAgentService()) == null ? void 0 : _a3.cancel(); + } + if (state.currentConversationId && state.messages.length > 0) { + await this.save(); + } + subagentManager.orphanAllActive(); + subagentManager.clear(); + cleanupThinkingBlock(state.currentThinkingState); + state.currentContentEl = null; + state.currentTextEl = null; + state.currentTextContent = ""; + state.currentThinkingState = null; + state.toolCallElements.clear(); + state.writeEditStates.clear(); + state.isStreaming = false; + state.currentConversationId = null; + state.clearMessages(); + state.usage = null; + state.currentTodos = null; + state.autoScrollEnabled = (_b = plugin.settings.enableAutoScroll) != null ? _b : true; + (_c = this.getAgentService()) == null ? void 0 : _c.setSessionId( + null, + plugin.settings.persistentExternalContextPaths || [] + ); + const messagesEl = this.deps.getMessagesEl(); + messagesEl.empty(); + const welcomeEl = messagesEl.createDiv({ cls: "claudian-welcome" }); + welcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: this.getGreeting() }); + this.deps.setWelcomeEl(welcomeEl); + (_d = this.deps.getStatusPanel()) == null ? void 0 : _d.remount(); + (_e = this.deps.getStatusPanel()) == null ? void 0 : _e.clearSubagents(); + this.deps.getInputEl().value = ""; + const fileCtx = this.deps.getFileContextManager(); + fileCtx == null ? void 0 : fileCtx.resetForNewConversation(); + fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile(); + (_f = this.deps.getImageContextManager()) == null ? void 0 : _f.clearImages(); + (_g = this.deps.getMcpServerSelector()) == null ? void 0 : _g.clearEnabled(); + (_h = this.deps.getExternalContextSelector()) == null ? void 0 : _h.clearExternalContexts( + plugin.settings.persistentExternalContextPaths || [] + ); + this.deps.clearQueuedMessage(); + (_j = (_i = this.callbacks).onNewConversation) == null ? void 0 : _j.call(_i); + } finally { + state.isCreatingConversation = false; + } + } + /** + * Loads the current tab conversation, or starts at entry point if none. + * + * Entry point (no conversation) shows welcome screen without + * creating a conversation. Conversation is created lazily on first message. + */ + async loadActive() { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m; + const { plugin, state, renderer } = this.deps; + const conversationId = state.currentConversationId; + const conversation = conversationId ? await plugin.getConversationById(conversationId) : null; + if (!conversation) { + state.currentConversationId = null; + state.clearMessages(); + state.usage = null; + state.currentTodos = null; + state.autoScrollEnabled = (_a3 = plugin.settings.enableAutoScroll) != null ? _a3 : true; + (_b = this.getAgentService()) == null ? void 0 : _b.setSessionId( + null, + plugin.settings.persistentExternalContextPaths || [] + ); + const fileCtx2 = this.deps.getFileContextManager(); + fileCtx2 == null ? void 0 : fileCtx2.resetForNewConversation(); + fileCtx2 == null ? void 0 : fileCtx2.autoAttachActiveFile(); + (_c = this.deps.getExternalContextSelector()) == null ? void 0 : _c.clearExternalContexts( + plugin.settings.persistentExternalContextPaths || [] + ); + (_d = this.deps.getMcpServerSelector()) == null ? void 0 : _d.clearEnabled(); + const welcomeEl2 = renderer.renderMessages( + [], + () => this.getGreeting() + ); + this.deps.setWelcomeEl(welcomeEl2); + this.updateWelcomeVisibility(); + (_f = (_e = this.callbacks).onConversationLoaded) == null ? void 0 : _f.call(_e); + return; + } + state.currentConversationId = conversation.id; + state.messages = [...conversation.messages]; + state.usage = (_g = conversation.usage) != null ? _g : null; + state.autoScrollEnabled = (_h = plugin.settings.enableAutoScroll) != null ? _h : true; + state.currentTodos = null; + (_i = this.deps.getStatusPanel()) == null ? void 0 : _i.clearSubagents(); + const hasMessages = state.messages.length > 0; + const externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : plugin.settings.persistentExternalContextPaths || []; + (_k = this.getAgentService()) == null ? void 0 : _k.setSessionId((_j = conversation.sessionId) != null ? _j : null, externalContextPaths); + const fileCtx = this.deps.getFileContextManager(); + fileCtx == null ? void 0 : fileCtx.resetForLoadedConversation(hasMessages); + if (conversation.currentNote) { + fileCtx == null ? void 0 : fileCtx.setCurrentNote(conversation.currentNote); + } else if (!hasMessages) { + fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile(); + } + this.restoreExternalContextPaths( + conversation.externalContextPaths, + !hasMessages + ); + const mcpServerSelector = this.deps.getMcpServerSelector(); + if (conversation.enabledMcpServers && conversation.enabledMcpServers.length > 0) { + mcpServerSelector == null ? void 0 : mcpServerSelector.setEnabledServers(conversation.enabledMcpServers); + } else { + mcpServerSelector == null ? void 0 : mcpServerSelector.clearEnabled(); + } + const welcomeEl = renderer.renderMessages( + state.messages, + () => this.getGreeting() + ); + this.deps.setWelcomeEl(welcomeEl); + this.updateWelcomeVisibility(); + (_m = (_l = this.callbacks).onConversationLoaded) == null ? void 0 : _m.call(_l); + } + /** Switches to a different conversation. */ + async switchTo(id) { + var _a3, _b, _c, _d, _e, _f, _g, _h; + const { plugin, state, renderer, subagentManager } = this.deps; + if (id === state.currentConversationId) return; + if (state.isStreaming) return; + if (state.isSwitchingConversation) return; + if (state.isCreatingConversation) return; + state.isSwitchingConversation = true; + try { + await this.save(); + subagentManager.orphanAllActive(); + subagentManager.clear(); + const conversation = await plugin.switchConversation(id); + if (!conversation) { + return; + } + state.currentConversationId = conversation.id; + state.messages = [...conversation.messages]; + state.usage = (_a3 = conversation.usage) != null ? _a3 : null; + state.autoScrollEnabled = (_b = plugin.settings.enableAutoScroll) != null ? _b : true; + state.currentTodos = null; + (_c = this.deps.getStatusPanel()) == null ? void 0 : _c.clearSubagents(); + const hasMessages = state.messages.length > 0; + const externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : plugin.settings.persistentExternalContextPaths || []; + (_e = this.getAgentService()) == null ? void 0 : _e.setSessionId((_d = conversation.sessionId) != null ? _d : null, externalContextPaths); + this.deps.getInputEl().value = ""; + this.deps.clearQueuedMessage(); + const fileCtx = this.deps.getFileContextManager(); + fileCtx == null ? void 0 : fileCtx.resetForLoadedConversation(hasMessages); + if (conversation.currentNote) { + fileCtx == null ? void 0 : fileCtx.setCurrentNote(conversation.currentNote); + } + this.restoreExternalContextPaths( + conversation.externalContextPaths, + !hasMessages + ); + const mcpServerSelector = this.deps.getMcpServerSelector(); + if (conversation.enabledMcpServers && conversation.enabledMcpServers.length > 0) { + mcpServerSelector == null ? void 0 : mcpServerSelector.setEnabledServers(conversation.enabledMcpServers); + } else { + mcpServerSelector == null ? void 0 : mcpServerSelector.clearEnabled(); + } + const welcomeEl = renderer.renderMessages( + state.messages, + () => this.getGreeting() + ); + this.deps.setWelcomeEl(welcomeEl); + (_f = this.deps.getHistoryDropdown()) == null ? void 0 : _f.removeClass("visible"); + this.updateWelcomeVisibility(); + (_h = (_g = this.callbacks).onConversationSwitched) == null ? void 0 : _h.call(_g); + } finally { + state.isSwitchingConversation = false; + } + } + /** + * Saves the current conversation. + * + * If we're at an entry point (no conversation yet) and have messages, + * creates a new conversation first (lazy creation). + * + * For native sessions (new conversations with sessionId from SDK), + * only metadata is saved - the SDK handles message persistence. + */ + async save(updateLastResponse = false) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i; + const { plugin, state } = this.deps; + if (!state.currentConversationId && state.messages.length === 0) { + return; + } + const agentService = this.getAgentService(); + const sessionId = (_a3 = agentService == null ? void 0 : agentService.getSessionId()) != null ? _a3 : null; + const sessionInvalidated = (_c = (_b = agentService == null ? void 0 : agentService.consumeSessionInvalidation) == null ? void 0 : _b.call(agentService)) != null ? _c : false; + if (!state.currentConversationId && state.messages.length > 0) { + const conversation2 = await plugin.createConversation(sessionId != null ? sessionId : void 0); + state.currentConversationId = conversation2.id; + } + const fileCtx = this.deps.getFileContextManager(); + const currentNote = (fileCtx == null ? void 0 : fileCtx.getCurrentNotePath()) || void 0; + const externalContextSelector = this.deps.getExternalContextSelector(); + const externalContextPaths = (_d = externalContextSelector == null ? void 0 : externalContextSelector.getExternalContexts()) != null ? _d : []; + const mcpServerSelector = this.deps.getMcpServerSelector(); + const enabledMcpServers = mcpServerSelector ? Array.from(mcpServerSelector.getEnabledServers()) : []; + const conversation = await plugin.getConversationById(state.currentConversationId); + const wasNative = (_e = conversation == null ? void 0 : conversation.isNative) != null ? _e : false; + const shouldPromote = !wasNative && !!sessionId; + const isNative = wasNative || shouldPromote; + const legacyMessages = (_f = conversation == null ? void 0 : conversation.messages) != null ? _f : []; + const legacyCutoffAt = shouldPromote ? (_g = legacyMessages[legacyMessages.length - 1]) == null ? void 0 : _g.timestamp : conversation == null ? void 0 : conversation.legacyCutoffAt; + const oldSdkSessionId = conversation == null ? void 0 : conversation.sdkSessionId; + const sessionChanged = isNative && sessionId && oldSdkSessionId && sessionId !== oldSdkSessionId; + const previousSdkSessionIds = sessionChanged ? [.../* @__PURE__ */ new Set([...(conversation == null ? void 0 : conversation.previousSdkSessionIds) || [], oldSdkSessionId])] : conversation == null ? void 0 : conversation.previousSdkSessionIds; + const updates = { + // For native sessions, don't persist messages (SDK handles that) + // For legacy sessions, persist messages as before + messages: isNative ? state.messages : state.getPersistedMessages(), + // Preserve existing sessionId when SDK hasn't captured a new one yet + sessionId: sessionInvalidated ? null : (_h = sessionId != null ? sessionId : conversation == null ? void 0 : conversation.sessionId) != null ? _h : null, + sdkSessionId: isNative && sessionId ? sessionId : conversation == null ? void 0 : conversation.sdkSessionId, + previousSdkSessionIds, + isNative: isNative || void 0, + legacyCutoffAt, + sdkMessagesLoaded: isNative ? true : void 0, + currentNote, + externalContextPaths: externalContextPaths.length > 0 ? externalContextPaths : void 0, + usage: (_i = state.usage) != null ? _i : void 0, + enabledMcpServers: enabledMcpServers.length > 0 ? enabledMcpServers : void 0 + }; + if (updateLastResponse) { + updates.lastResponseAt = Date.now(); + } + await plugin.updateConversation(state.currentConversationId, updates); + } + /** + * Restores external context paths based on session state. + * New or empty sessions get current persistent paths from settings. + * Sessions with messages restore exactly what was saved. + */ + restoreExternalContextPaths(savedPaths, isEmptySession) { + const { plugin } = this.deps; + const externalContextSelector = this.deps.getExternalContextSelector(); + if (!externalContextSelector) { + return; + } + if (isEmptySession) { + externalContextSelector.clearExternalContexts( + plugin.settings.persistentExternalContextPaths || [] + ); + } else { + externalContextSelector.setExternalContexts(savedPaths || []); + } + } + // ============================================ + // History Dropdown + // ============================================ + toggleHistoryDropdown() { + const dropdown = this.deps.getHistoryDropdown(); + if (!dropdown) return; + const isVisible = dropdown.hasClass("visible"); + if (isVisible) { + dropdown.removeClass("visible"); + } else { + this.updateHistoryDropdown(); + dropdown.addClass("visible"); + } + } + updateHistoryDropdown() { + const dropdown = this.deps.getHistoryDropdown(); + if (!dropdown) return; + this.renderHistoryItems(dropdown, { + onSelectConversation: (id) => this.switchTo(id), + onRerender: () => this.updateHistoryDropdown() + }); + } + /** + * Renders history dropdown items to a container. + * Shared implementation for updateHistoryDropdown() and renderHistoryDropdown(). + */ + renderHistoryItems(container, options) { + var _a3; + const { plugin, state } = this.deps; + container.empty(); + const dropdownHeader = container.createDiv({ cls: "claudian-history-header" }); + dropdownHeader.createSpan({ text: "Conversations" }); + const list = container.createDiv({ cls: "claudian-history-list" }); + const allConversations = plugin.getConversationList(); + if (allConversations.length === 0) { + list.createDiv({ cls: "claudian-history-empty", text: "No conversations" }); + return; + } + const conversations = [...allConversations].sort((a, b3) => { + var _a4, _b; + return ((_a4 = b3.lastResponseAt) != null ? _a4 : b3.createdAt) - ((_b = a.lastResponseAt) != null ? _b : a.createdAt); + }); + for (const conv of conversations) { + const isCurrent = conv.id === state.currentConversationId; + const item = list.createDiv({ + cls: `claudian-history-item${isCurrent ? " active" : ""}` + }); + const iconEl = item.createDiv({ cls: "claudian-history-item-icon" }); + (0, import_obsidian8.setIcon)(iconEl, isCurrent ? "message-square-dot" : "message-square"); + const content = item.createDiv({ cls: "claudian-history-item-content" }); + const titleEl = content.createDiv({ cls: "claudian-history-item-title", text: conv.title }); + titleEl.setAttribute("title", conv.title); + content.createDiv({ + cls: "claudian-history-item-date", + text: isCurrent ? "Current session" : this.formatDate((_a3 = conv.lastResponseAt) != null ? _a3 : conv.createdAt) + }); + if (!isCurrent) { + content.addEventListener("click", async (e2) => { + e2.stopPropagation(); + try { + await options.onSelectConversation(conv.id); + } catch (e3) { + } + }); + } + const actions = item.createDiv({ cls: "claudian-history-item-actions" }); + if (conv.titleGenerationStatus === "pending") { + const loadingEl = actions.createEl("span", { cls: "claudian-action-btn claudian-action-loading" }); + (0, import_obsidian8.setIcon)(loadingEl, "loader-2"); + loadingEl.setAttribute("aria-label", "Generating title..."); + } else if (conv.titleGenerationStatus === "failed") { + const regenerateBtn = actions.createEl("button", { cls: "claudian-action-btn" }); + (0, import_obsidian8.setIcon)(regenerateBtn, "refresh-cw"); + regenerateBtn.setAttribute("aria-label", "Regenerate title"); + regenerateBtn.addEventListener("click", async (e2) => { + e2.stopPropagation(); + try { + await this.regenerateTitle(conv.id); + } catch (e3) { + } + }); + } + const renameBtn = actions.createEl("button", { cls: "claudian-action-btn" }); + (0, import_obsidian8.setIcon)(renameBtn, "pencil"); + renameBtn.setAttribute("aria-label", "Rename"); + renameBtn.addEventListener("click", (e2) => { + e2.stopPropagation(); + this.showRenameInput(item, conv.id, conv.title); + }); + const deleteBtn = actions.createEl("button", { cls: "claudian-action-btn claudian-delete-btn" }); + (0, import_obsidian8.setIcon)(deleteBtn, "trash-2"); + deleteBtn.setAttribute("aria-label", "Delete"); + deleteBtn.addEventListener("click", async (e2) => { + e2.stopPropagation(); + if (state.isStreaming) return; + try { + await plugin.deleteConversation(conv.id); + options.onRerender(); + if (conv.id === state.currentConversationId) { + await this.loadActive(); + } + } catch (e3) { + } + }); + } + } + /** Shows inline rename input for a conversation. */ + showRenameInput(item, convId, currentTitle) { + const titleEl = item.querySelector(".claudian-history-item-title"); + if (!titleEl) return; + const input = document.createElement("input"); + input.type = "text"; + input.className = "claudian-rename-input"; + input.value = currentTitle; + titleEl.replaceWith(input); + input.focus(); + input.select(); + const finishRename = async () => { + try { + const newTitle = input.value.trim() || currentTitle; + await this.deps.plugin.renameConversation(convId, newTitle); + this.updateHistoryDropdown(); + } catch (e2) { + } + }; + input.addEventListener("blur", finishRename); + input.addEventListener("keydown", async (e2) => { + if (e2.key === "Enter" && !e2.isComposing) { + input.blur(); + } else if (e2.key === "Escape" && !e2.isComposing) { + input.value = currentTitle; + input.blur(); + } + }); + } + // ============================================ + // Welcome & Greeting + // ============================================ + /** Generates a dynamic greeting based on time/day. */ + getGreeting() { + var _a3; + const now = /* @__PURE__ */ new Date(); + const hour = now.getHours(); + const day = now.getDay(); + const name = (_a3 = this.deps.plugin.settings.userName) == null ? void 0 : _a3.trim(); + const personalize = (base, noNameFallback) => name ? `${base}, ${name}` : noNameFallback != null ? noNameFallback : base; + const dayGreetings = { + 0: [personalize("Happy Sunday"), "Sunday session?", "Welcome to the weekend"], + 1: [personalize("Happy Monday"), personalize("Back at it", "Back at it!")], + 2: [personalize("Happy Tuesday")], + 3: [personalize("Happy Wednesday")], + 4: [personalize("Happy Thursday")], + 5: [personalize("Happy Friday"), personalize("That Friday feeling")], + 6: [personalize("Happy Saturday", "Happy Saturday!"), personalize("Welcome to the weekend")] + }; + const getTimeGreetings = () => { + if (hour >= 5 && hour < 12) { + return [personalize("Good morning"), "Coffee and Claudian time?"]; + } else if (hour >= 12 && hour < 18) { + return [personalize("Good afternoon"), personalize("Hey there"), personalize("How's it going") + "?"]; + } else if (hour >= 18 && hour < 22) { + return [personalize("Good evening"), personalize("Evening"), personalize("How was your day") + "?"]; + } else { + return ["Hello, night owl", personalize("Evening")]; + } + }; + const generalGreetings = [ + personalize("Hey there"), + name ? `Hi ${name}, how are you?` : "Hi, how are you?", + personalize("How's it going") + "?", + personalize("Welcome back") + "!", + personalize("What's new") + "?", + ...name ? [`${name} returns!`] : [], + "You are absolutely right!" + ]; + const allGreetings = [ + ...dayGreetings[day] || [], + ...getTimeGreetings(), + ...generalGreetings + ]; + return allGreetings[Math.floor(Math.random() * allGreetings.length)]; + } + /** Updates welcome element visibility based on message count. */ + updateWelcomeVisibility() { + const welcomeEl = this.deps.getWelcomeEl(); + if (!welcomeEl) return; + if (this.deps.state.messages.length === 0) { + welcomeEl.style.display = ""; + } else { + welcomeEl.style.display = "none"; + } + } + /** + * Initializes the welcome greeting for a new tab without a conversation. + * Called when a new tab is activated and has no conversation loaded. + */ + initializeWelcome() { + const welcomeEl = this.deps.getWelcomeEl(); + if (!welcomeEl) return; + const fileCtx = this.deps.getFileContextManager(); + fileCtx == null ? void 0 : fileCtx.resetForNewConversation(); + fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile(); + if (!welcomeEl.querySelector(".claudian-welcome-greeting")) { + welcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: this.getGreeting() }); + } + this.updateWelcomeVisibility(); + } + // ============================================ + // Utilities + // ============================================ + /** Generates a fallback title from the first message (used when AI fails). */ + generateFallbackTitle(firstMessage) { + const firstSentence = firstMessage.split(/[.!?\n]/)[0].trim(); + const autoTitle = firstSentence.substring(0, 50); + const suffix = firstSentence.length > 50 ? "..." : ""; + return `${autoTitle}${suffix}`; + } + /** Regenerates AI title for a conversation. */ + async regenerateTitle(conversationId) { + const { plugin } = this.deps; + if (!plugin.settings.enableAutoTitleGeneration) return; + const titleService = this.deps.getTitleGenerationService(); + if (!titleService) return; + const fullConv = await plugin.getConversationById(conversationId); + if (!fullConv || fullConv.messages.length < 1) return; + const firstUserMsg = fullConv.messages.find((m) => m.role === "user"); + if (!firstUserMsg) return; + const userContent = firstUserMsg.displayContent || firstUserMsg.content; + const expectedTitle = fullConv.title; + await plugin.updateConversation(conversationId, { titleGenerationStatus: "pending" }); + this.updateHistoryDropdown(); + await titleService.generateTitle( + conversationId, + userContent, + async (convId, result) => { + const currentConv = await plugin.getConversationById(convId); + if (!currentConv) return; + const userManuallyRenamed = currentConv.title !== expectedTitle; + if (result.success && !userManuallyRenamed) { + await plugin.renameConversation(convId, result.title); + await plugin.updateConversation(convId, { titleGenerationStatus: "success" }); + } else if (!userManuallyRenamed) { + await plugin.updateConversation(convId, { titleGenerationStatus: "failed" }); + } else { + await plugin.updateConversation(convId, { titleGenerationStatus: void 0 }); + } + this.updateHistoryDropdown(); + } + ); + } + /** Formats a timestamp for display. */ + formatDate(timestamp) { + const date7 = new Date(timestamp); + const now = /* @__PURE__ */ new Date(); + if (date7.toDateString() === now.toDateString()) { + return date7.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", hour12: false }); + } + return date7.toLocaleDateString(void 0, { month: "short", day: "numeric" }); + } + // ============================================ + // History Dropdown Rendering (for ClaudianView) + // ============================================ + /** + * Renders the history dropdown content to a provided container. + * Used by ClaudianView to render the dropdown with custom selection callback. + */ + renderHistoryDropdown(container, options) { + this.renderHistoryItems(container, { + onSelectConversation: options.onSelectConversation, + onRerender: () => this.renderHistoryDropdown(container, options) + }); + } +}; + +// src/features/chat/controllers/InputController.ts +var import_obsidian11 = require("obsidian"); + +// src/shared/modals/ApprovalModal.ts +var import_obsidian9 = require("obsidian"); +var ApprovalModal = class extends import_obsidian9.Modal { + constructor(app, toolName, _input, description, resolve4, options = {}) { + super(app); + this.resolved = false; + this.buttons = []; + this.currentButtonIndex = 0; + this.documentKeydownHandler = null; + this.toolName = toolName; + this.description = description; + this.resolve = resolve4; + this.options = options; + } + onOpen() { + var _a3, _b; + const { contentEl } = this; + contentEl.addClass("claudian-approval-modal"); + this.setTitle((_a3 = this.options.title) != null ? _a3 : "Permission required"); + const infoEl = contentEl.createDiv({ cls: "claudian-approval-info" }); + const toolEl = infoEl.createDiv({ cls: "claudian-approval-tool" }); + const iconEl = toolEl.createSpan({ cls: "claudian-approval-icon" }); + iconEl.setAttribute("aria-hidden", "true"); + (0, import_obsidian9.setIcon)(iconEl, getToolIcon(this.toolName)); + toolEl.createSpan({ text: this.toolName, cls: "claudian-approval-tool-name" }); + if (this.options.decisionReason) { + const reasonEl = infoEl.createDiv({ cls: "claudian-approval-reason" }); + reasonEl.setText(this.options.decisionReason); + } + if (this.options.blockedPath) { + const pathEl = infoEl.createDiv({ cls: "claudian-approval-blocked-path" }); + pathEl.setText(this.options.blockedPath); + } + if (this.options.agentID) { + const agentEl = infoEl.createDiv({ cls: "claudian-approval-agent" }); + agentEl.setText(`Agent: ${this.options.agentID}`); + } + const descEl = contentEl.createDiv({ cls: "claudian-approval-desc" }); + descEl.setText(this.description); + const buttonsEl = contentEl.createDiv({ cls: "claudian-approval-buttons" }); + const denyBtn = buttonsEl.createEl("button", { + text: "Deny", + cls: "claudian-approval-btn claudian-deny-btn", + attr: { "aria-label": `Deny ${this.toolName} action` } + }); + denyBtn.addEventListener("click", () => this.handleDecision("deny")); + const allowBtn = buttonsEl.createEl("button", { + text: "Allow once", + cls: "claudian-approval-btn claudian-allow-btn", + attr: { "aria-label": `Allow ${this.toolName} action once` } + }); + allowBtn.addEventListener("click", () => this.handleDecision("allow")); + let alwaysAllowBtn = null; + if ((_b = this.options.showAlwaysAllow) != null ? _b : true) { + alwaysAllowBtn = buttonsEl.createEl("button", { + text: "Always allow", + cls: "claudian-approval-btn claudian-always-btn", + attr: { "aria-label": `Always allow ${this.toolName} actions` } + }); + alwaysAllowBtn.addEventListener("click", () => this.handleDecision("allow-always")); + } + this.buttons = [denyBtn, allowBtn]; + if (alwaysAllowBtn) { + this.buttons.push(alwaysAllowBtn); + } + this.currentButtonIndex = 0; + this.focusCurrentButton(); + this.attachDocumentHandler(); + } + handleDecision(decision) { + if (!this.resolved) { + this.resolved = true; + this.resolve(decision); + this.close(); + } + } + attachDocumentHandler() { + this.detachDocumentHandler(); + this.documentKeydownHandler = (e2) => { + if (!this.isNavigationKey(e2)) { + return; + } + e2.preventDefault(); + e2.stopPropagation(); + this.handleNavigationKey(e2); + }; + document.addEventListener("keydown", this.documentKeydownHandler, true); + } + detachDocumentHandler() { + if (this.documentKeydownHandler) { + document.removeEventListener("keydown", this.documentKeydownHandler, true); + this.documentKeydownHandler = null; + } + } + isNavigationKey(e2) { + return e2.key === "ArrowUp" || e2.key === "ArrowDown" || e2.key === "ArrowLeft" || e2.key === "ArrowRight" || e2.key === "Tab"; + } + handleNavigationKey(e2) { + if (!this.buttons.length) return; + let direction = 0; + switch (e2.key) { + case "ArrowUp": + case "ArrowLeft": + direction = -1; + break; + case "ArrowDown": + case "ArrowRight": + direction = 1; + break; + case "Tab": + direction = e2.shiftKey ? -1 : 1; + break; + default: + return; + } + const total = this.buttons.length; + this.currentButtonIndex = (this.currentButtonIndex + direction + total) % total; + this.focusCurrentButton(); + } + focusCurrentButton() { + const button = this.buttons[this.currentButtonIndex]; + button == null ? void 0 : button.focus(); + } + onClose() { + this.detachDocumentHandler(); + if (!this.resolved) { + this.resolved = true; + this.resolve("cancel"); + } + this.contentEl.empty(); + } +}; + +// src/shared/modals/InstructionConfirmModal.ts +var import_obsidian10 = require("obsidian"); +var InstructionModal = class extends import_obsidian10.Modal { + constructor(app, rawInstruction, callbacks) { + super(app); + this.state = "loading"; + this.resolved = false; + // UI elements + this.contentSectionEl = null; + this.loadingEl = null; + this.clarificationEl = null; + this.confirmationEl = null; + this.buttonsEl = null; + // Clarification state + this.clarificationTextEl = null; + this.responseTextarea = null; + this.isSubmitting = false; + // Confirmation state + this.refinedInstruction = ""; + this.editTextarea = null; + this.isEditing = false; + this.refinedDisplayEl = null; + this.editContainerEl = null; + this.editBtnEl = null; + this.rawInstruction = rawInstruction; + this.callbacks = callbacks; + } + onOpen() { + const { contentEl } = this; + contentEl.addClass("claudian-instruction-modal"); + this.setTitle("Add Custom Instruction"); + const inputSection = contentEl.createDiv({ cls: "claudian-instruction-section" }); + const inputLabel = inputSection.createDiv({ cls: "claudian-instruction-label" }); + inputLabel.setText("Your input:"); + const inputText = inputSection.createDiv({ cls: "claudian-instruction-original" }); + inputText.setText(this.rawInstruction); + this.contentSectionEl = contentEl.createDiv({ cls: "claudian-instruction-content-section" }); + this.loadingEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-loading" }); + this.loadingEl.createDiv({ cls: "claudian-instruction-spinner" }); + this.loadingEl.createSpan({ text: "Processing your instruction..." }); + this.clarificationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-clarification-section" }); + this.clarificationEl.style.display = "none"; + this.clarificationTextEl = this.clarificationEl.createDiv({ cls: "claudian-instruction-clarification" }); + const responseSection = this.clarificationEl.createDiv({ cls: "claudian-instruction-section" }); + const responseLabel = responseSection.createDiv({ cls: "claudian-instruction-label" }); + responseLabel.setText("Your response:"); + this.responseTextarea = new import_obsidian10.TextAreaComponent(responseSection); + this.responseTextarea.inputEl.addClass("claudian-instruction-response-textarea"); + this.responseTextarea.inputEl.rows = 3; + this.responseTextarea.inputEl.placeholder = "Provide more details..."; + this.responseTextarea.inputEl.addEventListener("keydown", (e2) => { + if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing && !this.isSubmitting) { + e2.preventDefault(); + this.submitClarification(); + } + }); + this.confirmationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-confirmation-section" }); + this.confirmationEl.style.display = "none"; + const refinedSection = this.confirmationEl.createDiv({ cls: "claudian-instruction-section" }); + const refinedLabel = refinedSection.createDiv({ cls: "claudian-instruction-label" }); + refinedLabel.setText("Refined snippet:"); + this.refinedDisplayEl = refinedSection.createDiv({ cls: "claudian-instruction-refined" }); + this.editContainerEl = refinedSection.createDiv({ cls: "claudian-instruction-edit-container" }); + this.editContainerEl.style.display = "none"; + this.editTextarea = new import_obsidian10.TextAreaComponent(this.editContainerEl); + this.editTextarea.inputEl.addClass("claudian-instruction-edit-textarea"); + this.editTextarea.inputEl.rows = 4; + this.buttonsEl = contentEl.createDiv({ cls: "claudian-instruction-buttons" }); + this.updateButtons(); + this.showState("loading"); + } + showClarification(clarification) { + var _a3; + if (this.clarificationTextEl) { + this.clarificationTextEl.setText(clarification); + } + if (this.responseTextarea) { + this.responseTextarea.setValue(""); + } + this.isSubmitting = false; + this.showState("clarification"); + (_a3 = this.responseTextarea) == null ? void 0 : _a3.inputEl.focus(); + } + showConfirmation(refinedInstruction) { + this.refinedInstruction = refinedInstruction; + if (this.refinedDisplayEl) { + this.refinedDisplayEl.setText(refinedInstruction); + } + if (this.editTextarea) { + this.editTextarea.setValue(refinedInstruction); + } + this.showState("confirmation"); + } + showError(error48) { + this.resolved = true; + this.close(); + } + showClarificationLoading() { + this.isSubmitting = true; + if (this.loadingEl) { + this.loadingEl.querySelector(".claudian-instruction-spinner"); + const text = this.loadingEl.querySelector("span"); + if (text) text.textContent = "Processing..."; + } + this.showState("loading"); + } + showState(state) { + this.state = state; + if (this.loadingEl) { + this.loadingEl.style.display = state === "loading" ? "flex" : "none"; + } + if (this.clarificationEl) { + this.clarificationEl.style.display = state === "clarification" ? "block" : "none"; + } + if (this.confirmationEl) { + this.confirmationEl.style.display = state === "confirmation" ? "block" : "none"; + } + this.updateButtons(); + } + updateButtons() { + if (!this.buttonsEl) return; + this.buttonsEl.empty(); + const cancelBtn = this.buttonsEl.createEl("button", { + text: "Cancel", + cls: "claudian-instruction-btn claudian-instruction-reject-btn", + attr: { "aria-label": "Cancel" } + }); + cancelBtn.addEventListener("click", () => this.handleReject()); + if (this.state === "clarification") { + const submitBtn = this.buttonsEl.createEl("button", { + text: "Submit", + cls: "claudian-instruction-btn claudian-instruction-accept-btn", + attr: { "aria-label": "Submit response" } + }); + submitBtn.addEventListener("click", () => this.submitClarification()); + } else if (this.state === "confirmation") { + this.editBtnEl = this.buttonsEl.createEl("button", { + text: "Edit", + cls: "claudian-instruction-btn claudian-instruction-edit-btn", + attr: { "aria-label": "Edit instruction" } + }); + this.editBtnEl.addEventListener("click", () => this.toggleEdit()); + const acceptBtn = this.buttonsEl.createEl("button", { + text: "Accept", + cls: "claudian-instruction-btn claudian-instruction-accept-btn", + attr: { "aria-label": "Accept instruction" } + }); + acceptBtn.addEventListener("click", () => this.handleAccept()); + acceptBtn.focus(); + } + } + async submitClarification() { + var _a3; + const response = (_a3 = this.responseTextarea) == null ? void 0 : _a3.getValue().trim(); + if (!response || this.isSubmitting) return; + this.showClarificationLoading(); + try { + await this.callbacks.onClarificationSubmit(response); + } catch (e2) { + this.isSubmitting = false; + this.showState("clarification"); + } + } + toggleEdit() { + var _a3, _b; + this.isEditing = !this.isEditing; + if (this.isEditing) { + if (this.refinedDisplayEl) this.refinedDisplayEl.style.display = "none"; + if (this.editContainerEl) this.editContainerEl.style.display = "block"; + if (this.editBtnEl) this.editBtnEl.setText("Preview"); + (_a3 = this.editTextarea) == null ? void 0 : _a3.inputEl.focus(); + } else { + const edited = ((_b = this.editTextarea) == null ? void 0 : _b.getValue()) || this.refinedInstruction; + this.refinedInstruction = edited; + if (this.refinedDisplayEl) { + this.refinedDisplayEl.setText(edited); + this.refinedDisplayEl.style.display = "block"; + } + if (this.editContainerEl) this.editContainerEl.style.display = "none"; + if (this.editBtnEl) this.editBtnEl.setText("Edit"); + } + } + handleAccept() { + var _a3; + if (this.resolved) return; + this.resolved = true; + const finalInstruction = this.isEditing ? ((_a3 = this.editTextarea) == null ? void 0 : _a3.getValue()) || this.refinedInstruction : this.refinedInstruction; + this.callbacks.onAccept(finalInstruction); + this.close(); + } + handleReject() { + if (this.resolved) return; + this.resolved = true; + this.callbacks.onReject(); + this.close(); + } + onClose() { + if (!this.resolved) { + this.resolved = true; + this.callbacks.onReject(); + } + this.contentEl.empty(); + } +}; + +// src/utils/editor.ts +function getEditorView(editor) { + return editor.cm; +} +function findNearestNonEmptyLine(getLine, lineCount, startLine, direction) { + const step = direction === "before" ? -1 : 1; + for (let i2 = startLine + step; i2 >= 0 && i2 < lineCount; i2 += step) { + const content = getLine(i2); + if (content.trim().length > 0) { + return content; + } + } + return ""; +} +function buildCursorContext(getLine, lineCount, line, column) { + const lineContent = getLine(line); + const beforeCursor = lineContent.substring(0, column); + const afterCursor = lineContent.substring(column); + const lineIsEmpty = lineContent.trim().length === 0; + const nothingBefore = beforeCursor.trim().length === 0; + const nothingAfter = afterCursor.trim().length === 0; + const isInbetween = lineIsEmpty || nothingBefore && nothingAfter; + let contextBefore = beforeCursor; + let contextAfter = afterCursor; + if (isInbetween) { + contextBefore = findNearestNonEmptyLine(getLine, lineCount, line, "before"); + contextAfter = findNearestNonEmptyLine(getLine, lineCount, line, "after"); + } + return { beforeCursor: contextBefore, afterCursor: contextAfter, isInbetween, line, column }; +} +function formatEditorContext(context) { + if (context.mode === "selection" && context.selectedText) { + const lineAttr = context.startLine && context.lineCount ? ` lines="${context.startLine}-${context.startLine + context.lineCount - 1}"` : ""; + return ` +${context.selectedText} +`; + } else if (context.mode === "cursor" && context.cursorContext) { + const ctx = context.cursorContext; + let content; + if (ctx.isInbetween) { + const parts = []; + if (ctx.beforeCursor) parts.push(ctx.beforeCursor); + parts.push("| #inbetween"); + if (ctx.afterCursor) parts.push(ctx.afterCursor); + content = parts.join("\n"); + } else { + content = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`; + } + return ` +${content} +`; + } + return ""; +} +function appendEditorContext(prompt, context) { + const formatted = formatEditorContext(context); + return formatted ? `${prompt} + +${formatted}` : prompt; +} + +// src/utils/markdown.ts +function appendMarkdownSnippet(existingPrompt, snippet) { + const trimmedSnippet = snippet.trim(); + if (!trimmedSnippet) { + return existingPrompt; + } + if (!existingPrompt.trim()) { + return trimmedSnippet; + } + const separator = existingPrompt.endsWith("\n\n") ? "" : existingPrompt.endsWith("\n") ? "\n" : "\n\n"; + return existingPrompt + separator + trimmedSnippet; +} + +// src/features/chat/controllers/InputController.ts +var InputController = class { + constructor(deps) { + this.pendingApprovalModal = null; + this.deps = deps; + } + getAgentService() { + var _a3, _b, _c; + return (_c = (_b = (_a3 = this.deps).getAgentService) == null ? void 0 : _b.call(_a3)) != null ? _c : null; + } + // ============================================ + // Message Sending + // ============================================ + async sendMessage(options) { + var _a3, _b, _c, _d, _e; + const { plugin, state, renderer, streamController, selectionController, conversationController } = this.deps; + if (state.isCreatingConversation || state.isSwitchingConversation) return; + const inputEl = this.deps.getInputEl(); + const imageContextManager = this.deps.getImageContextManager(); + const fileContextManager = this.deps.getFileContextManager(); + const mcpServerSelector = this.deps.getMcpServerSelector(); + const externalContextSelector = this.deps.getExternalContextSelector(); + const contentOverride = options == null ? void 0 : options.content; + const shouldUseInput = contentOverride === void 0; + const content = (contentOverride != null ? contentOverride : inputEl.value).trim(); + const hasImages = (_a3 = imageContextManager == null ? void 0 : imageContextManager.hasImages()) != null ? _a3 : false; + if (!content && !hasImages) return; + (_b = this.deps.getStatusPanel()) == null ? void 0 : _b.clearTerminalSubagents(); + const builtInCmd = detectBuiltInCommand(content); + if (builtInCmd) { + if (shouldUseInput) { + inputEl.value = ""; + this.deps.resetInputHeight(); + } + await this.executeBuiltInCommand(builtInCmd.command.action, builtInCmd.args); + return; + } + if (state.isStreaming) { + const images2 = hasImages ? [...(imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || []] : void 0; + const editorContext2 = selectionController.getContext(); + if (state.queuedMessage) { + state.queuedMessage.content += "\n\n" + content; + if (images2 && images2.length > 0) { + state.queuedMessage.images = [...state.queuedMessage.images || [], ...images2]; + } + state.queuedMessage.editorContext = editorContext2; + } else { + state.queuedMessage = { + content, + images: images2, + editorContext: editorContext2 + }; + } + if (shouldUseInput) { + inputEl.value = ""; + this.deps.resetInputHeight(); + } + imageContextManager == null ? void 0 : imageContextManager.clearImages(); + this.updateQueueIndicator(); + return; + } + if (shouldUseInput) { + inputEl.value = ""; + this.deps.resetInputHeight(); + } + state.isStreaming = true; + state.cancelRequested = false; + state.ignoreUsageUpdates = false; + this.deps.getSubagentManager().resetSpawnedCount(); + state.autoScrollEnabled = (_c = plugin.settings.enableAutoScroll) != null ? _c : true; + const streamGeneration = state.bumpStreamGeneration(); + const welcomeEl = this.deps.getWelcomeEl(); + if (welcomeEl) { + welcomeEl.style.display = "none"; + } + fileContextManager == null ? void 0 : fileContextManager.startSession(); + const displayContent = content; + let queryOptions; + const images = (imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || []; + const imagesForMessage = images.length > 0 ? [...images] : void 0; + if (shouldUseInput) { + imageContextManager == null ? void 0 : imageContextManager.clearImages(); + } + const currentNotePath = (fileContextManager == null ? void 0 : fileContextManager.getCurrentNotePath()) || null; + const shouldSendCurrentNote = (_d = fileContextManager == null ? void 0 : fileContextManager.shouldSendCurrentNote(currentNotePath)) != null ? _d : false; + const editorContextOverride = options == null ? void 0 : options.editorContextOverride; + const editorContext = editorContextOverride !== void 0 ? editorContextOverride : selectionController.getContext(); + const externalContextPaths = externalContextSelector == null ? void 0 : externalContextSelector.getExternalContexts(); + const isCompact = /^\/compact(\s|$)/i.test(content); + let promptToSend = content; + let currentNoteForMessage; + if (!isCompact) { + if (shouldSendCurrentNote && currentNotePath) { + promptToSend = appendCurrentNote(promptToSend, currentNotePath); + currentNoteForMessage = currentNotePath; + } + if (editorContext) { + promptToSend = appendEditorContext(promptToSend, editorContext); + } + if (fileContextManager) { + promptToSend = fileContextManager.transformContextMentions(promptToSend); + } + } + fileContextManager == null ? void 0 : fileContextManager.markCurrentNoteSent(); + const userMsg = { + id: this.deps.generateId(), + role: "user", + content: promptToSend, + // Full prompt with XML context (for history rebuild) + displayContent, + // Original user input (for UI display) + timestamp: Date.now(), + currentNote: currentNoteForMessage, + images: imagesForMessage + }; + state.addMessage(userMsg); + renderer.addMessage(userMsg); + await this.triggerTitleGeneration(); + const assistantMsg = { + id: this.deps.generateId(), + role: "assistant", + content: "", + timestamp: Date.now(), + toolCalls: [], + contentBlocks: [] + }; + state.addMessage(assistantMsg); + const msgEl = renderer.addMessage(assistantMsg); + const contentEl = msgEl.querySelector(".claudian-message-content"); + state.toolCallElements.clear(); + state.currentContentEl = contentEl; + state.currentTextEl = null; + state.currentTextContent = ""; + streamController.showThinkingIndicator( + isCompact ? "Compacting..." : void 0, + isCompact ? "claudian-thinking--compact" : void 0 + ); + state.responseStartTime = performance.now(); + const mcpMentions = plugin.mcpManager.extractMentions(promptToSend); + promptToSend = plugin.mcpManager.transformMentions(promptToSend); + const enabledMcpServers = mcpServerSelector == null ? void 0 : mcpServerSelector.getEnabledServers(); + if (mcpMentions.size > 0 || enabledMcpServers && enabledMcpServers.size > 0) { + queryOptions = { + ...queryOptions, + mcpMentions, + enabledMcpServers + }; + } + if (externalContextPaths && externalContextPaths.length > 0) { + queryOptions = { + ...queryOptions, + externalContextPaths + }; + } + let wasInterrupted = false; + let wasInvalidated = false; + if (this.deps.ensureServiceInitialized) { + const ready = await this.deps.ensureServiceInitialized(); + if (!ready) { + new import_obsidian11.Notice("Failed to initialize agent service. Please try again."); + streamController.hideThinkingIndicator(); + state.isStreaming = false; + return; + } + } + const agentService = this.getAgentService(); + if (!agentService) { + new import_obsidian11.Notice("Agent service not available. Please reload the plugin."); + return; + } + try { + const previousMessages = state.messages.slice(0, -2); + for await (const chunk of agentService.query(promptToSend, imagesForMessage, previousMessages, queryOptions)) { + if (state.streamGeneration !== streamGeneration) { + wasInvalidated = true; + break; + } + if (state.cancelRequested) { + wasInterrupted = true; + break; + } + await streamController.handleStreamChunk(chunk, assistantMsg); + } + } catch (error48) { + const errorMsg = error48 instanceof Error ? error48.message : "Unknown error"; + await streamController.appendText(` + +**Error:** ${errorMsg}`); + } finally { + state.clearFlavorTimerInterval(); + if (!wasInvalidated && state.streamGeneration === streamGeneration) { + if (wasInterrupted) { + await streamController.appendText('\n\nInterrupted \xB7 What should Claudian do instead?'); + } + streamController.hideThinkingIndicator(); + state.isStreaming = false; + state.cancelRequested = false; + const hasCompactBoundary = (_e = assistantMsg.contentBlocks) == null ? void 0 : _e.some((b3) => b3.type === "compact_boundary"); + if (!wasInterrupted && !hasCompactBoundary) { + const durationSeconds = state.responseStartTime ? Math.floor((performance.now() - state.responseStartTime) / 1e3) : 0; + if (durationSeconds > 0) { + const flavorWord = COMPLETION_FLAVOR_WORDS[Math.floor(Math.random() * COMPLETION_FLAVOR_WORDS.length)]; + assistantMsg.durationSeconds = durationSeconds; + assistantMsg.durationFlavorWord = flavorWord; + if (contentEl) { + const footerEl = contentEl.createDiv({ cls: "claudian-response-footer" }); + footerEl.createSpan({ + text: `* ${flavorWord} for ${formatDurationMmSs(durationSeconds)}`, + cls: "claudian-baked-duration" + }); + } + } + } + state.currentContentEl = null; + streamController.finalizeCurrentThinkingBlock(assistantMsg); + streamController.finalizeCurrentTextBlock(assistantMsg); + this.deps.getSubagentManager().resetStreamingState(); + if (state.currentTodos && state.currentTodos.every((t2) => t2.status === "completed")) { + state.currentTodos = null; + } + const statusPanel = this.deps.getStatusPanel(); + if (statusPanel == null ? void 0 : statusPanel.areAllSubagentsCompleted()) { + statusPanel.clearTerminalSubagents(); + } + await conversationController.save(true); + this.processQueuedMessage(); + } + } + } + // ============================================ + // Queue Management + // ============================================ + updateQueueIndicator() { + var _a3, _b; + const { state } = this.deps; + if (!state.queueIndicatorEl) return; + if (state.queuedMessage) { + const rawContent = state.queuedMessage.content.trim(); + const preview = rawContent.length > 40 ? rawContent.slice(0, 40) + "..." : rawContent; + const hasImages = ((_b = (_a3 = state.queuedMessage.images) == null ? void 0 : _a3.length) != null ? _b : 0) > 0; + let display = preview; + if (hasImages) { + display = display ? `${display} [images]` : "[images]"; + } + state.queueIndicatorEl.setText(`\u2319 Queued: ${display}`); + state.queueIndicatorEl.style.display = "block"; + } else { + state.queueIndicatorEl.style.display = "none"; + } + } + clearQueuedMessage() { + const { state } = this.deps; + state.queuedMessage = null; + this.updateQueueIndicator(); + } + restoreQueuedMessageToInput() { + var _a3; + const { state } = this.deps; + if (!state.queuedMessage) return; + const { content, images } = state.queuedMessage; + state.queuedMessage = null; + this.updateQueueIndicator(); + const inputEl = this.deps.getInputEl(); + inputEl.value = content; + if (images && images.length > 0) { + (_a3 = this.deps.getImageContextManager()) == null ? void 0 : _a3.setImages(images); + } + } + processQueuedMessage() { + var _a3; + const { state } = this.deps; + if (!state.queuedMessage) return; + const { content, images, editorContext } = state.queuedMessage; + state.queuedMessage = null; + this.updateQueueIndicator(); + const inputEl = this.deps.getInputEl(); + inputEl.value = content; + if (images && images.length > 0) { + (_a3 = this.deps.getImageContextManager()) == null ? void 0 : _a3.setImages(images); + } + setTimeout(() => this.sendMessage({ editorContextOverride: editorContext }), 0); + } + // ============================================ + // Title Generation + // ============================================ + /** + * Triggers AI title generation after first user message. + * Handles setting fallback title, firing async generation, and updating UI. + */ + async triggerTitleGeneration() { + var _a3, _b; + const { plugin, state, conversationController } = this.deps; + if (state.messages.length !== 1) { + return; + } + if (!state.currentConversationId) { + const sessionId = (_b = (_a3 = this.getAgentService()) == null ? void 0 : _a3.getSessionId()) != null ? _b : void 0; + const conversation = await plugin.createConversation(sessionId); + state.currentConversationId = conversation.id; + } + const firstUserMsg = state.messages.find((m) => m.role === "user"); + if (!firstUserMsg) { + return; + } + const userContent = firstUserMsg.displayContent || firstUserMsg.content; + const fallbackTitle = conversationController.generateFallbackTitle(userContent); + await plugin.renameConversation(state.currentConversationId, fallbackTitle); + if (!plugin.settings.enableAutoTitleGeneration) { + return; + } + const titleService = this.deps.getTitleGenerationService(); + if (!titleService) { + return; + } + await plugin.updateConversation(state.currentConversationId, { titleGenerationStatus: "pending" }); + conversationController.updateHistoryDropdown(); + const convId = state.currentConversationId; + const expectedTitle = fallbackTitle; + titleService.generateTitle( + convId, + userContent, + async (conversationId, result) => { + const currentConv = await plugin.getConversationById(conversationId); + if (!currentConv) return; + const userManuallyRenamed = currentConv.title !== expectedTitle; + if (result.success && !userManuallyRenamed) { + await plugin.renameConversation(conversationId, result.title); + await plugin.updateConversation(conversationId, { titleGenerationStatus: "success" }); + } else if (!userManuallyRenamed) { + await plugin.updateConversation(conversationId, { titleGenerationStatus: "failed" }); + } else { + await plugin.updateConversation(conversationId, { titleGenerationStatus: void 0 }); + } + conversationController.updateHistoryDropdown(); + } + ).catch(() => { + }); + } + // ============================================ + // Streaming Control + // ============================================ + cancelStreaming() { + var _a3; + const { state, streamController } = this.deps; + if (!state.isStreaming) return; + state.cancelRequested = true; + this.restoreQueuedMessageToInput(); + (_a3 = this.getAgentService()) == null ? void 0 : _a3.cancel(); + streamController.hideThinkingIndicator(); + } + // ============================================ + // Instruction Mode + // ============================================ + async handleInstructionSubmit(rawInstruction) { + const { plugin } = this.deps; + const instructionRefineService = this.deps.getInstructionRefineService(); + const instructionModeManager = this.deps.getInstructionModeManager(); + if (!instructionRefineService) return; + const existingPrompt = plugin.settings.systemPrompt; + let modal = null; + let wasCancelled = false; + try { + modal = new InstructionModal( + plugin.app, + rawInstruction, + { + onAccept: async (finalInstruction) => { + const currentPrompt = plugin.settings.systemPrompt; + plugin.settings.systemPrompt = appendMarkdownSnippet(currentPrompt, finalInstruction); + await plugin.saveSettings(); + new import_obsidian11.Notice("Instruction added to custom system prompt"); + instructionModeManager == null ? void 0 : instructionModeManager.clear(); + }, + onReject: () => { + wasCancelled = true; + instructionRefineService.cancel(); + instructionModeManager == null ? void 0 : instructionModeManager.clear(); + }, + onClarificationSubmit: async (response) => { + const result2 = await instructionRefineService.continueConversation(response); + if (wasCancelled) { + return; + } + if (!result2.success) { + if (result2.error === "Cancelled") { + return; + } + new import_obsidian11.Notice(result2.error || "Failed to process response"); + modal == null ? void 0 : modal.showError(result2.error || "Failed to process response"); + return; + } + if (result2.clarification) { + modal == null ? void 0 : modal.showClarification(result2.clarification); + } else if (result2.refinedInstruction) { + modal == null ? void 0 : modal.showConfirmation(result2.refinedInstruction); + } + } + } + ); + modal.open(); + instructionRefineService.resetConversation(); + const result = await instructionRefineService.refineInstruction( + rawInstruction, + existingPrompt + ); + if (wasCancelled) { + return; + } + if (!result.success) { + if (result.error === "Cancelled") { + instructionModeManager == null ? void 0 : instructionModeManager.clear(); + return; + } + new import_obsidian11.Notice(result.error || "Failed to refine instruction"); + modal.showError(result.error || "Failed to refine instruction"); + instructionModeManager == null ? void 0 : instructionModeManager.clear(); + return; + } + if (result.clarification) { + modal.showClarification(result.clarification); + } else if (result.refinedInstruction) { + modal.showConfirmation(result.refinedInstruction); + } else { + new import_obsidian11.Notice("No instruction received"); + modal.showError("No instruction received"); + instructionModeManager == null ? void 0 : instructionModeManager.clear(); + } + } catch (error48) { + const errorMsg = error48 instanceof Error ? error48.message : "Unknown error"; + new import_obsidian11.Notice(`Error: ${errorMsg}`); + modal == null ? void 0 : modal.showError(errorMsg); + instructionModeManager == null ? void 0 : instructionModeManager.clear(); + } + } + // ============================================ + // Approval Dialogs + // ============================================ + async handleApprovalRequest(toolName, input, description, options) { + const { plugin } = this.deps; + return new Promise((resolve4) => { + const modal = new ApprovalModal(plugin.app, toolName, input, description, (decision) => { + this.pendingApprovalModal = null; + resolve4(decision); + }, options); + this.pendingApprovalModal = modal; + modal.open(); + }); + } + dismissPendingApproval() { + if (this.pendingApprovalModal) { + this.pendingApprovalModal.close(); + this.pendingApprovalModal = null; + } + } + // ============================================ + // Built-in Commands + // ============================================ + async executeBuiltInCommand(action, args) { + const { conversationController } = this.deps; + switch (action) { + case "clear": + await conversationController.createNew(); + break; + case "add-dir": { + const externalContextSelector = this.deps.getExternalContextSelector(); + if (!externalContextSelector) { + new import_obsidian11.Notice("External context selector not available."); + return; + } + const result = externalContextSelector.addExternalContext(args); + if (result.success) { + new import_obsidian11.Notice(`Added external context: ${result.normalizedPath}`); + } else { + new import_obsidian11.Notice(result.error); + } + break; + } + default: + new import_obsidian11.Notice(`Unknown command: ${action}`); + } + } +}; + +// src/features/chat/controllers/NavigationController.ts +var SCROLL_SPEED = 8; +var NavigationController = class { + constructor(deps) { + this.scrollDirection = null; + this.animationFrameId = null; + this.initialized = false; + this.disposed = false; + this.scrollLoop = () => { + if (this.scrollDirection === null || this.disposed) return; + const messagesEl = this.deps.getMessagesEl(); + if (!messagesEl) { + this.stopScrolling(); + return; + } + const scrollAmount = this.scrollDirection === "up" ? -SCROLL_SPEED : SCROLL_SPEED; + messagesEl.scrollTop += scrollAmount; + this.animationFrameId = requestAnimationFrame(this.scrollLoop); + }; + this.deps = deps; + this.boundMessagesKeydown = this.handleMessagesKeydown.bind(this); + this.boundKeyup = this.handleKeyup.bind(this); + this.boundInputKeydown = this.handleInputKeydown.bind(this); + } + initialize() { + if (this.initialized || this.disposed) return; + const messagesEl = this.deps.getMessagesEl(); + const inputEl = this.deps.getInputEl(); + if (!messagesEl || !inputEl) return; + messagesEl.setAttribute("tabindex", "0"); + messagesEl.addClass("claudian-messages-focusable"); + messagesEl.addEventListener("keydown", this.boundMessagesKeydown); + document.addEventListener("keyup", this.boundKeyup); + inputEl.addEventListener("keydown", this.boundInputKeydown, { capture: true }); + this.initialized = true; + } + /** Cleans up event listeners and animation frames. */ + dispose() { + if (this.disposed) return; + this.disposed = true; + this.stopScrolling(); + document.removeEventListener("keyup", this.boundKeyup); + const messagesEl = this.deps.getMessagesEl(); + messagesEl == null ? void 0 : messagesEl.removeEventListener("keydown", this.boundMessagesKeydown); + messagesEl == null ? void 0 : messagesEl.removeClass("claudian-messages-focusable"); + const inputEl = this.deps.getInputEl(); + inputEl == null ? void 0 : inputEl.removeEventListener("keydown", this.boundInputKeydown, { capture: true }); + } + // ============================================ + // Messages Panel Keyboard Handling + // ============================================ + handleMessagesKeydown(e2) { + if (e2.ctrlKey || e2.metaKey || e2.altKey || e2.shiftKey) return; + const settings11 = this.deps.getSettings(); + const key = e2.key.toLowerCase(); + if (key === settings11.scrollUpKey.toLowerCase()) { + e2.preventDefault(); + this.startScrolling("up"); + return; + } + if (key === settings11.scrollDownKey.toLowerCase()) { + e2.preventDefault(); + this.startScrolling("down"); + return; + } + if (key === settings11.focusInputKey.toLowerCase()) { + e2.preventDefault(); + this.deps.getInputEl().focus(); + return; + } + } + handleKeyup(e2) { + const settings11 = this.deps.getSettings(); + const key = e2.key.toLowerCase(); + if (key === settings11.scrollUpKey.toLowerCase() || key === settings11.scrollDownKey.toLowerCase()) { + this.stopScrolling(); + } + } + // ============================================ + // Input Keyboard Handling (Escape) + // ============================================ + handleInputKeydown(e2) { + var _a3, _b; + if (e2.key !== "Escape") return; + if (e2.isComposing) return; + if (this.deps.isStreaming()) { + return; + } + if ((_b = (_a3 = this.deps).shouldSkipEscapeHandling) == null ? void 0 : _b.call(_a3)) { + return; + } + e2.preventDefault(); + e2.stopPropagation(); + this.deps.getInputEl().blur(); + this.deps.getMessagesEl().focus(); + } + // ============================================ + // Continuous Scrolling with requestAnimationFrame + // ============================================ + startScrolling(direction) { + if (this.scrollDirection === direction) { + return; + } + this.scrollDirection = direction; + this.scrollLoop(); + } + stopScrolling() { + this.scrollDirection = null; + if (this.animationFrameId !== null) { + cancelAnimationFrame(this.animationFrameId); + this.animationFrameId = null; + } + } + // ============================================ + // Public API + // ============================================ + /** Focuses the messages panel. */ + focusMessages() { + this.deps.getMessagesEl().focus(); + } + /** Focuses the input. */ + focusInput() { + this.deps.getInputEl().focus(); + } +}; + +// src/features/chat/controllers/SelectionController.ts +var import_obsidian12 = require("obsidian"); + +// src/shared/components/SelectionHighlight.ts +var import_state = require("@codemirror/state"); +var import_view = require("@codemirror/view"); +function createSelectionHighlighter() { + const showHighlight = import_state.StateEffect.define(); + const hideHighlight = import_state.StateEffect.define(); + const selectionHighlightField = import_state.StateField.define({ + create: () => import_view.Decoration.none, + update: (deco, tr) => { + for (const e2 of tr.effects) { + if (e2.is(showHighlight)) { + const builder = new import_state.RangeSetBuilder(); + builder.add(e2.value.from, e2.value.to, import_view.Decoration.mark({ + class: "claudian-selection-highlight" + })); + return builder.finish(); + } else if (e2.is(hideHighlight)) { + return import_view.Decoration.none; + } + } + return deco.map(tr.changes); + }, + provide: (f3) => import_view.EditorView.decorations.from(f3) + }); + const installedEditors2 = /* @__PURE__ */ new WeakSet(); + function ensureHighlightField(editorView) { + if (!installedEditors2.has(editorView)) { + editorView.dispatch({ + effects: import_state.StateEffect.appendConfig.of(selectionHighlightField) + }); + installedEditors2.add(editorView); + } + } + function show(editorView, from, to) { + ensureHighlightField(editorView); + editorView.dispatch({ + effects: showHighlight.of({ from, to }) + }); + } + function hide(editorView) { + if (installedEditors2.has(editorView)) { + editorView.dispatch({ + effects: hideHighlight.of(null) + }); + } + } + return { show, hide }; +} +var defaultHighlighter = createSelectionHighlighter(); +function showSelectionHighlight(editorView, from, to) { + defaultHighlighter.show(editorView, from, to); +} +function hideSelectionHighlight(editorView) { + defaultHighlighter.hide(editorView); +} + +// src/features/chat/controllers/SelectionController.ts +var SELECTION_POLL_INTERVAL = 250; +var SelectionController = class { + constructor(app, indicatorEl, inputEl, contextRowEl, onVisibilityChange) { + this.storedSelection = null; + this.pollInterval = null; + this.app = app; + this.indicatorEl = indicatorEl; + this.inputEl = inputEl; + this.contextRowEl = contextRowEl; + this.onVisibilityChange = onVisibilityChange != null ? onVisibilityChange : null; + } + start() { + if (this.pollInterval) return; + this.pollInterval = setInterval(() => this.poll(), SELECTION_POLL_INTERVAL); + } + stop() { + if (this.pollInterval) { + clearInterval(this.pollInterval); + this.pollInterval = null; + } + this.clear(); + } + dispose() { + this.stop(); + } + // ============================================ + // Selection Polling + // ============================================ + poll() { + var _a3, _b, _c, _d; + const view = this.app.workspace.getActiveViewOfType(import_obsidian12.MarkdownView); + if (!view) return; + const editor = view.editor; + const editorView = getEditorView(editor); + if (!editorView) return; + const selectedText = editor.getSelection(); + if (selectedText.trim()) { + const fromPos = editor.getCursor("from"); + const toPos = editor.getCursor("to"); + const from = editor.posToOffset(fromPos); + const to = editor.posToOffset(toPos); + const startLine = fromPos.line + 1; + const notePath = ((_a3 = view.file) == null ? void 0 : _a3.path) || "unknown"; + const lineCount = selectedText.split(/\r?\n/).length; + const sameRange = this.storedSelection && this.storedSelection.editorView === editorView && this.storedSelection.from === from && this.storedSelection.to === to && this.storedSelection.notePath === notePath; + const sameText = sameRange && ((_b = this.storedSelection) == null ? void 0 : _b.selectedText) === selectedText; + const sameLineCount = sameRange && ((_c = this.storedSelection) == null ? void 0 : _c.lineCount) === lineCount; + const sameStartLine = sameRange && ((_d = this.storedSelection) == null ? void 0 : _d.startLine) === startLine; + if (!sameRange || !sameText || !sameLineCount || !sameStartLine) { + if (this.storedSelection && !sameRange) { + this.clearHighlight(); + } + this.storedSelection = { notePath, selectedText, lineCount, startLine, from, to, editorView }; + this.updateIndicator(); + } + } else if (document.activeElement !== this.inputEl) { + this.clearHighlight(); + this.storedSelection = null; + this.updateIndicator(); + } + } + // ============================================ + // Highlight Management + // ============================================ + showHighlight() { + if (!this.storedSelection) return; + const { from, to, editorView } = this.storedSelection; + showSelectionHighlight(editorView, from, to); + } + clearHighlight() { + if (!this.storedSelection) return; + hideSelectionHighlight(this.storedSelection.editorView); + } + // ============================================ + // Indicator + // ============================================ + updateIndicator() { + if (!this.indicatorEl) return; + if (this.storedSelection) { + const lineText = this.storedSelection.lineCount === 1 ? "line" : "lines"; + this.indicatorEl.textContent = `${this.storedSelection.lineCount} ${lineText} selected`; + this.indicatorEl.style.display = "block"; + } else { + this.indicatorEl.style.display = "none"; + } + this.updateContextRowVisibility(); + } + updateContextRowVisibility() { + var _a3; + if (!this.contextRowEl) return; + const hasSelection = this.storedSelection !== null; + const fileIndicator = this.contextRowEl.querySelector(".claudian-file-indicator"); + const imagePreview = this.contextRowEl.querySelector(".claudian-image-preview"); + const hasFileChips = (fileIndicator == null ? void 0 : fileIndicator.style.display) === "flex"; + const hasImageChips = (imagePreview == null ? void 0 : imagePreview.style.display) === "flex"; + this.contextRowEl.classList.toggle("has-content", hasSelection || hasFileChips || hasImageChips); + (_a3 = this.onVisibilityChange) == null ? void 0 : _a3.call(this); + } + // ============================================ + // Context Access + // ============================================ + getContext() { + if (!this.storedSelection) return null; + return { + notePath: this.storedSelection.notePath, + mode: "selection", + selectedText: this.storedSelection.selectedText, + lineCount: this.storedSelection.lineCount, + startLine: this.storedSelection.startLine + }; + } + hasSelection() { + return this.storedSelection !== null; + } + // ============================================ + // Clear + // ============================================ + clear() { + this.clearHighlight(); + this.storedSelection = null; + this.updateIndicator(); + } +}; + +// src/utils/diff.ts +function structuredPatchToDiffLines(hunks) { + const result = []; + for (const hunk of hunks) { + let oldLineNum = hunk.oldStart; + let newLineNum = hunk.newStart; + for (const line of hunk.lines) { + const prefix = line[0]; + const text = line.slice(1); + if (prefix === "+") { + result.push({ type: "insert", text, newLineNum: newLineNum++ }); + } else if (prefix === "-") { + result.push({ type: "delete", text, oldLineNum: oldLineNum++ }); + } else { + result.push({ type: "equal", text, oldLineNum: oldLineNum++, newLineNum: newLineNum++ }); + } + } + } + return result; +} +function countLineChanges(diffLines) { + let added = 0; + let removed = 0; + for (const line of diffLines) { + if (line.type === "insert") added++; + else if (line.type === "delete") removed++; + } + return { added, removed }; +} +function extractDiffData(toolUseResult, toolCall) { + const filePath = toolCall.input.file_path || "file"; + if (toolUseResult && typeof toolUseResult === "object") { + const result = toolUseResult; + if (Array.isArray(result.structuredPatch) && result.structuredPatch.length > 0) { + const resultFilePath = (typeof result.filePath === "string" ? result.filePath : null) || filePath; + const hunks = result.structuredPatch; + const diffLines = structuredPatchToDiffLines(hunks); + const stats = countLineChanges(diffLines); + return { filePath: resultFilePath, diffLines, stats }; + } + } + return diffFromToolInput(toolCall, filePath); +} +function diffFromToolInput(toolCall, filePath) { + if (toolCall.name === "Edit") { + const oldStr = toolCall.input.old_string; + const newStr = toolCall.input.new_string; + if (typeof oldStr === "string" && typeof newStr === "string") { + const diffLines = []; + const oldLines = oldStr.split("\n"); + const newLines = newStr.split("\n"); + let oldLineNum = 1; + for (const line of oldLines) { + diffLines.push({ type: "delete", text: line, oldLineNum: oldLineNum++ }); + } + let newLineNum = 1; + for (const line of newLines) { + diffLines.push({ type: "insert", text: line, newLineNum: newLineNum++ }); + } + return { filePath, diffLines, stats: countLineChanges(diffLines) }; + } + } + if (toolCall.name === "Write") { + const content = toolCall.input.content; + if (typeof content === "string") { + const newLines = content.split("\n"); + const diffLines = newLines.map((text, i2) => ({ + type: "insert", + text, + newLineNum: i2 + 1 + })); + return { filePath, diffLines, stats: { added: newLines.length, removed: 0 } }; + } + } + return void 0; +} + +// src/features/chat/controllers/StreamController.ts +var _StreamController = class _StreamController { + constructor(deps) { + this.deps = deps; + } + // ============================================ + // Stream Chunk Handling + // ============================================ + async handleStreamChunk(chunk, msg) { + var _a3, _b, _c, _d, _e; + const { state } = this.deps; + if ("parentToolUseId" in chunk && chunk.parentToolUseId) { + await this.handleSubagentChunk(chunk, msg); + this.scrollToBottom(); + return; + } + switch (chunk.type) { + case "thinking": + this.flushPendingTools(); + if (state.currentTextEl) { + this.finalizeCurrentTextBlock(msg); + } + await this.appendThinking(chunk.content, msg); + break; + case "text": + this.flushPendingTools(); + if (state.currentThinkingState) { + this.finalizeCurrentThinkingBlock(msg); + } + msg.content += chunk.content; + await this.appendText(chunk.content); + break; + case "tool_use": { + if (state.currentThinkingState) { + this.finalizeCurrentThinkingBlock(msg); + } + this.finalizeCurrentTextBlock(msg); + if (chunk.name === TOOL_TASK) { + this.flushPendingTools(); + this.handleTaskToolUseViaManager(chunk, msg); + break; + } + if (chunk.name === TOOL_AGENT_OUTPUT) { + this.handleAgentOutputToolUse(chunk, msg); + break; + } + this.handleRegularToolUse(chunk, msg); + break; + } + case "tool_result": { + this.handleToolResult(chunk, msg); + break; + } + case "blocked": + this.flushPendingTools(); + await this.appendText(` + +\u26A0\uFE0F **Blocked:** ${chunk.content}`); + break; + case "error": + this.flushPendingTools(); + await this.appendText(` + +\u274C **Error:** ${chunk.content}`); + break; + case "done": + this.flushPendingTools(); + break; + case "compact_boundary": { + this.flushPendingTools(); + if (state.currentThinkingState) { + this.finalizeCurrentThinkingBlock(msg); + } + this.finalizeCurrentTextBlock(msg); + msg.contentBlocks = msg.contentBlocks || []; + msg.contentBlocks.push({ type: "compact_boundary" }); + this.renderCompactBoundary(); + break; + } + case "usage": { + const currentSessionId = (_d = (_c = (_b = (_a3 = this.deps).getAgentService) == null ? void 0 : _b.call(_a3)) == null ? void 0 : _c.getSessionId()) != null ? _d : null; + const chunkSessionId = (_e = chunk.sessionId) != null ? _e : null; + if (chunkSessionId && currentSessionId && chunkSessionId !== currentSessionId || chunkSessionId && !currentSessionId) { + break; + } + if (this.deps.subagentManager.subagentsSpawnedThisStream > 0) { + break; + } + if (!state.ignoreUsageUpdates) { + state.usage = chunk.usage; + } + break; + } + } + this.scrollToBottom(); + } + // ============================================ + // Tool Use Handling + // ============================================ + /** + * Handles regular tool_use chunks by buffering them. + * Tools are rendered when flushPendingTools is called (on next content type or tool_result). + */ + handleRegularToolUse(chunk, msg) { + var _a3, _b; + const { state } = this.deps; + const existingToolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === chunk.id); + if (existingToolCall) { + const newInput = chunk.input || {}; + if (Object.keys(newInput).length > 0) { + existingToolCall.input = { ...existingToolCall.input, ...newInput }; + if (existingToolCall.name === TOOL_TODO_WRITE) { + const todos = parseTodoInput(existingToolCall.input); + if (todos) { + this.deps.state.currentTodos = todos; + } + } + const toolEl = state.toolCallElements.get(chunk.id); + if (toolEl) { + const labelEl = (_b = toolEl.querySelector(".claudian-tool-label")) != null ? _b : toolEl.querySelector(".claudian-write-edit-label"); + if (labelEl) { + labelEl.setText(getToolLabel(existingToolCall.name, existingToolCall.input)); + } + } + } + return; + } + const toolCall = { + id: chunk.id, + name: chunk.name, + input: chunk.input, + status: "running", + isExpanded: false + }; + msg.toolCalls = msg.toolCalls || []; + msg.toolCalls.push(toolCall); + msg.contentBlocks = msg.contentBlocks || []; + msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id }); + if (chunk.name === TOOL_TODO_WRITE) { + const todos = parseTodoInput(chunk.input); + if (todos) { + this.deps.state.currentTodos = todos; + } + } + if (state.currentContentEl) { + state.pendingTools.set(chunk.id, { + toolCall, + parentEl: state.currentContentEl + }); + this.showThinkingIndicator(); + } + } + /** + * Flushes all pending tool calls by rendering them. + * Called when a different content type arrives or stream ends. + */ + flushPendingTools() { + const { state } = this.deps; + if (state.pendingTools.size === 0) { + return; + } + for (const toolId of state.pendingTools.keys()) { + this.renderPendingTool(toolId); + } + state.pendingTools.clear(); + } + /** + * Renders a single pending tool call and moves it from pending to rendered state. + */ + renderPendingTool(toolId) { + const { state } = this.deps; + const pending = state.pendingTools.get(toolId); + if (!pending) return; + const { toolCall, parentEl } = pending; + if (!parentEl) return; + if (isWriteEditTool(toolCall.name)) { + const writeEditState = createWriteEditBlock(parentEl, toolCall); + state.writeEditStates.set(toolId, writeEditState); + state.toolCallElements.set(toolId, writeEditState.wrapperEl); + } else { + renderToolCall(parentEl, toolCall, state.toolCallElements); + } + state.pendingTools.delete(toolId); + } + handleToolResult(chunk, msg) { + var _a3; + const { state, subagentManager } = this.deps; + if (subagentManager.hasPendingTask(chunk.id)) { + this.renderPendingTaskViaManager(chunk.id, msg); + } + const subagentState = subagentManager.getSyncSubagent(chunk.id); + if (subagentState) { + this.finalizeSubagent(chunk, msg); + return; + } + if (this.handleAsyncTaskToolResult(chunk)) { + this.showThinkingIndicator(); + return; + } + if (this.handleAgentOutputToolResult(chunk)) { + this.showThinkingIndicator(); + return; + } + if (state.pendingTools.has(chunk.id)) { + this.renderPendingTool(chunk.id); + } + const existingToolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === chunk.id); + const isBlocked = isBlockedToolResult(chunk.content, chunk.isError); + if (existingToolCall) { + existingToolCall.status = isBlocked ? "blocked" : chunk.isError ? "error" : "completed"; + existingToolCall.result = chunk.content; + const writeEditState = state.writeEditStates.get(chunk.id); + if (writeEditState && isWriteEditTool(existingToolCall.name)) { + if (!chunk.isError && !isBlocked) { + const diffData = extractDiffData(chunk.toolUseResult, existingToolCall); + if (diffData) { + existingToolCall.diffData = diffData; + updateWriteEditWithDiff(writeEditState, diffData); + } + } + finalizeWriteEditBlock(writeEditState, chunk.isError || isBlocked); + } else { + updateToolCallResult(chunk.id, existingToolCall, state.toolCallElements); + } + } + this.showThinkingIndicator(); + } + // ============================================ + // Text Block Management + // ============================================ + async appendText(text) { + const { state, renderer } = this.deps; + if (!state.currentContentEl) return; + this.hideThinkingIndicator(); + if (!state.currentTextEl) { + state.currentTextEl = state.currentContentEl.createDiv({ cls: "claudian-text-block" }); + state.currentTextContent = ""; + } + state.currentTextContent += text; + await renderer.renderContent(state.currentTextEl, state.currentTextContent); + } + finalizeCurrentTextBlock(msg) { + const { state, renderer } = this.deps; + if (msg && state.currentTextContent) { + msg.contentBlocks = msg.contentBlocks || []; + msg.contentBlocks.push({ type: "text", content: state.currentTextContent }); + if (state.currentTextEl) { + renderer.addTextCopyButton(state.currentTextEl, state.currentTextContent); + } + } + state.currentTextEl = null; + state.currentTextContent = ""; + } + // ============================================ + // Thinking Block Management + // ============================================ + async appendThinking(content, msg) { + const { state, renderer } = this.deps; + if (!state.currentContentEl) return; + this.hideThinkingIndicator(); + if (!state.currentThinkingState) { + state.currentThinkingState = createThinkingBlock( + state.currentContentEl, + (el, md) => renderer.renderContent(el, md) + ); + } + await appendThinkingContent(state.currentThinkingState, content, (el, md) => renderer.renderContent(el, md)); + } + finalizeCurrentThinkingBlock(msg) { + const { state } = this.deps; + if (!state.currentThinkingState) return; + const durationSeconds = finalizeThinkingBlock(state.currentThinkingState); + if (msg && state.currentThinkingState.content) { + msg.contentBlocks = msg.contentBlocks || []; + msg.contentBlocks.push({ + type: "thinking", + content: state.currentThinkingState.content, + durationSeconds + }); + } + state.currentThinkingState = null; + } + // ============================================ + // Task Tool Handling (via SubagentManager) + // ============================================ + /** Delegates Task tool_use to SubagentManager and updates message based on result. */ + handleTaskToolUseViaManager(chunk, msg) { + const { state, subagentManager } = this.deps; + const result = subagentManager.handleTaskToolUse(chunk.id, chunk.input, state.currentContentEl); + switch (result.action) { + case "created_sync": + this.recordSubagentInMessage(msg, result.subagentState.info, chunk.id); + this.showThinkingIndicator(); + break; + case "created_async": + this.recordSubagentInMessage(msg, result.info, chunk.id, "async"); + this.showThinkingIndicator(); + break; + case "buffered": + this.showThinkingIndicator(); + break; + case "label_updated": + break; + } + } + /** Renders a pending Task via SubagentManager and updates message. */ + renderPendingTaskViaManager(toolId, msg) { + const result = this.deps.subagentManager.renderPendingTask(toolId, this.deps.state.currentContentEl); + if (!result) return; + if (result.mode === "sync") { + this.recordSubagentInMessage(msg, result.subagentState.info, toolId); + } else { + this.recordSubagentInMessage(msg, result.info, toolId, "async"); + } + } + recordSubagentInMessage(msg, info, toolId, mode) { + msg.subagents = msg.subagents || []; + msg.subagents.push(info); + msg.contentBlocks = msg.contentBlocks || []; + msg.contentBlocks.push( + mode ? { type: "subagent", subagentId: toolId, mode } : { type: "subagent", subagentId: toolId } + ); + } + async handleSubagentChunk(chunk, msg) { + if (!("parentToolUseId" in chunk) || !chunk.parentToolUseId) { + return; + } + const parentToolUseId = chunk.parentToolUseId; + const { subagentManager } = this.deps; + if (subagentManager.hasPendingTask(parentToolUseId)) { + this.renderPendingTaskViaManager(parentToolUseId, msg); + } + const subagentState = subagentManager.getSyncSubagent(parentToolUseId); + if (!subagentState) { + return; + } + switch (chunk.type) { + case "tool_use": { + const toolCall = { + id: chunk.id, + name: chunk.name, + input: chunk.input, + status: "running", + isExpanded: false + }; + subagentManager.addSyncToolCall(parentToolUseId, toolCall); + this.showThinkingIndicator(); + break; + } + case "tool_result": { + const toolCall = subagentState.info.toolCalls.find((tc) => tc.id === chunk.id); + if (toolCall) { + const isBlocked = isBlockedToolResult(chunk.content, chunk.isError); + toolCall.status = isBlocked ? "blocked" : chunk.isError ? "error" : "completed"; + toolCall.result = chunk.content; + subagentManager.updateSyncToolResult(parentToolUseId, chunk.id, toolCall); + } + break; + } + case "text": + case "thinking": + break; + } + } + /** Finalizes a sync subagent when its Task tool_result is received. */ + finalizeSubagent(chunk, msg) { + var _a3; + const isError = chunk.isError || false; + this.deps.subagentManager.finalizeSyncSubagent(chunk.id, chunk.content, isError); + const subagentInfo = (_a3 = msg.subagents) == null ? void 0 : _a3.find((s) => s.id === chunk.id); + if (subagentInfo) { + subagentInfo.status = isError ? "error" : "completed"; + subagentInfo.result = chunk.content; + } + this.showThinkingIndicator(); + } + // ============================================ + // Async Subagent Handling + // ============================================ + /** Handles TaskOutput tool_use (invisible, links to async subagent). */ + handleAgentOutputToolUse(chunk, _msg) { + const toolCall = { + id: chunk.id, + name: chunk.name, + input: chunk.input, + status: "running", + isExpanded: false + }; + this.deps.subagentManager.handleAgentOutputToolUse(toolCall); + this.showThinkingIndicator(); + } + handleAsyncTaskToolResult(chunk) { + const { subagentManager } = this.deps; + if (!subagentManager.isPendingAsyncTask(chunk.id)) { + return false; + } + subagentManager.handleTaskToolResult(chunk.id, chunk.content, chunk.isError); + return true; + } + /** Handles TaskOutput result to finalize async subagent. */ + handleAgentOutputToolResult(chunk) { + const { subagentManager } = this.deps; + const isLinked = subagentManager.isLinkedAgentOutputTool(chunk.id); + const handled = subagentManager.handleAgentOutputToolResult( + chunk.id, + chunk.content, + chunk.isError || false + ); + return isLinked || handled !== void 0; + } + /** Callback from SubagentManager when async state changes. Updates messages only (DOM handled by manager). */ + onAsyncSubagentStateChange(subagent) { + this.updateSubagentInMessages(subagent); + this.scrollToBottom(); + } + updateSubagentInMessages(subagent) { + const { state } = this.deps; + for (let i2 = state.messages.length - 1; i2 >= 0; i2--) { + const msg = state.messages[i2]; + if (msg.role === "assistant" && msg.subagents) { + const idx = msg.subagents.findIndex((s) => s.id === subagent.id); + if (idx !== -1) { + msg.subagents[idx] = subagent; + return; + } + } + } + } + /** + * Schedules showing the thinking indicator after a delay. + * If content arrives before the delay, the indicator won't show. + * This prevents the indicator from appearing during active streaming. + * Note: Flavor text is hidden when model thinking block is active (thinking takes priority). + */ + showThinkingIndicator(overrideText, overrideCls) { + const { state } = this.deps; + if (!state.currentContentEl) return; + if (state.thinkingIndicatorTimeout) { + clearTimeout(state.thinkingIndicatorTimeout); + state.thinkingIndicatorTimeout = null; + } + if (state.currentThinkingState) { + return; + } + if (state.thinkingEl) { + state.currentContentEl.appendChild(state.thinkingEl); + this.deps.updateQueueIndicator(); + return; + } + state.thinkingIndicatorTimeout = setTimeout(() => { + state.thinkingIndicatorTimeout = null; + if (!state.currentContentEl || state.thinkingEl || state.currentThinkingState) return; + const cls = overrideCls ? `claudian-thinking ${overrideCls}` : "claudian-thinking"; + state.thinkingEl = state.currentContentEl.createDiv({ cls }); + const text = overrideText || FLAVOR_TEXTS[Math.floor(Math.random() * FLAVOR_TEXTS.length)]; + state.thinkingEl.createSpan({ text }); + const timerSpan = state.thinkingEl.createSpan({ cls: "claudian-thinking-hint" }); + const updateTimer = () => { + if (!state.responseStartTime) return; + if (!timerSpan.isConnected) { + if (state.flavorTimerInterval) { + clearInterval(state.flavorTimerInterval); + state.flavorTimerInterval = null; + } + return; + } + const elapsedSeconds = Math.floor((performance.now() - state.responseStartTime) / 1e3); + timerSpan.setText(` (esc to interrupt \xB7 ${formatDurationMmSs(elapsedSeconds)})`); + }; + updateTimer(); + if (state.flavorTimerInterval) { + clearInterval(state.flavorTimerInterval); + } + state.flavorTimerInterval = setInterval(updateTimer, 1e3); + state.queueIndicatorEl = state.thinkingEl.createDiv({ cls: "claudian-queue-indicator" }); + this.deps.updateQueueIndicator(); + }, _StreamController.THINKING_INDICATOR_DELAY); + } + /** Hides the thinking indicator and cancels any pending show timeout. */ + hideThinkingIndicator() { + const { state } = this.deps; + if (state.thinkingIndicatorTimeout) { + clearTimeout(state.thinkingIndicatorTimeout); + state.thinkingIndicatorTimeout = null; + } + state.clearFlavorTimerInterval(); + if (state.thinkingEl) { + state.thinkingEl.remove(); + state.thinkingEl = null; + } + state.queueIndicatorEl = null; + } + // ============================================ + // Compact Boundary + // ============================================ + renderCompactBoundary() { + const { state } = this.deps; + if (!state.currentContentEl) return; + this.hideThinkingIndicator(); + const el = state.currentContentEl.createDiv({ cls: "claudian-compact-boundary" }); + el.createSpan({ cls: "claudian-compact-boundary-label", text: "Conversation compacted" }); + } + // ============================================ + // Utilities + // ============================================ + /** Scrolls messages to bottom if auto-scroll is enabled. */ + scrollToBottom() { + var _a3; + const { state, plugin } = this.deps; + if (!((_a3 = plugin.settings.enableAutoScroll) != null ? _a3 : true)) return; + if (!state.autoScrollEnabled) return; + const messagesEl = this.deps.getMessagesEl(); + messagesEl.scrollTop = messagesEl.scrollHeight; + } + resetStreamingState() { + const { state } = this.deps; + this.hideThinkingIndicator(); + state.currentContentEl = null; + state.currentTextEl = null; + state.currentTextContent = ""; + state.currentThinkingState = null; + this.deps.subagentManager.resetStreamingState(); + state.pendingTools.clear(); + state.responseStartTime = null; + } +}; +// ============================================ +// Thinking Indicator +// ============================================ +/** Debounce delay before showing thinking indicator (ms). */ +_StreamController.THINKING_INDICATOR_DELAY = 400; +var StreamController = _StreamController; + +// src/core/prompts/instructionRefine.ts +function buildRefineSystemPrompt(existingInstructions) { + const existingSection = existingInstructions.trim() ? ` + +EXISTING INSTRUCTIONS (already in the user's system prompt): +\`\`\` +${existingInstructions.trim()} +\`\`\` + +When refining the new instruction: +- Consider how it fits with existing instructions +- Avoid duplicating existing instructions +- If the new instruction conflicts with an existing one, refine it to be complementary or note the conflict +- Match the format of existing instructions (section, heading, bullet points, style, etc.)` : ""; + return `You are an expert Prompt Engineer. You help users craft precise, effective system instructions for their AI assistant. + +**Your Goal**: Transform vague or simple user requests into **high-quality, actionable, and non-conflicting** system prompt instructions. + +**Process**: +1. **Analyze Intent**: What behavior does the user want to enforce or change? +2. **Check Context**: Does this conflict with existing instructions? + - *No Conflict*: Add as new. + - *Conflict*: Propose a **merged instruction** that resolves the contradiction (or ask if unsure). +3. **Refine**: Draft a clear, positive instruction (e.g., "Do X" instead of "Don't do Y"). +4. **Format**: Return *only* the Markdown snippet wrapped in \`\` tags. + +**Guidelines**: +- **Clarity**: Use precise language. Avoid ambiguity. +- **Scope**: Keep it focused. Don't add unrelated rules. +- **Format**: Valid Markdown (bullets \`-\` or sections \`##\`). +- **No Header**: Do NOT include a top-level header like \`# Custom Instructions\`. +- **Conflict Handling**: If the new rule directly contradicts an existing one, rewrite the *new* one to override specific cases or ask for clarification. + +**Output Format**: +- **Success**: \`...markdown content...\` +- **Ambiguity**: Plain text question. + +${existingSection} + +**Examples**: + +Input: "typescript for code" +Output: - **Code Language**: Always use TypeScript for code examples. Include proper type annotations and interfaces. + +Input: "be concise" +Output: - **Conciseness**: Provide brief, direct responses. Omit conversational filler and unnecessary explanations. + +Input: "organize coding style rules" +Output: ## Coding Standards + +- **Language**: Use TypeScript. +- **Style**: Prefer functional patterns. +- **Review**: Keep diffs small. + +Input: "use that thing from before" +Output: I'm not sure what you're referring to. Could you please clarify?`; +} + +// src/features/chat/services/InstructionRefineService.ts +var InstructionRefineService = class { + constructor(plugin) { + this.abortController = null; + this.sessionId = null; + this.existingInstructions = ""; + this.plugin = plugin; + } + /** Resets conversation state for a new refinement session. */ + resetConversation() { + this.sessionId = null; + } + /** Refines a raw instruction from user input. */ + async refineInstruction(rawInstruction, existingInstructions, onProgress) { + this.sessionId = null; + this.existingInstructions = existingInstructions; + const prompt = `Please refine this instruction: "${rawInstruction}"`; + return this.sendMessage(prompt, onProgress); + } + /** Continues conversation with a follow-up message (for clarifications). */ + async continueConversation(message, onProgress) { + if (!this.sessionId) { + return { success: false, error: "No active conversation to continue" }; + } + return this.sendMessage(message, onProgress); + } + /** Cancels any ongoing query. */ + cancel() { + if (this.abortController) { + this.abortController.abort(); + this.abortController = null; + } + } + async sendMessage(prompt, onProgress) { + var _a3; + const vaultPath = getVaultPath(this.plugin.app); + if (!vaultPath) { + return { success: false, error: "Could not determine vault path" }; + } + const resolvedClaudePath = this.plugin.getResolvedClaudeCliPath(); + if (!resolvedClaudePath) { + return { success: false, error: "Claude CLI not found. Please install Claude Code CLI." }; + } + this.abortController = new AbortController(); + const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables()); + const enhancedPath = getEnhancedPath(customEnv.PATH, resolvedClaudePath); + const missingNodeError = getMissingNodeError(resolvedClaudePath, enhancedPath); + if (missingNodeError) { + return { success: false, error: missingNodeError }; + } + const options = { + cwd: vaultPath, + systemPrompt: buildRefineSystemPrompt(this.existingInstructions), + model: this.plugin.settings.model, + abortController: this.abortController, + pathToClaudeCodeExecutable: resolvedClaudePath, + env: { + ...process.env, + ...customEnv, + PATH: enhancedPath + }, + tools: [], + // No tools needed for instruction refinement + permissionMode: "bypassPermissions", + allowDangerouslySkipPermissions: true, + settingSources: this.plugin.settings.loadUserClaudeSettings ? ["user", "project"] : ["project"] + }; + if (this.sessionId) { + options.resume = this.sessionId; + } + const budgetSetting = this.plugin.settings.thinkingBudget; + const budgetConfig = THINKING_BUDGETS.find((b3) => b3.value === budgetSetting); + if (budgetConfig && budgetConfig.tokens > 0) { + options.maxThinkingTokens = budgetConfig.tokens; + } + try { + const response = u_({ prompt, options }); + let responseText = ""; + for await (const message of response) { + if ((_a3 = this.abortController) == null ? void 0 : _a3.signal.aborted) { + await response.interrupt(); + return { success: false, error: "Cancelled" }; + } + if (message.type === "system" && message.subtype === "init" && message.session_id) { + this.sessionId = message.session_id; + } + const text = this.extractTextFromMessage(message); + if (text) { + responseText += text; + if (onProgress) { + const partialResult = this.parseResponse(responseText); + onProgress(partialResult); + } + } + } + return this.parseResponse(responseText); + } catch (error48) { + const msg = error48 instanceof Error ? error48.message : "Unknown error"; + return { success: false, error: msg }; + } finally { + this.abortController = null; + } + } + /** Parses response text for tag. */ + parseResponse(responseText) { + const instructionMatch = responseText.match(/([\s\S]*?)<\/instruction>/); + if (instructionMatch) { + return { success: true, refinedInstruction: instructionMatch[1].trim() }; + } + const trimmed = responseText.trim(); + if (trimmed) { + return { success: true, clarification: trimmed }; + } + return { success: false, error: "Empty response" }; + } + /** Extracts text content from SDK message. */ + extractTextFromMessage(message) { + var _a3; + if (message.type !== "assistant" || !((_a3 = message.message) == null ? void 0 : _a3.content)) { + return ""; + } + return message.message.content.filter((block) => block.type === "text" && !!block.text).map((block) => block.text).join(""); + } +}; + +// src/features/chat/services/SubagentManager.ts +var SubagentManager = class { + constructor(onStateChange) { + this.syncSubagents = /* @__PURE__ */ new Map(); + this.pendingTasks = /* @__PURE__ */ new Map(); + this._spawnedThisStream = 0; + this.activeAsyncSubagents = /* @__PURE__ */ new Map(); + this.pendingAsyncSubagents = /* @__PURE__ */ new Map(); + this.taskIdToAgentId = /* @__PURE__ */ new Map(); + this.outputToolIdToAgentId = /* @__PURE__ */ new Map(); + this.asyncDomStates = /* @__PURE__ */ new Map(); + this.onStateChange = onStateChange; + } + setCallback(callback) { + this.onStateChange = callback; + } + // ============================================ + // Unified Task Entry Point + // ============================================ + /** + * Handles a Task tool_use chunk with minimal buffering to determine sync vs async. + * Returns a typed result so StreamController can update messages accordingly. + */ + handleTaskToolUse(taskToolId, taskInput, currentContentEl) { + const existingSyncState = this.syncSubagents.get(taskToolId); + if (existingSyncState) { + this.updateSubagentLabel(existingSyncState.wrapperEl, existingSyncState.info, taskInput); + return { action: "label_updated" }; + } + const existingAsyncState = this.asyncDomStates.get(taskToolId); + if (existingAsyncState) { + this.updateSubagentLabel(existingAsyncState.wrapperEl, existingAsyncState.info, taskInput); + const canonical = this.getByTaskId(taskToolId); + if (canonical && canonical !== existingAsyncState.info) { + if (taskInput.description) canonical.description = taskInput.description; + if (taskInput.prompt) canonical.prompt = taskInput.prompt; + } + return { action: "label_updated" }; + } + const pending = this.pendingTasks.get(taskToolId); + if (pending) { + const newInput = taskInput || {}; + if (Object.keys(newInput).length > 0) { + pending.toolCall.input = { ...pending.toolCall.input, ...newInput }; + } + if (currentContentEl) { + pending.parentEl = currentContentEl; + } + const runInBackground2 = pending.toolCall.input.run_in_background; + if (runInBackground2 !== void 0) { + const result = this.renderPendingTask(taskToolId, currentContentEl); + if (result) { + return result.mode === "sync" ? { action: "created_sync", subagentState: result.subagentState } : { action: "created_async", info: result.info, domState: result.domState }; + } + } + return { action: "buffered" }; + } + if (!currentContentEl) { + const toolCall2 = { + id: taskToolId, + name: "Task", + input: taskInput || {}, + status: "running", + isExpanded: false + }; + this.pendingTasks.set(taskToolId, { toolCall: toolCall2, parentEl: null }); + return { action: "buffered" }; + } + const runInBackground = taskInput == null ? void 0 : taskInput.run_in_background; + if (runInBackground !== void 0) { + this._spawnedThisStream++; + if (runInBackground === true) { + return this.createAsyncTask(taskToolId, taskInput, currentContentEl); + } else { + return this.createSyncTask(taskToolId, taskInput, currentContentEl); + } + } + const toolCall = { + id: taskToolId, + name: "Task", + input: taskInput || {}, + status: "running", + isExpanded: false + }; + this.pendingTasks.set(taskToolId, { + toolCall, + parentEl: currentContentEl + }); + return { action: "buffered" }; + } + // ============================================ + // Pending Task Resolution + // ============================================ + hasPendingTask(toolId) { + return this.pendingTasks.has(toolId); + } + /** + * Renders a buffered pending task. Called when a child chunk or tool_result + * confirms the task is sync, or when run_in_background becomes known. + * Uses the optional parentEl override, falling back to the stored parentEl. + */ + renderPendingTask(toolId, parentElOverride) { + const pending = this.pendingTasks.get(toolId); + if (!pending) return null; + const input = pending.toolCall.input; + const targetEl = parentElOverride != null ? parentElOverride : pending.parentEl; + if (!targetEl) return null; + this.pendingTasks.delete(toolId); + try { + if (input.run_in_background === true) { + const result = this.createAsyncTask(pending.toolCall.id, input, targetEl); + if (result.action === "created_async") { + this._spawnedThisStream++; + return { mode: "async", info: result.info, domState: result.domState }; + } + } else { + const result = this.createSyncTask(pending.toolCall.id, input, targetEl); + if (result.action === "created_sync") { + this._spawnedThisStream++; + return { mode: "sync", subagentState: result.subagentState }; + } + } + } catch (e2) { + } + return null; + } + // ============================================ + // Sync Subagent Operations + // ============================================ + getSyncSubagent(toolId) { + return this.syncSubagents.get(toolId); + } + addSyncToolCall(parentToolUseId, toolCall) { + const subagentState = this.syncSubagents.get(parentToolUseId); + if (!subagentState) return; + addSubagentToolCall(subagentState, toolCall); + } + updateSyncToolResult(parentToolUseId, toolId, toolCall) { + const subagentState = this.syncSubagents.get(parentToolUseId); + if (!subagentState) return; + updateSubagentToolResult(subagentState, toolId, toolCall); + } + finalizeSyncSubagent(toolId, result, isError) { + const subagentState = this.syncSubagents.get(toolId); + if (!subagentState) return null; + finalizeSubagentBlock(subagentState, result, isError); + this.syncSubagents.delete(toolId); + return subagentState.info; + } + // ============================================ + // Async Subagent Lifecycle + // ============================================ + isAsyncTask(taskInput) { + return taskInput.run_in_background === true; + } + handleTaskToolResult(taskToolId, result, isError) { + const subagent = this.pendingAsyncSubagents.get(taskToolId); + if (!subagent) return; + if (isError) { + this.transitionToError(subagent, taskToolId, result || "Task failed to start"); + return; + } + const agentId = this.parseAgentId(result); + if (!agentId) { + const truncatedResult = result.length > 100 ? result.substring(0, 100) + "..." : result; + this.transitionToError(subagent, taskToolId, `Failed to parse agent_id. Result: ${truncatedResult}`); + return; + } + subagent.asyncStatus = "running"; + subagent.agentId = agentId; + subagent.startedAt = Date.now(); + this.pendingAsyncSubagents.delete(taskToolId); + this.activeAsyncSubagents.set(agentId, subagent); + this.taskIdToAgentId.set(taskToolId, agentId); + this.updateAsyncDomState(subagent); + this.onStateChange(subagent); + } + handleAgentOutputToolUse(toolCall) { + const agentId = this.extractAgentIdFromInput(toolCall.input); + if (!agentId) return; + const subagent = this.activeAsyncSubagents.get(agentId); + if (!subagent) return; + subagent.outputToolId = toolCall.id; + this.outputToolIdToAgentId.set(toolCall.id, agentId); + } + handleAgentOutputToolResult(toolId, result, isError) { + let agentId = this.outputToolIdToAgentId.get(toolId); + let subagent = agentId ? this.activeAsyncSubagents.get(agentId) : void 0; + if (!subagent) { + const inferredAgentId = this.inferAgentIdFromResult(result); + if (inferredAgentId) { + agentId = inferredAgentId; + subagent = this.activeAsyncSubagents.get(inferredAgentId); + } + } + if (!subagent) return void 0; + if (agentId) { + subagent.agentId = subagent.agentId || agentId; + this.outputToolIdToAgentId.set(toolId, agentId); + } + if (subagent.asyncStatus !== "running") { + return void 0; + } + const stillRunning = this.isStillRunningResult(result, isError); + if (stillRunning) { + this.outputToolIdToAgentId.delete(toolId); + return subagent; + } + const extractedResult = this.extractAgentResult(result, agentId != null ? agentId : ""); + subagent.asyncStatus = isError ? "error" : "completed"; + subagent.status = isError ? "error" : "completed"; + subagent.result = extractedResult; + subagent.completedAt = Date.now(); + if (agentId) this.activeAsyncSubagents.delete(agentId); + this.outputToolIdToAgentId.delete(toolId); + this.updateAsyncDomState(subagent); + this.onStateChange(subagent); + return subagent; + } + isPendingAsyncTask(taskToolId) { + return this.pendingAsyncSubagents.has(taskToolId); + } + isLinkedAgentOutputTool(toolId) { + return this.outputToolIdToAgentId.has(toolId); + } + getByAgentId(agentId) { + return this.activeAsyncSubagents.get(agentId); + } + getByTaskId(taskToolId) { + const pending = this.pendingAsyncSubagents.get(taskToolId); + if (pending) return pending; + const agentId = this.taskIdToAgentId.get(taskToolId); + if (agentId) { + return this.activeAsyncSubagents.get(agentId); + } + return void 0; + } + getAsyncDomState(taskToolId) { + return this.asyncDomStates.get(taskToolId); + } + // ============================================ + // Lifecycle + // ============================================ + get subagentsSpawnedThisStream() { + return this._spawnedThisStream; + } + resetSpawnedCount() { + this._spawnedThisStream = 0; + } + resetStreamingState() { + this.syncSubagents.clear(); + this.pendingTasks.clear(); + } + orphanAllActive() { + const orphaned = []; + for (const subagent of this.pendingAsyncSubagents.values()) { + this.markOrphaned(subagent); + orphaned.push(subagent); + } + for (const subagent of this.activeAsyncSubagents.values()) { + if (subagent.asyncStatus === "running") { + this.markOrphaned(subagent); + orphaned.push(subagent); + } + } + this.pendingAsyncSubagents.clear(); + this.activeAsyncSubagents.clear(); + this.taskIdToAgentId.clear(); + this.outputToolIdToAgentId.clear(); + return orphaned; + } + clear() { + this.syncSubagents.clear(); + this.pendingTasks.clear(); + this.pendingAsyncSubagents.clear(); + this.activeAsyncSubagents.clear(); + this.taskIdToAgentId.clear(); + this.outputToolIdToAgentId.clear(); + this.asyncDomStates.clear(); + } + getAllActive() { + return [ + ...this.pendingAsyncSubagents.values(), + ...this.activeAsyncSubagents.values() + ]; + } + hasActiveAsync() { + return this.pendingAsyncSubagents.size > 0 || this.activeAsyncSubagents.size > 0; + } + // ============================================ + // Private: State Transitions + // ============================================ + markOrphaned(subagent) { + subagent.asyncStatus = "orphaned"; + subagent.status = "error"; + subagent.result = "Conversation ended before task completed"; + subagent.completedAt = Date.now(); + this.updateAsyncDomState(subagent); + this.onStateChange(subagent); + } + transitionToError(subagent, taskToolId, errorResult) { + subagent.asyncStatus = "error"; + subagent.status = "error"; + subagent.result = errorResult; + subagent.completedAt = Date.now(); + this.pendingAsyncSubagents.delete(taskToolId); + this.updateAsyncDomState(subagent); + this.onStateChange(subagent); + } + // ============================================ + // Private: Task Creation + // ============================================ + createSyncTask(taskToolId, taskInput, parentEl) { + const subagentState = createSubagentBlock(parentEl, taskToolId, taskInput); + this.syncSubagents.set(taskToolId, subagentState); + return { action: "created_sync", subagentState }; + } + createAsyncTask(taskToolId, taskInput, parentEl) { + const description = taskInput.description || "Background task"; + const prompt = taskInput.prompt || ""; + const info = { + id: taskToolId, + description, + prompt, + mode: "async", + isExpanded: false, + status: "running", + toolCalls: [], + asyncStatus: "pending" + }; + this.pendingAsyncSubagents.set(taskToolId, info); + const domState = createAsyncSubagentBlock(parentEl, taskToolId, taskInput); + this.asyncDomStates.set(taskToolId, domState); + return { action: "created_async", info, domState }; + } + // ============================================ + // Private: Label Update + // ============================================ + updateSubagentLabel(wrapperEl, info, newInput) { + if (!newInput || Object.keys(newInput).length === 0) return; + const description = newInput.description || ""; + if (description) { + info.description = description; + const labelEl = wrapperEl.querySelector(".claudian-subagent-label"); + if (labelEl) { + const truncated = description.length > 40 ? description.substring(0, 40) + "..." : description; + labelEl.setText(truncated); + } + } + const prompt = newInput.prompt || ""; + if (prompt) { + info.prompt = prompt; + } + } + // ============================================ + // Private: Async DOM State Updates + // ============================================ + updateAsyncDomState(subagent) { + let asyncState = this.asyncDomStates.get(subagent.id); + if (!asyncState) { + for (const s of this.asyncDomStates.values()) { + if (s.info.agentId === subagent.agentId) { + asyncState = s; + break; + } + } + if (!asyncState) return; + } + asyncState.info = subagent; + switch (subagent.asyncStatus) { + case "running": + updateAsyncSubagentRunning(asyncState, subagent.agentId || ""); + break; + case "completed": + case "error": + finalizeAsyncSubagent(asyncState, subagent.result || "", subagent.asyncStatus === "error"); + break; + case "orphaned": + markAsyncSubagentOrphaned(asyncState); + break; + } + } + // ============================================ + // Private: Async Parsing Logic + // ============================================ + isStillRunningResult(result, isError) { + const trimmed = (result == null ? void 0 : result.trim()) || ""; + const payload = this.unwrapTextPayload(trimmed); + if (isError) return false; + if (!trimmed) return false; + try { + const parsed = JSON.parse(payload); + const status = parsed.retrieval_status || parsed.status; + const hasAgents = parsed.agents && Object.keys(parsed.agents).length > 0; + if (status === "not_ready" || status === "running" || status === "pending") { + return true; + } + if (hasAgents) { + const agentStatuses = Object.values(parsed.agents).map((a) => a && typeof a.status === "string" ? a.status.toLowerCase() : ""); + const anyRunning = agentStatuses.some( + (s) => s === "running" || s === "pending" || s === "not_ready" + ); + if (anyRunning) return true; + return false; + } + if (status === "success" || status === "completed") { + return false; + } + return false; + } catch (e2) { + } + const lowerResult = payload.toLowerCase(); + if (lowerResult.includes("not_ready") || lowerResult.includes("not ready")) { + return true; + } + const xmlStatusMatch = lowerResult.match(/([^<]+)<\/status>/); + if (xmlStatusMatch) { + const status = xmlStatusMatch[1].trim(); + if (status === "running" || status === "pending" || status === "not_ready") { + return true; + } + } + return false; + } + extractAgentResult(result, agentId) { + const payload = this.unwrapTextPayload(result); + try { + const parsed = JSON.parse(payload); + if (parsed.agents && agentId && parsed.agents[agentId]) { + const agentData = parsed.agents[agentId]; + if (agentData.result) { + return agentData.result; + } + return JSON.stringify(agentData, null, 2); + } + if (parsed.agents) { + const agentIds = Object.keys(parsed.agents); + if (agentIds.length > 0) { + const firstAgent = parsed.agents[agentIds[0]]; + if (firstAgent.result) { + return firstAgent.result; + } + return JSON.stringify(firstAgent, null, 2); + } + } + } catch (e2) { + } + return payload; + } + parseAgentId(result) { + var _a3; + const regexPatterns = [ + /"agent_id"\s*:\s*"([^"]+)"/, + /"agentId"\s*:\s*"([^"]+)"/, + /agent_id[=:]\s*"?([a-zA-Z0-9_-]+)"?/i, + /agentId[=:]\s*"?([a-zA-Z0-9_-]+)"?/i, + /\b([a-f0-9]{8})\b/ + ]; + for (const pattern of regexPatterns) { + const match = result.match(pattern); + if (match && match[1]) { + return match[1]; + } + } + try { + const parsed = JSON.parse(result); + const agentId = parsed.agent_id || parsed.agentId; + if (typeof agentId === "string" && agentId.length > 0) { + return agentId; + } + if ((_a3 = parsed.data) == null ? void 0 : _a3.agent_id) { + return parsed.data.agent_id; + } + if (parsed.id && typeof parsed.id === "string") { + return parsed.id; + } + } catch (e2) { + } + return null; + } + inferAgentIdFromResult(result) { + try { + const parsed = JSON.parse(result); + if (parsed.agents && typeof parsed.agents === "object") { + const keys = Object.keys(parsed.agents); + if (keys.length > 0) { + return keys[0]; + } + } + } catch (e2) { + } + return null; + } + unwrapTextPayload(raw) { + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + const textBlock = parsed.find((b3) => b3 && typeof b3.text === "string"); + if (textBlock == null ? void 0 : textBlock.text) return textBlock.text; + } else if (parsed && typeof parsed === "object" && typeof parsed.text === "string") { + return parsed.text; + } + } catch (e2) { + } + return raw; + } + extractAgentIdFromInput(input) { + const agentId = input.task_id || input.agentId || input.agent_id; + return agentId || null; + } +}; + +// src/core/prompts/titleGeneration.ts +var TITLE_GENERATION_SYSTEM_PROMPT = `You are a specialist in summarizing user intent. + +**Task**: Generate a **concise, descriptive title** (max 50 chars) summarizing the user's task/request. + +**Rules**: +1. **Format**: Sentence case. No periods/quotes. +2. **Structure**: Start with a **strong verb** (e.g., Create, Fix, Debug, Explain, Analyze). +3. **Forbidden**: "Conversation with...", "Help me...", "Question about...", "I need...". +4. **Tech Context**: Detect and include the primary language/framework if code is present (e.g., "Debug Python script", "Refactor React hook"). + +**Output**: Return ONLY the raw title text.`; + +// src/features/chat/services/TitleGenerationService.ts +var TitleGenerationService = class { + constructor(plugin) { + this.activeGenerations = /* @__PURE__ */ new Map(); + this.plugin = plugin; + } + /** + * Generates a title for a conversation based on the first user message. + * Non-blocking: calls callback when complete. + */ + async generateTitle(conversationId, userMessage, callback) { + const vaultPath = getVaultPath(this.plugin.app); + if (!vaultPath) { + await this.safeCallback(callback, conversationId, { + success: false, + error: "Could not determine vault path" + }); + return; + } + const envVars = parseEnvironmentVariables( + this.plugin.getActiveEnvironmentVariables() + ); + const resolvedClaudePath = this.plugin.getResolvedClaudeCliPath(); + if (!resolvedClaudePath) { + await this.safeCallback(callback, conversationId, { + success: false, + error: "Claude CLI not found" + }); + return; + } + const enhancedPath = getEnhancedPath(envVars.PATH, resolvedClaudePath); + const missingNodeError = getMissingNodeError(resolvedClaudePath, enhancedPath); + if (missingNodeError) { + await this.safeCallback(callback, conversationId, { + success: false, + error: missingNodeError + }); + return; + } + const titleModel = this.plugin.settings.titleGenerationModel || envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL || "claude-haiku-4-5"; + const existingController = this.activeGenerations.get(conversationId); + if (existingController) { + existingController.abort(); + } + const abortController = new AbortController(); + this.activeGenerations.set(conversationId, abortController); + const truncatedUser = this.truncateText(userMessage, 500); + const prompt = `User's request: +""" +${truncatedUser} +""" + +Generate a title for this conversation:`; + const options = { + cwd: vaultPath, + systemPrompt: TITLE_GENERATION_SYSTEM_PROMPT, + model: titleModel, + abortController, + pathToClaudeCodeExecutable: resolvedClaudePath, + env: { + ...process.env, + ...envVars, + PATH: enhancedPath + }, + tools: [], + // No tools needed for title generation + permissionMode: "bypassPermissions", + allowDangerouslySkipPermissions: true, + settingSources: this.plugin.settings.loadUserClaudeSettings ? ["user", "project"] : ["project"], + persistSession: false + // Don't save title generation queries to session history + }; + try { + const response = u_({ prompt, options }); + let responseText = ""; + for await (const message of response) { + if (abortController.signal.aborted) { + await this.safeCallback(callback, conversationId, { + success: false, + error: "Cancelled" + }); + return; + } + const text = this.extractTextFromMessage(message); + if (text) { + responseText += text; + } + } + const title = this.parseTitle(responseText); + if (title) { + await this.safeCallback(callback, conversationId, { success: true, title }); + } else { + await this.safeCallback(callback, conversationId, { + success: false, + error: "Failed to parse title from response" + }); + } + } catch (error48) { + const msg = error48 instanceof Error ? error48.message : "Unknown error"; + await this.safeCallback(callback, conversationId, { success: false, error: msg }); + } finally { + this.activeGenerations.delete(conversationId); + } + } + /** Cancels all ongoing title generations. */ + cancel() { + for (const controller of this.activeGenerations.values()) { + controller.abort(); + } + this.activeGenerations.clear(); + } + /** Truncates text to a maximum length with ellipsis. */ + truncateText(text, maxLength) { + if (text.length <= maxLength) return text; + return text.substring(0, maxLength) + "..."; + } + /** Extracts text content from SDK message. */ + extractTextFromMessage(message) { + var _a3; + if (message.type !== "assistant" || !((_a3 = message.message) == null ? void 0 : _a3.content)) { + return ""; + } + return message.message.content.filter( + (block) => block.type === "text" && !!block.text + ).map((block) => block.text).join(""); + } + /** Parses and cleans the title from response. */ + parseTitle(responseText) { + const trimmed = responseText.trim(); + if (!trimmed) return null; + let title = trimmed; + if (title.startsWith('"') && title.endsWith('"') || title.startsWith("'") && title.endsWith("'")) { + title = title.slice(1, -1); + } + title = title.replace(/[.!?:;,]+$/, ""); + if (title.length > 50) { + title = title.substring(0, 47) + "..."; + } + return title || null; + } + /** Safely invokes callback with try-catch to prevent unhandled errors. */ + async safeCallback(callback, conversationId, result) { + try { + await callback(conversationId, result); + } catch (e2) { + } + } +}; + +// src/features/chat/state/ChatState.ts +function createInitialState() { + return { + messages: [], + isStreaming: false, + cancelRequested: false, + streamGeneration: 0, + isCreatingConversation: false, + isSwitchingConversation: false, + currentConversationId: null, + queuedMessage: null, + currentContentEl: null, + currentTextEl: null, + currentTextContent: "", + currentThinkingState: null, + thinkingEl: null, + queueIndicatorEl: null, + thinkingIndicatorTimeout: null, + toolCallElements: /* @__PURE__ */ new Map(), + writeEditStates: /* @__PURE__ */ new Map(), + pendingTools: /* @__PURE__ */ new Map(), + usage: null, + ignoreUsageUpdates: false, + currentTodos: null, + needsAttention: false, + autoScrollEnabled: true, + // Default; controllers will override based on settings + responseStartTime: null, + flavorTimerInterval: null + }; +} +var ChatState = class { + constructor(callbacks = {}) { + this.state = createInitialState(); + this._callbacks = callbacks; + } + get callbacks() { + return this._callbacks; + } + set callbacks(value) { + this._callbacks = value; + } + // ============================================ + // Messages + // ============================================ + get messages() { + return [...this.state.messages]; + } + set messages(value) { + var _a3, _b; + this.state.messages = value; + (_b = (_a3 = this._callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a3); + } + addMessage(msg) { + var _a3, _b; + this.state.messages.push(msg); + (_b = (_a3 = this._callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a3); + } + clearMessages() { + var _a3, _b; + this.state.messages = []; + (_b = (_a3 = this._callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a3); + } + // ============================================ + // Streaming Control + // ============================================ + get isStreaming() { + return this.state.isStreaming; + } + set isStreaming(value) { + var _a3, _b; + this.state.isStreaming = value; + (_b = (_a3 = this._callbacks).onStreamingStateChanged) == null ? void 0 : _b.call(_a3, value); + } + get cancelRequested() { + return this.state.cancelRequested; + } + set cancelRequested(value) { + this.state.cancelRequested = value; + } + get streamGeneration() { + return this.state.streamGeneration; + } + bumpStreamGeneration() { + this.state.streamGeneration += 1; + return this.state.streamGeneration; + } + get isCreatingConversation() { + return this.state.isCreatingConversation; + } + set isCreatingConversation(value) { + this.state.isCreatingConversation = value; + } + get isSwitchingConversation() { + return this.state.isSwitchingConversation; + } + set isSwitchingConversation(value) { + this.state.isSwitchingConversation = value; + } + // ============================================ + // Conversation + // ============================================ + get currentConversationId() { + return this.state.currentConversationId; + } + set currentConversationId(value) { + var _a3, _b; + this.state.currentConversationId = value; + (_b = (_a3 = this._callbacks).onConversationChanged) == null ? void 0 : _b.call(_a3, value); + } + // ============================================ + // Queued Message + // ============================================ + get queuedMessage() { + return this.state.queuedMessage; + } + set queuedMessage(value) { + this.state.queuedMessage = value; + } + // ============================================ + // Streaming DOM State + // ============================================ + get currentContentEl() { + return this.state.currentContentEl; + } + set currentContentEl(value) { + this.state.currentContentEl = value; + } + get currentTextEl() { + return this.state.currentTextEl; + } + set currentTextEl(value) { + this.state.currentTextEl = value; + } + get currentTextContent() { + return this.state.currentTextContent; + } + set currentTextContent(value) { + this.state.currentTextContent = value; + } + get currentThinkingState() { + return this.state.currentThinkingState; + } + set currentThinkingState(value) { + this.state.currentThinkingState = value; + } + get thinkingEl() { + return this.state.thinkingEl; + } + set thinkingEl(value) { + this.state.thinkingEl = value; + } + get queueIndicatorEl() { + return this.state.queueIndicatorEl; + } + set queueIndicatorEl(value) { + this.state.queueIndicatorEl = value; + } + get thinkingIndicatorTimeout() { + return this.state.thinkingIndicatorTimeout; + } + set thinkingIndicatorTimeout(value) { + this.state.thinkingIndicatorTimeout = value; + } + // ============================================ + // Tool Tracking Maps (mutable references) + // ============================================ + get toolCallElements() { + return this.state.toolCallElements; + } + get writeEditStates() { + return this.state.writeEditStates; + } + get pendingTools() { + return this.state.pendingTools; + } + // ============================================ + // Usage State + // ============================================ + get usage() { + return this.state.usage; + } + set usage(value) { + var _a3, _b; + this.state.usage = value; + (_b = (_a3 = this._callbacks).onUsageChanged) == null ? void 0 : _b.call(_a3, value); + } + get ignoreUsageUpdates() { + return this.state.ignoreUsageUpdates; + } + set ignoreUsageUpdates(value) { + this.state.ignoreUsageUpdates = value; + } + // ============================================ + // Current Todos (for persistent bottom panel) + // ============================================ + get currentTodos() { + return this.state.currentTodos ? [...this.state.currentTodos] : null; + } + set currentTodos(value) { + var _a3, _b; + const normalizedValue = value && value.length > 0 ? value : null; + this.state.currentTodos = normalizedValue; + (_b = (_a3 = this._callbacks).onTodosChanged) == null ? void 0 : _b.call(_a3, normalizedValue); + } + // ============================================ + // Attention State (approval pending, error, etc.) + // ============================================ + get needsAttention() { + return this.state.needsAttention; + } + set needsAttention(value) { + var _a3, _b; + this.state.needsAttention = value; + (_b = (_a3 = this._callbacks).onAttentionChanged) == null ? void 0 : _b.call(_a3, value); + } + // ============================================ + // Auto-Scroll Control + // ============================================ + get autoScrollEnabled() { + return this.state.autoScrollEnabled; + } + set autoScrollEnabled(value) { + var _a3, _b; + const changed = this.state.autoScrollEnabled !== value; + this.state.autoScrollEnabled = value; + if (changed) { + (_b = (_a3 = this._callbacks).onAutoScrollChanged) == null ? void 0 : _b.call(_a3, value); + } + } + // ============================================ + // Response Timer State + // ============================================ + get responseStartTime() { + return this.state.responseStartTime; + } + set responseStartTime(value) { + this.state.responseStartTime = value; + } + get flavorTimerInterval() { + return this.state.flavorTimerInterval; + } + set flavorTimerInterval(value) { + this.state.flavorTimerInterval = value; + } + // ============================================ + // Reset Methods + // ============================================ + clearFlavorTimerInterval() { + if (this.state.flavorTimerInterval) { + clearInterval(this.state.flavorTimerInterval); + this.state.flavorTimerInterval = null; + } + } + resetStreamingState() { + this.state.currentContentEl = null; + this.state.currentTextEl = null; + this.state.currentTextContent = ""; + this.state.currentThinkingState = null; + this.state.isStreaming = false; + this.state.cancelRequested = false; + if (this.state.thinkingIndicatorTimeout) { + clearTimeout(this.state.thinkingIndicatorTimeout); + this.state.thinkingIndicatorTimeout = null; + } + this.clearFlavorTimerInterval(); + this.state.responseStartTime = null; + } + clearMaps() { + this.state.toolCallElements.clear(); + this.state.writeEditStates.clear(); + this.state.pendingTools.clear(); + } + resetForNewConversation() { + this.clearMessages(); + this.resetStreamingState(); + this.clearMaps(); + this.state.queuedMessage = null; + this.usage = null; + this.currentTodos = null; + this.autoScrollEnabled = true; + } + getPersistedMessages() { + return this.state.messages; + } +}; + +// src/features/chat/ui/FileContext.ts +var import_obsidian15 = require("obsidian"); + +// src/shared/mention/MentionDropdownController.ts +var import_obsidian13 = require("obsidian"); + +// src/utils/externalContext.ts +var fs5 = __toESM(require("fs")); +function normalizePathForComparison3(p2) { + return normalizePathForComparison(p2); +} +function normalizePathForDisplay(p2) { + if (!p2) return ""; + return p2.replace(/\\/g, "/").replace(/\/+$/, ""); } function findConflictingPath(newPath, existingPaths) { - const normalizedNew = normalizePathForComparison2(newPath); + const normalizedNew = normalizePathForComparison3(newPath); for (const existing of existingPaths) { - const normalizedExisting = normalizePathForComparison2(existing); + const normalizedExisting = normalizePathForComparison3(existing); if (normalizedNew.startsWith(normalizedExisting + "/")) { return { path: existing, type: "parent" }; } @@ -26619,15 +56111,43 @@ function findConflictingPath(newPath, existingPaths) { } return null; } -function getFolderName(p) { - const normalized = normalizePathForDisplay(p); +function getFolderName(p2) { + const normalized = normalizePathForDisplay(p2); const segments = normalized.split("/"); return segments[segments.length - 1] || normalized; } +function validateDirectoryPath(p2) { + try { + const stats = fs5.statSync(p2); + if (!stats.isDirectory()) { + return { valid: false, error: "Path exists but is not a directory" }; + } + return { valid: true }; + } catch (err) { + const error48 = err; + if (error48.code === "ENOENT") { + return { valid: false, error: "Path does not exist" }; + } + if (error48.code === "EACCES") { + return { valid: false, error: "Permission denied" }; + } + return { valid: false, error: `Cannot access path: ${error48.message}` }; + } +} +function isValidDirectoryPath(p2) { + return validateDirectoryPath(p2).valid; +} +function filterValidPaths(paths) { + return paths.filter(isValidDirectoryPath); +} +function isDuplicatePath(newPath, existingPaths) { + const normalizedNew = normalizePathForComparison3(newPath); + return existingPaths.some((existing) => normalizePathForComparison3(existing) === normalizedNew); +} -// src/utils/contextPathScanner.ts -var fs7 = __toESM(require("fs")); -var path8 = __toESM(require("path")); +// src/utils/externalContextScanner.ts +var fs6 = __toESM(require("fs")); +var path6 = __toESM(require("path")); var CACHE_TTL_MS = 3e4; var MAX_FILES_PER_PATH = 1e3; var MAX_DEPTH = 10; @@ -26648,18 +56168,14 @@ var SKIP_DIRECTORIES = /* @__PURE__ */ new Set([ "vendor", "Pods" ]); -var ContextPathScanner = class { +var ExternalContextScanner = class { constructor() { this.cache = /* @__PURE__ */ new Map(); } - /** - * Scans all context paths and returns matching files. - * Uses cached results when available. - */ - scanPaths(contextPaths) { + scanPaths(externalContextPaths) { const allFiles = []; const now = Date.now(); - for (const contextPath of contextPaths) { + for (const contextPath of externalContextPaths) { const expandedPath = normalizePathForFilesystem(contextPath); const cached2 = this.cache.get(expandedPath); if (cached2 && now - cached2.timestamp < CACHE_TTL_MS) { @@ -26672,264 +56188,52 @@ var ContextPathScanner = class { } return allFiles; } - /** - * Recursively scans a directory for files. - */ scanDirectory(dir, contextRoot, depth) { if (depth > MAX_DEPTH) return []; const files = []; try { - if (!fs7.existsSync(dir)) return []; - const stat = fs7.statSync(dir); + if (!fs6.existsSync(dir)) return []; + const stat = fs6.statSync(dir); if (!stat.isDirectory()) return []; - const entries = fs7.readdirSync(dir, { withFileTypes: true }); + const entries = fs6.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { if (entry.name.startsWith(".")) continue; if (SKIP_DIRECTORIES.has(entry.name)) continue; if (entry.isSymbolicLink()) continue; - const fullPath = path8.join(dir, entry.name); + const fullPath = path6.join(dir, entry.name); if (entry.isDirectory()) { const subFiles = this.scanDirectory(fullPath, contextRoot, depth + 1); files.push(...subFiles); } else if (entry.isFile()) { try { - const fileStat = fs7.statSync(fullPath); + const fileStat = fs6.statSync(fullPath); files.push({ path: fullPath, name: entry.name, - relativePath: path8.relative(contextRoot, fullPath), + relativePath: path6.relative(contextRoot, fullPath), contextRoot, mtime: fileStat.mtimeMs }); - } catch (err) { - console.debug(`Skipped file ${fullPath}: ${err instanceof Error ? err.message : String(err)}`); + } catch (e2) { } } if (files.length >= MAX_FILES_PER_PATH) break; } - } catch (err) { - console.warn(`Failed to scan context directory ${dir}: ${err instanceof Error ? err.message : String(err)}`); + } catch (e2) { } return files; } - /** Clears all cached results. */ invalidateCache() { this.cache.clear(); } - /** Clears cached results for a specific context path. */ invalidatePath(contextPath) { const expandedPath = normalizePathForFilesystem(contextPath); this.cache.delete(expandedPath); } }; -var contextPathScanner = new ContextPathScanner(); +var externalContextScanner = new ExternalContextScanner(); -// src/utils/mcp.ts -function extractMcpMentions(text, validNames) { - const mentions = /* @__PURE__ */ new Set(); - const regex = /@([a-zA-Z0-9._-]+)(?!\/)/g; - let match; - while ((match = regex.exec(text)) !== null) { - const name = match[1]; - if (validNames.has(name)) { - mentions.add(name); - } - } - return mentions; -} -function transformMcpMentions(text, validNames) { - if (validNames.size === 0) return text; - const sortedNames = Array.from(validNames).sort((a, b) => b.length - a.length); - const escapedNames = sortedNames.map(escapeRegExp).join("|"); - const pattern = new RegExp( - `@(${escapedNames})(?! MCP)(?!/)(?![a-zA-Z0-9_-])(?!\\.[a-zA-Z0-9_-])`, - "g" - ); - return text.replace(pattern, "@$1 MCP"); -} -function escapeRegExp(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -function parseCommand(command, providedArgs) { - if (providedArgs && providedArgs.length > 0) { - return { cmd: command, args: providedArgs }; - } - const parts = splitCommandString(command); - if (parts.length === 0) { - return { cmd: "", args: [] }; - } - return { cmd: parts[0], args: parts.slice(1) }; -} -function splitCommandString(cmdStr) { - const parts = []; - let current = ""; - let inQuote = false; - let quoteChar = ""; - for (let i = 0; i < cmdStr.length; i++) { - const char = cmdStr[i]; - if ((char === '"' || char === "'") && !inQuote) { - inQuote = true; - quoteChar = char; - continue; - } - if (char === quoteChar && inQuote) { - inQuote = false; - quoteChar = ""; - continue; - } - if (/\s/.test(char) && !inQuote) { - if (current) { - parts.push(current); - current = ""; - } - continue; - } - current += char; - } - if (current) { - parts.push(current); - } - return parts; -} -function parseSseEvent(raw) { - const lines = raw.split(/\r?\n/); - let event; - const dataLines = []; - for (const line of lines) { - if (!line || line.startsWith(":")) continue; - if (line.startsWith("event:")) { - event = line.slice("event:".length).trim(); - continue; - } - if (line.startsWith("data:")) { - dataLines.push(line.slice("data:".length).trimStart()); - } - } - if (!event && dataLines.length === 0) { - return null; - } - return { event, data: dataLines.join("\n") }; -} -async function consumeSseStream(body, onEvent) { - const reader = body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - try { - let done = false; - while (!done) { - const result = await reader.read(); - done = result.done; - const value = result.value; - if (done) break; - buffer += decoder.decode(value, { stream: true }); - const parts = buffer.split(/\r?\n\r?\n/); - buffer = parts.pop() || ""; - for (const part of parts) { - const event = parseSseEvent(part); - if (event) { - onEvent(event); - } - } - } - } catch (e) { - } finally { - reader.releaseLock(); - } -} -function parseRpcId(id) { - if (typeof id === "number" && Number.isFinite(id)) return id; - if (typeof id === "string" && id.trim()) { - const asNumber = Number(id); - if (Number.isFinite(asNumber)) return asNumber; - } - return null; -} -function tryParseJson(data) { - if (!data) return null; - try { - return JSON.parse(data); - } catch (e) { - return null; - } -} -function resolveSseEndpoint(data, baseUrl) { - const payload = tryParseJson(data); - if (payload && typeof payload === "object") { - const record2 = payload; - const endpoint = typeof record2.endpoint === "string" && record2.endpoint || typeof record2.messageEndpoint === "string" && record2.messageEndpoint || typeof record2.url === "string" && record2.url || typeof record2.messageUrl === "string" && record2.messageUrl; - if (endpoint) { - try { - return new URL(endpoint, baseUrl); - } catch (e) { - return null; - } - } - } - const trimmed = data.trim(); - if (!trimmed) return null; - try { - return new URL(trimmed, baseUrl); - } catch (e) { - return null; - } -} -function waitForRpcResponse(pending, id, timeoutMs) { - return new Promise((resolve7, reject) => { - const timer = setTimeout(() => { - pending.delete(id); - reject(new Error(`Response timeout (${timeoutMs}ms)`)); - }, timeoutMs); - pending.set(id, (msg) => { - clearTimeout(timer); - pending.delete(id); - resolve7(msg); - }); - }); -} -async function postJsonRpc(url, headers, payload, options = {}) { - const requestHeaders = { ...headers }; - if (!requestHeaders["Content-Type"]) { - requestHeaders["Content-Type"] = "application/json"; - } - let controller = null; - let timeoutId = null; - let signal = options.signal; - if (options.timeoutMs !== void 0 || options.signal) { - controller = new AbortController(); - signal = controller.signal; - } - const abortHandler = () => controller == null ? void 0 : controller.abort(); - if (controller && options.signal) { - if (options.signal.aborted) { - controller.abort(); - } else { - options.signal.addEventListener("abort", abortHandler, { once: true }); - } - } - if (controller && options.timeoutMs !== void 0) { - timeoutId = setTimeout(() => controller == null ? void 0 : controller.abort(), options.timeoutMs); - } - const requestInit = { - method: "POST", - headers: requestHeaders, - body: JSON.stringify(payload) - }; - if (signal) { - requestInit.signal = signal; - } - try { - return await fetch(url.toString(), requestInit); - } finally { - if (timeoutId !== null) { - clearTimeout(timeoutId); - } - if (controller && options.signal) { - options.signal.removeEventListener("abort", abortHandler); - } - } -} - -// src/ui/components/SelectableDropdown.ts +// src/shared/components/SelectableDropdown.ts var SelectableDropdown = class { constructor(containerEl, options) { this.dropdownEl = null; @@ -26940,8 +56244,8 @@ var SelectableDropdown = class { this.options = options; } isVisible() { - var _a, _b; - return (_b = (_a = this.dropdownEl) == null ? void 0 : _a.hasClass("visible")) != null ? _b : false; + var _a3, _b; + return (_b = (_a3 = this.dropdownEl) == null ? void 0 : _a3.hasClass("visible")) != null ? _b : false; } getElement() { return this.dropdownEl; @@ -26950,8 +56254,8 @@ var SelectableDropdown = class { return this.selectedIndex; } getSelectedItem() { - var _a; - return (_a = this.items[this.selectedIndex]) != null ? _a : null; + var _a3; + return (_a3 = this.items[this.selectedIndex]) != null ? _a3 : null; } getItems() { return this.items; @@ -26968,7 +56272,7 @@ var SelectableDropdown = class { } } render(options) { - var _a; + var _a3; this.items = options.items; this.selectedIndex = options.selectedIndex; if (!this.dropdownEl) { @@ -26980,30 +56284,30 @@ var SelectableDropdown = class { const emptyEl = this.dropdownEl.createDiv({ cls: this.options.emptyClassName }); emptyEl.setText(options.emptyText); } else { - for (let i = 0; i < options.items.length; i++) { - const item = options.items[i]; + for (let i2 = 0; i2 < options.items.length; i2++) { + const item = options.items[i2]; const itemEl = this.dropdownEl.createDiv({ cls: this.options.itemClassName }); - const extraClass = (_a = options.getItemClass) == null ? void 0 : _a.call(options, item); + const extraClass = (_a3 = options.getItemClass) == null ? void 0 : _a3.call(options, item); if (Array.isArray(extraClass)) { extraClass.forEach((cls) => itemEl.addClass(cls)); } else if (extraClass) { itemEl.addClass(extraClass); } - if (i === this.selectedIndex) { + if (i2 === this.selectedIndex) { itemEl.addClass("selected"); } options.renderItem(item, itemEl); - itemEl.addEventListener("click", () => { - var _a2; - this.selectedIndex = i; + itemEl.addEventListener("click", (e2) => { + var _a4; + this.selectedIndex = i2; this.updateSelection(); - (_a2 = options.onItemClick) == null ? void 0 : _a2.call(options, item, i); + (_a4 = options.onItemClick) == null ? void 0 : _a4.call(options, item, i2, e2); }); itemEl.addEventListener("mouseenter", () => { - var _a2; - this.selectedIndex = i; + var _a4; + this.selectedIndex = i2; this.updateSelection(); - (_a2 = options.onItemHover) == null ? void 0 : _a2.call(options, item, i); + (_a4 = options.onItemHover) == null ? void 0 : _a4.call(options, item, i2); }); this.itemEls.push(itemEl); } @@ -27031,8 +56335,8 @@ var SelectableDropdown = class { } }; -// src/ui/components/file-context/mention/types.ts -function createContextPathEntry(contextRoot, folderName, displayName) { +// src/shared/mention/types.ts +function createExternalContextEntry(contextRoot, folderName, displayName) { return { contextRoot, folderName, @@ -27041,7 +56345,7 @@ function createContextPathEntry(contextRoot, folderName, displayName) { }; } -// src/ui/components/file-context/mention/MentionDropdownController.ts +// src/shared/mention/MentionDropdownController.ts var MentionDropdownController = class { constructor(containerEl, inputEl, callbacks, options = {}) { this.mentionStartIndex = -1; @@ -27049,12 +56353,14 @@ var MentionDropdownController = class { this.filteredMentionItems = []; this.filteredContextFiles = []; this.activeContextFilter = null; - this.mcpService = null; - var _a; + this.activeAgentFilter = false; + this.mcpManager = null; + this.agentService = null; + var _a3; this.containerEl = containerEl; this.inputEl = inputEl; this.callbacks = callbacks; - this.fixed = (_a = options.fixed) != null ? _a : false; + this.fixed = (_a3 = options.fixed) != null ? _a3 : false; this.dropdown = new SelectableDropdown(this.containerEl, { listClassName: "claudian-mention-dropdown", itemClassName: "claudian-mention-item", @@ -27063,20 +56369,19 @@ var MentionDropdownController = class { fixedClassName: "claudian-mention-dropdown-fixed" }); } - setMcpService(service) { - this.mcpService = service; + setMcpManager(manager) { + this.mcpManager = manager; } - preScanContextPaths() { - const contextPaths = this.callbacks.getContextPaths() || []; - if (contextPaths.length === 0) return; + setAgentService(service) { + this.agentService = service; + } + preScanExternalContexts() { + const externalContexts = this.callbacks.getExternalContexts() || []; + if (externalContexts.length === 0) return; setTimeout(() => { try { - contextPathScanner.scanPaths(contextPaths); - } catch (err) { - console.warn( - "Failed to pre-scan context paths:", - err instanceof Error ? err.message : String(err) - ); + externalContextScanner.scanPaths(externalContexts); + } catch (e2) { } }, 0); } @@ -27088,22 +56393,22 @@ var MentionDropdownController = class { this.mentionStartIndex = -1; } containsElement(el) { - var _a, _b; - return (_b = (_a = this.dropdown.getElement()) == null ? void 0 : _a.contains(el)) != null ? _b : false; + var _a3, _b; + return (_b = (_a3 = this.dropdown.getElement()) == null ? void 0 : _a3.contains(el)) != null ? _b : false; } destroy() { this.dropdown.destroy(); } updateMcpMentionsFromText(text) { - var _a, _b; - if (!this.mcpService) return; + var _a3, _b; + if (!this.mcpManager) return; const validNames = new Set( - this.mcpService.getContextSavingServers().map((s) => s.name) + this.mcpManager.getContextSavingServers().map((s) => s.name) ); const newMentions = extractMcpMentions(text, validNames); const changed = this.callbacks.setMentionedMcpServers(newMentions); if (changed) { - (_b = (_a = this.callbacks).onMcpMentionChange) == null ? void 0 : _b.call(_a, newMentions); + (_b = (_a3 = this.callbacks).onMcpMentionChange) == null ? void 0 : _b.call(_a3, newMentions); } } handleInputChange() { @@ -27129,49 +56434,53 @@ var MentionDropdownController = class { this.mentionStartIndex = lastAtIndex; this.showMentionDropdown(searchText); } - handleKeydown(e) { + handleKeydown(e2) { if (!this.dropdown.isVisible()) return false; - if (e.key === "ArrowDown") { - e.preventDefault(); + if (e2.key === "ArrowDown") { + e2.preventDefault(); this.dropdown.moveSelection(1); this.selectedMentionIndex = this.dropdown.getSelectedIndex(); return true; } - if (e.key === "ArrowUp") { - e.preventDefault(); + if (e2.key === "ArrowUp") { + e2.preventDefault(); this.dropdown.moveSelection(-1); this.selectedMentionIndex = this.dropdown.getSelectedIndex(); return true; } - if (e.key === "Enter" || e.key === "Tab") { - e.preventDefault(); + if ((e2.key === "Enter" || e2.key === "Tab") && !e2.isComposing) { + e2.preventDefault(); this.selectMentionItem(); return true; } - if (e.key === "Escape") { - e.preventDefault(); + if (e2.key === "Escape" && !e2.isComposing) { + e2.preventDefault(); + if (this.activeContextFilter || this.activeAgentFilter) { + this.returnToFirstLevel(); + return true; + } this.hide(); return true; } return false; } - buildContextPathEntries(contextPaths) { - var _a; + buildExternalContextEntries(externalContexts) { + var _a3; const counts = /* @__PURE__ */ new Map(); const normalizedPaths = /* @__PURE__ */ new Map(); - for (const contextPath of contextPaths) { - const normalized = normalizePathForComparison2(contextPath); + for (const contextPath of externalContexts) { + const normalized = normalizePathForComparison3(contextPath); normalizedPaths.set(contextPath, normalized); const folderName = getFolderName(normalized); - counts.set(folderName, ((_a = counts.get(folderName)) != null ? _a : 0) + 1); + counts.set(folderName, ((_a3 = counts.get(folderName)) != null ? _a3 : 0) + 1); } - return contextPaths.map((contextRoot) => { - var _a2, _b; - const normalized = (_a2 = normalizedPaths.get(contextRoot)) != null ? _a2 : normalizePathForComparison2(contextRoot); + return externalContexts.map((contextRoot) => { + var _a4, _b; + const normalized = (_a4 = normalizedPaths.get(contextRoot)) != null ? _a4 : normalizePathForComparison3(contextRoot); const folderName = getFolderName(contextRoot); const needsDisambiguation = ((_b = counts.get(folderName)) != null ? _b : 0) > 1; const displayName = this.getContextDisplayName(normalized, folderName, needsDisambiguation); - return createContextPathEntry(contextRoot, folderName, displayName); + return createExternalContextEntry(contextRoot, folderName, displayName); }); } getContextDisplayName(normalizedPath, folderName, needsDisambiguation) { @@ -27186,12 +56495,32 @@ var MentionDropdownController = class { const searchLower = searchText.toLowerCase(); this.filteredMentionItems = []; this.filteredContextFiles = []; - const contextPaths = this.callbacks.getContextPaths() || []; - const contextEntries = this.buildContextPathEntries(contextPaths); + const externalContexts = this.callbacks.getExternalContexts() || []; + const contextEntries = this.buildExternalContextEntries(externalContexts); const isFilterSearch = searchText.includes("/"); let fileSearchText = searchLower; + if (isFilterSearch && searchLower.startsWith("agents/")) { + this.activeAgentFilter = true; + this.activeContextFilter = null; + const agentSearchText = searchText.substring("agents/".length).toLowerCase(); + if (this.agentService) { + const matchingAgents = this.agentService.searchAgents(agentSearchText); + for (const agent of matchingAgents) { + this.filteredMentionItems.push({ + type: "agent", + id: agent.id, + name: agent.name, + description: agent.description, + source: agent.source + }); + } + } + this.selectedMentionIndex = 0; + this.renderMentionDropdown(); + return; + } if (isFilterSearch) { - const matchingContext = contextEntries.filter((entry) => searchLower.startsWith(`${entry.displayNameLower}/`)).sort((a, b) => b.displayNameLower.length - a.displayNameLower.length)[0]; + const matchingContext = contextEntries.filter((entry) => searchLower.startsWith(`${entry.displayNameLower}/`)).sort((a, b3) => b3.displayNameLower.length - a.displayNameLower.length)[0]; if (matchingContext) { const prefixLength = matchingContext.displayName.length + 1; fileSearchText = searchText.substring(prefixLength).toLowerCase(); @@ -27204,26 +56533,26 @@ var MentionDropdownController = class { } } if (this.activeContextFilter && isFilterSearch) { - const contextFiles = contextPathScanner.scanPaths([this.activeContextFilter.contextRoot]); - this.filteredContextFiles = contextFiles.filter((file) => { - const relativePath = file.relativePath.replace(/\\/g, "/"); + const contextFiles = externalContextScanner.scanPaths([this.activeContextFilter.contextRoot]); + this.filteredContextFiles = contextFiles.filter((file2) => { + const relativePath = file2.relativePath.replace(/\\/g, "/"); const pathLower = relativePath.toLowerCase(); - const nameLower = file.name.toLowerCase(); + const nameLower = file2.name.toLowerCase(); return pathLower.includes(fileSearchText) || nameLower.includes(fileSearchText); - }).sort((a, b) => { + }).sort((a, b3) => { const aNameMatch = a.name.toLowerCase().startsWith(fileSearchText); - const bNameMatch = b.name.toLowerCase().startsWith(fileSearchText); + const bNameMatch = b3.name.toLowerCase().startsWith(fileSearchText); if (aNameMatch && !bNameMatch) return -1; if (!aNameMatch && bNameMatch) return 1; - return b.mtime - a.mtime; - }).slice(0, 10); - for (const file of this.filteredContextFiles) { - const relativePath = file.relativePath.replace(/\\/g, "/"); + return b3.mtime - a.mtime; + }); + for (const file2 of this.filteredContextFiles) { + const relativePath = file2.relativePath.replace(/\\/g, "/"); this.filteredMentionItems.push({ type: "context-file", name: relativePath, - absolutePath: file.path, - contextRoot: file.contextRoot, + absolutePath: file2.path, + contextRoot: file2.contextRoot, folderName: this.activeContextFilter.folderName }); } @@ -27232,8 +56561,9 @@ var MentionDropdownController = class { return; } this.activeContextFilter = null; - if (this.mcpService) { - const mcpServers = this.mcpService.getContextSavingServers(); + this.activeAgentFilter = false; + if (this.mcpManager) { + const mcpServers = this.mcpManager.getContextSavingServers(); for (const server of mcpServers) { if (server.name.toLowerCase().includes(searchLower)) { this.filteredMentionItems.push({ @@ -27243,6 +56573,15 @@ var MentionDropdownController = class { } } } + if (this.agentService) { + const hasAgents = this.agentService.searchAgents("").length > 0; + if (hasAgents && "agents".includes(searchLower)) { + this.filteredMentionItems.push({ + type: "agent-folder", + name: "Agents" + }); + } + } if (contextEntries.length > 0) { const matchingFolders = /* @__PURE__ */ new Set(); for (const entry of contextEntries) { @@ -27258,29 +56597,25 @@ var MentionDropdownController = class { } } const firstVaultFileIndex = this.filteredMentionItems.length; - const remainingSlots = 10 - this.filteredMentionItems.length; - let vaultFiles = []; - if (remainingSlots > 0) { - const allFiles = this.callbacks.getCachedMarkdownFiles(); - vaultFiles = allFiles.filter((file) => { - const pathLower = file.path.toLowerCase(); - const nameLower = file.name.toLowerCase(); - return pathLower.includes(searchLower) || nameLower.includes(searchLower); - }).sort((a, b) => { - const aNameMatch = a.name.toLowerCase().startsWith(searchLower); - const bNameMatch = b.name.toLowerCase().startsWith(searchLower); - if (aNameMatch && !bNameMatch) return -1; - if (!aNameMatch && bNameMatch) return 1; - return b.stat.mtime - a.stat.mtime; - }).slice(0, remainingSlots); - for (const file of vaultFiles) { - this.filteredMentionItems.push({ - type: "file", - name: file.name, - path: file.path, - file - }); - } + const allFiles = this.callbacks.getCachedMarkdownFiles(); + const vaultFiles = allFiles.filter((file2) => { + const pathLower = file2.path.toLowerCase(); + const nameLower = file2.name.toLowerCase(); + return pathLower.includes(searchLower) || nameLower.includes(searchLower); + }).sort((a, b3) => { + const aNameMatch = a.name.toLowerCase().startsWith(searchLower); + const bNameMatch = b3.name.toLowerCase().startsWith(searchLower); + if (aNameMatch && !bNameMatch) return -1; + if (!aNameMatch && bNameMatch) return 1; + return b3.stat.mtime - a.stat.mtime; + }); + for (const file2 of vaultFiles) { + this.filteredMentionItems.push({ + type: "file", + name: file2.name, + path: file2.path, + file: file2 + }); } if (vaultFiles.length > 0) { this.selectedMentionIndex = firstVaultFileIndex; @@ -27296,6 +56631,8 @@ var MentionDropdownController = class { emptyText: "No matches", getItemClass: (item) => { if (item.type === "mcp-server") return "mcp-server"; + if (item.type === "agent") return "agent"; + if (item.type === "agent-folder") return "agent-folder"; if (item.type === "context-file") return "context-file"; if (item.type === "context-folder") return "context-folder"; return void 0; @@ -27304,17 +56641,31 @@ var MentionDropdownController = class { const iconEl = itemEl.createSpan({ cls: "claudian-mention-icon" }); if (item.type === "mcp-server") { iconEl.innerHTML = MCP_ICON_SVG; + } else if (item.type === "agent" || item.type === "agent-folder") { + (0, import_obsidian13.setIcon)(iconEl, "bot"); } else if (item.type === "context-file") { - (0, import_obsidian2.setIcon)(iconEl, "folder-open"); + (0, import_obsidian13.setIcon)(iconEl, "folder-open"); } else if (item.type === "context-folder") { - (0, import_obsidian2.setIcon)(iconEl, "folder"); + (0, import_obsidian13.setIcon)(iconEl, "folder"); } else { - (0, import_obsidian2.setIcon)(iconEl, "file-text"); + (0, import_obsidian13.setIcon)(iconEl, "file-text"); } const textEl = itemEl.createSpan({ cls: "claudian-mention-text" }); if (item.type === "mcp-server") { const nameEl = textEl.createSpan({ cls: "claudian-mention-name" }); nameEl.setText(`@${item.name}`); + } else if (item.type === "agent-folder") { + const nameEl = textEl.createSpan({ + cls: "claudian-mention-name claudian-mention-name-agent-folder" + }); + nameEl.setText(`@${item.name}/`); + } else if (item.type === "agent") { + const nameEl = textEl.createSpan({ cls: "claudian-mention-name claudian-mention-name-agent" }); + nameEl.setText(`@${item.id}`); + if (item.description) { + const descEl = textEl.createSpan({ cls: "claudian-mention-agent-desc" }); + descEl.setText(item.description); + } } else if (item.type === "context-folder") { const nameEl = textEl.createSpan({ cls: "claudian-mention-name claudian-mention-name-folder" @@ -27330,7 +56681,10 @@ var MentionDropdownController = class { pathEl.setText(item.path || item.name); } }, - onItemClick: (_item, index) => { + onItemClick: (item, index, e2) => { + if (item.type === "context-folder" || item.type === "agent-folder") { + e2.stopPropagation(); + } this.selectedMentionIndex = index; this.selectMentionItem(); }, @@ -27353,8 +56707,19 @@ var MentionDropdownController = class { dropdownEl.style.width = `${Math.max(inputRect.width, 280)}px`; dropdownEl.style.zIndex = "10001"; } + returnToFirstLevel() { + const text = this.inputEl.value; + const beforeAt = text.substring(0, this.mentionStartIndex); + const cursorPos = this.inputEl.selectionStart || 0; + const afterCursor = text.substring(cursorPos); + this.inputEl.value = beforeAt + "@" + afterCursor; + this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + 1; + this.activeContextFilter = null; + this.activeAgentFilter = false; + this.showMentionDropdown(""); + } selectMentionItem() { - var _a, _b; + var _a3, _b, _c, _d, _e; if (this.filteredMentionItems.length === 0) return; const selectedIndex = this.dropdown.getSelectedIndex(); this.selectedMentionIndex = selectedIndex; @@ -27369,7 +56734,17 @@ var MentionDropdownController = class { this.inputEl.value = beforeAt + replacement + afterCursor; this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length; this.callbacks.addMentionedMcpServer(selectedItem.name); - (_b = (_a = this.callbacks).onMcpMentionChange) == null ? void 0 : _b.call(_a, this.callbacks.getMentionedMcpServers()); + (_b = (_a3 = this.callbacks).onMcpMentionChange) == null ? void 0 : _b.call(_a3, this.callbacks.getMentionedMcpServers()); + } else if (selectedItem.type === "agent-folder") { + this.activeAgentFilter = true; + this.inputEl.focus(); + this.showMentionDropdown("Agents/"); + return; + } else if (selectedItem.type === "agent") { + const replacement = `@${selectedItem.id} (agent) `; + this.inputEl.value = beforeAt + replacement + afterCursor; + this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length; + (_d = (_c = this.callbacks).onAgentMentionSelect) == null ? void 0 : _d.call(_c, selectedItem.id); } else if (selectedItem.type === "context-folder") { const replacement = `@${selectedItem.name}/`; this.inputEl.value = beforeAt + replacement + afterCursor; @@ -27378,27 +56753,25 @@ var MentionDropdownController = class { this.handleInputChange(); return; } else if (selectedItem.type === "context-file") { - if (selectedItem.absolutePath) { - this.callbacks.onAttachFile(selectedItem.absolutePath); - } const displayName = selectedItem.folderName ? `@${selectedItem.folderName}/${selectedItem.name}` : `@${selectedItem.name}`; + if (selectedItem.absolutePath) { + if (this.callbacks.onAttachContextFile) { + this.callbacks.onAttachContextFile(displayName, selectedItem.absolutePath); + } else { + this.callbacks.onAttachFile(selectedItem.absolutePath); + } + } const replacement = `${displayName} `; this.inputEl.value = beforeAt + replacement + afterCursor; this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length; } else { - const file = selectedItem.file; - if (file) { - const normalizedPath = this.callbacks.normalizePathForVault(file.path); - if (normalizedPath) { - this.callbacks.onAttachFile(normalizedPath); - } - } else if (selectedItem.path) { - const normalizedPath = this.callbacks.normalizePathForVault(selectedItem.path); - if (normalizedPath) { - this.callbacks.onAttachFile(normalizedPath); - } + const file2 = selectedItem.file; + const rawPath = (_e = file2 == null ? void 0 : file2.path) != null ? _e : selectedItem.path; + const normalizedPath = this.callbacks.normalizePathForVault(rawPath); + if (normalizedPath) { + this.callbacks.onAttachFile(normalizedPath); } - const replacement = `@${selectedItem.name} `; + const replacement = `@${normalizedPath != null ? normalizedPath : selectedItem.name} `; this.inputEl.value = beforeAt + replacement + afterCursor; this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length; } @@ -27407,13 +56780,18 @@ var MentionDropdownController = class { } }; -// src/ui/components/file-context/state/FileContextState.ts +// src/features/chat/ui/file-context/state/FileContextState.ts +function escapeRegExp2(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} var FileContextState = class { constructor() { this.attachedFiles = /* @__PURE__ */ new Set(); this.sessionStarted = false; this.mentionedMcpServers = /* @__PURE__ */ new Set(); this.currentNoteSent = false; + /** Maps display name to absolute path for external context files only. */ + this.contextFileMap = /* @__PURE__ */ new Map(); } getAttachedFiles() { return new Set(this.attachedFiles); @@ -27434,28 +56812,44 @@ var FileContextState = class { this.sessionStarted = false; this.currentNoteSent = false; this.attachedFiles.clear(); + this.contextFileMap.clear(); this.clearMcpMentions(); } resetForLoadedConversation(hasMessages) { this.currentNoteSent = hasMessages; this.attachedFiles.clear(); + this.contextFileMap.clear(); this.sessionStarted = hasMessages; this.clearMcpMentions(); } setAttachedFiles(files) { this.attachedFiles.clear(); - for (const file of files) { - this.attachedFiles.add(file); + for (const file2 of files) { + this.attachedFiles.add(file2); } } - attachFile(path12) { - this.attachedFiles.add(path12); + attachFile(path10) { + this.attachedFiles.add(path10); } - detachFile(path12) { - this.attachedFiles.delete(path12); + /** Attach an external context file with display name to absolute path mapping. */ + attachContextFile(displayName, absolutePath) { + this.attachedFiles.add(absolutePath); + this.contextFileMap.set(displayName, absolutePath); + } + detachFile(path10) { + this.attachedFiles.delete(path10); } clearAttachments() { this.attachedFiles.clear(); + this.contextFileMap.clear(); + } + /** Transform text by replacing external context file display names with absolute paths. */ + transformContextMentions(text) { + let result = text; + for (const [displayName, absolutePath] of this.contextFileMap) { + result = result.replace(new RegExp(escapeRegExp2(displayName), "g"), absolutePath); + } + return result; } getMentionedMcpServers() { return new Set(this.mentionedMcpServers); @@ -27475,7 +56869,7 @@ var FileContextState = class { } }; -// src/ui/components/file-context/state/MarkdownFileCache.ts +// src/features/chat/ui/file-context/state/MarkdownFileCache.ts var MarkdownFileCache = class { constructor(app) { this.cachedFiles = []; @@ -27490,12 +56884,12 @@ var MarkdownFileCache = class { this.cachedFiles = this.app.vault.getMarkdownFiles(); this.dirty = false; } - return this.cachedFiles; + return [...this.cachedFiles]; } }; -// src/ui/components/file-context/view/FileChipsView.ts -var import_obsidian3 = require("obsidian"); +// src/features/chat/ui/file-context/view/FileChipsView.ts +var import_obsidian14 = require("obsidian"); var FileChipsView = class { constructor(containerEl, callbacks) { this.containerEl = containerEl; @@ -27509,7 +56903,6 @@ var FileChipsView = class { destroy() { this.fileIndicatorEl.remove(); } - /** Renders chip for the current/focus note only. */ renderCurrentNote(filePath) { this.fileIndicatorEl.empty(); if (!filePath) { @@ -27524,7 +56917,7 @@ var FileChipsView = class { renderFileChip(filePath, onRemove) { const chipEl = this.fileIndicatorEl.createDiv({ cls: "claudian-file-chip" }); const iconEl = chipEl.createSpan({ cls: "claudian-file-chip-icon" }); - (0, import_obsidian3.setIcon)(iconEl, "file-text"); + (0, import_obsidian14.setIcon)(iconEl, "file-text"); const normalizedPath = filePath.replace(/\\/g, "/"); const filename = normalizedPath.split("/").pop() || filePath; const nameEl = chipEl.createSpan({ cls: "claudian-file-chip-name" }); @@ -27533,8 +56926,8 @@ var FileChipsView = class { const removeEl = chipEl.createSpan({ cls: "claudian-file-chip-remove" }); removeEl.setText("\xD7"); removeEl.setAttribute("aria-label", "Remove"); - chipEl.addEventListener("click", (e) => { - if (!e.target.closest(".claudian-file-chip-remove")) { + chipEl.addEventListener("click", (e2) => { + if (!e2.target.closest(".claudian-file-chip-remove")) { this.callbacks.onOpenFile(filePath); } }); @@ -27544,23 +56937,23 @@ var FileChipsView = class { } }; -// src/ui/components/FileContext.ts +// src/features/chat/ui/FileContext.ts var FileContextManager = class { - constructor(app, containerEl, inputEl, callbacks) { + constructor(app, chipsContainerEl, inputEl, callbacks, dropdownContainerEl) { this.deleteEventRef = null; this.renameEventRef = null; // Current note (shown as chip) this.currentNotePath = null; // MCP server support - this.mcpService = null; this.onMcpMentionChange = null; this.app = app; - this.containerEl = containerEl; + this.chipsContainerEl = chipsContainerEl; + this.dropdownContainerEl = dropdownContainerEl != null ? dropdownContainerEl : chipsContainerEl; this.inputEl = inputEl; this.callbacks = callbacks; this.state = new FileContextState(); this.fileCache = new MarkdownFileCache(this.app); - this.chipsView = new FileChipsView(this.containerEl, { + this.chipsView = new FileChipsView(this.chipsContainerEl, { onRemoveAttachment: (filePath) => { if (filePath === this.currentNotePath) { this.currentNotePath = null; @@ -27569,49 +56962,57 @@ var FileContextManager = class { } }, onOpenFile: async (filePath) => { - const file = this.app.vault.getAbstractFileByPath(filePath); - if (!(file instanceof import_obsidian4.TFile)) { - new import_obsidian4.Notice(`Could not open file: ${filePath}`); + const file2 = this.app.vault.getAbstractFileByPath(filePath); + if (!(file2 instanceof import_obsidian15.TFile)) { + new import_obsidian15.Notice(`Could not open file: ${filePath}`); return; } try { - await this.app.workspace.getLeaf().openFile(file); - } catch (error2) { - new import_obsidian4.Notice(`Failed to open file: ${error2 instanceof Error ? error2.message : String(error2)}`); + await this.app.workspace.getLeaf().openFile(file2); + } catch (error48) { + new import_obsidian15.Notice(`Failed to open file: ${error48 instanceof Error ? error48.message : String(error48)}`); } } }); this.mentionDropdown = new MentionDropdownController( - this.containerEl, + this.dropdownContainerEl, this.inputEl, { onAttachFile: (filePath) => this.state.attachFile(filePath), + onAttachContextFile: (displayName, absolutePath) => this.state.attachContextFile(displayName, absolutePath), onMcpMentionChange: (servers) => { - var _a; - return (_a = this.onMcpMentionChange) == null ? void 0 : _a.call(this, servers); + var _a3; + return (_a3 = this.onMcpMentionChange) == null ? void 0 : _a3.call(this, servers); + }, + onAgentMentionSelect: (agentId) => { + var _a3, _b; + return (_b = (_a3 = this.callbacks).onAgentMentionSelect) == null ? void 0 : _b.call(_a3, agentId); }, getMentionedMcpServers: () => this.state.getMentionedMcpServers(), setMentionedMcpServers: (mentions) => this.state.setMentionedMcpServers(mentions), addMentionedMcpServer: (name) => this.state.addMentionedMcpServer(name), - getContextPaths: () => { - var _a, _b; - return ((_b = (_a = this.callbacks).getContextPaths) == null ? void 0 : _b.call(_a)) || []; + getExternalContexts: () => { + var _a3, _b; + return ((_b = (_a3 = this.callbacks).getExternalContexts) == null ? void 0 : _b.call(_a3)) || []; }, getCachedMarkdownFiles: () => this.fileCache.getFiles(), normalizePathForVault: (rawPath) => this.normalizePathForVault(rawPath) } ); - this.deleteEventRef = this.app.vault.on("delete", (file) => { - if (file instanceof import_obsidian4.TFile) this.handleFileDeleted(file.path); + this.deleteEventRef = this.app.vault.on("delete", (file2) => { + if (file2 instanceof import_obsidian15.TFile) this.handleFileDeleted(file2.path); }); - this.renameEventRef = this.app.vault.on("rename", (file, oldPath) => { - if (file instanceof import_obsidian4.TFile) this.handleFileRenamed(oldPath, file.path); + this.renameEventRef = this.app.vault.on("rename", (file2, oldPath) => { + if (file2 instanceof import_obsidian15.TFile) this.handleFileRenamed(oldPath, file2.path); }); } /** Returns the current note path (shown as chip). */ getCurrentNotePath() { return this.currentNotePath; } + getAttachedFiles() { + return this.state.getAttachedFiles(); + } /** Checks whether current note should be sent for this session. */ shouldSendCurrentNote(notePath) { const resolvedPath = notePath != null ? notePath : this.currentNotePath; @@ -27660,12 +57061,12 @@ var FileContextManager = class { } } /** Handles file open event. */ - handleFileOpen(file) { - const normalizedPath = this.normalizePathForVault(file.path); + handleFileOpen(file2) { + const normalizedPath = this.normalizePathForVault(file2.path); if (!normalizedPath) return; if (!this.state.isSessionStarted()) { this.state.clearAttachments(); - if (!this.hasExcludedTag(file)) { + if (!this.hasExcludedTag(file2)) { this.currentNotePath = normalizedPath; this.state.attachFile(normalizedPath); } else { @@ -27682,8 +57083,8 @@ var FileContextManager = class { this.mentionDropdown.handleInputChange(); } /** Handles keyboard navigation in mention dropdown. Returns true if handled. */ - handleMentionKeydown(e) { - return this.mentionDropdown.handleKeydown(e); + handleMentionKeydown(e2) { + return this.mentionDropdown.handleKeydown(e2); } isMentionDropdownVisible() { return this.mentionDropdown.isVisible(); @@ -27694,6 +57095,9 @@ var FileContextManager = class { containsElement(el) { return this.mentionDropdown.containsElement(el); } + transformContextMentions(text) { + return this.state.transformContextMentions(text); + } /** Cleans up event listeners (call on view close). */ destroy() { if (this.deleteEventRef) this.app.vault.offref(this.deleteEventRef); @@ -27703,23 +57107,13 @@ var FileContextManager = class { } /** Normalizes a file path to be vault-relative with forward slashes. */ normalizePathForVault(rawPath) { - if (!rawPath) return null; - const normalizedRaw = normalizePathForFilesystem(rawPath); const vaultPath = getVaultPath(this.app); - if (vaultPath && isPathWithinVault(normalizedRaw, vaultPath)) { - const absolute = path9.isAbsolute(normalizedRaw) ? normalizedRaw : path9.resolve(vaultPath, normalizedRaw); - const relative5 = path9.relative(vaultPath, absolute); - if (relative5) { - return relative5.replace(/\\/g, "/"); - } - return null; - } - return normalizedRaw.replace(/\\/g, "/"); + return normalizePathForVault(rawPath, vaultPath); } refreshCurrentNoteChip() { - var _a, _b; + var _a3, _b; this.chipsView.renderCurrentNote(this.currentNotePath); - (_b = (_a = this.callbacks).onChipsChanged) == null ? void 0 : _b.call(_a); + (_b = (_a3 = this.callbacks).onChipsChanged) == null ? void 0 : _b.call(_a3); } handleFileRenamed(oldPath, newPath) { const normalizedOld = this.normalizePathForVault(oldPath); @@ -27760,62 +57154,58 @@ var FileContextManager = class { // ======================================== // MCP Server Support // ======================================== - /** Set the MCP service for @-mention autocomplete. */ - setMcpService(service) { - this.mcpService = service; - this.mentionDropdown.setMcpService(service); + setMcpManager(manager) { + this.mentionDropdown.setMcpManager(manager); + } + setAgentService(agentManager) { + this.mentionDropdown.setAgentService(agentManager); } - /** Set callback for when MCP mentions change (for McpServerSelector integration). */ setOnMcpMentionChange(callback) { this.onMcpMentionChange = callback; } /** - * Pre-scans context paths in the background to warm the cache. - * Should be called when context paths are added/changed. + * Pre-scans external context paths in the background to warm the cache. + * Should be called when external context paths are added/changed. */ - preScanContextPaths() { - this.mentionDropdown.preScanContextPaths(); + preScanExternalContexts() { + this.mentionDropdown.preScanExternalContexts(); } - /** Get currently @-mentioned MCP servers. */ getMentionedMcpServers() { return this.state.getMentionedMcpServers(); } - /** Clear MCP mentions (call on new conversation). */ clearMcpMentions() { this.state.clearMcpMentions(); } - /** Update MCP mentions from input text. */ updateMcpMentionsFromText(text) { this.mentionDropdown.updateMcpMentionsFromText(text); } - hasExcludedTag(file) { - var _a; + hasExcludedTag(file2) { + var _a3; const excludedTags = this.callbacks.getExcludedTags(); if (excludedTags.length === 0) return false; - const cache = this.app.metadataCache.getFileCache(file); + const cache = this.app.metadataCache.getFileCache(file2); if (!cache) return false; const fileTags = []; - if ((_a = cache.frontmatter) == null ? void 0 : _a.tags) { + if ((_a3 = cache.frontmatter) == null ? void 0 : _a3.tags) { const fmTags = cache.frontmatter.tags; if (Array.isArray(fmTags)) { - fileTags.push(...fmTags.map((t) => t.replace(/^#/, ""))); + fileTags.push(...fmTags.map((t2) => t2.replace(/^#/, ""))); } else if (typeof fmTags === "string") { fileTags.push(fmTags.replace(/^#/, "")); } } if (cache.tags) { - fileTags.push(...cache.tags.map((t) => t.tag.replace(/^#/, ""))); + fileTags.push(...cache.tags.map((t2) => t2.tag.replace(/^#/, ""))); } return fileTags.some((tag) => excludedTags.includes(tag)); } }; -// src/ui/components/ImageContext.ts -var fs8 = __toESM(require("fs")); -var import_obsidian5 = require("obsidian"); -var path10 = __toESM(require("path")); +// src/features/chat/ui/ImageContext.ts +var import_obsidian16 = require("obsidian"); +var path7 = __toESM(require("path")); var MAX_IMAGE_SIZE = 5 * 1024 * 1024; -var IMAGE_EXTENSIONS = { +var IMAGE_EXTENSIONS2 = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", @@ -27823,17 +57213,17 @@ var IMAGE_EXTENSIONS = { ".webp": "image/webp" }; var ImageContextManager = class { - constructor(app, containerEl, inputEl, callbacks) { + constructor(containerEl, inputEl, callbacks, previewContainerEl) { this.dropOverlay = null; this.attachedImages = /* @__PURE__ */ new Map(); - this.app = app; this.containerEl = containerEl; + this.previewContainerEl = previewContainerEl != null ? previewContainerEl : containerEl; this.inputEl = inputEl; this.callbacks = callbacks; - const fileIndicator = this.containerEl.querySelector(".claudian-file-indicator"); - this.imagePreviewEl = this.containerEl.createDiv({ cls: "claudian-image-preview" }); - if (fileIndicator) { - this.containerEl.insertBefore(this.imagePreviewEl, fileIndicator); + const fileIndicator = this.previewContainerEl.querySelector(".claudian-file-indicator"); + this.imagePreviewEl = this.previewContainerEl.createDiv({ cls: "claudian-image-preview" }); + if (fileIndicator && fileIndicator.parentElement === this.previewContainerEl) { + this.previewContainerEl.insertBefore(this.imagePreviewEl, fileIndicator); } this.setupDragAndDrop(); this.setupPasteHandler(); @@ -27858,74 +57248,6 @@ var ImageContextManager = class { this.updateImagePreview(); this.callbacks.onImagesChanged(); } - /** Adds an image from a file path. Returns true if successful. */ - async addImageFromPath(imagePath) { - try { - const result = await this.loadImageFromPath(imagePath); - if (result) { - this.attachedImages.set(result.id, result); - this.updateImagePreview(); - this.callbacks.onImagesChanged(); - return true; - } - this.notifyImageError(`Unable to load image from path: ${imagePath}`); - } catch (error2) { - this.notifyImageError(`Failed to load image from path: ${imagePath}`, error2); - } - return false; - } - /** Extracts an image path from text if present. */ - extractImagePath(text) { - const info = this.extractImagePathInfo(text); - return info ? info.normalized : null; - } - /** Handles potential image path in message text. Returns cleaned text if image was loaded. */ - async handleImagePathInText(text) { - const info = this.extractImagePathInfo(text); - if (!info) { - return { text, imageLoaded: false }; - } - const loaded = await this.addImageFromPath(info.normalized); - if (loaded) { - const cleanedText = text.replace(info.raw, "").replace(info.normalized, "").replace(/["']\s*["']/g, "").trim(); - return { text: cleanedText, imageLoaded: true }; - } - return { text, imageLoaded: false }; - } - extractImagePathInfo(text) { - const markdownMatch = text.match(/!\[[^\]]*]\(([^)]+)\)/); - if (markdownMatch && markdownMatch[1]) { - const markdownCandidate = this.extractMarkdownImagePath(text); - const normalizedMarkdown = this.normalizeCandidatePath(markdownCandidate); - if (normalizedMarkdown) { - return { raw: markdownMatch[1], normalized: normalizedMarkdown }; - } - } - const htmlCandidate = this.extractHtmlImagePath(text); - const normalizedHtml = this.normalizeCandidatePath(htmlCandidate); - if (htmlCandidate && normalizedHtml) { - return { raw: htmlCandidate, normalized: normalizedHtml }; - } - const fileUrlPattern = /file:\/\/[^\s"'<>()[\]]+/gi; - let sanitizedText = text; - const fileMatches = text.match(fileUrlPattern) || []; - for (const raw of fileMatches) { - const normalized = this.normalizeCandidatePath(raw); - if (normalized) { - return { raw, normalized }; - } - sanitizedText = sanitizedText.replace(raw, " "); - } - const tokenPattern = /[^\s"'<>()[\]]+?\.(?:jpe?g|png|gif|webp)\b/gi; - const matches = sanitizedText.match(tokenPattern) || []; - for (const raw of matches) { - const normalized = this.normalizeCandidatePath(raw); - if (normalized) { - return { raw, normalized }; - } - } - return null; - } setupDragAndDrop() { const inputWrapper = this.containerEl.querySelector(".claudian-input-wrapper"); if (!inputWrapper) return; @@ -27953,195 +57275,109 @@ var ImageContextManager = class { dropContent.appendChild(svg); dropContent.createSpan({ text: "Drop image here" }); const dropZone = inputWrapper; - dropZone.addEventListener("dragenter", (e) => this.handleDragEnter(e)); - dropZone.addEventListener("dragover", (e) => this.handleDragOver(e)); - dropZone.addEventListener("dragleave", (e) => this.handleDragLeave(e)); - dropZone.addEventListener("drop", (e) => this.handleDrop(e)); + dropZone.addEventListener("dragenter", (e2) => this.handleDragEnter(e2)); + dropZone.addEventListener("dragover", (e2) => this.handleDragOver(e2)); + dropZone.addEventListener("dragleave", (e2) => this.handleDragLeave(e2)); + dropZone.addEventListener("drop", (e2) => this.handleDrop(e2)); } - handleDragEnter(e) { - var _a, _b; - e.preventDefault(); - e.stopPropagation(); - if ((_a = e.dataTransfer) == null ? void 0 : _a.types.includes("Files")) { + handleDragEnter(e2) { + var _a3, _b; + e2.preventDefault(); + e2.stopPropagation(); + if ((_a3 = e2.dataTransfer) == null ? void 0 : _a3.types.includes("Files")) { (_b = this.dropOverlay) == null ? void 0 : _b.addClass("visible"); } } - handleDragOver(e) { - e.preventDefault(); - e.stopPropagation(); + handleDragOver(e2) { + e2.preventDefault(); + e2.stopPropagation(); } - handleDragLeave(e) { - var _a, _b; - e.preventDefault(); - e.stopPropagation(); + handleDragLeave(e2) { + var _a3, _b; + e2.preventDefault(); + e2.stopPropagation(); const inputWrapper = this.containerEl.querySelector(".claudian-input-wrapper"); if (!inputWrapper) { - (_a = this.dropOverlay) == null ? void 0 : _a.removeClass("visible"); + (_a3 = this.dropOverlay) == null ? void 0 : _a3.removeClass("visible"); return; } const rect = inputWrapper.getBoundingClientRect(); - if (e.clientX <= rect.left || e.clientX >= rect.right || e.clientY <= rect.top || e.clientY >= rect.bottom) { + if (e2.clientX <= rect.left || e2.clientX >= rect.right || e2.clientY <= rect.top || e2.clientY >= rect.bottom) { (_b = this.dropOverlay) == null ? void 0 : _b.removeClass("visible"); } } - async handleDrop(e) { - var _a, _b; - e.preventDefault(); - e.stopPropagation(); - (_a = this.dropOverlay) == null ? void 0 : _a.removeClass("visible"); - const files = (_b = e.dataTransfer) == null ? void 0 : _b.files; + async handleDrop(e2) { + var _a3, _b; + e2.preventDefault(); + e2.stopPropagation(); + (_a3 = this.dropOverlay) == null ? void 0 : _a3.removeClass("visible"); + const files = (_b = e2.dataTransfer) == null ? void 0 : _b.files; if (!files) return; - for (let i = 0; i < files.length; i++) { - const file = files[i]; - if (this.isImageFile(file)) { - await this.addImageFromFile(file, "drop"); + for (let i2 = 0; i2 < files.length; i2++) { + const file2 = files[i2]; + if (this.isImageFile(file2)) { + await this.addImageFromFile(file2, "drop"); } } } setupPasteHandler() { - this.inputEl.addEventListener("paste", async (e) => { - var _a; - const items = (_a = e.clipboardData) == null ? void 0 : _a.items; + this.inputEl.addEventListener("paste", async (e2) => { + var _a3; + const items = (_a3 = e2.clipboardData) == null ? void 0 : _a3.items; if (!items) return; - for (let i = 0; i < items.length; i++) { - const item = items[i]; + for (let i2 = 0; i2 < items.length; i2++) { + const item = items[i2]; if (item.type.startsWith("image/")) { - e.preventDefault(); - const file = item.getAsFile(); - if (file) { - await this.addImageFromFile(file, "paste"); + e2.preventDefault(); + const file2 = item.getAsFile(); + if (file2) { + await this.addImageFromFile(file2, "paste"); } return; } } }); } - isImageFile(file) { - return file.type.startsWith("image/") && this.getMediaType(file.name) !== null; + isImageFile(file2) { + return file2.type.startsWith("image/") && this.getMediaType(file2.name) !== null; } getMediaType(filename) { - const ext = path10.extname(filename).toLowerCase(); - return IMAGE_EXTENSIONS[ext] || null; + const ext = path7.extname(filename).toLowerCase(); + return IMAGE_EXTENSIONS2[ext] || null; } - async addImageFromFile(file, source) { - if (file.size > MAX_IMAGE_SIZE) { + async addImageFromFile(file2, source) { + if (file2.size > MAX_IMAGE_SIZE) { this.notifyImageError(`Image exceeds ${this.formatSize(MAX_IMAGE_SIZE)} limit.`); return false; } - const mediaType = this.getMediaType(file.name) || file.type; + const mediaType = this.getMediaType(file2.name) || file2.type; if (!mediaType) { this.notifyImageError("Unsupported image type."); return false; } try { - const { buffer, base64: base642 } = await this.fileToBufferAndBase64(file); - const cacheEntry = saveImageToCache(this.app, buffer, mediaType, file.name); - if (!cacheEntry) { - this.notifyImageError("Failed to save image to cache."); - return false; - } + const base643 = await this.fileToBase64(file2); const attachment = { id: this.generateId(), - name: file.name || `image-${Date.now()}.${mediaType.split("/")[1]}`, + name: file2.name || `image-${Date.now()}.${mediaType.split("/")[1]}`, mediaType, - data: base642, - cachePath: cacheEntry.relPath, - size: file.size, + data: base643, + size: file2.size, source }; this.attachedImages.set(attachment.id, attachment); this.updateImagePreview(); this.callbacks.onImagesChanged(); return true; - } catch (error2) { - this.notifyImageError("Failed to attach image.", error2); + } catch (error48) { + this.notifyImageError("Failed to attach image.", error48); return false; } } - async loadImageFromPath(imagePath) { - var _a, _b; - const mediaType = this.getMediaType(imagePath); - if (!mediaType) { - return null; - } - const normalizedInput = normalizePathForFilesystem(imagePath); - let fullPath = normalizedInput; - const vaultPath = getVaultPath(this.app); - const mediaFolder = this.callbacks.getMediaFolder ? this.callbacks.getMediaFolder().trim() : void 0; - if (!path10.isAbsolute(normalizedInput)) { - const candidates = []; - if (vaultPath) { - candidates.push(path10.join(vaultPath, normalizedInput)); - if (mediaFolder) { - candidates.push(path10.join(vaultPath, mediaFolder, normalizedInput)); - } - } - const foundPath = candidates.find((p) => fs8.existsSync(p)); - if (foundPath) { - fullPath = foundPath; - } - } - if (!fs8.existsSync(fullPath)) { - const normalizedMediaFolder = mediaFolder == null ? void 0 : mediaFolder.replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); - const vaultRelativePath = normalizedInput.replace(/\\/g, "/"); - const vaultPaths = [ - vaultRelativePath, - normalizedMediaFolder ? `${normalizedMediaFolder}/${vaultRelativePath}` : null - ].filter(Boolean); - for (const vaultRelativePath2 of vaultPaths) { - const file = this.app.vault.getAbstractFileByPath(vaultRelativePath2); - if (file instanceof import_obsidian5.TFile) { - const fileSize = (_b = (_a = file.stat) == null ? void 0 : _a.size) != null ? _b : 0; - if (fileSize > MAX_IMAGE_SIZE) { - return null; - } - const arrayBuffer = await this.app.vault.readBinary(file); - const base643 = this.arrayBufferToBase64(arrayBuffer); - return { - id: this.generateId(), - name: file.name, - mediaType, - data: base643, - filePath: file.path, - size: arrayBuffer.byteLength, - source: "file" - }; - } - } - return null; - } - const stats = fs8.statSync(fullPath); - if (stats.size > MAX_IMAGE_SIZE) { - return null; - } - const buffer = fs8.readFileSync(fullPath); - const base642 = buffer.toString("base64"); - const storedPath = this.getStoredFilePath(fullPath, vaultPath); - return { - id: this.generateId(), - name: path10.basename(fullPath), - mediaType, - data: base642, - filePath: storedPath, - size: stats.size, - source: "file" - }; - } - async fileToBufferAndBase64(file) { - const arrayBuffer = await file.arrayBuffer(); + async fileToBase64(file2) { + const arrayBuffer = await file2.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); - return { - buffer, - base64: buffer.toString("base64") - }; - } - arrayBufferToBase64(buffer) { - const bytes = new Uint8Array(buffer); - let binary = ""; - for (let i = 0; i < bytes.byteLength; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); + return buffer.toString("base64"); } // ============================================ // Private: Image Preview @@ -28175,8 +57411,8 @@ var ImageContextManager = class { const removeEl = previewEl.createSpan({ cls: "claudian-image-remove" }); removeEl.setText("\xD7"); removeEl.setAttribute("aria-label", "Remove image"); - removeEl.addEventListener("click", (e) => { - e.stopPropagation(); + removeEl.addEventListener("click", (e2) => { + e2.stopPropagation(); this.attachedImages.delete(id); this.updateImagePreview(); this.callbacks.onImagesChanged(); @@ -28196,8 +57432,8 @@ var ImageContextManager = class { }); const closeBtn = modal.createDiv({ cls: "claudian-image-modal-close" }); closeBtn.setText("\xD7"); - const handleEsc = (e) => { - if (e.key === "Escape") { + const handleEsc = (e2) => { + if (e2.key === "Escape") { close(); } }; @@ -28206,8 +57442,8 @@ var ImageContextManager = class { overlay.remove(); }; closeBtn.addEventListener("click", close); - overlay.addEventListener("click", (e) => { - if (e.target === overlay) close(); + overlay.addEventListener("click", (e2) => { + if (e2.target === overlay) close(); }); document.addEventListener("keydown", handleEsc); } @@ -28216,7 +57452,7 @@ var ImageContextManager = class { } truncateName(name, maxLen) { if (name.length <= maxLen) return name; - const ext = path10.extname(name); + const ext = path7.extname(name); const base = name.slice(0, name.length - ext.length); const truncatedBase = base.slice(0, maxLen - ext.length - 3); return `${truncatedBase}...${ext}`; @@ -28226,116 +57462,31 @@ var ImageContextManager = class { if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; } - cleanImagePathToken(token) { - let cleaned = token.trim(); - cleaned = cleaned.replace(/^["'`]+|["'`]+$/g, ""); - cleaned = cleaned.replace(/^!\[[^\]]*]\(/, ""); - cleaned = cleaned.replace(/^[[(<]+/, ""); - cleaned = cleaned.replace(/[)\],.;>]+$/g, ""); - return cleaned || null; - } - normalizeCandidatePath(candidate) { - if (!candidate) return null; - const cleaned = this.cleanImagePathToken(candidate); - if (!cleaned) return null; - if (/^file:\/\//i.test(cleaned)) { - return this.parseFileUrlToPath(cleaned); - } - if (/^https?:\/\//i.test(cleaned)) { - return null; - } - if (cleaned.includes("../") || cleaned.includes("..\\")) { - return null; - } - return cleaned; - } - extractMarkdownImagePath(text) { - var _a, _b; - const match = text.match(/!\[[^\]]*]\(([^)]+)\)/); - if (!match) return null; - let inside = match[1].trim(); - if (inside.startsWith("<") && inside.endsWith(">")) { - inside = inside.slice(1, -1).trim(); - } - const quoted = inside.match(/^"([^"]+)"|^'([^']+)'/); - if (quoted) { - inside = (_b = (_a = quoted[1]) != null ? _a : quoted[2]) != null ? _b : inside; - } - if (/\s/.test(inside)) { - inside = inside.split(/\s+/)[0]; - } - return inside || null; - } - extractHtmlImagePath(text) { - var _a, _b, _c; - const match = text.match(/]+src\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+))/i); - if (!match) return null; - return (_c = (_b = (_a = match[1]) != null ? _a : match[2]) != null ? _b : match[3]) != null ? _c : null; - } - parseFileUrlToPath(value) { - try { - const url = new URL(value); - if (url.protocol !== "file:") return null; - const host = url.hostname; - const hostLower = host.toLowerCase(); - const isLocalHost = hostLower === "" || hostLower === "localhost" || hostLower === "127.0.0.1" || hostLower === "::1"; - let pathname = decodeURIComponent(url.pathname || ""); - if (!pathname) return null; - if (isLocalHost && /^\/[a-zA-Z]:\//.test(pathname)) { - pathname = pathname.slice(1); - return pathname.replace(/\//g, "\\"); - } - if (/^[a-zA-Z]:$/.test(host)) { - const combined = `${host}${pathname}`; - return combined.replace(/\//g, "\\"); - } - if (!isLocalHost && host) { - return `\\\\${host}${pathname.replace(/\//g, "\\")}`; - } - return pathname; - } catch (error2) { - console.warn("Failed to parse file URL:", value, error2); - return null; - } - } - notifyImageError(message, error2) { - if (error2) { - console.error(message, error2); - } else { - console.warn(message); - } + notifyImageError(message, error48) { let userMessage = message; - if (error2 instanceof Error) { - if (error2.message.includes("ENOENT") || error2.message.includes("no such file")) { + if (error48 instanceof Error) { + if (error48.message.includes("ENOENT") || error48.message.includes("no such file")) { userMessage = `${message} (File not found)`; - } else if (error2.message.includes("EACCES") || error2.message.includes("permission denied")) { + } else if (error48.message.includes("EACCES") || error48.message.includes("permission denied")) { userMessage = `${message} (Permission denied)`; } } - new import_obsidian5.Notice(userMessage); - } - getStoredFilePath(fullPath, vaultPath) { - const normalizedFull = normalizePathForFilesystem(fullPath); - if (vaultPath && isPathWithinVault(normalizedFull, vaultPath)) { - const absolute = path10.isAbsolute(normalizedFull) ? normalizedFull : path10.resolve(vaultPath, normalizedFull); - const relative5 = path10.relative(vaultPath, absolute); - return relative5.replace(/\\/g, "/"); - } - return normalizedFull; + new import_obsidian16.Notice(userMessage); } }; -// src/ui/components/InputToolbar.ts -var import_obsidian6 = require("obsidian"); +// src/features/chat/ui/InputToolbar.ts +var import_obsidian17 = require("obsidian"); +var path8 = __toESM(require("path")); var ModelSelector = class { constructor(parentEl, callbacks) { this.buttonEl = null; this.dropdownEl = null; + this.isReady = false; this.callbacks = callbacks; this.container = parentEl.createDiv({ cls: "claudian-model-selector" }); this.render(); } - /** Returns available models (custom from env vars, or defaults). */ getAvailableModels() { let models = []; if (this.callbacks.getEnvironmentVariables) { @@ -28350,11 +57501,18 @@ var ModelSelector = class { } else { models = [...DEFAULT_CLAUDE_MODELS]; } + const settings11 = this.callbacks.getSettings(); + if (settings11.show1MModel) { + models = models.map( + (m) => m.value === "sonnet" ? { ...m, label: "Sonnet (1M)" } : m + ); + } return models; } render() { this.container.empty(); this.buttonEl = this.container.createDiv({ cls: "claudian-model-btn" }); + this.setReady(this.isReady); this.updateDisplay(); this.dropdownEl = this.container.createDiv({ cls: "claudian-model-dropdown" }); this.renderOptions(); @@ -28369,6 +57527,11 @@ var ModelSelector = class { const labelEl = this.buttonEl.createSpan({ cls: "claudian-model-label" }); labelEl.setText((displayModel == null ? void 0 : displayModel.label) || "Unknown"); } + setReady(ready) { + var _a3; + this.isReady = ready; + (_a3 = this.buttonEl) == null ? void 0 : _a3.toggleClass("ready", ready); + } renderOptions() { if (!this.dropdownEl) return; this.dropdownEl.empty(); @@ -28383,8 +57546,8 @@ var ModelSelector = class { if (model.description) { option.setAttribute("title", model.description); } - option.addEventListener("click", async (e) => { - e.stopPropagation(); + option.addEventListener("click", async (e2) => { + e2.stopPropagation(); await this.callbacks.onModelChange(model.value); this.updateDisplay(); this.renderOptions(); @@ -28410,7 +57573,7 @@ var ThinkingBudgetSelector = class { if (!this.gearsEl) return; this.gearsEl.empty(); const currentBudget = this.callbacks.getSettings().thinkingBudget; - const currentBudgetInfo = THINKING_BUDGETS.find((b) => b.value === currentBudget); + const currentBudgetInfo = THINKING_BUDGETS.find((b3) => b3.value === currentBudget); const currentEl = this.gearsEl.createDiv({ cls: "claudian-thinking-current" }); currentEl.setText((currentBudgetInfo == null ? void 0 : currentBudgetInfo.label) || "Off"); const optionsEl = this.gearsEl.createDiv({ cls: "claudian-thinking-options" }); @@ -28421,8 +57584,8 @@ var ThinkingBudgetSelector = class { if (budget.value === currentBudget) { gearEl.addClass("selected"); } - gearEl.addEventListener("click", async (e) => { - e.stopPropagation(); + gearEl.addEventListener("click", async (e2) => { + e2.stopPropagation(); await this.callbacks.onThinkingBudgetChange(budget.value); this.updateDisplay(); }); @@ -28436,7 +57599,6 @@ var PermissionToggle = class { constructor(parentEl, callbacks) { this.toggleEl = null; this.labelEl = null; - this.onPlanModeToggle = null; this.callbacks = callbacks; this.container = parentEl.createDiv({ cls: "claudian-permission-toggle" }); this.render(); @@ -28447,45 +57609,9 @@ var PermissionToggle = class { this.toggleEl = this.container.createDiv({ cls: "claudian-toggle-switch" }); this.updateDisplay(); this.toggleEl.addEventListener("click", () => this.toggle()); - this.container.addEventListener("click", (e) => { - if (this.isPlanModeLocked() && e.target !== this.toggleEl) { - new import_obsidian6.Notice("Plan mode is active until the plan is approved."); - } - }); - } - /** Set callback for plan mode toggle. */ - setOnPlanModeToggle(callback) { - this.onPlanModeToggle = callback; - } - /** Set plan mode active state. */ - setPlanModeActive(_active) { - this.updateDisplay(); - } - /** Check if plan mode is active. */ - isPlanModeActive() { - return this.isPlanModeLocked() || this.isPlanModeRequested(); - } - isPlanModeLocked() { - return this.callbacks.getSettings().permissionMode === "plan"; - } - isPlanModeRequested() { - var _a, _b, _c; - return (_c = (_b = (_a = this.callbacks).isPlanModeRequested) == null ? void 0 : _b.call(_a)) != null ? _c : false; } updateDisplay() { if (!this.toggleEl || !this.labelEl) return; - if (this.isPlanModeActive()) { - this.toggleEl.removeClass("active"); - this.container.addClass("plan-mode"); - this.labelEl.empty(); - const iconEl = this.labelEl.createSpan({ cls: "claudian-plan-mode-icon" }); - iconEl.textContent = "\u258E\u258E"; - iconEl.style.fontSize = "0.8em"; - iconEl.style.letterSpacing = "-4px"; - this.labelEl.createSpan({ text: "Plan Mode" }); - return; - } - this.container.removeClass("plan-mode"); const isYolo = this.callbacks.getSettings().permissionMode === "yolo"; if (isYolo) { this.toggleEl.addClass("active"); @@ -28495,138 +57621,237 @@ var PermissionToggle = class { this.labelEl.setText(isYolo ? "YOLO" : "Safe"); } async toggle() { - if (this.isPlanModeLocked()) { - new import_obsidian6.Notice("Plan mode is active until the plan is approved."); - return; - } const current = this.callbacks.getSettings().permissionMode; const newMode = current === "yolo" ? "normal" : "yolo"; await this.callbacks.onPermissionModeChange(newMode); this.updateDisplay(); } - /** Toggle plan mode on/off. */ - async togglePlanMode() { - var _a; - if (this.isPlanModeLocked()) { - new import_obsidian6.Notice("Plan mode is active until the plan is approved."); - return; - } - const nextRequested = !this.isPlanModeRequested(); - (_a = this.onPlanModeToggle) == null ? void 0 : _a.call(this, nextRequested); - this.updateDisplay(); - } }; -var ContextPathSelector = class { +var ExternalContextSelector = class { constructor(parentEl, callbacks) { this.iconEl = null; this.badgeEl = null; this.dropdownEl = null; - /** Session-specific context paths (resets on new conversation). */ - this.sessionContextPaths = []; + /** + * Current external context paths. May contain: + * - Persistent paths only (new sessions via clearExternalContexts) + * - Restored session paths (loaded sessions via setExternalContexts) + * - Mixed paths during active sessions + */ + this.externalContextPaths = []; + /** Paths that persist across all sessions (stored in settings). */ + this.persistentPaths = /* @__PURE__ */ new Set(); this.onChangeCallback = null; + this.onPersistenceChangeCallback = null; this.callbacks = callbacks; - this.container = parentEl.createDiv({ cls: "claudian-context-path-selector" }); + this.container = parentEl.createDiv({ cls: "claudian-external-context-selector" }); this.render(); } - /** Set callback for when context paths change. */ setOnChange(callback) { this.onChangeCallback = callback; } - /** Get current session context paths. */ - getContextPaths() { - return [...this.sessionContextPaths]; + setOnPersistenceChange(callback) { + this.onPersistenceChangeCallback = callback; } - /** Set session context paths (for restoring from conversation). */ - setContextPaths(paths) { - this.sessionContextPaths = [...paths]; + getExternalContexts() { + return [...this.externalContextPaths]; + } + getPersistentPaths() { + return [...this.persistentPaths]; + } + setPersistentPaths(paths) { + var _a3; + const validPaths = filterValidPaths(paths); + const invalidPaths = paths.filter((p2) => !validPaths.includes(p2)); + this.persistentPaths = new Set(validPaths); + this.mergePersistentPaths(); + this.updateDisplay(); + this.renderDropdown(); + if (invalidPaths.length > 0) { + const pathNames = invalidPaths.map((p2) => this.shortenPath(p2)).join(", "); + new import_obsidian17.Notice(`Removed ${invalidPaths.length} invalid external context path(s): ${pathNames}`, 5e3); + (_a3 = this.onPersistenceChangeCallback) == null ? void 0 : _a3.call(this, [...this.persistentPaths]); + } + } + togglePersistence(path10) { + var _a3; + if (this.persistentPaths.has(path10)) { + this.persistentPaths.delete(path10); + } else { + if (!isValidDirectoryPath(path10)) { + new import_obsidian17.Notice(`Cannot persist "${this.shortenPath(path10)}" - directory no longer exists`, 4e3); + return; + } + this.persistentPaths.add(path10); + } + (_a3 = this.onPersistenceChangeCallback) == null ? void 0 : _a3.call(this, [...this.persistentPaths]); + this.renderDropdown(); + } + mergePersistentPaths() { + const pathSet = new Set(this.externalContextPaths); + for (const path10 of this.persistentPaths) { + pathSet.add(path10); + } + this.externalContextPaths = [...pathSet]; + } + /** + * Restore exact external context paths from a saved conversation. + * Does NOT merge with persistent paths - preserves the session's historical state. + * Use clearExternalContexts() for new sessions to start with current persistent paths. + */ + setExternalContexts(paths) { + this.externalContextPaths = [...paths]; this.updateDisplay(); this.renderDropdown(); } - /** Clear session context paths (call on new conversation). */ - clearContextPaths() { - this.sessionContextPaths = []; + /** + * Remove a path from external contexts (and persistent paths if applicable). + * Exposed for testing the remove button behavior. + */ + removePath(pathStr) { + var _a3, _b; + this.externalContextPaths = this.externalContextPaths.filter((p2) => p2 !== pathStr); + if (this.persistentPaths.has(pathStr)) { + this.persistentPaths.delete(pathStr); + (_a3 = this.onPersistenceChangeCallback) == null ? void 0 : _a3.call(this, [...this.persistentPaths]); + } + (_b = this.onChangeCallback) == null ? void 0 : _b.call(this, this.externalContextPaths); + this.updateDisplay(); + this.renderDropdown(); + } + /** + * Add an external context path programmatically (e.g., from /add-dir command). + * Validates the path and handles duplicates/conflicts. + * @param pathInput - Path string (supports ~/ expansion) + * @returns Result with success status and normalized path, or error message on failure + */ + addExternalContext(pathInput) { + var _a3; + const trimmed = pathInput == null ? void 0 : pathInput.trim(); + if (!trimmed) { + return { success: false, error: "No path provided. Usage: /add-dir /absolute/path" }; + } + let cleanPath = trimmed; + if (cleanPath.startsWith('"') && cleanPath.endsWith('"') || cleanPath.startsWith("'") && cleanPath.endsWith("'")) { + cleanPath = cleanPath.slice(1, -1); + } + const expandedPath = expandHomePath(cleanPath); + const normalizedPath = normalizePathForFilesystem(expandedPath); + if (!path8.isAbsolute(normalizedPath)) { + return { success: false, error: "Path must be absolute. Usage: /add-dir /absolute/path" }; + } + const validation = validateDirectoryPath(normalizedPath); + if (!validation.valid) { + return { success: false, error: `${validation.error}: ${pathInput}` }; + } + if (isDuplicatePath(normalizedPath, this.externalContextPaths)) { + return { success: false, error: "This folder is already added as an external context." }; + } + const conflict = findConflictingPath(normalizedPath, this.externalContextPaths); + if (conflict) { + return { success: false, error: this.formatConflictMessage(normalizedPath, conflict) }; + } + this.externalContextPaths = [...this.externalContextPaths, normalizedPath]; + (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.externalContextPaths); + this.updateDisplay(); + this.renderDropdown(); + return { success: true, normalizedPath }; + } + /** + * Clear session-only external context paths (call on new conversation). + * Uses persistent paths from settings if provided, otherwise falls back to local cache. + * Validates paths before using them (silently filters invalid during session init). + */ + clearExternalContexts(persistentPathsFromSettings) { + if (persistentPathsFromSettings) { + const validPaths = filterValidPaths(persistentPathsFromSettings); + this.persistentPaths = new Set(validPaths); + } + this.externalContextPaths = [...this.persistentPaths]; this.updateDisplay(); this.renderDropdown(); } render() { this.container.empty(); - const iconWrapper = this.container.createDiv({ cls: "claudian-context-path-icon-wrapper" }); - this.iconEl = iconWrapper.createDiv({ cls: "claudian-context-path-icon" }); - (0, import_obsidian6.setIcon)(this.iconEl, "folder"); - this.badgeEl = iconWrapper.createDiv({ cls: "claudian-context-path-badge" }); + const iconWrapper = this.container.createDiv({ cls: "claudian-external-context-icon-wrapper" }); + this.iconEl = iconWrapper.createDiv({ cls: "claudian-external-context-icon" }); + (0, import_obsidian17.setIcon)(this.iconEl, "folder"); + this.badgeEl = iconWrapper.createDiv({ cls: "claudian-external-context-badge" }); this.updateDisplay(); - iconWrapper.addEventListener("click", (e) => { - e.stopPropagation(); + iconWrapper.addEventListener("click", (e2) => { + e2.stopPropagation(); this.openFolderPicker(); }); - this.dropdownEl = this.container.createDiv({ cls: "claudian-context-path-dropdown" }); + this.dropdownEl = this.container.createDiv({ cls: "claudian-external-context-dropdown" }); this.renderDropdown(); } async openFolderPicker() { - var _a; + var _a3; try { const { remote } = require("electron"); const result = await remote.dialog.showOpenDialog({ properties: ["openDirectory"], - title: "Select Context Path (Read-Only)" + title: "Select External Context" }); if (!result.canceled && result.filePaths.length > 0) { const selectedPath = result.filePaths[0]; - if (this.sessionContextPaths.includes(selectedPath)) { + if (isDuplicatePath(selectedPath, this.externalContextPaths)) { + new import_obsidian17.Notice("This folder is already added as an external context.", 3e3); return; } - const conflict = findConflictingPath(selectedPath, this.sessionContextPaths); + const conflict = findConflictingPath(selectedPath, this.externalContextPaths); if (conflict) { - this.showConflictNotice(selectedPath, conflict); + new import_obsidian17.Notice(this.formatConflictMessage(selectedPath, conflict), 5e3); return; } - this.sessionContextPaths = [...this.sessionContextPaths, selectedPath]; - (_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.sessionContextPaths); + this.externalContextPaths = [...this.externalContextPaths, selectedPath]; + (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.externalContextPaths); this.updateDisplay(); this.renderDropdown(); } - } catch (err) { - console.error("Failed to open folder picker:", err); + } catch (e2) { + new import_obsidian17.Notice("Unable to open folder picker.", 5e3); } } - /** Shows a notice when a conflicting path is detected. */ - showConflictNotice(newPath, conflict) { + /** Formats a conflict error message for display. */ + formatConflictMessage(newPath, conflict) { const shortNew = this.shortenPath(newPath); const shortExisting = this.shortenPath(conflict.path); - let message; - if (conflict.type === "parent") { - message = `Cannot add "${shortNew}" - it's inside existing path "${shortExisting}"`; - } else { - message = `Cannot add "${shortNew}" - it contains existing path "${shortExisting}"`; - } - new import_obsidian6.Notice(message, 5e3); + return conflict.type === "parent" ? `Cannot add "${shortNew}" - it's inside existing path "${shortExisting}"` : `Cannot add "${shortNew}" - it contains existing path "${shortExisting}"`; } renderDropdown() { if (!this.dropdownEl) return; this.dropdownEl.empty(); - const headerEl = this.dropdownEl.createDiv({ cls: "claudian-context-path-header" }); - headerEl.setText("Context Paths (Read-Only)"); - const listEl = this.dropdownEl.createDiv({ cls: "claudian-context-path-list" }); - if (this.sessionContextPaths.length === 0) { - const emptyEl = listEl.createDiv({ cls: "claudian-context-path-empty" }); + const headerEl = this.dropdownEl.createDiv({ cls: "claudian-external-context-header" }); + headerEl.setText("External Contexts"); + const listEl = this.dropdownEl.createDiv({ cls: "claudian-external-context-list" }); + if (this.externalContextPaths.length === 0) { + const emptyEl = listEl.createDiv({ cls: "claudian-external-context-empty" }); emptyEl.setText("Click folder icon to add"); } else { - for (const pathStr of this.sessionContextPaths) { - const itemEl = listEl.createDiv({ cls: "claudian-context-path-item" }); - const pathTextEl = itemEl.createSpan({ cls: "claudian-context-path-text" }); + for (const pathStr of this.externalContextPaths) { + const itemEl = listEl.createDiv({ cls: "claudian-external-context-item" }); + const pathTextEl = itemEl.createSpan({ cls: "claudian-external-context-text" }); const displayPath = this.shortenPath(pathStr); pathTextEl.setText(displayPath); pathTextEl.setAttribute("title", pathStr); - const removeBtn = itemEl.createSpan({ cls: "claudian-context-path-remove" }); - (0, import_obsidian6.setIcon)(removeBtn, "x"); + const isPersistent = this.persistentPaths.has(pathStr); + const lockBtn = itemEl.createSpan({ cls: "claudian-external-context-lock" }); + if (isPersistent) { + lockBtn.addClass("locked"); + } + (0, import_obsidian17.setIcon)(lockBtn, isPersistent ? "lock" : "unlock"); + lockBtn.setAttribute("title", isPersistent ? "Persistent (click to make session-only)" : "Session-only (click to persist)"); + lockBtn.addEventListener("click", (e2) => { + e2.stopPropagation(); + this.togglePersistence(pathStr); + }); + const removeBtn = itemEl.createSpan({ cls: "claudian-external-context-remove" }); + (0, import_obsidian17.setIcon)(removeBtn, "x"); removeBtn.setAttribute("title", "Remove path"); - removeBtn.addEventListener("click", (e) => { - var _a; - e.stopPropagation(); - this.sessionContextPaths = this.sessionContextPaths.filter((p) => p !== pathStr); - (_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.sessionContextPaths); - this.updateDisplay(); - this.renderDropdown(); + removeBtn.addEventListener("click", (e2) => { + e2.stopPropagation(); + this.removePath(pathStr); }); } } @@ -28634,26 +57859,27 @@ var ContextPathSelector = class { /** Shorten path for display (replace home dir with ~) */ shortenPath(fullPath) { try { - const os3 = require("os"); - const homeDir = os3.homedir(); + const os6 = require("os"); + const homeDir = os6.homedir(); const normalize2 = (value) => value.replace(/\\/g, "/"); const normalizedFull = normalize2(fullPath); const normalizedHome = normalize2(homeDir); const compareFull = process.platform === "win32" ? normalizedFull.toLowerCase() : normalizedFull; const compareHome = process.platform === "win32" ? normalizedHome.toLowerCase() : normalizedHome; if (compareFull.startsWith(compareHome)) { - return "~" + fullPath.slice(homeDir.length); + const remainder = normalizedFull.slice(normalizedHome.length); + return "~" + remainder; } - } catch (e) { + } catch (e2) { } return fullPath; } updateDisplay() { if (!this.iconEl || !this.badgeEl) return; - const count = this.sessionContextPaths.length; + const count = this.externalContextPaths.length; if (count > 0) { this.iconEl.addClass("active"); - this.iconEl.setAttribute("title", `${count} context path${count > 1 ? "s" : ""} (click to add more)`); + this.iconEl.setAttribute("title", `${count} external context${count > 1 ? "s" : ""} (click to add more)`); if (count > 1) { this.badgeEl.setText(String(count)); this.badgeEl.addClass("visible"); @@ -28662,7 +57888,7 @@ var ContextPathSelector = class { } } else { this.iconEl.removeClass("active"); - this.iconEl.setAttribute("title", "Add context paths (click)"); + this.iconEl.setAttribute("title", "Add external contexts (click)"); this.badgeEl.removeClass("visible"); } } @@ -28672,28 +57898,24 @@ var McpServerSelector = class { this.iconEl = null; this.badgeEl = null; this.dropdownEl = null; - this.mcpService = null; + this.mcpManager = null; this.enabledServers = /* @__PURE__ */ new Set(); this.onChangeCallback = null; this.container = parentEl.createDiv({ cls: "claudian-mcp-selector" }); this.render(); } - /** Set the MCP service for fetching server list. */ - setMcpService(service) { - this.mcpService = service; + setMcpManager(manager) { + this.mcpManager = manager; this.pruneEnabledServers(); this.updateDisplay(); this.renderDropdown(); } - /** Set callback for when enabled servers change. */ setOnChange(callback) { this.onChangeCallback = callback; } - /** Get currently enabled servers (via click or @-mention). */ getEnabledServers() { return new Set(this.enabledServers); } - /** Add servers from @-mentions. */ addMentionedServers(names) { let changed = false; for (const name of names) { @@ -28707,16 +57929,21 @@ var McpServerSelector = class { this.renderDropdown(); } } - /** Clear enabled servers (call on new conversation). */ clearEnabled() { this.enabledServers.clear(); this.updateDisplay(); this.renderDropdown(); } + setEnabledServers(names) { + this.enabledServers = new Set(names); + this.pruneEnabledServers(); + this.updateDisplay(); + this.renderDropdown(); + } pruneEnabledServers() { - var _a; - if (!this.mcpService) return; - const activeNames = new Set(this.mcpService.getServers().filter((s) => s.enabled).map((s) => s.name)); + var _a3; + if (!this.mcpManager) return; + const activeNames = new Set(this.mcpManager.getServers().filter((s) => s.enabled).map((s) => s.name)); let changed = false; for (const name of this.enabledServers) { if (!activeNames.has(name)) { @@ -28725,7 +57952,7 @@ var McpServerSelector = class { } } if (changed) { - (_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.enabledServers); + (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.enabledServers); } } render() { @@ -28742,14 +57969,14 @@ var McpServerSelector = class { }); } renderDropdown() { - var _a; + var _a3; if (!this.dropdownEl) return; this.pruneEnabledServers(); this.dropdownEl.empty(); const headerEl = this.dropdownEl.createDiv({ cls: "claudian-mcp-selector-header" }); headerEl.setText("MCP Servers"); const listEl = this.dropdownEl.createDiv({ cls: "claudian-mcp-selector-list" }); - const allServers = ((_a = this.mcpService) == null ? void 0 : _a.getServers()) || []; + const allServers = ((_a3 = this.mcpManager) == null ? void 0 : _a3.getServers()) || []; const servers = allServers.filter((s) => s.enabled); if (servers.length === 0) { const emptyEl = listEl.createDiv({ cls: "claudian-mcp-selector-empty" }); @@ -28769,7 +57996,7 @@ var McpServerSelector = class { } const checkEl = itemEl.createDiv({ cls: "claudian-mcp-selector-check" }); if (isEnabled) { - (0, import_obsidian6.setIcon)(checkEl, "check"); + checkEl.innerHTML = CHECK_ICON_SVG; } const infoEl = itemEl.createDiv({ cls: "claudian-mcp-selector-item-info" }); const nameEl = infoEl.createSpan({ cls: "claudian-mcp-selector-item-name" }); @@ -28779,38 +58006,37 @@ var McpServerSelector = class { csEl.setText("@"); csEl.setAttribute("title", "Context-saving: can also enable via @" + server.name); } - itemEl.addEventListener("click", (e) => { - e.stopPropagation(); + itemEl.addEventListener("mousedown", (e2) => { + e2.preventDefault(); + e2.stopPropagation(); this.toggleServer(server.name, itemEl); }); } toggleServer(name, itemEl) { - var _a; + var _a3; if (this.enabledServers.has(name)) { this.enabledServers.delete(name); } else { this.enabledServers.add(name); } - if (itemEl) { - const isEnabled = this.enabledServers.has(name); - const checkEl = itemEl.querySelector(".claudian-mcp-selector-check"); - if (isEnabled) { - itemEl.addClass("enabled"); - if (checkEl) (0, import_obsidian6.setIcon)(checkEl, "check"); - } else { - itemEl.removeClass("enabled"); - if (checkEl) checkEl.empty(); - } + const isEnabled = this.enabledServers.has(name); + const checkEl = itemEl.querySelector(".claudian-mcp-selector-check"); + if (isEnabled) { + itemEl.addClass("enabled"); + if (checkEl) checkEl.innerHTML = CHECK_ICON_SVG; + } else { + itemEl.removeClass("enabled"); + if (checkEl) checkEl.innerHTML = ""; } this.updateDisplay(); - (_a = this.onChangeCallback) == null ? void 0 : _a.call(this, this.enabledServers); + (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.enabledServers); } updateDisplay() { - var _a; + var _a3; this.pruneEnabledServers(); if (!this.iconEl || !this.badgeEl) return; const count = this.enabledServers.size; - const hasServers = (((_a = this.mcpService) == null ? void 0 : _a.getServers().length) || 0) > 0; + const hasServers = (((_a3 = this.mcpManager) == null ? void 0 : _a3.getServers().length) || 0) > 0; if (!hasServers) { this.container.style.display = "none"; return; @@ -28854,18 +58080,18 @@ var ContextUsageMeter = class { this.circumference = radius * arcRadians; const startRad = startAngle * Math.PI / 180; const endRad = endAngle * Math.PI / 180; - const x1 = cx + radius * Math.cos(startRad); - const y1 = cy + radius * Math.sin(startRad); - const x2 = cx + radius * Math.cos(endRad); - const y2 = cy + radius * Math.sin(endRad); + const x12 = cx + radius * Math.cos(startRad); + const y12 = cy + radius * Math.sin(startRad); + const x22 = cx + radius * Math.cos(endRad); + const y22 = cy + radius * Math.sin(endRad); const gaugeEl = this.container.createDiv({ cls: "claudian-context-meter-gauge" }); gaugeEl.innerHTML = ` @@ -28874,7 +58100,7 @@ var ContextUsageMeter = class { this.percentEl = this.container.createSpan({ cls: "claudian-context-meter-percent" }); } update(usage) { - if (!usage) { + if (!usage || usage.contextTokens <= 0) { this.container.style.display = "none"; return; } @@ -28891,10 +58117,12 @@ var ContextUsageMeter = class { } else { this.container.removeClass("warning"); } - const tooltip = `${this.formatTokens(usage.contextTokens)} / ${this.formatTokens(usage.contextWindow)}`; + let tooltip = `${this.formatTokens(usage.contextTokens)} / ${this.formatTokens(usage.contextWindow)}`; + if (usage.percentage > 80) { + tooltip += " (Approaching limit, run `/compact` to continue)"; + } this.container.setAttribute("data-tooltip", tooltip); } - /** Format token count (e.g., 45000 -> "45k", 200000 -> "200k") */ formatTokens(tokens) { if (tokens >= 1e3) { return `${Math.round(tokens / 1e3)}k`; @@ -28906,13 +58134,13 @@ function createInputToolbar(parentEl, callbacks) { const modelSelector = new ModelSelector(parentEl, callbacks); const thinkingBudgetSelector = new ThinkingBudgetSelector(parentEl, callbacks); const contextUsageMeter = new ContextUsageMeter(parentEl); - const contextPathSelector = new ContextPathSelector(parentEl, callbacks); + const externalContextSelector = new ExternalContextSelector(parentEl, callbacks); const mcpServerSelector = new McpServerSelector(parentEl); const permissionToggle = new PermissionToggle(parentEl, callbacks); - return { modelSelector, thinkingBudgetSelector, contextUsageMeter, contextPathSelector, mcpServerSelector, permissionToggle }; + return { modelSelector, thinkingBudgetSelector, contextUsageMeter, externalContextSelector, mcpServerSelector, permissionToggle }; } -// src/ui/components/InstructionModeManager.ts +// src/features/chat/ui/InstructionModeManager.ts var INSTRUCTION_MODE_PLACEHOLDER = "# Save in custom system prompt"; var InstructionModeManager = class { constructor(inputEl, callbacks) { @@ -28927,10 +58155,10 @@ var InstructionModeManager = class { * Handles keydown to detect # trigger. * Returns true if the event was consumed (should prevent default). */ - handleTriggerKey(e) { - if (!this.state.active && this.inputEl.value === "" && e.key === "#") { + handleTriggerKey(e2) { + if (!this.state.active && this.inputEl.value === "" && e2.key === "#") { if (this.enterMode()) { - e.preventDefault(); + e2.preventDefault(); return true; } } @@ -28969,18 +58197,18 @@ var InstructionModeManager = class { this.inputEl.placeholder = this.originalPlaceholder; } /** Handles keydown events. Returns true if handled. */ - handleKeydown(e) { + handleKeydown(e2) { if (!this.state.active) return false; - if (e.key === "Enter" && !e.shiftKey) { + if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing) { if (!this.state.rawInstruction.trim()) { return false; } - e.preventDefault(); + e2.preventDefault(); this.submit(); return true; } - if (e.key === "Escape") { - e.preventDefault(); + if (e2.key === "Escape" && !e2.isComposing) { + e2.preventDefault(); this.cancel(); return true; } @@ -29008,13 +58236,17 @@ var InstructionModeManager = class { } /** Cancels instruction mode and clears input. */ cancel() { + var _a3, _b; this.inputEl.value = ""; this.exitMode(); + (_b = (_a3 = this.callbacks).resetInputHeight) == null ? void 0 : _b.call(_a3); } /** Clears the input and resets state (called after successful submission). */ clear() { + var _a3, _b; this.inputEl.value = ""; this.exitMode(); + (_b = (_a3 = this.callbacks).resetInputHeight) == null ? void 0 : _b.call(_a3); } /** Cleans up event listeners. */ destroy() { @@ -29026,679 +58258,25 @@ var InstructionModeManager = class { } }; -// src/ui/components/PlanApprovalPanel.ts -function findInputElements2(containerEl) { - const inputContainer = containerEl.querySelector(".claudian-input-container"); - const inputWrapper = containerEl.querySelector(".claudian-input-wrapper"); - return { inputContainer, inputWrapper }; -} -var APPROVAL_OPTIONS = [ - { label: "Approve", isRevise: false }, - { label: "Approve && New Session", isRevise: false }, - { label: "Type here to tell Claudian what to change", isRevise: true } -]; -var PlanApprovalPanel = class { - constructor(_app, options) { - this.isDestroyed = false; - this.reviseInputEl = null; - this.currentOptionIndex = 0; - this.optionsEl = null; - // Input area references (for hiding/showing) - this.inputContainer = null; - this.inputWrapper = null; - this.containerEl = options.containerEl; - this.onApprove = options.onApprove; - this.onApproveNewSession = options.onApproveNewSession; - this.onRevise = options.onRevise; - this.onCancel = options.onCancel; - const { inputContainer, inputWrapper } = findInputElements2(this.containerEl); - this.inputContainer = inputContainer; - this.inputWrapper = inputWrapper; - if (this.inputWrapper) { - this.inputWrapper.style.display = "none"; - } - this.panelEl = this.createPanel(); - if (this.inputContainer) { - this.inputContainer.appendChild(this.panelEl); - } else { - this.containerEl.appendChild(this.panelEl); - } - this.panelEl.focus(); - } - /** Create the panel DOM structure. */ - createPanel() { - const panel = document.createElement("div"); - panel.className = "claudian-plan-approval-panel"; - panel.setAttribute("tabindex", "0"); - panel.setAttribute("role", "dialog"); - panel.setAttribute("aria-label", "Review implementation plan"); - panel.addEventListener("keydown", this.handleKeyDown.bind(this)); - const headerEl = document.createElement("div"); - headerEl.className = "claudian-plan-approval-header"; - headerEl.textContent = "Would you like to proceed?"; - panel.appendChild(headerEl); - this.optionsEl = document.createElement("div"); - this.optionsEl.className = "claudian-plan-approval-options"; - this.renderOptions(); - panel.appendChild(this.optionsEl); - return panel; - } - /** Render the option rows. */ - renderOptions() { - if (!this.optionsEl) return; - this.optionsEl.innerHTML = ""; - APPROVAL_OPTIONS.forEach((option, index) => { - const optionEl = document.createElement("div"); - optionEl.className = "claudian-plan-approval-option"; - optionEl.setAttribute("data-option-index", String(index)); - const caretEl = document.createElement("span"); - caretEl.className = "claudian-plan-approval-caret"; - caretEl.textContent = index === this.currentOptionIndex ? ">" : " "; - optionEl.appendChild(caretEl); - const numberEl = document.createElement("span"); - numberEl.className = "claudian-plan-approval-number"; - numberEl.textContent = `${index + 1}.`; - optionEl.appendChild(numberEl); - if (option.isRevise) { - this.reviseInputEl = document.createElement("input"); - this.reviseInputEl.type = "text"; - this.reviseInputEl.className = "claudian-plan-approval-revise-inline"; - this.reviseInputEl.placeholder = option.label; - this.reviseInputEl.addEventListener("click", (e) => { - e.stopPropagation(); - this.currentOptionIndex = index; - this.updateOptionFocus(); - }); - this.reviseInputEl.addEventListener("keydown", (e) => { - var _a; - if (e.key === "Enter") { - e.preventDefault(); - this.handleReviseSubmit(); - } else if (e.key === "Escape") { - e.preventDefault(); - if ((_a = this.reviseInputEl) == null ? void 0 : _a.value) { - this.reviseInputEl.value = ""; - } else { - this.handleCancel(); - } - } else if (e.key === "ArrowUp") { - e.preventDefault(); - this.currentOptionIndex = Math.max(0, this.currentOptionIndex - 1); - this.updateOptionFocus(); - this.panelEl.focus(); - } - e.stopPropagation(); - }); - this.reviseInputEl.addEventListener("focus", () => { - this.currentOptionIndex = index; - this.updateOptionFocus(); - }); - optionEl.appendChild(this.reviseInputEl); - } else { - const labelEl = document.createElement("span"); - labelEl.className = "claudian-plan-approval-option-label"; - labelEl.textContent = option.label; - optionEl.appendChild(labelEl); - } - optionEl.addEventListener("click", () => { - var _a; - this.currentOptionIndex = index; - this.updateOptionFocus(); - if (!option.isRevise) { - this.selectCurrentOption(); - } else { - (_a = this.reviseInputEl) == null ? void 0 : _a.focus(); - } - }); - optionEl.addEventListener("mouseenter", () => { - this.currentOptionIndex = index; - this.updateOptionFocus(); - }); - if (index === this.currentOptionIndex) { - optionEl.classList.add("focused"); - } - this.optionsEl.appendChild(optionEl); - }); - } - /** Update the visual focus indicator on options. */ - updateOptionFocus() { - if (!this.optionsEl) return; - const options = this.optionsEl.querySelectorAll(".claudian-plan-approval-option"); - options.forEach((opt, i) => { - const caret = opt.querySelector(".claudian-plan-approval-caret"); - const isFocused = i === this.currentOptionIndex; - opt.classList.toggle("focused", isFocused); - if (caret) { - caret.textContent = isFocused ? ">" : " "; - } - }); - if (this.currentOptionIndex !== 2 && this.reviseInputEl && document.activeElement === this.reviseInputEl) { - this.reviseInputEl.blur(); - this.panelEl.focus(); - } - if (this.currentOptionIndex === 2 && this.reviseInputEl) { - this.reviseInputEl.focus(); - } - } - /** Select the currently focused option. */ - selectCurrentOption() { - var _a; - switch (this.currentOptionIndex) { - case 0: - this.handleApprove(); - break; - case 1: - this.handleApproveNewSession(); - break; - case 2: - (_a = this.reviseInputEl) == null ? void 0 : _a.focus(); - break; - } - } - /** Handle keyboard events. */ - handleKeyDown(e) { - var _a; - if (this.isDestroyed) return; - if (document.activeElement === this.reviseInputEl) { - return; - } - switch (e.key) { - case "ArrowUp": - e.preventDefault(); - this.currentOptionIndex = Math.max(0, this.currentOptionIndex - 1); - this.updateOptionFocus(); - break; - case "ArrowDown": - e.preventDefault(); - this.currentOptionIndex = Math.min(APPROVAL_OPTIONS.length - 1, this.currentOptionIndex + 1); - this.updateOptionFocus(); - break; - case "Enter": - e.preventDefault(); - this.selectCurrentOption(); - break; - case "Escape": - e.preventDefault(); - this.handleCancel(); - break; - case "1": - e.preventDefault(); - this.currentOptionIndex = 0; - this.updateOptionFocus(); - this.selectCurrentOption(); - break; - case "2": - e.preventDefault(); - this.currentOptionIndex = 1; - this.updateOptionFocus(); - this.selectCurrentOption(); - break; - case "3": - e.preventDefault(); - this.currentOptionIndex = 2; - this.updateOptionFocus(); - (_a = this.reviseInputEl) == null ? void 0 : _a.focus(); - break; - default: - if (this.currentOptionIndex === 2 && e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) { - e.preventDefault(); - if (this.reviseInputEl) { - this.reviseInputEl.focus(); - this.reviseInputEl.value = e.key; - this.reviseInputEl.setSelectionRange(1, 1); - } - } - break; - } - } - /** Handle approve action. */ - handleApprove() { - if (this.isDestroyed) return; - this.destroy(); - this.onApprove(); - } - /** Handle approve with new session action. */ - handleApproveNewSession() { - if (this.isDestroyed) return; - this.destroy(); - this.onApproveNewSession(); - } - /** Handle cancel action (Esc). */ - handleCancel() { - if (this.isDestroyed) return; - this.destroy(); - this.onCancel(); - } - /** Handle revise submission. */ - handleReviseSubmit() { - var _a; - if (this.isDestroyed) return; - const feedback = (_a = this.reviseInputEl) == null ? void 0 : _a.value.trim(); - if (!feedback) return; - this.destroy(); - this.onRevise(feedback); - } - /** Destroy the panel and restore input area. */ - destroy() { - if (this.isDestroyed) return; - this.isDestroyed = true; - this.panelEl.remove(); - if (this.inputWrapper) { - this.inputWrapper.style.display = ""; - } - } -}; -function showPlanApprovalPanel(app, containerEl, planContent, component) { - return new Promise((resolve7) => { - new PlanApprovalPanel(app, { - containerEl, - planContent, - component, - onApprove: () => resolve7({ decision: "approve" }), - onApproveNewSession: () => resolve7({ decision: "approve_new_session" }), - onRevise: (feedback) => resolve7({ decision: "revise", feedback }), - onCancel: () => resolve7({ decision: "cancel" }) - }); - }); -} - -// src/ui/components/PlanBanner.ts -var import_obsidian7 = require("obsidian"); -var PlanBanner = class { - constructor(options) { - this.containerEl = null; - this.bannerEl = null; - this.contentEl = null; - this.isExpanded = false; - this.planContent = ""; - this.app = options.app; - this.component = options.component; - } - /** - * Mount the banner into the container. - * Should be called after the container is created, inserts between header and messages. - */ - mount(containerEl) { - this.containerEl = containerEl; - } - /** - * Show the banner with the given plan content. - */ - async show(planContent) { - if (!this.containerEl) return; - if (this.bannerEl) { - this.bannerEl.remove(); - this.bannerEl = null; - this.contentEl = null; - } - this.planContent = planContent; - this.isExpanded = false; - this.bannerEl = document.createElement("div"); - this.bannerEl.className = "claudian-plan-banner"; - const headerEl = document.createElement("div"); - headerEl.className = "claudian-plan-banner-header"; - headerEl.addEventListener("click", () => this.toggle()); - const chevronEl = document.createElement("span"); - chevronEl.className = "claudian-plan-banner-chevron"; - chevronEl.textContent = "\u25B6"; - headerEl.appendChild(chevronEl); - const titleEl = document.createElement("span"); - titleEl.className = "claudian-plan-banner-title"; - titleEl.textContent = "Approved Plan"; - headerEl.appendChild(titleEl); - this.bannerEl.appendChild(headerEl); - this.contentEl = document.createElement("div"); - this.contentEl.className = "claudian-plan-banner-content"; - this.contentEl.style.display = "none"; - await this.renderContent(); - this.bannerEl.appendChild(this.contentEl); - const messagesEl = this.containerEl.querySelector(".claudian-messages"); - if (messagesEl) { - this.containerEl.insertBefore(this.bannerEl, messagesEl); - } else { - this.containerEl.appendChild(this.bannerEl); - } - } - /** - * Hide and remove the banner. - */ - hide() { - if (this.bannerEl) { - this.bannerEl.remove(); - this.bannerEl = null; - this.contentEl = null; - } - this.isExpanded = false; - this.planContent = ""; - } - /** - * Toggle the banner's expanded/collapsed state. - */ - toggle() { - this.isExpanded = !this.isExpanded; - this.updateDisplay(); - } - /** - * Update the display based on expanded state. - */ - updateDisplay() { - if (!this.bannerEl || !this.contentEl) return; - const chevron = this.bannerEl.querySelector(".claudian-plan-banner-chevron"); - if (chevron) { - chevron.textContent = this.isExpanded ? "\u25BC" : "\u25B6"; - } - this.contentEl.style.display = this.isExpanded ? "block" : "none"; - this.bannerEl.classList.toggle("expanded", this.isExpanded); - } - /** - * Render the plan content as markdown. - */ - async renderContent() { - if (!this.contentEl) return; - try { - await import_obsidian7.MarkdownRenderer.render( - this.app, - this.planContent, - this.contentEl, - "", - this.component - ); - } catch (e) { - this.contentEl.textContent = this.planContent; - } - } - /** - * Check if the banner is currently visible. - */ - isVisible() { - return this.bannerEl !== null; - } - /** - * Get the current plan content. - */ - getPlanContent() { - return this.planContent; - } -}; - -// src/ui/components/SelectionHighlight.ts -var import_state = require("@codemirror/state"); -var import_view = require("@codemirror/view"); -function createSelectionHighlighter() { - const showHighlight = import_state.StateEffect.define(); - const hideHighlight = import_state.StateEffect.define(); - const selectionHighlightField = import_state.StateField.define({ - create: () => import_view.Decoration.none, - update: (deco, tr) => { - for (const e of tr.effects) { - if (e.is(showHighlight)) { - const builder = new import_state.RangeSetBuilder(); - builder.add(e.value.from, e.value.to, import_view.Decoration.mark({ - class: "claudian-selection-highlight" - })); - return builder.finish(); - } else if (e.is(hideHighlight)) { - return import_view.Decoration.none; - } - } - return deco.map(tr.changes); - }, - provide: (f) => import_view.EditorView.decorations.from(f) - }); - const installedEditors2 = /* @__PURE__ */ new WeakSet(); - function ensureHighlightField(editorView) { - if (!installedEditors2.has(editorView)) { - editorView.dispatch({ - effects: import_state.StateEffect.appendConfig.of(selectionHighlightField) - }); - installedEditors2.add(editorView); - } - } - function show(editorView, from, to) { - ensureHighlightField(editorView); - editorView.dispatch({ - effects: showHighlight.of({ from, to }) - }); - } - function hide(editorView) { - if (installedEditors2.has(editorView)) { - editorView.dispatch({ - effects: hideHighlight.of(null) - }); - } - } - return { show, hide }; -} -var defaultHighlighter = createSelectionHighlighter(); -function showSelectionHighlight(editorView, from, to) { - defaultHighlighter.show(editorView, from, to); -} -function hideSelectionHighlight(editorView) { - defaultHighlighter.hide(editorView); -} - -// src/ui/components/SlashCommandDropdown.ts -var SlashCommandDropdown = class { - constructor(containerEl, inputEl, callbacks, options = {}) { - this.dropdownEl = null; - this.slashStartIndex = -1; - this.selectedIndex = 0; - this.filteredCommands = []; - var _a; - this.containerEl = containerEl; - this.inputEl = inputEl; - this.callbacks = callbacks; - this.isFixed = (_a = options.fixed) != null ? _a : false; - this.onInput = () => this.handleInputChange(); - this.inputEl.addEventListener("input", this.onInput); - } - /** Handles input changes to detect / trigger. */ - handleInputChange() { - const text = this.getInputValue(); - const cursorPos = this.getCursorPosition(); - const textBeforeCursor = text.substring(0, cursorPos); - const lastSlashIndex = textBeforeCursor.lastIndexOf("/"); - if (lastSlashIndex === -1) { - this.hide(); - return; - } - const charBeforeSlash = lastSlashIndex > 0 ? textBeforeCursor[lastSlashIndex - 1] : " "; - if (!/\s/.test(charBeforeSlash) && lastSlashIndex !== 0) { - this.hide(); - return; - } - const searchText = textBeforeCursor.substring(lastSlashIndex + 1); - if (/\s/.test(searchText)) { - this.hide(); - return; - } - this.slashStartIndex = lastSlashIndex; - this.showDropdown(searchText); - } - /** Handles keyboard navigation. Returns true if handled. */ - handleKeydown(e) { - if (!this.isVisible()) return false; - switch (e.key) { - case "ArrowDown": - e.preventDefault(); - this.navigate(1); - return true; - case "ArrowUp": - e.preventDefault(); - this.navigate(-1); - return true; - case "Enter": - case "Tab": - if (this.filteredCommands.length > 0) { - e.preventDefault(); - this.selectItem(); - return true; - } - return false; - case "Escape": - e.preventDefault(); - this.hide(); - return true; - } - return false; - } - /** Checks if dropdown is currently visible. */ - isVisible() { - var _a, _b; - return (_b = (_a = this.dropdownEl) == null ? void 0 : _a.hasClass("visible")) != null ? _b : false; - } - /** Hides the dropdown. */ - hide() { - if (this.dropdownEl) { - this.dropdownEl.removeClass("visible"); - } - this.slashStartIndex = -1; - this.callbacks.onHide(); - } - /** Destroys the dropdown and cleans up. */ - destroy() { - this.inputEl.removeEventListener("input", this.onInput); - if (this.dropdownEl) { - this.dropdownEl.remove(); - this.dropdownEl = null; - } - } - getInputValue() { - return this.inputEl.value; - } - getCursorPosition() { - return this.inputEl.selectionStart || 0; - } - setInputValue(value) { - this.inputEl.value = value; - } - setCursorPosition(pos) { - this.inputEl.selectionStart = pos; - this.inputEl.selectionEnd = pos; - } - showDropdown(searchText) { - const allCommands = this.callbacks.getCommands(); - const searchLower = searchText.toLowerCase(); - this.filteredCommands = allCommands.filter( - (cmd) => { - var _a; - return cmd.name.toLowerCase().includes(searchLower) || ((_a = cmd.description) == null ? void 0 : _a.toLowerCase().includes(searchLower)); - } - ).slice(0, 10); - if (searchText.length > 0 && this.filteredCommands.length === 0) { - this.hide(); - return; - } - this.selectedIndex = 0; - this.render(); - } - render() { - if (!this.dropdownEl) { - this.dropdownEl = this.createDropdownElement(); - } - this.dropdownEl.empty(); - if (this.filteredCommands.length === 0) { - const emptyEl = this.dropdownEl.createDiv({ cls: "claudian-slash-empty" }); - emptyEl.setText("No matching commands"); - } else { - for (let i = 0; i < this.filteredCommands.length; i++) { - const cmd = this.filteredCommands[i]; - const itemEl = this.dropdownEl.createDiv({ cls: "claudian-slash-item" }); - if (i === this.selectedIndex) { - itemEl.addClass("selected"); - } - const nameEl = itemEl.createSpan({ cls: "claudian-slash-name" }); - nameEl.setText(`/${cmd.name}`); - if (cmd.argumentHint) { - const hintEl = itemEl.createSpan({ cls: "claudian-slash-hint" }); - hintEl.setText(cmd.argumentHint); - } - if (cmd.description) { - const descEl = itemEl.createDiv({ cls: "claudian-slash-desc" }); - descEl.setText(cmd.description); - } - itemEl.addEventListener("click", () => { - this.selectedIndex = i; - this.selectItem(); - }); - itemEl.addEventListener("mouseenter", () => { - this.selectedIndex = i; - this.updateSelection(); - }); - } - } - this.dropdownEl.addClass("visible"); - if (this.isFixed) { - this.positionFixed(); - } - } - createDropdownElement() { - if (this.isFixed) { - const dropdown = this.containerEl.createDiv({ - cls: "claudian-slash-dropdown claudian-slash-dropdown-fixed" - }); - return dropdown; - } else { - return this.containerEl.createDiv({ cls: "claudian-slash-dropdown" }); - } - } - positionFixed() { - if (!this.dropdownEl || !this.isFixed) return; - const inputRect = this.inputEl.getBoundingClientRect(); - this.dropdownEl.style.position = "fixed"; - this.dropdownEl.style.bottom = `${window.innerHeight - inputRect.top + 4}px`; - this.dropdownEl.style.left = `${inputRect.left}px`; - this.dropdownEl.style.right = "auto"; - this.dropdownEl.style.width = `${Math.max(inputRect.width, 280)}px`; - this.dropdownEl.style.zIndex = "10001"; - } - navigate(direction) { - const maxIndex = this.filteredCommands.length - 1; - this.selectedIndex = Math.max(0, Math.min(maxIndex, this.selectedIndex + direction)); - this.updateSelection(); - } - updateSelection() { - var _a; - const items = (_a = this.dropdownEl) == null ? void 0 : _a.querySelectorAll(".claudian-slash-item"); - items == null ? void 0 : items.forEach((item, index) => { - if (index === this.selectedIndex) { - item.addClass("selected"); - item.scrollIntoView({ block: "nearest" }); - } else { - item.removeClass("selected"); - } - }); - } - selectItem() { - if (this.filteredCommands.length === 0) return; - const selected = this.filteredCommands[this.selectedIndex]; - if (!selected) return; - const text = this.getInputValue(); - const beforeSlash = text.substring(0, this.slashStartIndex); - const afterCursor = text.substring(this.getCursorPosition()); - const replacement = `/${selected.name} `; - this.setInputValue(beforeSlash + replacement + afterCursor); - this.setCursorPosition(beforeSlash.length + replacement.length); - this.hide(); - this.callbacks.onSelect(selected); - this.inputEl.focus(); - } -}; - -// src/ui/components/TodoPanel.ts -var import_obsidian8 = require("obsidian"); -var TodoPanel = class { +// src/features/chat/ui/StatusPanel.ts +var import_obsidian18 = require("obsidian"); +var TERMINAL_STATES = ["completed", "error", "orphaned"]; +var StatusPanel = class { constructor() { this.containerEl = null; this.panelEl = null; + // Async subagent section (above todos) + this.subagentContainerEl = null; + this.currentSubagents = /* @__PURE__ */ new Map(); + // Todo section this.todoContainerEl = null; this.todoHeaderEl = null; this.todoContentEl = null; - this.isExpanded = false; + this.isTodoExpanded = false; this.currentTodos = null; // Event handler references for cleanup - this.clickHandler = null; - this.keydownHandler = null; + this.todoClickHandler = null; + this.todoKeydownHandler = null; } /** * Mount the panel into the messages container. @@ -29709,50 +58287,70 @@ var TodoPanel = class { this.createPanel(); } /** - * Remount the panel after the container was cleared. - * Called when messagesEl.empty() removes the panel from DOM. + * Remount the panel to restore state after conversation changes. + * Re-creates the panel structure and re-renders current state. */ remount() { if (!this.containerEl) { - console.warn("[TodoPanel] Cannot remount - no containerEl set"); return; } + if (this.todoHeaderEl) { + if (this.todoClickHandler) { + this.todoHeaderEl.removeEventListener("click", this.todoClickHandler); + } + if (this.todoKeydownHandler) { + this.todoHeaderEl.removeEventListener("keydown", this.todoKeydownHandler); + } + } + this.todoClickHandler = null; + this.todoKeydownHandler = null; + if (this.panelEl) { + this.panelEl.remove(); + } this.panelEl = null; + this.subagentContainerEl = null; this.todoContainerEl = null; this.todoHeaderEl = null; this.todoContentEl = null; this.createPanel(); + this.renderSubagentStatus(); + if (this.currentTodos && this.currentTodos.length > 0) { + this.updateTodos(this.currentTodos); + } } /** * Create the panel structure. */ createPanel() { if (!this.containerEl) { - console.warn("[TodoPanel] Cannot create panel - containerEl not set. Was mount() called correctly?"); return; } this.panelEl = document.createElement("div"); - this.panelEl.className = "claudian-todo-panel"; + this.panelEl.className = "claudian-status-panel"; + this.subagentContainerEl = document.createElement("div"); + this.subagentContainerEl.className = "claudian-status-panel-subagents"; + this.subagentContainerEl.style.display = "none"; + this.panelEl.appendChild(this.subagentContainerEl); this.todoContainerEl = document.createElement("div"); - this.todoContainerEl.className = "claudian-todo-panel-todos"; + this.todoContainerEl.className = "claudian-status-panel-todos"; this.todoContainerEl.style.display = "none"; this.panelEl.appendChild(this.todoContainerEl); this.todoHeaderEl = document.createElement("div"); - this.todoHeaderEl.className = "claudian-todo-panel-header"; + this.todoHeaderEl.className = "claudian-status-panel-header"; this.todoHeaderEl.setAttribute("tabindex", "0"); this.todoHeaderEl.setAttribute("role", "button"); - this.clickHandler = () => this.toggle(); - this.keydownHandler = (e) => { - if (e.key === "Enter" || e.key === " ") { - e.preventDefault(); - this.toggle(); + this.todoClickHandler = () => this.toggleTodos(); + this.todoKeydownHandler = (e2) => { + if (e2.key === "Enter" || e2.key === " ") { + e2.preventDefault(); + this.toggleTodos(); } }; - this.todoHeaderEl.addEventListener("click", this.clickHandler); - this.todoHeaderEl.addEventListener("keydown", this.keydownHandler); + this.todoHeaderEl.addEventListener("click", this.todoClickHandler); + this.todoHeaderEl.addEventListener("keydown", this.todoKeydownHandler); this.todoContainerEl.appendChild(this.todoHeaderEl); this.todoContentEl = document.createElement("div"); - this.todoContentEl.className = "claudian-todo-panel-content"; + this.todoContentEl.className = "claudian-status-panel-content claudian-todo-list-container"; this.todoContentEl.style.display = "none"; this.todoContainerEl.appendChild(this.todoContentEl); this.containerEl.appendChild(this.panelEl); @@ -29764,9 +58362,6 @@ var TodoPanel = class { */ updateTodos(todos) { if (!this.todoContainerEl || !this.todoHeaderEl || !this.todoContentEl) { - if (todos && todos.length > 0) { - console.warn("[TodoPanel] Cannot update todos - component not mounted or destroyed"); - } return; } this.currentTodos = todos; @@ -29777,103 +58372,83 @@ var TodoPanel = class { return; } this.todoContainerEl.style.display = "block"; - const completedCount = todos.filter((t) => t.status === "completed").length; + const completedCount = todos.filter((t2) => t2.status === "completed").length; const totalCount = todos.length; - const currentTask = todos.find((t) => t.status === "in_progress"); - this.renderHeader(completedCount, totalCount, currentTask); - this.renderContent(todos); - this.updateAriaLabel(completedCount, totalCount); + const currentTask = todos.find((t2) => t2.status === "in_progress"); + this.renderTodoHeader(completedCount, totalCount, currentTask); + this.renderTodoContent(todos); + this.updateTodoAriaLabel(completedCount, totalCount); this.scrollToBottom(); } /** - * Render the collapsed header. + * Render the todo collapsed header. */ - renderHeader(completedCount, totalCount, currentTask) { + renderTodoHeader(completedCount, totalCount, currentTask) { if (!this.todoHeaderEl) return; this.todoHeaderEl.empty(); const icon = document.createElement("span"); - icon.className = "claudian-todo-panel-icon"; - (0, import_obsidian8.setIcon)(icon, "list-checks"); + icon.className = "claudian-status-panel-icon"; + (0, import_obsidian18.setIcon)(icon, getToolIcon(TOOL_TODO_WRITE)); this.todoHeaderEl.appendChild(icon); const label = document.createElement("span"); - label.className = "claudian-todo-panel-label"; + label.className = "claudian-status-panel-label"; label.textContent = `Tasks (${completedCount}/${totalCount})`; this.todoHeaderEl.appendChild(label); - if (!this.isExpanded && currentTask) { - const current = document.createElement("span"); - current.className = "claudian-todo-panel-current"; - current.textContent = currentTask.activeForm; - this.todoHeaderEl.appendChild(current); + if (!this.isTodoExpanded) { + if (completedCount === totalCount && totalCount > 0) { + const status = document.createElement("span"); + status.className = "claudian-status-panel-status status-completed"; + (0, import_obsidian18.setIcon)(status, "check"); + this.todoHeaderEl.appendChild(status); + } + if (currentTask) { + const current = document.createElement("span"); + current.className = "claudian-status-panel-current"; + current.textContent = currentTask.activeForm; + this.todoHeaderEl.appendChild(current); + } } } /** - * Render the expanded content. + * Render the expanded todo content. */ - renderContent(todos) { + renderTodoContent(todos) { if (!this.todoContentEl) return; - this.todoContentEl.empty(); - for (const todo of todos) { - const itemEl = document.createElement("div"); - itemEl.className = `claudian-todo-item claudian-todo-${todo.status}`; - const statusIcon = document.createElement("div"); - statusIcon.className = "claudian-todo-status-icon"; - statusIcon.setAttribute("aria-hidden", "true"); - (0, import_obsidian8.setIcon)(statusIcon, this.getStatusIcon(todo.status)); - itemEl.appendChild(statusIcon); - const text = document.createElement("div"); - text.className = "claudian-todo-text"; - text.textContent = todo.status === "in_progress" ? todo.activeForm : todo.content; - itemEl.appendChild(text); - this.todoContentEl.appendChild(itemEl); - } + renderTodoItems(this.todoContentEl, todos); } /** - * Get status icon name for a todo item. + * Toggle todo expanded/collapsed state. */ - getStatusIcon(status) { - switch (status) { - case "completed": - return "check-circle-2"; - case "in_progress": - return "circle-dot"; - case "pending": - default: - return "circle"; - } + toggleTodos() { + this.isTodoExpanded = !this.isTodoExpanded; + this.updateTodoDisplay(); } /** - * Toggle expanded/collapsed state. + * Update todo display based on expanded state. */ - toggle() { - this.isExpanded = !this.isExpanded; - this.updateDisplay(); - } - /** - * Update display based on expanded state. - */ - updateDisplay() { + updateTodoDisplay() { if (!this.todoContentEl || !this.todoHeaderEl) return; - this.todoContentEl.style.display = this.isExpanded ? "block" : "none"; + this.todoContentEl.style.display = this.isTodoExpanded ? "block" : "none"; if (this.currentTodos && this.currentTodos.length > 0) { - const completedCount = this.currentTodos.filter((t) => t.status === "completed").length; + const completedCount = this.currentTodos.filter((t2) => t2.status === "completed").length; const totalCount = this.currentTodos.length; - const currentTask = this.currentTodos.find((t) => t.status === "in_progress"); - this.renderHeader(completedCount, totalCount, currentTask); - this.updateAriaLabel(completedCount, totalCount); + const currentTask = this.currentTodos.find((t2) => t2.status === "in_progress"); + this.renderTodoHeader(completedCount, totalCount, currentTask); + this.updateTodoAriaLabel(completedCount, totalCount); } this.scrollToBottom(); } /** - * Update ARIA label. + * Update todo ARIA label. */ - updateAriaLabel(completedCount, totalCount) { + updateTodoAriaLabel(completedCount, totalCount) { if (!this.todoHeaderEl) return; - const action = this.isExpanded ? "Collapse" : "Expand"; + const action = this.isTodoExpanded ? "Collapse" : "Expand"; this.todoHeaderEl.setAttribute( "aria-label", `${action} task list - ${completedCount} of ${totalCount} completed` ); - this.todoHeaderEl.setAttribute("aria-expanded", String(this.isExpanded)); + this.todoHeaderEl.setAttribute("aria-expanded", String(this.isTodoExpanded)); } /** * Scroll messages container to bottom. @@ -29883,24 +58458,157 @@ var TodoPanel = class { this.containerEl.scrollTop = this.containerEl.scrollHeight; } } + // ============================================ + // Async Subagent Status Methods + // ============================================ + /** + * Add or update an async subagent in the panel. + */ + updateSubagent(info) { + this.currentSubagents.set(info.id, info); + this.renderSubagentStatus(); + } + /** + * Remove a subagent from the panel. + */ + removeSubagent(id) { + this.currentSubagents.delete(id); + this.renderSubagentStatus(); + } + /** + * Clear all subagents from the panel. + */ + clearSubagents() { + this.currentSubagents.clear(); + this.renderSubagentStatus(); + } + /** + * Clear completed/error/orphaned subagents from the panel. + * Called when user sends a new query - done entries are dismissed. + */ + clearTerminalSubagents() { + for (const [id, info] of this.currentSubagents) { + if (TERMINAL_STATES.includes(info.status)) { + this.currentSubagents.delete(id); + } + } + this.renderSubagentStatus(); + } + /** + * Check if all subagents completed successfully. + * Used for auto-hide on response completion. + * Returns false if empty or any subagent is pending, running, error, or orphaned. + */ + areAllSubagentsCompleted() { + if (this.currentSubagents.size === 0) return false; + for (const info of this.currentSubagents.values()) { + if (info.status !== "completed") { + return false; + } + } + return true; + } + /** + * Truncate description for display. + */ + truncateDescription(description, maxLength = 50) { + if (description.length <= maxLength) return description; + return description.substring(0, maxLength) + "..."; + } + /** + * Format running task count text. + */ + formatRunningCount(count) { + const taskWord = count === 1 ? "background task" : "background tasks"; + return `${count} ${taskWord}`; + } + /** + * Render the subagent status section. + * - Completed tasks: show ✓ + description for each + * - Running tasks: show "X background tasks" count + */ + renderSubagentStatus() { + if (!this.subagentContainerEl) return; + const runningSubagents = []; + const completedSubagents = []; + for (const info of this.currentSubagents.values()) { + switch (info.status) { + case "pending": + case "running": + runningSubagents.push(info); + break; + case "completed": + completedSubagents.push(info); + break; + } + } + if (runningSubagents.length === 0 && completedSubagents.length === 0) { + this.subagentContainerEl.style.display = "none"; + return; + } + this.subagentContainerEl.style.display = "block"; + this.subagentContainerEl.empty(); + const lastDoneIndex = completedSubagents.length - 1; + for (let i2 = 0; i2 < completedSubagents.length; i2++) { + const subagent = completedSubagents[i2]; + const isLastDone = i2 === lastDoneIndex; + const showRunningOnThisRow = isLastDone && runningSubagents.length > 0; + const rowEl = document.createElement("div"); + rowEl.className = showRunningOnThisRow ? "claudian-status-panel-done-row claudian-status-panel-combined-row" : "claudian-status-panel-done-row"; + const botIconEl = document.createElement("span"); + botIconEl.className = "claudian-status-panel-icon claudian-status-panel-bot-icon"; + (0, import_obsidian18.setIcon)(botIconEl, getToolIcon(TOOL_TASK)); + rowEl.appendChild(botIconEl); + const textEl = document.createElement("span"); + textEl.className = "claudian-status-panel-done-text"; + textEl.textContent = this.truncateDescription(subagent.description); + rowEl.appendChild(textEl); + const iconEl = document.createElement("span"); + iconEl.className = "claudian-status-panel-icon claudian-status-panel-done-icon"; + (0, import_obsidian18.setIcon)(iconEl, "check"); + rowEl.appendChild(iconEl); + if (showRunningOnThisRow) { + const runningEl = document.createElement("span"); + runningEl.className = "claudian-status-panel-running-text"; + runningEl.textContent = this.formatRunningCount(runningSubagents.length); + rowEl.appendChild(runningEl); + } + this.subagentContainerEl.appendChild(rowEl); + } + if (runningSubagents.length > 0 && completedSubagents.length === 0) { + const rowEl = document.createElement("div"); + rowEl.className = "claudian-status-panel-running-row"; + const textEl = document.createElement("span"); + textEl.className = "claudian-status-panel-running-text"; + textEl.textContent = this.formatRunningCount(runningSubagents.length); + rowEl.appendChild(textEl); + this.subagentContainerEl.appendChild(rowEl); + } + this.scrollToBottom(); + } + // ============================================ + // Cleanup + // ============================================ /** * Destroy the panel. */ destroy() { if (this.todoHeaderEl) { - if (this.clickHandler) { - this.todoHeaderEl.removeEventListener("click", this.clickHandler); + if (this.todoClickHandler) { + this.todoHeaderEl.removeEventListener("click", this.todoClickHandler); } - if (this.keydownHandler) { - this.todoHeaderEl.removeEventListener("keydown", this.keydownHandler); + if (this.todoKeydownHandler) { + this.todoHeaderEl.removeEventListener("keydown", this.todoKeydownHandler); } } - this.clickHandler = null; - this.keydownHandler = null; + this.todoClickHandler = null; + this.todoKeydownHandler = null; + this.currentSubagents.clear(); if (this.panelEl) { this.panelEl.remove(); this.panelEl = null; } + this.subagentContainerEl = null; this.todoContainerEl = null; this.todoHeaderEl = null; this.todoContentEl = null; @@ -29909,163 +58617,1493 @@ var TodoPanel = class { } }; -// src/ui/modals/ApprovalModal.ts -var import_obsidian9 = require("obsidian"); - -// src/core/tools/toolIcons.ts -var TOOL_ICONS = { - [TOOL_READ]: "file-text", - [TOOL_WRITE]: "edit-3", - [TOOL_EDIT]: "edit", - [TOOL_NOTEBOOK_EDIT]: "edit", - [TOOL_BASH]: "terminal", - [TOOL_BASH_OUTPUT]: "terminal", - [TOOL_KILL_SHELL]: "terminal", - [TOOL_GLOB]: "folder-search", - [TOOL_GREP]: "search", - [TOOL_LS]: "list", - [TOOL_TODO_WRITE]: "list-checks", - [TOOL_TASK]: "list-checks", - [TOOL_ASK_USER_QUESTION]: "help-circle", - [TOOL_LIST_MCP_RESOURCES]: "list", - [TOOL_READ_MCP_RESOURCE]: "file-text", - [TOOL_MCP]: "wrench", - [TOOL_WEB_SEARCH]: "globe", - [TOOL_WEB_FETCH]: "download", - [TOOL_AGENT_OUTPUT]: "bot", - [TOOL_SKILL]: "zap" -}; -var MCP_ICON_MARKER = "__mcp_icon__"; -function getToolIcon(toolName) { - if (toolName.startsWith("mcp__")) { - return MCP_ICON_MARKER; - } - return TOOL_ICONS[toolName] || "wrench"; +// src/features/chat/tabs/types.ts +var DEFAULT_MAX_TABS = 3; +var MIN_TABS = 3; +var MAX_TABS = 10; +var TEXTAREA_MIN_MAX_HEIGHT = 150; +var TEXTAREA_MAX_HEIGHT_PERCENT = 0.55; +function generateTabId() { + return `tab-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`; } -// src/ui/modals/ApprovalModal.ts -var ApprovalModal = class extends import_obsidian9.Modal { - constructor(app, toolName, _input, description, resolve7, options = {}) { - super(app); - this.resolved = false; - this.buttons = []; - this.currentButtonIndex = 0; - this.documentKeydownHandler = null; - this.toolName = toolName; - this.description = description; - this.resolve = resolve7; - this.options = options; +// src/features/chat/tabs/Tab.ts +function createTab(options) { + var _a3; + const { + containerEl, + conversation, + tabId, + onStreamingChanged, + onAttentionChanged, + onConversationIdChanged + } = options; + const id = tabId != null ? tabId : generateTabId(); + const contentEl = containerEl.createDiv({ cls: "claudian-tab-content" }); + contentEl.style.display = "none"; + const state = new ChatState({ + onStreamingStateChanged: (isStreaming) => { + onStreamingChanged == null ? void 0 : onStreamingChanged(isStreaming); + }, + onAttentionChanged: (needsAttention) => { + onAttentionChanged == null ? void 0 : onAttentionChanged(needsAttention); + }, + onConversationChanged: (conversationId) => { + onConversationIdChanged == null ? void 0 : onConversationIdChanged(conversationId); + } + }); + const subagentManager = new SubagentManager(() => { + }); + const dom = buildTabDOM(contentEl); + const tab = { + id, + conversationId: (_a3 = conversation == null ? void 0 : conversation.id) != null ? _a3 : null, + service: null, + serviceInitialized: false, + state, + controllers: { + selectionController: null, + conversationController: null, + streamController: null, + inputController: null, + navigationController: null + }, + services: { + subagentManager, + instructionRefineService: null, + titleGenerationService: null + }, + ui: { + fileContextManager: null, + imageContextManager: null, + modelSelector: null, + thinkingBudgetSelector: null, + externalContextSelector: null, + mcpServerSelector: null, + permissionToggle: null, + slashCommandDropdown: null, + instructionModeManager: null, + contextUsageMeter: null, + statusPanel: null + }, + dom, + renderer: null + }; + return tab; +} +function autoResizeTextarea(textarea) { + var _a3, _b; + textarea.style.minHeight = ""; + const viewHeight = (_b = (_a3 = textarea.closest(".claudian-container")) == null ? void 0 : _a3.clientHeight) != null ? _b : window.innerHeight; + const maxHeight = Math.max(TEXTAREA_MIN_MAX_HEIGHT, viewHeight * TEXTAREA_MAX_HEIGHT_PERCENT); + const flexAllocatedHeight = textarea.offsetHeight; + const contentHeight = Math.min(textarea.scrollHeight, maxHeight); + if (contentHeight > flexAllocatedHeight) { + textarea.style.minHeight = `${contentHeight}px`; } - onOpen() { - var _a, _b; - const { contentEl } = this; - contentEl.addClass("claudian-approval-modal"); - this.setTitle((_a = this.options.title) != null ? _a : "Permission required"); - const infoEl = contentEl.createDiv({ cls: "claudian-approval-info" }); - const toolEl = infoEl.createDiv({ cls: "claudian-approval-tool" }); - const iconEl = toolEl.createSpan({ cls: "claudian-approval-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian9.setIcon)(iconEl, getToolIcon(this.toolName)); - toolEl.createSpan({ text: this.toolName, cls: "claudian-approval-tool-name" }); - const descEl = contentEl.createDiv({ cls: "claudian-approval-desc" }); - descEl.setText(this.description); - const buttonsEl = contentEl.createDiv({ cls: "claudian-approval-buttons" }); - const denyBtn = buttonsEl.createEl("button", { - text: "Deny", - cls: "claudian-approval-btn claudian-deny-btn", - attr: { "aria-label": `Deny ${this.toolName} action` } + textarea.style.maxHeight = `${maxHeight}px`; +} +function buildTabDOM(contentEl) { + const messagesWrapperEl = contentEl.createDiv({ cls: "claudian-messages-wrapper" }); + const messagesEl = messagesWrapperEl.createDiv({ cls: "claudian-messages" }); + const welcomeEl = messagesEl.createDiv({ cls: "claudian-welcome" }); + const scrollToBottomEl = messagesWrapperEl.createEl("button", { + cls: "claudian-scroll-to-bottom", + attr: { + "aria-label": "Scroll to bottom", + type: "button" + } + }); + scrollToBottomEl.textContent = "Scroll to bottom"; + const statusPanelContainerEl = contentEl.createDiv({ cls: "claudian-status-panel-container" }); + const inputContainerEl = contentEl.createDiv({ cls: "claudian-input-container" }); + const navRowEl = inputContainerEl.createDiv({ cls: "claudian-input-nav-row" }); + const inputWrapper = inputContainerEl.createDiv({ cls: "claudian-input-wrapper" }); + const contextRowEl = inputWrapper.createDiv({ cls: "claudian-context-row" }); + const inputEl = inputWrapper.createEl("textarea", { + cls: "claudian-input", + attr: { + placeholder: "How can I help you today?", + rows: "3" + } + }); + return { + contentEl, + messagesEl, + welcomeEl, + statusPanelContainerEl, + inputContainerEl, + inputWrapper, + inputEl, + navRowEl, + contextRowEl, + selectionIndicatorEl: null, + scrollToBottomEl, + eventCleanups: [] + }; +} +async function initializeTabService(tab, plugin, mcpManager) { + var _a3; + if (tab.serviceInitialized) { + return; + } + let service = null; + let unsubscribeReadyState = null; + try { + service = new ClaudianService(plugin, mcpManager); + unsubscribeReadyState = service.onReadyStateChange((ready) => { + var _a4; + (_a4 = tab.ui.modelSelector) == null ? void 0 : _a4.setReady(ready); }); - denyBtn.addEventListener("click", () => this.handleDecision("deny")); - const allowBtn = buttonsEl.createEl("button", { - text: "Allow once", - cls: "claudian-approval-btn claudian-allow-btn", - attr: { "aria-label": `Allow ${this.toolName} action once` } + tab.dom.eventCleanups.push(() => unsubscribeReadyState == null ? void 0 : unsubscribeReadyState()); + let sessionId; + let externalContextPaths = plugin.settings.persistentExternalContextPaths || []; + if (tab.conversationId) { + const conversation = await plugin.getConversationById(tab.conversationId); + sessionId = (_a3 = conversation == null ? void 0 : conversation.sessionId) != null ? _a3 : void 0; + if (conversation) { + const hasMessages = conversation.messages.length > 0; + externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : plugin.settings.persistentExternalContextPaths || []; + } + } + service.ensureReady({ + sessionId, + externalContextPaths + }).catch(() => { }); - allowBtn.addEventListener("click", () => this.handleDecision("allow")); - let alwaysBtn = null; - if ((_b = this.options.showAlwaysAllow) != null ? _b : true) { - alwaysBtn = buttonsEl.createEl("button", { - text: "Always allow", - cls: "claudian-approval-btn claudian-always-btn", - attr: { "aria-label": `Always allow ${this.toolName} actions` } - }); - alwaysBtn.addEventListener("click", () => this.handleDecision("allow-always")); - } - this.buttons = [denyBtn, allowBtn]; - if (alwaysBtn) { - this.buttons.push(alwaysBtn); - } - this.currentButtonIndex = 0; - this.focusCurrentButton(); - this.attachDocumentHandler(); + tab.service = service; + tab.serviceInitialized = true; + } catch (error48) { + unsubscribeReadyState == null ? void 0 : unsubscribeReadyState(); + service == null ? void 0 : service.closePersistentQuery("initialization failed"); + tab.service = null; + tab.serviceInitialized = false; + throw error48; } - handleDecision(decision) { - if (!this.resolved) { - this.resolved = true; - this.resolve(decision); - this.close(); +} +function initializeContextManagers(tab, plugin) { + const { dom } = tab; + const app = plugin.app; + tab.ui.fileContextManager = new FileContextManager( + app, + dom.contextRowEl, + dom.inputEl, + { + getExcludedTags: () => plugin.settings.excludedTags, + onChipsChanged: () => { + var _a3, _b; + (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.updateContextRowVisibility(); + autoResizeTextarea(dom.inputEl); + (_b = tab.renderer) == null ? void 0 : _b.scrollToBottomIfNeeded(); + }, + getExternalContexts: () => { + var _a3; + return ((_a3 = tab.ui.externalContextSelector) == null ? void 0 : _a3.getExternalContexts()) || []; + } + }, + dom.inputContainerEl + ); + tab.ui.fileContextManager.setMcpManager(plugin.mcpManager); + tab.ui.fileContextManager.setAgentService(plugin.agentManager); + tab.ui.imageContextManager = new ImageContextManager( + dom.inputContainerEl, + dom.inputEl, + { + onImagesChanged: () => { + var _a3, _b; + (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.updateContextRowVisibility(); + autoResizeTextarea(dom.inputEl); + (_b = tab.renderer) == null ? void 0 : _b.scrollToBottomIfNeeded(); + } + }, + dom.contextRowEl + ); +} +function initializeSlashCommands(tab, getSdkCommands, getHiddenCommands) { + var _a3; + const { dom } = tab; + tab.ui.slashCommandDropdown = new SlashCommandDropdown( + dom.inputContainerEl, + dom.inputEl, + { + onSelect: () => { + }, + onHide: () => { + }, + getSdkCommands + }, + { + hiddenCommands: (_a3 = getHiddenCommands == null ? void 0 : getHiddenCommands()) != null ? _a3 : /* @__PURE__ */ new Set() + } + ); +} +function initializeInstructionAndTodo(tab, plugin) { + const { dom } = tab; + tab.services.instructionRefineService = new InstructionRefineService(plugin); + tab.services.titleGenerationService = new TitleGenerationService(plugin); + tab.ui.instructionModeManager = new InstructionModeManager( + dom.inputEl, + { + onSubmit: async (rawInstruction) => { + var _a3; + await ((_a3 = tab.controllers.inputController) == null ? void 0 : _a3.handleInstructionSubmit(rawInstruction)); + }, + getInputWrapper: () => dom.inputWrapper + } + ); + tab.ui.statusPanel = new StatusPanel(); + tab.ui.statusPanel.mount(dom.statusPanelContainerEl); +} +function initializeInputToolbar(tab, plugin) { + var _a3; + const { dom } = tab; + const inputToolbar = dom.inputWrapper.createDiv({ cls: "claudian-input-toolbar" }); + const toolbarComponents = createInputToolbar(inputToolbar, { + getSettings: () => ({ + model: plugin.settings.model, + thinkingBudget: plugin.settings.thinkingBudget, + permissionMode: plugin.settings.permissionMode, + show1MModel: plugin.settings.show1MModel + }), + getEnvironmentVariables: () => plugin.getActiveEnvironmentVariables(), + onModelChange: async (model) => { + var _a4, _b, _c; + plugin.settings.model = model; + const isDefaultModel = DEFAULT_CLAUDE_MODELS.find((m) => m.value === model); + if (isDefaultModel) { + plugin.settings.thinkingBudget = DEFAULT_THINKING_BUDGET[model]; + plugin.settings.lastClaudeModel = model; + } else { + plugin.settings.lastCustomModel = model; + } + await plugin.saveSettings(); + (_a4 = tab.ui.thinkingBudgetSelector) == null ? void 0 : _a4.updateDisplay(); + (_b = tab.ui.modelSelector) == null ? void 0 : _b.updateDisplay(); + (_c = tab.ui.modelSelector) == null ? void 0 : _c.renderOptions(); + const currentUsage = tab.state.usage; + if (currentUsage) { + const newContextWindow = getContextWindowSize(model, plugin.settings.show1MModel, plugin.settings.customContextLimits); + const newPercentage = Math.min(100, Math.max(0, Math.round(currentUsage.contextTokens / newContextWindow * 100))); + tab.state.usage = { + ...currentUsage, + model, + contextWindow: newContextWindow, + percentage: newPercentage + }; + } + }, + onThinkingBudgetChange: async (budget) => { + plugin.settings.thinkingBudget = budget; + await plugin.saveSettings(); + }, + onPermissionModeChange: async (mode) => { + plugin.settings.permissionMode = mode; + await plugin.saveSettings(); + } + }); + tab.ui.modelSelector = toolbarComponents.modelSelector; + tab.ui.thinkingBudgetSelector = toolbarComponents.thinkingBudgetSelector; + tab.ui.contextUsageMeter = toolbarComponents.contextUsageMeter; + tab.ui.externalContextSelector = toolbarComponents.externalContextSelector; + tab.ui.mcpServerSelector = toolbarComponents.mcpServerSelector; + tab.ui.permissionToggle = toolbarComponents.permissionToggle; + tab.ui.mcpServerSelector.setMcpManager(plugin.mcpManager); + (_a3 = tab.ui.fileContextManager) == null ? void 0 : _a3.setOnMcpMentionChange((servers) => { + var _a4; + (_a4 = tab.ui.mcpServerSelector) == null ? void 0 : _a4.addMentionedServers(servers); + }); + tab.ui.externalContextSelector.setOnChange(() => { + var _a4; + (_a4 = tab.ui.fileContextManager) == null ? void 0 : _a4.preScanExternalContexts(); + }); + tab.ui.externalContextSelector.setPersistentPaths( + plugin.settings.persistentExternalContextPaths || [] + ); + tab.ui.externalContextSelector.setOnPersistenceChange(async (paths) => { + plugin.settings.persistentExternalContextPaths = paths; + await plugin.saveSettings(); + }); +} +function initializeTabUI(tab, plugin, options = {}) { + const { dom, state } = tab; + initializeContextManagers(tab, plugin); + dom.selectionIndicatorEl = dom.contextRowEl.createDiv({ cls: "claudian-selection-indicator" }); + dom.selectionIndicatorEl.style.display = "none"; + initializeSlashCommands( + tab, + options.getSdkCommands, + () => new Set((plugin.settings.hiddenSlashCommands || []).map((c3) => c3.toLowerCase())) + ); + initializeInstructionAndTodo(tab, plugin); + initializeInputToolbar(tab, plugin); + const updateScrollToBottomVisibility = () => { + if (dom.scrollToBottomEl) { + const hasOverflow = dom.messagesEl.scrollHeight > dom.messagesEl.clientHeight; + const shouldShow = !state.autoScrollEnabled && hasOverflow; + dom.scrollToBottomEl.classList.toggle("visible", shouldShow); + } + }; + dom.updateScrollVisibility = updateScrollToBottomVisibility; + state.callbacks = { + ...state.callbacks, + onUsageChanged: (usage) => { + var _a3; + return (_a3 = tab.ui.contextUsageMeter) == null ? void 0 : _a3.update(usage); + }, + onTodosChanged: (todos) => { + var _a3; + return (_a3 = tab.ui.statusPanel) == null ? void 0 : _a3.updateTodos(todos); + }, + onAutoScrollChanged: () => updateScrollToBottomVisibility() + }; + const resizeObserver = new ResizeObserver(() => { + updateScrollToBottomVisibility(); + }); + resizeObserver.observe(dom.messagesEl); + dom.eventCleanups.push(() => resizeObserver.disconnect()); + updateScrollToBottomVisibility(); +} +function initializeTabControllers(tab, plugin, component, mcpManager) { + const { dom, state, services, ui } = tab; + tab.renderer = new MessageRenderer(plugin, component, dom.messagesEl); + tab.controllers.selectionController = new SelectionController( + plugin.app, + dom.selectionIndicatorEl, + dom.inputEl, + dom.contextRowEl, + () => autoResizeTextarea(dom.inputEl) + ); + tab.controllers.streamController = new StreamController({ + plugin, + state, + renderer: tab.renderer, + subagentManager: services.subagentManager, + getMessagesEl: () => dom.messagesEl, + getFileContextManager: () => ui.fileContextManager, + updateQueueIndicator: () => { + var _a3; + return (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.updateQueueIndicator(); + }, + getAgentService: () => tab.service + }); + services.subagentManager.setCallback( + (subagent) => { + var _a3; + (_a3 = tab.controllers.streamController) == null ? void 0 : _a3.onAsyncSubagentStateChange(subagent); + if (subagent.mode === "async" && ui.statusPanel) { + ui.statusPanel.updateSubagent({ + id: subagent.id, + description: subagent.description, + status: subagent.asyncStatus === "completed" ? "completed" : subagent.asyncStatus === "error" ? "error" : subagent.asyncStatus === "orphaned" ? "orphaned" : subagent.asyncStatus === "running" ? "running" : "pending", + prompt: subagent.prompt, + result: subagent.result + }); + } + } + ); + tab.controllers.conversationController = new ConversationController( + { + plugin, + state, + renderer: tab.renderer, + subagentManager: services.subagentManager, + getHistoryDropdown: () => null, + // Tab doesn't have its own history dropdown + getWelcomeEl: () => dom.welcomeEl, + setWelcomeEl: (el) => { + dom.welcomeEl = el; + }, + getMessagesEl: () => dom.messagesEl, + getInputEl: () => dom.inputEl, + getFileContextManager: () => ui.fileContextManager, + getImageContextManager: () => ui.imageContextManager, + getMcpServerSelector: () => ui.mcpServerSelector, + getExternalContextSelector: () => ui.externalContextSelector, + clearQueuedMessage: () => { + var _a3; + return (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.clearQueuedMessage(); + }, + getTitleGenerationService: () => services.titleGenerationService, + getStatusPanel: () => ui.statusPanel, + getAgentService: () => tab.service + // Use tab's service instead of plugin's + }, + {} + ); + const generateId = () => `msg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`; + tab.controllers.inputController = new InputController({ + plugin, + state, + renderer: tab.renderer, + streamController: tab.controllers.streamController, + selectionController: tab.controllers.selectionController, + conversationController: tab.controllers.conversationController, + getInputEl: () => dom.inputEl, + getWelcomeEl: () => dom.welcomeEl, + getMessagesEl: () => dom.messagesEl, + getFileContextManager: () => ui.fileContextManager, + getImageContextManager: () => ui.imageContextManager, + getMcpServerSelector: () => ui.mcpServerSelector, + getExternalContextSelector: () => ui.externalContextSelector, + getInstructionModeManager: () => ui.instructionModeManager, + getInstructionRefineService: () => services.instructionRefineService, + getTitleGenerationService: () => services.titleGenerationService, + getStatusPanel: () => ui.statusPanel, + generateId, + resetInputHeight: () => { + }, + // Override to use tab's service instead of plugin.agentService + getAgentService: () => tab.service, + getSubagentManager: () => services.subagentManager, + // Lazy initialization: ensure service is ready before first query + // initializeTabService() handles session ID resolution from tab.conversationId + ensureServiceInitialized: async () => { + if (tab.serviceInitialized) { + return true; + } + try { + await initializeTabService(tab, plugin, mcpManager); + setupApprovalCallback(tab); + return true; + } catch (e2) { + return false; + } + } + }); + tab.controllers.navigationController = new NavigationController({ + getMessagesEl: () => dom.messagesEl, + getInputEl: () => dom.inputEl, + getSettings: () => plugin.settings.keyboardNavigation, + isStreaming: () => state.isStreaming, + shouldSkipEscapeHandling: () => { + var _a3, _b, _c; + if ((_a3 = ui.instructionModeManager) == null ? void 0 : _a3.isActive()) return true; + if ((_b = ui.slashCommandDropdown) == null ? void 0 : _b.isVisible()) return true; + if ((_c = ui.fileContextManager) == null ? void 0 : _c.isMentionDropdownVisible()) return true; + return false; + } + }); + tab.controllers.navigationController.initialize(); +} +function wireTabInputEvents(tab, plugin) { + const { dom, ui, state, controllers } = tab; + const keydownHandler = (e2) => { + var _a3, _b, _c, _d, _e, _f; + if ((_a3 = ui.instructionModeManager) == null ? void 0 : _a3.handleTriggerKey(e2)) { + return; } - } - attachDocumentHandler() { - this.detachDocumentHandler(); - this.documentKeydownHandler = (e) => { - if (!this.isNavigationKey(e)) { - return; + if ((_b = ui.instructionModeManager) == null ? void 0 : _b.handleKeydown(e2)) { + return; + } + if ((_c = ui.slashCommandDropdown) == null ? void 0 : _c.handleKeydown(e2)) { + return; + } + if ((_d = ui.fileContextManager) == null ? void 0 : _d.handleMentionKeydown(e2)) { + return; + } + if (e2.key === "Escape" && !e2.isComposing && state.isStreaming) { + e2.preventDefault(); + (_e = controllers.inputController) == null ? void 0 : _e.cancelStreaming(); + return; + } + if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing) { + e2.preventDefault(); + void ((_f = controllers.inputController) == null ? void 0 : _f.sendMessage()); + } + }; + dom.inputEl.addEventListener("keydown", keydownHandler); + dom.eventCleanups.push(() => dom.inputEl.removeEventListener("keydown", keydownHandler)); + const inputHandler = () => { + var _a3, _b; + (_a3 = ui.fileContextManager) == null ? void 0 : _a3.handleInputChange(); + (_b = ui.instructionModeManager) == null ? void 0 : _b.handleInputChange(); + autoResizeTextarea(dom.inputEl); + }; + dom.inputEl.addEventListener("input", inputHandler); + dom.eventCleanups.push(() => dom.inputEl.removeEventListener("input", inputHandler)); + const focusHandler = () => { + var _a3; + (_a3 = controllers.selectionController) == null ? void 0 : _a3.showHighlight(); + }; + dom.inputEl.addEventListener("focus", focusHandler); + dom.eventCleanups.push(() => dom.inputEl.removeEventListener("focus", focusHandler)); + const SCROLL_THRESHOLD = 20; + const RE_ENABLE_DELAY = 150; + let reEnableTimeout = null; + const isAutoScrollAllowed = () => { + var _a3; + return (_a3 = plugin.settings.enableAutoScroll) != null ? _a3 : true; + }; + const scrollHandler = () => { + if (!isAutoScrollAllowed()) { + if (reEnableTimeout) { + clearTimeout(reEnableTimeout); + reEnableTimeout = null; + } + state.autoScrollEnabled = false; + return; + } + const { scrollTop, scrollHeight, clientHeight } = dom.messagesEl; + const isAtBottom = scrollHeight - scrollTop - clientHeight <= SCROLL_THRESHOLD; + if (!isAtBottom) { + if (reEnableTimeout) { + clearTimeout(reEnableTimeout); + reEnableTimeout = null; + } + state.autoScrollEnabled = false; + } else if (!state.autoScrollEnabled) { + if (!reEnableTimeout) { + reEnableTimeout = setTimeout(() => { + reEnableTimeout = null; + const { scrollTop: scrollTop2, scrollHeight: scrollHeight2, clientHeight: clientHeight2 } = dom.messagesEl; + if (scrollHeight2 - scrollTop2 - clientHeight2 <= SCROLL_THRESHOLD) { + state.autoScrollEnabled = true; + } + }, RE_ENABLE_DELAY); + } + } + }; + dom.messagesEl.addEventListener("scroll", scrollHandler, { passive: true }); + dom.eventCleanups.push(() => { + dom.messagesEl.removeEventListener("scroll", scrollHandler); + if (reEnableTimeout) clearTimeout(reEnableTimeout); + }); + if (dom.scrollToBottomEl) { + const scrollToBottomHandler = () => { + dom.messagesEl.scrollTop = dom.messagesEl.scrollHeight; + if (isAutoScrollAllowed()) { + state.autoScrollEnabled = true; } - e.preventDefault(); - e.stopPropagation(); - this.handleNavigationKey(e); }; - document.addEventListener("keydown", this.documentKeydownHandler, true); + dom.scrollToBottomEl.addEventListener("click", scrollToBottomHandler); + dom.eventCleanups.push(() => { + var _a3; + return (_a3 = dom.scrollToBottomEl) == null ? void 0 : _a3.removeEventListener("click", scrollToBottomHandler); + }); } - detachDocumentHandler() { - if (this.documentKeydownHandler) { - document.removeEventListener("keydown", this.documentKeydownHandler, true); - this.documentKeydownHandler = null; +} +function activateTab(tab) { + var _a3, _b, _c; + tab.dom.contentEl.style.display = "flex"; + (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.start(); + (_c = (_b = tab.dom).updateScrollVisibility) == null ? void 0 : _c.call(_b); +} +function deactivateTab(tab) { + var _a3; + tab.dom.contentEl.style.display = "none"; + (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.stop(); +} +async function destroyTab(tab) { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j; + (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.stop(); + (_b = tab.controllers.selectionController) == null ? void 0 : _b.clear(); + (_c = tab.controllers.navigationController) == null ? void 0 : _c.dispose(); + cleanupThinkingBlock(tab.state.currentThinkingState); + tab.state.currentThinkingState = null; + (_d = tab.ui.fileContextManager) == null ? void 0 : _d.destroy(); + (_e = tab.ui.slashCommandDropdown) == null ? void 0 : _e.destroy(); + tab.ui.slashCommandDropdown = null; + (_f = tab.ui.instructionModeManager) == null ? void 0 : _f.destroy(); + tab.ui.instructionModeManager = null; + (_g = tab.services.instructionRefineService) == null ? void 0 : _g.cancel(); + tab.services.instructionRefineService = null; + (_h = tab.services.titleGenerationService) == null ? void 0 : _h.cancel(); + tab.services.titleGenerationService = null; + (_i = tab.ui.statusPanel) == null ? void 0 : _i.destroy(); + tab.ui.statusPanel = null; + tab.services.subagentManager.orphanAllActive(); + tab.services.subagentManager.clear(); + for (const cleanup of tab.dom.eventCleanups) { + cleanup(); + } + tab.dom.eventCleanups.length = 0; + (_j = tab.service) == null ? void 0 : _j.closePersistentQuery("tab closed"); + tab.service = null; + tab.dom.contentEl.remove(); +} +function getTabTitle(tab, plugin) { + if (tab.conversationId) { + const conversation = plugin.getConversationSync(tab.conversationId); + if (conversation == null ? void 0 : conversation.title) { + return conversation.title; } } - isNavigationKey(e) { - return e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Tab"; + return "New Chat"; +} +function setupApprovalCallback(tab) { + if (tab.service && tab.controllers.inputController) { + tab.service.setApprovalCallback( + (toolName, input, description, options) => tab.controllers.inputController.handleApprovalRequest(toolName, input, description, options) + ); + tab.service.setApprovalDismisser( + () => { + var _a3; + return (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.dismissPendingApproval(); + } + ); } - handleNavigationKey(e) { - if (!this.buttons.length) return; - let direction = 0; - switch (e.key) { - case "ArrowUp": - case "ArrowLeft": - direction = -1; - break; - case "ArrowDown": - case "ArrowRight": - direction = 1; - break; - case "Tab": - direction = e.shiftKey ? -1 : 1; - break; - default: - return; +} + +// src/features/chat/tabs/TabBar.ts +var TabBar = class { + constructor(containerEl, callbacks) { + this.containerEl = containerEl; + this.callbacks = callbacks; + this.build(); + } + /** Builds the tab bar UI. */ + build() { + this.containerEl.addClass("claudian-tab-badges"); + } + /** + * Updates the tab bar with new tab data. + * @param items Tab items to render. + */ + update(items) { + this.containerEl.empty(); + for (const item of items) { + this.renderBadge(item); } - const total = this.buttons.length; - this.currentButtonIndex = (this.currentButtonIndex + direction + total) % total; - this.focusCurrentButton(); } - focusCurrentButton() { - const button = this.buttons[this.currentButtonIndex]; - button == null ? void 0 : button.focus(); - } - onClose() { - this.detachDocumentHandler(); - if (!this.resolved) { - this.resolved = true; - this.resolve("cancel"); + /** Renders a single tab badge. */ + renderBadge(item) { + let stateClass = "claudian-tab-badge-idle"; + if (item.isActive) { + stateClass = "claudian-tab-badge-active"; + } else if (item.needsAttention) { + stateClass = "claudian-tab-badge-attention"; + } else if (item.isStreaming) { + stateClass = "claudian-tab-badge-streaming"; } - this.contentEl.empty(); + const badgeEl = this.containerEl.createDiv({ + cls: `claudian-tab-badge ${stateClass}`, + text: String(item.index) + }); + badgeEl.setAttribute("aria-label", item.title); + badgeEl.setAttribute("title", item.title); + badgeEl.addEventListener("click", () => { + this.callbacks.onTabClick(item.id); + }); + if (item.canClose) { + badgeEl.addEventListener("contextmenu", (e2) => { + e2.preventDefault(); + this.callbacks.onTabClose(item.id); + }); + } + } + /** Destroys the tab bar. */ + destroy() { + this.containerEl.empty(); + this.containerEl.removeClass("claudian-tab-badges"); } }; -// src/ui/modals/InlineEditModal.ts -var import_obsidian10 = require("obsidian"); -var path11 = __toESM(require("path")); +// src/features/chat/tabs/TabManager.ts +var TabManager = class { + constructor(plugin, mcpManager, containerEl, view, callbacks = {}) { + this.tabs = /* @__PURE__ */ new Map(); + this.activeTabId = null; + /** Guard to prevent concurrent tab switches. */ + this.isSwitchingTab = false; + this.plugin = plugin; + this.mcpManager = mcpManager; + this.containerEl = containerEl; + this.view = view; + this.callbacks = callbacks; + } + /** + * Gets the current max tabs limit from settings. + * Clamps to MIN_TABS and MAX_TABS bounds. + */ + getMaxTabs() { + var _a3; + const settingsValue = (_a3 = this.plugin.settings.maxTabs) != null ? _a3 : DEFAULT_MAX_TABS; + return Math.max(MIN_TABS, Math.min(MAX_TABS, settingsValue)); + } + // ============================================ + // Tab Lifecycle + // ============================================ + /** + * Creates a new tab. + * @param conversationId Optional conversation to load into the tab. + * @param tabId Optional tab ID (for restoration). + * @returns The created tab, or null if max tabs reached. + */ + async createTab(conversationId, tabId) { + var _a3, _b; + const maxTabs = this.getMaxTabs(); + if (this.tabs.size >= maxTabs) { + return null; + } + const conversation = conversationId ? await this.plugin.getConversationById(conversationId) : void 0; + const tab = createTab({ + plugin: this.plugin, + mcpManager: this.mcpManager, + containerEl: this.containerEl, + conversation: conversation != null ? conversation : void 0, + tabId, + onStreamingChanged: (isStreaming) => { + var _a4, _b2; + (_b2 = (_a4 = this.callbacks).onTabStreamingChanged) == null ? void 0 : _b2.call(_a4, tab.id, isStreaming); + }, + onTitleChanged: (title) => { + var _a4, _b2; + (_b2 = (_a4 = this.callbacks).onTabTitleChanged) == null ? void 0 : _b2.call(_a4, tab.id, title); + }, + onAttentionChanged: (needsAttention) => { + var _a4, _b2; + (_b2 = (_a4 = this.callbacks).onTabAttentionChanged) == null ? void 0 : _b2.call(_a4, tab.id, needsAttention); + }, + onConversationIdChanged: (conversationId2) => { + var _a4, _b2; + tab.conversationId = conversationId2; + (_b2 = (_a4 = this.callbacks).onTabConversationChanged) == null ? void 0 : _b2.call(_a4, tab.id, conversationId2); + } + }); + initializeTabUI(tab, this.plugin, { + getSdkCommands: () => this.getSdkCommands() + }); + initializeTabControllers(tab, this.plugin, this.view, this.mcpManager); + wireTabInputEvents(tab, this.plugin); + this.tabs.set(tab.id, tab); + (_b = (_a3 = this.callbacks).onTabCreated) == null ? void 0 : _b.call(_a3, tab); + await this.switchToTab(tab.id); + return tab; + } + /** + * Switches to a different tab. + * @param tabId The tab to switch to. + */ + async switchToTab(tabId) { + var _a3, _b, _c, _d, _e; + const tab = this.tabs.get(tabId); + if (!tab) { + return; + } + if (this.isSwitchingTab) { + return; + } + this.isSwitchingTab = true; + const previousTabId = this.activeTabId; + try { + if (previousTabId && previousTabId !== tabId) { + const currentTab = this.tabs.get(previousTabId); + if (currentTab) { + deactivateTab(currentTab); + } + } + this.activeTabId = tabId; + activateTab(tab); + if (tab.conversationId && tab.state.messages.length === 0) { + await ((_a3 = tab.controllers.conversationController) == null ? void 0 : _a3.switchTo(tab.conversationId)); + } else if (tab.conversationId && tab.state.messages.length > 0 && tab.service) { + const conversation = await this.plugin.getConversationById(tab.conversationId); + if (conversation) { + const hasMessages = conversation.messages.length > 0; + const externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : this.plugin.settings.persistentExternalContextPaths || []; + tab.service.setSessionId((_b = conversation.sessionId) != null ? _b : null, externalContextPaths); + } + } else if (!tab.conversationId && tab.state.messages.length === 0) { + (_c = tab.controllers.conversationController) == null ? void 0 : _c.initializeWelcome(); + } + (_e = (_d = this.callbacks).onTabSwitched) == null ? void 0 : _e.call(_d, previousTabId, tabId); + } finally { + this.isSwitchingTab = false; + } + } + /** + * Closes a tab. + * @param tabId The tab to close. + * @param force If true, close even if streaming. + * @returns True if the tab was closed. + */ + async closeTab(tabId, force = false) { + var _a3, _b, _c; + const tab = this.tabs.get(tabId); + if (!tab) { + return false; + } + if (tab.state.isStreaming && !force) { + return false; + } + if (this.tabs.size === 1 && !tab.conversationId && tab.state.messages.length === 0) { + return false; + } + await ((_a3 = tab.controllers.conversationController) == null ? void 0 : _a3.save()); + const tabIdsBefore = Array.from(this.tabs.keys()); + const closingIndex = tabIdsBefore.indexOf(tabId); + await destroyTab(tab); + this.tabs.delete(tabId); + (_c = (_b = this.callbacks).onTabClosed) == null ? void 0 : _c.call(_b, tabId); + if (this.activeTabId === tabId) { + this.activeTabId = null; + if (this.tabs.size > 0) { + const fallbackTabId = closingIndex === 0 ? tabIdsBefore[1] : tabIdsBefore[closingIndex - 1]; + if (fallbackTabId && this.tabs.has(fallbackTabId)) { + await this.switchToTab(fallbackTabId); + if (this.tabs.size === 1) { + await this.initializeActiveTabService(); + } + } + } else { + await this.createTab(); + await this.initializeActiveTabService(); + } + } + return true; + } + // ============================================ + // Tab Queries + // ============================================ + /** Gets the currently active tab. */ + getActiveTab() { + var _a3; + return this.activeTabId ? (_a3 = this.tabs.get(this.activeTabId)) != null ? _a3 : null : null; + } + /** Gets the active tab ID. */ + getActiveTabId() { + return this.activeTabId; + } + /** Gets a tab by ID. */ + getTab(tabId) { + var _a3; + return (_a3 = this.tabs.get(tabId)) != null ? _a3 : null; + } + /** Gets all tabs. */ + getAllTabs() { + return Array.from(this.tabs.values()); + } + /** Gets the number of tabs. */ + getTabCount() { + return this.tabs.size; + } + /** Checks if more tabs can be created. */ + canCreateTab() { + return this.tabs.size < this.getMaxTabs(); + } + // ============================================ + // Tab Bar Data + // ============================================ + /** Gets data for rendering the tab bar. */ + getTabBarItems() { + const items = []; + let index = 1; + for (const tab of this.tabs.values()) { + items.push({ + id: tab.id, + index: index++, + title: getTabTitle(tab, this.plugin), + isActive: tab.id === this.activeTabId, + isStreaming: tab.state.isStreaming, + needsAttention: tab.state.needsAttention, + canClose: this.tabs.size > 1 || !tab.state.isStreaming + }); + } + return items; + } + // ============================================ + // Conversation Management + // ============================================ + /** + * Opens a conversation in a new tab or existing tab. + * @param conversationId The conversation to open. + * @param preferNewTab If true, prefer opening in a new tab. + */ + async openConversation(conversationId, preferNewTab = false) { + var _a3, _b; + for (const tab of this.tabs.values()) { + if (tab.conversationId === conversationId) { + await this.switchToTab(tab.id); + return; + } + } + const crossViewResult = this.plugin.findConversationAcrossViews(conversationId); + const isSameView = (crossViewResult == null ? void 0 : crossViewResult.view) === this.view; + if (crossViewResult && !isSameView) { + this.plugin.app.workspace.revealLeaf(crossViewResult.view.leaf); + await ((_a3 = crossViewResult.view.getTabManager()) == null ? void 0 : _a3.switchToTab(crossViewResult.tabId)); + return; + } + if (preferNewTab && this.canCreateTab()) { + await this.createTab(conversationId); + } else { + const activeTab = this.getActiveTab(); + if (activeTab) { + await ((_b = activeTab.controllers.conversationController) == null ? void 0 : _b.switchTo(conversationId)); + } + } + } + /** + * Creates a new conversation in the active tab. + */ + async createNewConversation() { + var _a3; + const activeTab = this.getActiveTab(); + if (activeTab) { + await ((_a3 = activeTab.controllers.conversationController) == null ? void 0 : _a3.createNew()); + activeTab.conversationId = activeTab.state.currentConversationId; + } + } + // ============================================ + // Persistence + // ============================================ + /** Gets the state to persist. */ + getPersistedState() { + const openTabs = []; + for (const tab of this.tabs.values()) { + openTabs.push({ + tabId: tab.id, + conversationId: tab.conversationId + }); + } + return { + openTabs, + activeTabId: this.activeTabId + }; + } + /** Restores state from persisted data. */ + async restoreState(state) { + for (const tabState of state.openTabs) { + try { + await this.createTab(tabState.conversationId, tabState.tabId); + } catch (e2) { + } + } + if (state.activeTabId && this.tabs.has(state.activeTabId)) { + try { + await this.switchToTab(state.activeTabId); + } catch (e2) { + } + } + if (this.tabs.size === 0) { + await this.createTab(); + } + await this.initializeActiveTabService(); + } + /** + * Initializes the active tab's service if not already done. + * Called after restore to ensure the visible tab is ready immediately. + */ + async initializeActiveTabService() { + const activeTab = this.getActiveTab(); + if (!activeTab || activeTab.serviceInitialized) { + return; + } + try { + await initializeTabService(activeTab, this.plugin, this.mcpManager); + setupApprovalCallback(activeTab); + } catch (e2) { + } + } + // ============================================ + // SDK Commands (Shared) + // ============================================ + /** + * Gets SDK supported commands from any ready service. + * The command list is the same for all tabs, so we just need one ready service. + * @returns Array of SDK commands, or empty array if no service is ready. + */ + async getSdkCommands() { + var _a3; + for (const tab of this.tabs.values()) { + if ((_a3 = tab.service) == null ? void 0 : _a3.isReady()) { + return tab.service.getSupportedCommands(); + } + } + return []; + } + // ============================================ + // Broadcast + // ============================================ + /** + * Broadcasts a function call to all tabs' ClaudianService instances. + * Used by settings managers to apply configuration changes to all tabs. + * @param fn Function to call on each service. + */ + async broadcastToAllTabs(fn) { + const promises = []; + for (const tab of this.tabs.values()) { + if (tab.service && tab.serviceInitialized) { + promises.push( + fn(tab.service).catch(() => { + }) + ); + } + } + await Promise.all(promises); + } + // ============================================ + // Cleanup + // ============================================ + /** Destroys all tabs and cleans up resources. */ + async destroy() { + var _a3; + for (const tab of this.tabs.values()) { + await ((_a3 = tab.controllers.conversationController) == null ? void 0 : _a3.save()); + } + for (const tab of this.tabs.values()) { + await destroyTab(tab); + } + this.tabs.clear(); + this.activeTabId = null; + } +}; + +// src/features/chat/ClaudianView.ts +var ClaudianView = class extends import_obsidian19.ItemView { + constructor(leaf, plugin) { + super(leaf); + // Tab management + this.tabManager = null; + this.tabBar = null; + this.tabBarContainerEl = null; + this.tabContentEl = null; + this.navRowContent = null; + // DOM Elements + this.viewContainerEl = null; + this.headerEl = null; + this.titleSlotEl = null; + this.logoEl = null; + this.titleTextEl = null; + this.headerActionsEl = null; + this.headerActionsContent = null; + // Header elements + this.historyDropdown = null; + // Event refs for cleanup + this.eventRefs = []; + // Debouncing for tab bar updates + this.pendingTabBarUpdate = null; + // Debouncing for tab state persistence + this.pendingPersist = null; + this.plugin = plugin; + const originalLoad = Object.getPrototypeOf(this).load.bind(this); + Object.defineProperty(this, "load", { + value: async () => { + if (!this.containerEl) { + this.containerEl = createDiv({ cls: "view-content" }); + } + try { + return await originalLoad(); + } catch (e2) { + } + }, + writable: false, + configurable: false + }); + } + getViewType() { + return VIEW_TYPE_CLAUDIAN; + } + getDisplayText() { + return "Claudian"; + } + getIcon() { + return "bot"; + } + /** Refreshes the model selector display (used after env var changes). */ + refreshModelSelector() { + var _a3, _b, _c; + const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab(); + (_b = activeTab == null ? void 0 : activeTab.ui.modelSelector) == null ? void 0 : _b.updateDisplay(); + (_c = activeTab == null ? void 0 : activeTab.ui.modelSelector) == null ? void 0 : _c.renderOptions(); + } + /** Updates hidden slash commands on all tabs (used after settings change). */ + updateHiddenSlashCommands() { + var _a3, _b, _c; + const hiddenCommands = new Set( + (this.plugin.settings.hiddenSlashCommands || []).map((c3) => c3.toLowerCase()) + ); + for (const tab of (_b = (_a3 = this.tabManager) == null ? void 0 : _a3.getAllTabs()) != null ? _b : []) { + (_c = tab.ui.slashCommandDropdown) == null ? void 0 : _c.setHiddenCommands(hiddenCommands); + } + } + async onOpen() { + var _a3; + if (!this.containerEl) { + return; + } + let container = (_a3 = this.contentEl) != null ? _a3 : this.containerEl.children[1]; + if (!container) { + container = this.containerEl.createDiv(); + } + this.viewContainerEl = container; + this.viewContainerEl.empty(); + this.viewContainerEl.addClass("claudian-container"); + const header = this.viewContainerEl.createDiv({ cls: "claudian-header" }); + this.buildHeader(header); + this.navRowContent = this.buildNavRowContent(); + this.tabContentEl = this.viewContainerEl.createDiv({ cls: "claudian-tab-content-container" }); + this.tabManager = new TabManager( + this.plugin, + this.plugin.mcpManager, + this.tabContentEl, + this, + { + onTabCreated: () => { + this.updateTabBar(); + this.updateNavRowLocation(); + this.persistTabState(); + }, + onTabSwitched: () => { + this.updateTabBar(); + this.updateHistoryDropdown(); + this.updateNavRowLocation(); + this.persistTabState(); + }, + onTabClosed: () => { + this.updateTabBar(); + this.persistTabState(); + }, + onTabStreamingChanged: () => this.updateTabBar(), + onTabTitleChanged: () => this.updateTabBar(), + onTabAttentionChanged: () => this.updateTabBar(), + onTabConversationChanged: () => { + this.persistTabState(); + } + } + ); + this.wireEventHandlers(); + await this.restoreOrCreateTabs(); + this.updateLayoutForPosition(); + } + async onClose() { + var _a3, _b; + if (this.pendingTabBarUpdate !== null) { + cancelAnimationFrame(this.pendingTabBarUpdate); + this.pendingTabBarUpdate = null; + } + for (const ref of this.eventRefs) { + this.plugin.app.vault.offref(ref); + } + this.eventRefs = []; + await this.persistTabStateImmediate(); + await ((_a3 = this.tabManager) == null ? void 0 : _a3.destroy()); + this.tabManager = null; + (_b = this.tabBar) == null ? void 0 : _b.destroy(); + this.tabBar = null; + } + // ============================================ + // UI Building + // ============================================ + buildHeader(header) { + this.headerEl = header; + this.titleSlotEl = header.createDiv({ cls: "claudian-title-slot" }); + this.logoEl = this.titleSlotEl.createSpan({ cls: "claudian-logo" }); + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("viewBox", LOGO_SVG.viewBox); + svg.setAttribute("width", LOGO_SVG.width); + svg.setAttribute("height", LOGO_SVG.height); + svg.setAttribute("fill", "none"); + const path10 = document.createElementNS("http://www.w3.org/2000/svg", "path"); + path10.setAttribute("d", LOGO_SVG.path); + path10.setAttribute("fill", LOGO_SVG.fill); + svg.appendChild(path10); + this.logoEl.appendChild(svg); + this.titleTextEl = this.titleSlotEl.createEl("h4", { text: "Claudian", cls: "claudian-title-text" }); + this.headerActionsEl = header.createDiv({ cls: "claudian-header-actions claudian-header-actions-slot" }); + this.headerActionsEl.style.display = "none"; + } + /** + * Builds the nav row content (tab badges + header actions). + * This is called once and the content is moved between locations. + */ + buildNavRowContent() { + const fragment = document.createDocumentFragment(); + this.tabBarContainerEl = document.createElement("div"); + this.tabBarContainerEl.className = "claudian-tab-bar-container"; + this.tabBar = new TabBar(this.tabBarContainerEl, { + onTabClick: (tabId) => this.handleTabClick(tabId), + onTabClose: (tabId) => this.handleTabClose(tabId), + onNewTab: () => this.handleNewTab() + }); + fragment.appendChild(this.tabBarContainerEl); + this.headerActionsContent = document.createElement("div"); + this.headerActionsContent.className = "claudian-header-actions"; + const newTabBtn = this.headerActionsContent.createDiv({ cls: "claudian-header-btn claudian-new-tab-btn" }); + (0, import_obsidian19.setIcon)(newTabBtn, "square-plus"); + newTabBtn.setAttribute("aria-label", "New tab"); + newTabBtn.addEventListener("click", async () => { + await this.handleNewTab(); + }); + const newBtn = this.headerActionsContent.createDiv({ cls: "claudian-header-btn" }); + (0, import_obsidian19.setIcon)(newBtn, "square-pen"); + newBtn.setAttribute("aria-label", "New conversation"); + newBtn.addEventListener("click", async () => { + var _a3; + await ((_a3 = this.tabManager) == null ? void 0 : _a3.createNewConversation()); + this.updateHistoryDropdown(); + }); + const historyContainer = this.headerActionsContent.createDiv({ cls: "claudian-history-container" }); + const historyBtn = historyContainer.createDiv({ cls: "claudian-header-btn" }); + (0, import_obsidian19.setIcon)(historyBtn, "history"); + historyBtn.setAttribute("aria-label", "Chat history"); + this.historyDropdown = historyContainer.createDiv({ cls: "claudian-history-menu" }); + historyBtn.addEventListener("click", (e2) => { + e2.stopPropagation(); + this.toggleHistoryDropdown(); + }); + fragment.appendChild(this.headerActionsContent); + const wrapper = document.createElement("div"); + wrapper.style.display = "contents"; + wrapper.appendChild(fragment); + return wrapper; + } + /** + * Moves nav row content based on tabBarPosition setting. + * - 'input' mode: Both tab badges and actions go to active tab's navRowEl + * - 'header' mode: Tab badges go to title slot (after logo), actions go to header right side + */ + updateNavRowLocation() { + var _a3; + if (!this.tabBarContainerEl || !this.headerActionsContent) return; + const isHeaderMode = this.plugin.settings.tabBarPosition === "header"; + if (isHeaderMode) { + if (this.titleSlotEl) { + this.titleSlotEl.appendChild(this.tabBarContainerEl); + } + if (this.headerActionsEl) { + this.headerActionsEl.appendChild(this.headerActionsContent); + this.headerActionsEl.style.display = "flex"; + } + } else { + const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab(); + if (activeTab && this.navRowContent) { + this.navRowContent.appendChild(this.tabBarContainerEl); + this.navRowContent.appendChild(this.headerActionsContent); + activeTab.dom.navRowEl.appendChild(this.navRowContent); + } + if (this.headerActionsEl) { + this.headerActionsEl.style.display = "none"; + } + } + } + /** + * Updates layout when tabBarPosition setting changes. + * Called from settings when user changes the tab bar position. + */ + updateLayoutForPosition() { + if (!this.viewContainerEl) return; + const isHeaderMode = this.plugin.settings.tabBarPosition === "header"; + this.viewContainerEl.toggleClass("claudian-container--header-mode", isHeaderMode); + this.updateNavRowLocation(); + this.updateTabBarVisibility(); + } + // ============================================ + // Tab Management + // ============================================ + handleTabClick(tabId) { + var _a3; + (_a3 = this.tabManager) == null ? void 0 : _a3.switchToTab(tabId); + } + async handleTabClose(tabId) { + var _a3, _b, _c; + const tab = (_a3 = this.tabManager) == null ? void 0 : _a3.getTab(tabId); + const force = (_b = tab == null ? void 0 : tab.state.isStreaming) != null ? _b : false; + await ((_c = this.tabManager) == null ? void 0 : _c.closeTab(tabId, force)); + this.updateTabBarVisibility(); + } + async handleNewTab() { + var _a3, _b; + const tab = await ((_a3 = this.tabManager) == null ? void 0 : _a3.createTab()); + if (!tab) { + const maxTabs = (_b = this.plugin.settings.maxTabs) != null ? _b : 3; + new import_obsidian19.Notice(`Maximum ${maxTabs} tabs allowed`); + return; + } + this.updateTabBarVisibility(); + } + updateTabBar() { + if (!this.tabManager || !this.tabBar) return; + if (this.pendingTabBarUpdate !== null) { + cancelAnimationFrame(this.pendingTabBarUpdate); + } + this.pendingTabBarUpdate = requestAnimationFrame(() => { + this.pendingTabBarUpdate = null; + if (!this.tabManager || !this.tabBar) return; + const items = this.tabManager.getTabBarItems(); + this.tabBar.update(items); + this.updateTabBarVisibility(); + }); + } + updateTabBarVisibility() { + if (!this.tabBarContainerEl || !this.tabManager) return; + const tabCount = this.tabManager.getTabCount(); + const showTabBar = tabCount >= 2; + const isHeaderMode = this.plugin.settings.tabBarPosition === "header"; + this.tabBarContainerEl.style.display = showTabBar ? "flex" : "none"; + const hideBranding = showTabBar && isHeaderMode; + if (this.logoEl) { + this.logoEl.style.display = hideBranding ? "none" : ""; + } + if (this.titleTextEl) { + this.titleTextEl.style.display = hideBranding ? "none" : ""; + } + } + // ============================================ + // History Dropdown + // ============================================ + toggleHistoryDropdown() { + if (!this.historyDropdown) return; + const isVisible = this.historyDropdown.hasClass("visible"); + if (isVisible) { + this.historyDropdown.removeClass("visible"); + } else { + this.updateHistoryDropdown(); + this.historyDropdown.addClass("visible"); + } + } + updateHistoryDropdown() { + var _a3; + if (!this.historyDropdown) return; + this.historyDropdown.empty(); + const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab(); + const conversationController = activeTab == null ? void 0 : activeTab.controllers.conversationController; + if (conversationController) { + conversationController.renderHistoryDropdown(this.historyDropdown, { + onSelectConversation: async (conversationId) => { + var _a4, _b, _c, _d, _e, _f; + const existingTab = this.findTabWithConversation(conversationId); + if (existingTab) { + await ((_a4 = this.tabManager) == null ? void 0 : _a4.switchToTab(existingTab.id)); + (_b = this.historyDropdown) == null ? void 0 : _b.removeClass("visible"); + return; + } + const crossViewResult = this.plugin.findConversationAcrossViews(conversationId); + if (crossViewResult && crossViewResult.view !== this) { + this.plugin.app.workspace.revealLeaf(crossViewResult.view.leaf); + await ((_c = crossViewResult.view.getTabManager()) == null ? void 0 : _c.switchToTab(crossViewResult.tabId)); + (_d = this.historyDropdown) == null ? void 0 : _d.removeClass("visible"); + return; + } + await ((_e = this.tabManager) == null ? void 0 : _e.openConversation(conversationId)); + (_f = this.historyDropdown) == null ? void 0 : _f.removeClass("visible"); + } + }); + } + } + findTabWithConversation(conversationId) { + var _a3, _b, _c; + const tabs = (_b = (_a3 = this.tabManager) == null ? void 0 : _a3.getAllTabs()) != null ? _b : []; + return (_c = tabs.find((tab) => tab.conversationId === conversationId)) != null ? _c : null; + } + // ============================================ + // Event Wiring + // ============================================ + wireEventHandlers() { + this.registerDomEvent(document, "click", () => { + var _a3; + (_a3 = this.historyDropdown) == null ? void 0 : _a3.removeClass("visible"); + }); + this.registerDomEvent(document, "keydown", (e2) => { + var _a3, _b; + if (e2.key === "Escape" && !e2.isComposing) { + const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab(); + if (activeTab == null ? void 0 : activeTab.state.isStreaming) { + e2.preventDefault(); + (_b = activeTab.controllers.inputController) == null ? void 0 : _b.cancelStreaming(); + } + } + }); + const markDirty = () => { + var _a3, _b, _c; + (_c = (_b = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab()) == null ? void 0 : _b.ui.fileContextManager) == null ? void 0 : _c.markFilesCacheDirty(); + }; + this.eventRefs.push( + this.plugin.app.vault.on("create", markDirty), + this.plugin.app.vault.on("delete", markDirty), + this.plugin.app.vault.on("rename", markDirty), + this.plugin.app.vault.on("modify", markDirty) + ); + this.registerEvent( + this.plugin.app.workspace.on("file-open", (file2) => { + var _a3, _b, _c; + if (file2) { + (_c = (_b = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab()) == null ? void 0 : _b.ui.fileContextManager) == null ? void 0 : _c.handleFileOpen(file2); + } + }) + ); + this.registerDomEvent(document, "click", (e2) => { + var _a3; + const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab(); + if (activeTab) { + const fcm = activeTab.ui.fileContextManager; + if (fcm && !fcm.containsElement(e2.target) && e2.target !== activeTab.dom.inputEl) { + fcm.hideMentionDropdown(); + } + } + }); + } + // ============================================ + // Persistence + // ============================================ + async restoreOrCreateTabs() { + if (!this.tabManager) return; + const persistedState = await this.plugin.storage.getTabManagerState(); + if (persistedState && persistedState.openTabs.length > 0) { + await this.tabManager.restoreState(persistedState); + await this.plugin.storage.clearLegacyActiveConversationId(); + return; + } + const legacyActiveId = await this.plugin.storage.getLegacyActiveConversationId(); + if (legacyActiveId) { + const conversation = await this.plugin.getConversationById(legacyActiveId); + if (conversation) { + await this.tabManager.createTab(conversation.id); + } else { + await this.tabManager.createTab(); + } + await this.plugin.storage.clearLegacyActiveConversationId(); + return; + } + await this.tabManager.createTab(); + await this.plugin.storage.clearLegacyActiveConversationId(); + } + persistTabState() { + if (this.pendingPersist !== null) { + clearTimeout(this.pendingPersist); + } + this.pendingPersist = setTimeout(() => { + this.pendingPersist = null; + if (!this.tabManager) return; + const state = this.tabManager.getPersistedState(); + this.plugin.storage.setTabManagerState(state).catch(() => { + }); + }, 300); + } + /** Force immediate persistence (for onClose/onunload). */ + async persistTabStateImmediate() { + if (this.pendingPersist !== null) { + clearTimeout(this.pendingPersist); + this.pendingPersist = null; + } + if (!this.tabManager) return; + const state = this.tabManager.getPersistedState(); + await this.plugin.storage.setTabManagerState(state); + } + // ============================================ + // Public API + // ============================================ + /** Gets the currently active tab. */ + getActiveTab() { + var _a3, _b; + return (_b = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab()) != null ? _b : null; + } + /** Gets the tab manager. */ + getTabManager() { + return this.tabManager; + } +}; + +// src/features/inline-edit/ui/InlineEditModal.ts +var import_obsidian20 = require("obsidian"); + +// src/utils/inlineEdit.ts +function normalizeInsertionText(text) { + return text.replace(/^(?:\r?\n)+|(?:\r?\n)+$/g, ""); +} +function escapeHtml2(text) { + return text.replace(//g, ">"); +} // src/core/prompts/inlineEdit.ts function getInlineEditSystemPrompt() { @@ -30082,28 +60120,30 @@ You are **Claudian**, an expert editor and writing assistant embedded in Obsidia ## Input Format -User messages use XML tags: +User messages have the instruction first, followed by XML context tags: ### Selection Mode -\`\`\`xml +\`\`\` +user's instruction + selected text here - - -user's instruction - \`\`\` Use \`\` tags for edits. ### Cursor Mode -\`\`\`xml +\`\`\` +user's instruction + text before|text after #inline \`\`\` Or between paragraphs: -\`\`\`xml +\`\`\` +user's instruction + Previous paragraph | #inbetween @@ -30168,28 +60208,24 @@ If the request is ambiguous, ask a clarifying question. Keep questions concise a ### Selection Mode Input: -\`\`\`xml +\`\`\` +translate to French + Hello world - - -translate to French - \`\`\` CORRECT (replacement): Bonjour le monde Input: -\`\`\`xml +\`\`\` +what does this do? + const x = arr.reduce((a, b) => a + b, 0); - - -what does this do? - \`\`\` CORRECT (question - no tags): @@ -30198,14 +60234,12 @@ This code sums all numbers in the array \`arr\`. It uses \`reduce\` to iterate t ### Cursor Mode Input: -\`\`\`xml +\`\`\` +what animal? + The quick brown | jumps over the lazy dog. #inline - - -what animal? - \`\`\` CORRECT (insertion): @@ -30213,17 +60247,15 @@ CORRECT (insertion): ### Q&A Input: -\`\`\`xml +\`\`\` +add a brief description section + # Introduction This is my project. | #inbetween ## Features - - -add a brief description section - \`\`\` CORRECT (insertion): @@ -30234,14 +60266,12 @@ This project provides tools for managing your notes efficiently. Input: -\`\`\`xml +\`\`\` +translate to Spanish + The bank was steep. - - -translate to Spanish - \`\`\` CORRECT (asking for clarification): @@ -30252,70 +60282,211 @@ Then after user clarifies "river bank": } // src/features/inline-edit/InlineEditService.ts +function parseInlineEditResponse(responseText) { + const replacementMatch = responseText.match(/([\s\S]*?)<\/replacement>/); + if (replacementMatch) { + return { success: true, editedText: replacementMatch[1] }; + } + const insertionMatch = responseText.match(/([\s\S]*?)<\/insertion>/); + if (insertionMatch) { + return { success: true, insertedText: insertionMatch[1] }; + } + const trimmed = responseText.trim(); + if (trimmed) { + return { success: true, clarification: trimmed }; + } + return { success: false, error: "Empty response" }; +} +function buildCursorPrompt(request) { + const ctx = request.cursorContext; + const lineAttr = ` line="${ctx.line + 1}"`; + let cursorContent; + if (ctx.isInbetween) { + const parts = []; + if (ctx.beforeCursor) parts.push(ctx.beforeCursor); + parts.push("| #inbetween"); + if (ctx.afterCursor) parts.push(ctx.afterCursor); + cursorContent = parts.join("\n"); + } else { + cursorContent = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`; + } + return [ + request.instruction, + "", + ``, + cursorContent, + "" + ].join("\n"); +} +function buildInlineEditPrompt(request) { + let prompt; + if (request.mode === "cursor") { + prompt = buildCursorPrompt(request); + } else { + const lineAttr = request.startLine && request.lineCount ? ` lines="${request.startLine}-${request.startLine + request.lineCount - 1}"` : ""; + prompt = [ + request.instruction, + "", + ``, + request.selectedText, + "" + ].join("\n"); + } + if (request.contextFiles && request.contextFiles.length > 0) { + prompt = appendContextFiles(prompt, request.contextFiles); + } + return prompt; +} +function createReadOnlyHook() { + return { + hooks: [ + async (hookInput) => { + const input = hookInput; + const toolName = input.tool_name; + if (isReadOnlyTool(toolName)) { + return { continue: true }; + } + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `Inline edit mode: tool "${toolName}" is not allowed (read-only)` + } + }; + } + ] + }; +} +function createVaultRestrictionHook2(vaultPath) { + const fileTools = [TOOL_READ, TOOL_GLOB, TOOL_GREP, TOOL_LS]; + return { + hooks: [ + async (hookInput) => { + const input = hookInput; + const toolName = input.tool_name; + if (!fileTools.includes(toolName)) { + return { continue: true }; + } + const filePath = getPathFromToolInput(toolName, input.tool_input); + if (!filePath) { + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `Access denied: Could not determine path for "${toolName}" tool.` + } + }; + } + let accessType; + try { + accessType = getPathAccessType(filePath, void 0, void 0, vaultPath); + } catch (e2) { + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `Access denied: Failed to validate path "${filePath}".` + } + }; + } + if (accessType === "vault" || accessType === "context" || accessType === "readwrite") { + return { continue: true }; + } + return { + continue: false, + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `Access denied: Path "${filePath}" is outside allowed paths. Inline edit is restricted to vault and ~/.claude/ directories.` + } + }; + } + ] + }; +} +function extractTextFromSdkMessage(message) { + var _a3, _b, _c; + if (message.type === "assistant" && ((_a3 = message.message) == null ? void 0 : _a3.content)) { + for (const block of message.message.content) { + if (block.type === "text" && block.text) { + return block.text; + } + } + } + if (message.type === "stream_event") { + const event = message.event; + if ((event == null ? void 0 : event.type) === "content_block_start" && ((_b = event.content_block) == null ? void 0 : _b.type) === "text") { + return event.content_block.text || null; + } + if ((event == null ? void 0 : event.type) === "content_block_delta" && ((_c = event.delta) == null ? void 0 : _c.type) === "text_delta") { + return event.delta.text || null; + } + } + return null; +} var InlineEditService = class { constructor(plugin) { this.abortController = null; - this.resolvedClaudePath = null; this.sessionId = null; this.plugin = plugin; } - /** Resets conversation state for a new edit session. */ resetConversation() { this.sessionId = null; } - findClaudeCLI() { - return findClaudeCLIPath(); - } - /** Edits text according to instructions (initial request). */ async editText(request) { this.sessionId = null; - const prompt = await this.buildPrompt(request); + const prompt = buildInlineEditPrompt(request); return this.sendMessage(prompt); } - /** Continues conversation with a follow-up message. */ async continueConversation(message, contextFiles) { if (!this.sessionId) { return { success: false, error: "No active conversation to continue" }; } let prompt = message; if (contextFiles && contextFiles.length > 0) { - const vaultPath = getVaultPath(this.plugin.app); - prompt = await prependContextFiles(message, contextFiles, vaultPath); + prompt = appendContextFiles(message, contextFiles); } return this.sendMessage(prompt); } async sendMessage(prompt) { - var _a; + var _a3; const vaultPath = getVaultPath(this.plugin.app); if (!vaultPath) { return { success: false, error: "Could not determine vault path" }; } - if (!this.resolvedClaudePath) { - this.resolvedClaudePath = this.findClaudeCLI(); - } - if (!this.resolvedClaudePath) { + const resolvedClaudePath = this.plugin.getResolvedClaudeCliPath(); + if (!resolvedClaudePath) { return { success: false, error: "Claude CLI not found. Please install Claude Code CLI." }; } this.abortController = new AbortController(); const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables()); + const enhancedPath = getEnhancedPath(customEnv.PATH, resolvedClaudePath); + const missingNodeError = getMissingNodeError(resolvedClaudePath, enhancedPath); + if (missingNodeError) { + return { success: false, error: missingNodeError }; + } const options = { cwd: vaultPath, systemPrompt: getInlineEditSystemPrompt(), model: this.plugin.settings.model, abortController: this.abortController, - pathToClaudeCodeExecutable: this.resolvedClaudePath, + pathToClaudeCodeExecutable: resolvedClaudePath, env: { ...process.env, ...customEnv, - PATH: getEnhancedPath(customEnv.PATH) + PATH: enhancedPath }, - allowedTools: [...READ_ONLY_TOOLS], + tools: [...READ_ONLY_TOOLS], permissionMode: "bypassPermissions", allowDangerouslySkipPermissions: true, + settingSources: this.plugin.settings.loadUserClaudeSettings ? ["user", "project"] : ["project"], hooks: { PreToolUse: [ - this.createReadOnlyHook(), - this.createVaultRestrictionHook(vaultPath) + createReadOnlyHook(), + createVaultRestrictionHook2(vaultPath) ] } }; @@ -30323,166 +60494,34 @@ var InlineEditService = class { options.resume = this.sessionId; } const budgetSetting = this.plugin.settings.thinkingBudget; - const budgetConfig = THINKING_BUDGETS.find((b) => b.value === budgetSetting); + const budgetConfig = THINKING_BUDGETS.find((b3) => b3.value === budgetSetting); if (budgetConfig && budgetConfig.tokens > 0) { options.maxThinkingTokens = budgetConfig.tokens; } try { - const response = query({ prompt, options }); + const response = u_({ prompt, options }); let responseText = ""; for await (const message of response) { - if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted) { + if ((_a3 = this.abortController) == null ? void 0 : _a3.signal.aborted) { await response.interrupt(); return { success: false, error: "Cancelled" }; } if (message.type === "system" && message.subtype === "init" && message.session_id) { this.sessionId = message.session_id; } - const text = this.extractTextFromMessage(message); + const text = extractTextFromSdkMessage(message); if (text) { responseText += text; } } - return this.parseResponse(responseText); - } catch (error2) { - console.error("[InlineEditService] Error:", error2); - const msg = error2 instanceof Error ? error2.message : "Unknown error"; + return parseInlineEditResponse(responseText); + } catch (error48) { + const msg = error48 instanceof Error ? error48.message : "Unknown error"; return { success: false, error: msg }; } finally { this.abortController = null; } } - /** Parses response text for or tag. */ - parseResponse(responseText) { - const replacementMatch = responseText.match(/([\s\S]*?)<\/replacement>/); - if (replacementMatch) { - return { success: true, editedText: replacementMatch[1] }; - } - const insertionMatch = responseText.match(/([\s\S]*?)<\/insertion>/); - if (insertionMatch) { - return { success: true, insertedText: insertionMatch[1] }; - } - const trimmed = responseText.trim(); - if (trimmed) { - return { success: true, clarification: trimmed }; - } - return { success: false, error: "Empty response" }; - } - async buildPrompt(request) { - let prompt; - if (request.mode === "cursor") { - prompt = this.buildCursorPrompt(request); - } else { - const lineAttr = request.startLine && request.lineCount ? ` lines="${request.startLine}-${request.startLine + request.lineCount - 1}"` : ""; - prompt = [ - ``, - request.selectedText, - "", - "", - "", - request.instruction, - "" - ].join("\n"); - } - if (request.contextFiles && request.contextFiles.length > 0) { - const vaultPath = getVaultPath(this.plugin.app); - prompt = await prependContextFiles(prompt, request.contextFiles, vaultPath); - } - return prompt; - } - buildCursorPrompt(request) { - const ctx = request.cursorContext; - const lineAttr = ` line="${ctx.line + 1}"`; - let cursorContent; - if (ctx.isInbetween) { - const parts = []; - if (ctx.beforeCursor) parts.push(ctx.beforeCursor); - parts.push("| #inbetween"); - if (ctx.afterCursor) parts.push(ctx.afterCursor); - cursorContent = parts.join("\n"); - } else { - cursorContent = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`; - } - return [ - ``, - cursorContent, - "", - "", - "", - request.instruction, - "" - ].join("\n"); - } - /** Creates PreToolUse hook to enforce read-only mode. */ - createReadOnlyHook() { - return { - hooks: [ - async (hookInput) => { - const input = hookInput; - const toolName = input.tool_name; - if (isReadOnlyTool(toolName)) { - return { continue: true }; - } - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Inline edit mode: tool "${toolName}" is not allowed (read-only)` - } - }; - } - ] - }; - } - /** Creates PreToolUse hook to restrict file tools to the vault. */ - createVaultRestrictionHook(vaultPath) { - const fileTools = [TOOL_READ, TOOL_GLOB, TOOL_GREP, TOOL_LS]; - return { - hooks: [ - async (hookInput) => { - const input = hookInput; - const toolName = input.tool_name; - if (!fileTools.includes(toolName)) { - return { continue: true }; - } - const filePath = getPathFromToolInput(toolName, input.tool_input); - if (filePath && !isPathWithinVault(filePath, vaultPath)) { - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Access denied: Path "${filePath}" is outside the vault. Inline edit is restricted to vault directory only.` - } - }; - } - return { continue: true }; - } - ] - }; - } - extractTextFromMessage(message) { - var _a, _b, _c; - if (message.type === "assistant" && ((_a = message.message) == null ? void 0 : _a.content)) { - for (const block of message.message.content) { - if (block.type === "text" && block.text) { - return block.text; - } - } - } - if (message.type === "stream_event") { - const event = message.event; - if ((event == null ? void 0 : event.type) === "content_block_start" && ((_b = event.content_block) == null ? void 0 : _b.type) === "text") { - return event.content_block.text || null; - } - if ((event == null ? void 0 : event.type) === "content_block_delta" && ((_c = event.delta) == null ? void 0 : _c.type) === "text_delta") { - return event.delta.text || null; - } - } - return null; - } - /** Cancels the current edit operation. */ cancel() { if (this.abortController) { this.abortController.abort(); @@ -30490,21 +60529,13 @@ var InlineEditService = class { } }; -// src/utils/inlineEdit.ts -function normalizeInsertionText(text) { - return text.replace(/^(?:\r?\n)+|(?:\r?\n)+$/g, ""); -} -function escapeHtml(text) { - return text.replace(//g, ">"); -} - -// src/ui/modals/InlineEditModal.ts -var import_state2 = require("@codemirror/state"); +// src/features/inline-edit/ui/InlineEditModal.ts +var import_state3 = require("@codemirror/state"); var import_view2 = require("@codemirror/view"); -var showInlineEdit = import_state2.StateEffect.define(); -var showDiff = import_state2.StateEffect.define(); -var showInsertion = import_state2.StateEffect.define(); -var hideInlineEdit = import_state2.StateEffect.define(); +var showInlineEdit = import_state3.StateEffect.define(); +var showDiff = import_state3.StateEffect.define(); +var showInsertion = import_state3.StateEffect.define(); +var hideInlineEdit = import_state3.StateEffect.define(); var activeController = null; var DiffWidget = class extends import_view2.WidgetType { constructor(diffHtml, controller) { @@ -30555,68 +60586,68 @@ var InputWidget = class extends import_view2.WidgetType { return true; } }; -var inlineEditField = import_state2.StateField.define({ +var inlineEditField = import_state3.StateField.define({ create: () => import_view2.Decoration.none, update: (deco, tr) => { - var _a; + var _a3; deco = deco.map(tr.changes); - for (const e of tr.effects) { - if (e.is(showInlineEdit)) { - const builder = new import_state2.RangeSetBuilder(); - const isInbetween = (_a = e.value.isInbetween) != null ? _a : false; - builder.add(e.value.inputPos, e.value.inputPos, import_view2.Decoration.widget({ - widget: new InputWidget(e.value.widget), + for (const e2 of tr.effects) { + if (e2.is(showInlineEdit)) { + const builder = new import_state3.RangeSetBuilder(); + const isInbetween = (_a3 = e2.value.isInbetween) != null ? _a3 : false; + builder.add(e2.value.inputPos, e2.value.inputPos, import_view2.Decoration.widget({ + widget: new InputWidget(e2.value.widget), block: !isInbetween, side: isInbetween ? 1 : -1 })); deco = builder.finish(); - } else if (e.is(showDiff)) { - const builder = new import_state2.RangeSetBuilder(); - builder.add(e.value.from, e.value.to, import_view2.Decoration.replace({ - widget: new DiffWidget(e.value.diffHtml, e.value.widget) + } else if (e2.is(showDiff)) { + const builder = new import_state3.RangeSetBuilder(); + builder.add(e2.value.from, e2.value.to, import_view2.Decoration.replace({ + widget: new DiffWidget(e2.value.diffHtml, e2.value.widget) })); deco = builder.finish(); - } else if (e.is(showInsertion)) { - const builder = new import_state2.RangeSetBuilder(); - builder.add(e.value.pos, e.value.pos, import_view2.Decoration.widget({ - widget: new DiffWidget(e.value.diffHtml, e.value.widget), + } else if (e2.is(showInsertion)) { + const builder = new import_state3.RangeSetBuilder(); + builder.add(e2.value.pos, e2.value.pos, import_view2.Decoration.widget({ + widget: new DiffWidget(e2.value.diffHtml, e2.value.widget), side: 1 - // Display after the position + // After the position })); deco = builder.finish(); - } else if (e.is(hideInlineEdit)) { + } else if (e2.is(hideInlineEdit)) { deco = import_view2.Decoration.none; } } return deco; }, - provide: (f) => import_view2.EditorView.decorations.from(f) + provide: (f3) => import_view2.EditorView.decorations.from(f3) }); var installedEditors = /* @__PURE__ */ new WeakSet(); function computeDiff(oldText, newText) { const oldWords = oldText.split(/(\s+)/); const newWords = newText.split(/(\s+)/); - const m = oldWords.length, n = newWords.length; - const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0)); - for (let i2 = 1; i2 <= m; i2++) { - for (let j2 = 1; j2 <= n; j2++) { - dp[i2][j2] = oldWords[i2 - 1] === newWords[j2 - 1] ? dp[i2 - 1][j2 - 1] + 1 : Math.max(dp[i2 - 1][j2], dp[i2][j2 - 1]); + const m = oldWords.length, n2 = newWords.length; + const dp = Array(m + 1).fill(null).map(() => Array(n2 + 1).fill(0)); + for (let i3 = 1; i3 <= m; i3++) { + for (let j5 = 1; j5 <= n2; j5++) { + dp[i3][j5] = oldWords[i3 - 1] === newWords[j5 - 1] ? dp[i3 - 1][j5 - 1] + 1 : Math.max(dp[i3 - 1][j5], dp[i3][j5 - 1]); } } const ops = []; - let i = m, j = n; + let i2 = m, j3 = n2; const temp = []; - while (i > 0 || j > 0) { - if (i > 0 && j > 0 && oldWords[i - 1] === newWords[j - 1]) { - temp.push({ type: "equal", text: oldWords[i - 1] }); - i--; - j--; - } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) { - temp.push({ type: "insert", text: newWords[j - 1] }); - j--; + while (i2 > 0 || j3 > 0) { + if (i2 > 0 && j3 > 0 && oldWords[i2 - 1] === newWords[j3 - 1]) { + temp.push({ type: "equal", text: oldWords[i2 - 1] }); + i2--; + j3--; + } else if (j3 > 0 && (i2 === 0 || dp[i2][j3 - 1] >= dp[i2 - 1][j3])) { + temp.push({ type: "insert", text: newWords[j3 - 1] }); + j3--; } else { - temp.push({ type: "delete", text: oldWords[i - 1] }); - i--; + temp.push({ type: "delete", text: oldWords[i2 - 1] }); + i2--; } } temp.reverse(); @@ -30631,7 +60662,7 @@ function computeDiff(oldText, newText) { } function diffToHtml(ops) { return ops.map((op) => { - const escaped = escapeHtml(op.text); + const escaped = escapeHtml2(op.text); switch (op.type) { case "delete": return `${escaped}`; @@ -30655,12 +60686,12 @@ var InlineEditModal = class { activeController.reject(); return { decision: "reject" }; } - const view = this.app.workspace.getActiveViewOfType(import_obsidian10.MarkdownView); + const view = this.app.workspace.getActiveViewOfType(import_obsidian20.MarkdownView); if (!view) return { decision: "reject" }; const editor = view.editor; - const editorView = editor.cm; + const editorView = getEditorView(editor); if (!editorView) return { decision: "reject" }; - return new Promise((resolve7) => { + return new Promise((resolve4) => { this.controller = new InlineEditController( this.app, this.plugin, @@ -30668,7 +60699,7 @@ var InlineEditModal = class { editor, this.editContext, this.notePath, - resolve7 + resolve4 ); activeController = this.controller; this.controller.show(); @@ -30676,13 +60707,13 @@ var InlineEditModal = class { } }; var InlineEditController = class { - constructor(app, plugin, editorView, editor, editContext, notePath, resolve7) { + constructor(app, plugin, editorView, editor, editContext, notePath, resolve4) { this.app = app; this.plugin = plugin; this.editorView = editorView; this.editor = editor; this.notePath = notePath; - this.resolve = resolve7; + this.resolve = resolve4; this.inputEl = null; this.spinnerEl = null; this.agentReplyEl = null; @@ -30694,8 +60725,6 @@ var InlineEditController = class { this.escHandler = null; this.selectionListener = null; this.isConversing = false; - // True when agent asked clarification - this.slashCommandManager = null; this.slashCommandDropdown = null; this.mentionDropdown = null; this.attachedFiles = /* @__PURE__ */ new Set(); @@ -30730,7 +60759,7 @@ var InlineEditController = class { show() { if (!installedEditors.has(this.editorView)) { this.editorView.dispatch({ - effects: import_state2.StateEffect.appendConfig.of(inlineEditField) + effects: import_state3.StateEffect.appendConfig.of(inlineEditField) }); installedEditors.add(this.editorView); } @@ -30738,18 +60767,18 @@ var InlineEditController = class { if (this.mode === "selection") { this.attachSelectionListeners(); } - this.escHandler = (e) => { - if (e.key === "Escape") { + this.escHandler = (e2) => { + if (e2.key === "Escape" && !e2.isComposing) { this.reject(); } }; document.addEventListener("keydown", this.escHandler); } updateHighlight() { - var _a; + var _a3; const doc = this.editorView.state.doc; const line = doc.lineAt(this.selFrom); - const isInbetween = this.mode === "cursor" && ((_a = this.cursorContext) == null ? void 0 : _a.isInbetween); + const isInbetween = this.mode === "cursor" && ((_a3 = this.cursorContext) == null ? void 0 : _a3.isInbetween); this.editorView.dispatch({ effects: showInlineEdit.of({ inputPos: isInbetween ? this.selFrom : line.from, @@ -30770,8 +60799,8 @@ var InlineEditController = class { } attachSelectionListeners() { this.removeSelectionListeners(); - this.selectionListener = (e) => { - const target = e.target; + this.selectionListener = (e2) => { + const target = e2.target; if (target && this.inputEl && (target === this.inputEl || this.inputEl.contains(target))) { return; } @@ -30809,24 +60838,22 @@ var InlineEditController = class { this.spinnerEl.className = "claudian-inline-spinner"; this.spinnerEl.style.display = "none"; inputWrap.appendChild(this.spinnerEl); - const vaultPath = getVaultPath(this.app); - if (vaultPath) { - this.slashCommandManager = new SlashCommandManager(this.app, vaultPath); - this.slashCommandManager.setCommands(this.plugin.settings.slashCommands); - this.slashCommandDropdown = new SlashCommandDropdown( - document.body, - // Use body for fixed positioning - this.inputEl, - { - onSelect: () => { - }, - onHide: () => { - }, - getCommands: () => this.plugin.settings.slashCommands + this.slashCommandDropdown = new SlashCommandDropdown( + document.body, + // Fixed positioning + this.inputEl, + { + onSelect: () => { }, - { fixed: true } - ); - } + onHide: () => { + }, + getSdkCommands: () => this.plugin.getSdkCommands() + }, + { + fixed: true, + hiddenCommands: new Set((this.plugin.settings.hiddenSlashCommands || []).map((c3) => c3.toLowerCase())) + } + ); this.mentionDropdown = new MentionDropdownController( document.body, this.inputEl, @@ -30838,12 +60865,11 @@ var InlineEditController = class { setMentionedMcpServers: () => false, addMentionedMcpServer: () => { }, - getContextPaths: () => [], + getExternalContexts: () => [], getCachedMarkdownFiles: () => { try { return this.app.vault.getMarkdownFiles(); - } catch (error2) { - console.error("[InlineEditModal] getCachedMarkdownFiles error:", error2); + } catch (e2) { return []; } }, @@ -30851,47 +60877,21 @@ var InlineEditController = class { }, { fixed: true } ); - this.inputEl.addEventListener("keydown", (e) => this.handleKeydown(e)); + this.inputEl.addEventListener("keydown", (e2) => this.handleKeydown(e2)); this.inputEl.addEventListener("input", () => { - var _a; - return (_a = this.mentionDropdown) == null ? void 0 : _a.handleInputChange(); + var _a3; + return (_a3 = this.mentionDropdown) == null ? void 0 : _a3.handleInputChange(); }); setTimeout(() => { - var _a; - return (_a = this.inputEl) == null ? void 0 : _a.focus(); + var _a3; + return (_a3 = this.inputEl) == null ? void 0 : _a3.focus(); }, 50); return container; } async generate() { if (!this.inputEl || !this.spinnerEl) return; - let userMessage = this.inputEl.value.trim(); + const userMessage = this.inputEl.value.trim(); if (!userMessage) return; - if (this.slashCommandManager) { - this.slashCommandManager.setCommands(this.plugin.settings.slashCommands); - const detected = this.slashCommandManager.detectCommand(userMessage); - if (detected) { - const cmd = this.plugin.settings.slashCommands.find( - (c) => c.name.toLowerCase() === detected.commandName.toLowerCase() - ); - if (cmd) { - const expansion = await this.slashCommandManager.expandCommand(cmd, detected.args, { - bash: { - enabled: true, - shouldBlockCommand: (bashCommand) => isCommandBlocked( - bashCommand, - getBashToolBlockedCommands(this.plugin.settings.blockedCommands), - this.plugin.settings.enableBlocklist - ), - requestApproval: this.plugin.settings.permissionMode !== "yolo" ? (bashCommand) => this.requestInlineBashApproval(bashCommand) : void 0 - } - }); - userMessage = expansion.expandedPrompt; - if (expansion.errors.length > 0) { - new import_obsidian10.Notice(formatSlashCommandWarnings(expansion.errors)); - } - } - } - } this.removeSelectionListeners(); this.inputEl.disabled = true; this.spinnerEl.style.display = "block"; @@ -30944,14 +60944,12 @@ var InlineEditController = class { this.handleError(result.error || "Error - try again"); } } - /** Show agent's clarification message. */ showAgentReply(message) { if (!this.agentReplyEl || !this.containerEl) return; this.agentReplyEl.style.display = "block"; this.agentReplyEl.textContent = message; this.containerEl.classList.add("has-agent-reply"); } - /** Handle error state. */ handleError(errorMessage) { if (!this.inputEl) return; this.inputEl.disabled = false; @@ -30977,22 +60975,21 @@ var InlineEditController = class { if (this.escHandler) { document.removeEventListener("keydown", this.escHandler); } - this.escHandler = (e) => { - if (e.key === "Escape") { + this.escHandler = (e2) => { + if (e2.key === "Escape" && !e2.isComposing) { this.reject(); - } else if (e.key === "Enter") { + } else if (e2.key === "Enter" && !e2.isComposing) { this.accept(); } }; document.addEventListener("keydown", this.escHandler); } - /** Show insertion preview (all green, no deletions) for cursor mode. */ showInsertionInPlace() { if (this.insertedText === null) return; hideSelectionHighlight(this.editorView); const trimmedText = normalizeInsertionText(this.insertedText); this.insertedText = trimmedText; - const escaped = escapeHtml(trimmedText); + const escaped = escapeHtml2(trimmedText); const diffHtml = `${escaped}`; this.editorView.dispatch({ effects: showInsertion.of({ @@ -31004,18 +61001,18 @@ var InlineEditController = class { if (this.escHandler) { document.removeEventListener("keydown", this.escHandler); } - this.escHandler = (e) => { - if (e.key === "Escape") { + this.escHandler = (e2) => { + if (e2.key === "Escape" && !e2.isComposing) { this.reject(); - } else if (e.key === "Enter") { + } else if (e2.key === "Enter" && !e2.isComposing) { this.accept(); } }; document.addEventListener("keydown", this.escHandler); } accept() { - var _a; - const textToInsert = (_a = this.editedText) != null ? _a : this.insertedText; + var _a3; + const textToInsert = (_a3 = this.editedText) != null ? _a3 : this.insertedText; if (textToInsert !== null) { const doc = this.editorView.state.doc; const fromLine = doc.lineAt(this.selFrom); @@ -31043,7 +61040,7 @@ var InlineEditController = class { } } cleanup(options) { - var _a, _b; + var _a3, _b; this.inlineEditService.cancel(); this.inlineEditService.resetConversation(); this.isConversing = false; @@ -31051,9 +61048,8 @@ var InlineEditController = class { if (this.escHandler) { document.removeEventListener("keydown", this.escHandler); } - (_a = this.slashCommandDropdown) == null ? void 0 : _a.destroy(); + (_a3 = this.slashCommandDropdown) == null ? void 0 : _a3.destroy(); this.slashCommandDropdown = null; - this.slashCommandManager = null; (_b = this.mentionDropdown) == null ? void 0 : _b.destroy(); this.mentionDropdown = null; this.attachedFiles.clear(); @@ -31073,280 +61069,3176 @@ var InlineEditController = class { } showSelectionHighlight(this.editorView, this.selFrom, this.selTo); } - handleKeydown(e) { - var _a, _b; - if ((_a = this.mentionDropdown) == null ? void 0 : _a.handleKeydown(e)) { + handleKeydown(e2) { + var _a3, _b; + if ((_a3 = this.mentionDropdown) == null ? void 0 : _a3.handleKeydown(e2)) { return; } - if ((_b = this.slashCommandDropdown) == null ? void 0 : _b.handleKeydown(e)) { + if ((_b = this.slashCommandDropdown) == null ? void 0 : _b.handleKeydown(e2)) { return; } - if (e.key === "Enter" && !e.isComposing) { - e.preventDefault(); + if (e2.key === "Enter" && !e2.isComposing) { + e2.preventDefault(); this.generate(); } } normalizePathForVault(rawPath) { - if (!rawPath) return null; try { - const normalizedRaw = normalizePathForFilesystem(rawPath); const vaultPath = getVaultPath(this.app); - if (vaultPath && isPathWithinVault(normalizedRaw, vaultPath)) { - const absolute = path11.isAbsolute(normalizedRaw) ? normalizedRaw : path11.resolve(vaultPath, normalizedRaw); - const relative5 = path11.relative(vaultPath, absolute); - return relative5 ? relative5.replace(/\\/g, "/") : null; - } - return normalizedRaw.replace(/\\/g, "/"); - } catch (error2) { - console.error("[InlineEditModal] normalizePathForVault error:", error2); - new import_obsidian10.Notice("Failed to attach file: invalid path"); + return normalizePathForVault(rawPath, vaultPath); + } catch (e2) { + new import_obsidian20.Notice("Failed to attach file: invalid path"); return null; } } - async requestInlineBashApproval(command) { - const description = `Execute inline bash command: -${command}`; - return new Promise((resolve7) => { - const modal = new ApprovalModal( - this.app, - TOOL_BASH, - { command }, - description, - (decision) => resolve7(decision === "allow" || decision === "allow-always"), - { showAlwaysAllow: false, title: "Inline bash execution" } - ); - modal.open(); - }); - } }; -// src/ui/modals/InstructionConfirmModal.ts -var import_obsidian11 = require("obsidian"); -var InstructionModal = class extends import_obsidian11.Modal { - constructor(app, rawInstruction, callbacks) { +// src/features/settings/ClaudianSettings.ts +var fs7 = __toESM(require("fs")); +var import_obsidian29 = require("obsidian"); + +// src/i18n/locales/de.json +var de_exports = {}; +__export(de_exports, { + common: () => common, + default: () => de_default2, + settings: () => settings +}); +var common = { + save: "Speichern", + cancel: "Abbrechen", + delete: "L\xF6schen", + edit: "Bearbeiten", + add: "Hinzuf\xFCgen", + remove: "Entfernen", + clear: "L\xF6schen", + clearAll: "Alle l\xF6schen", + loading: "L\xE4dt", + error: "Fehler", + success: "Erfolg", + warning: "Warnung", + confirm: "Best\xE4tigen", + settings: "Einstellungen", + advanced: "Erweitert", + enabled: "Aktiviert", + disabled: "Deaktiviert", + platform: "Plattform" +}; +var settings = { + title: "Claudian Einstellungen", + customization: "Anpassung", + userName: { + name: "Wie soll Claudian dich nennen?", + desc: "Dein Name f\xFCr personalisierte Begr\xFC\xDFungen (leer lassen f\xFCr allgemeine Begr\xFC\xDFungen)" + }, + excludedTags: { + name: "Ausgeschlossene Tags", + desc: "Notizen mit diesen Tags werden nicht automatisch als Kontext geladen (einer pro Zeile, ohne #)" + }, + mediaFolder: { + name: "Medienordner", + desc: "Ordner mit Anh\xE4ngen/Bildern. Wenn Notizen ![[image.jpg]] verwenden, sucht Claude hier. Leer lassen f\xFCr Vault-Stammverzeichnis." + }, + systemPrompt: { + name: "Benutzerdefinierter System-Prompt", + desc: "Zus\xE4tzliche Anweisungen, die an den Standard-System-Prompt angeh\xE4ngt werden" + }, + autoTitle: { + name: "Konversationstitel automatisch generieren", + desc: "Generiert automatisch Konversationstitel nach der ersten Nutzernachricht." + }, + titleModel: { + name: "Titel-Generierungsmodell", + desc: "Modell zur automatischen Generierung von Konversationstiteln.", + auto: "Automatisch (Haiku)" + }, + navMappings: { + name: "Vim-Style Navigationszuordnungen", + desc: 'Eine Zuordnung pro Zeile. Format: "map " (Aktionen: scrollUp, scrollDown, focusInput).' + }, + hotkeys: "Tastenk\xFCrzel", + inlineEditHotkey: { + name: "Inline-Bearbeitung", + descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}", + descNoKey: "Kein Tastenk\xFCrzel festgelegt", + btnChange: "\xC4ndern", + btnSet: "Festlegen" + }, + openChatHotkey: { + name: "Chat \xF6ffnen", + descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}", + descNoKey: "Kein Tastenk\xFCrzel festgelegt", + btnChange: "\xC4ndern", + btnSet: "Festlegen" + }, + newSessionHotkey: { + name: "Neue Sitzung", + descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}", + descNoKey: "Kein Tastenk\xFCrzel festgelegt", + btnChange: "\xC4ndern", + btnSet: "Festlegen" + }, + newTabHotkey: { + name: "Neuer Tab", + descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}", + descNoKey: "Kein Tastenk\xFCrzel festgelegt", + btnChange: "\xC4ndern", + btnSet: "Festlegen" + }, + closeTabHotkey: { + name: "Tab schlie\xDFen", + descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}", + descNoKey: "Kein Tastenk\xFCrzel festgelegt", + btnChange: "\xC4ndern", + btnSet: "Festlegen" + }, + slashCommands: { + name: "Befehle und F\xE4higkeiten", + desc: "Definiere benutzerdefinierte Befehle und F\xE4higkeiten, die durch /Name ausgel\xF6st werden." + }, + hiddenSlashCommands: { + name: "Ausgeblendete Befehle", + desc: "Bestimmte Schr\xE4gstrich-Befehle aus dem Dropdown ausblenden. N\xFCtzlich, um Claude Code-Befehle auszublenden, die f\xFCr Claudian nicht relevant sind. Gib Befehlsnamen ohne f\xFChrenden Schr\xE4gstrich ein, einen pro Zeile.", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "MCP-Server", + desc: "Konfiguriere Model Context Protocol Server, um Claude mit externen Tools und Datenquellen zu erweitern. Server mit Kontext-Speichermodus ben\xF6tigen @mention zur Aktivierung." + }, + plugins: { + name: "Claude Code Plugins", + desc: "Aktiviere oder deaktiviere Claude Code Plugins aus ~/.claude/plugins. Aktivierte Plugins werden pro Vault gespeichert." + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "Sicherheit", + loadUserSettings: { + name: "Benutzer-Claude-Einstellungen laden", + desc: "L\xE4dt ~/.claude/settings.json. Wenn aktiviert, k\xF6nnen Benutzer-Claude-Code-Berechtigungsregeln den Sicherheitsmodus umgehen." + }, + enableBlocklist: { + name: "Befehlsblockliste aktivieren", + desc: "Blockiert potenziell gef\xE4hrliche Bash-Befehle" + }, + blockedCommands: { + name: "Blockierte Befehle ({platform})", + desc: "Muster zum Blockieren auf {platform} (einer pro Zeile). Unterst\xFCtzt Regex.", + unixName: "Blockierte Befehle (Unix/Git Bash)", + unixDesc: "Unix-Muster werden auch auf Windows blockiert, da Git Bash sie aufrufen kann." + }, + exportPaths: { + name: "Zugelassene Exportpfade", + desc: "Pfade au\xDFerhalb des Vaults, in die Dateien exportiert werden k\xF6nnen (einer pro Zeile). Unterst\xFCtzt ~ f\xFCr Home-Verzeichnis." + }, + environment: "Umgebung", + customVariables: { + name: "Benutzerdefinierte Variablen", + desc: "Umgebungsvariablen f\xFCr Claude SDK (KEY=VALUE-Format, eine pro Zeile). Export-Pr\xE4fix unterst\xFCtzt." + }, + envSnippets: { + name: "Snippets", + addBtn: "Snippet hinzuf\xFCgen", + noSnippets: "Keine gespeicherten Umgebungsvariablen-Snippets. Klicken Sie auf +, um Ihre aktuelle Konfiguration zu speichern.", + nameRequired: "Bitte geben Sie einen Namen f\xFCr das Snippet ein", + modal: { + titleEdit: "Snippet bearbeiten", + titleSave: "Snippet speichern", + name: "Name", + namePlaceholder: "Ein beschreibender Name f\xFCr diese Umgebungskonfiguration", + description: "Beschreibung", + descPlaceholder: "Optionale Beschreibung", + envVars: "Umgebungsvariablen", + envVarsPlaceholder: "KEY=VALUE-Format, eine pro Zeile (export-Pr\xE4fix unterst\xFCtzt)", + save: "Speichern", + update: "Aktualisieren", + cancel: "Abbrechen" + } + }, + customContextLimits: { + name: "Benutzerdefinierte Kontextlimits", + desc: "Legen Sie die Kontextfenstergr\xF6\xDFen f\xFCr Ihre benutzerdefinierten Modelle fest. Leer lassen f\xFCr den Standardwert (200k Token).", + invalid: "Ung\xFCltiges Format. Verwenden Sie: 256k, 1m oder exakte Anzahl (1000-10000000)." + }, + advanced: "Erweitert", + show1MModel: { + name: "Sonnet mit 1M-Kontextfenster aktivieren", + desc: "Standard-Sonnet durch Sonnet (1M) in der Modellauswahl ersetzen. Gleiche Preise unter 200k Token. Erfordert Max-Abonnement." + }, + enableChrome: { + name: "Chrome-Erweiterung aktivieren", + desc: "Erlaubt Claude die Interaktion mit Chrome \xFCber die claude-in-chrome-Erweiterung. Die Erweiterung muss installiert sein. Erfordert Neustart der Sitzung." + }, + maxTabs: { + name: "Maximale Chat-Tabs", + desc: "Maximale Anzahl gleichzeitiger Chat-Tabs (3-10). Jeder Tab verwendet eine separate Claude-Sitzung.", + warning: "Mehr als 5 Tabs k\xF6nnen Leistung und Speichernutzung beeintr\xE4chtigen." + }, + tabBarPosition: { + name: "Tab-Leiste Position", + desc: "W\xE4hlen Sie, wo Tab-Badges und Aktionsschaltfl\xE4chen angezeigt werden", + input: "\xDCber Eingabefeld (Standard)", + header: "In Kopfzeile" + }, + enableAutoScroll: { + name: "Automatisches Scrollen w\xE4hrend Streaming", + desc: "Automatisch nach unten scrollen, w\xE4hrend Claude Antworten streamt. Deaktivieren, um oben zu bleiben und von Anfang an zu lesen." + }, + openInMainTab: { + name: "Im Haupteditorbereich \xF6ffnen", + desc: "Chat-Panel als Haupttab im zentralen Editorbereich statt in der rechten Seitenleiste \xF6ffnen" + }, + cliPath: { + name: "Claude CLI-Pfad", + desc: "Benutzerdefinierter Pfad zum Claude Code CLI. Leer lassen f\xFCr automatische Erkennung.", + descWindows: "F\xFCr den nativen Installer verwenden Sie claude.exe. F\xFCr npm/pnpm/yarn oder andere Paketmanager-Installationen verwenden Sie den cli.js-Pfad (nicht claude.cmd).", + descUnix: 'F\xFCgen Sie die Ausgabe von "which claude" ein \u2014 funktioniert sowohl f\xFCr native als auch npm/pnpm/yarn-Installationen.', + validation: { + notExist: "Pfad existiert nicht", + isDirectory: "Pfad ist ein Verzeichnis, keine Datei" + } + }, + language: { + name: "Sprache", + desc: "Anzeigesprache der Plugin-Oberfl\xE4che \xE4ndern" + } +}; +var de_default2 = { + common, + settings +}; + +// src/i18n/locales/en.json +var en_exports = {}; +__export(en_exports, { + common: () => common2, + default: () => en_default3, + settings: () => settings2 +}); +var common2 = { + save: "Save", + cancel: "Cancel", + delete: "Delete", + edit: "Edit", + add: "Add", + remove: "Remove", + clear: "Clear", + clearAll: "Clear all", + loading: "Loading", + error: "Error", + success: "Success", + warning: "Warning", + confirm: "Confirm", + settings: "Settings", + advanced: "Advanced", + enabled: "Enabled", + disabled: "Disabled", + platform: "Platform" +}; +var settings2 = { + title: "Claudian Settings", + customization: "Customization", + userName: { + name: "What should Claudian call you?", + desc: "Your name for personalized greetings (leave empty for generic greetings)" + }, + excludedTags: { + name: "Excluded tags", + desc: "Notes with these tags will not auto-load as context (one per line, without #)" + }, + mediaFolder: { + name: "Media folder", + desc: "Folder containing attachments/images. When notes use ![[image.jpg]], Claude will look here. Leave empty for vault root." + }, + systemPrompt: { + name: "Custom system prompt", + desc: "Additional instructions appended to the default system prompt" + }, + autoTitle: { + name: "Auto-generate conversation titles", + desc: "Automatically generate conversation titles after the first user message is sent." + }, + titleModel: { + name: "Title generation model", + desc: "Model used for auto-generating conversation titles.", + auto: "Auto (Haiku)" + }, + navMappings: { + name: "Vim-style navigation mappings", + desc: 'One mapping per line. Format: "map " (actions: scrollUp, scrollDown, focusInput).' + }, + hotkeys: "Hotkeys", + inlineEditHotkey: { + name: "Inline Edit", + descWithKey: "Current hotkey: {hotkey}", + descNoKey: "No hotkey set", + btnChange: "Change", + btnSet: "Set hotkey" + }, + openChatHotkey: { + name: "Open Chat", + descWithKey: "Current hotkey: {hotkey}", + descNoKey: "No hotkey set", + btnChange: "Change", + btnSet: "Set hotkey" + }, + newSessionHotkey: { + name: "New Session", + descWithKey: "Current hotkey: {hotkey}", + descNoKey: "No hotkey set", + btnChange: "Change", + btnSet: "Set hotkey" + }, + newTabHotkey: { + name: "New Tab", + descWithKey: "Current hotkey: {hotkey}", + descNoKey: "No hotkey set", + btnChange: "Change", + btnSet: "Set hotkey" + }, + closeTabHotkey: { + name: "Close Tab", + descWithKey: "Current hotkey: {hotkey}", + descNoKey: "No hotkey set", + btnChange: "Change", + btnSet: "Set hotkey" + }, + slashCommands: { + name: "Commands and Skills", + desc: "Define custom commands and skills triggered by /name." + }, + hiddenSlashCommands: { + name: "Hidden Commands", + desc: "Hide specific slash commands from the dropdown. Useful for hiding Claude Code commands that are not relevant to Claudian. Enter command names without the leading slash, one per line.", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "MCP Servers", + desc: "Configure Model Context Protocol servers to extend Claude's capabilities with external tools and data sources. Servers with context-saving mode require @mention to activate." + }, + plugins: { + name: "Claude Code Plugins", + desc: "Enable or disable Claude Code plugins discovered from ~/.claude/plugins. Enabled plugins are stored per vault." + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "Safety", + loadUserSettings: { + name: "Load user Claude settings", + desc: "Load ~/.claude/settings.json. When enabled, user's Claude Code permission rules may bypass Safe mode." + }, + enableBlocklist: { + name: "Enable command blocklist", + desc: "Block potentially dangerous bash commands" + }, + blockedCommands: { + name: "Blocked commands ({platform})", + desc: "Patterns to block on {platform} (one per line). Supports regex.", + unixName: "Blocked commands (Unix/Git Bash)", + unixDesc: "Unix patterns also blocked on Windows because Git Bash can invoke them." + }, + exportPaths: { + name: "Allowed export paths", + desc: "Paths outside the vault where files can be exported (one per line). Supports ~ for home directory." + }, + environment: "Environment", + customVariables: { + name: "Custom variables", + desc: "Environment variables for Claude SDK (KEY=VALUE format, one per line). Shell export prefix supported." + }, + envSnippets: { + name: "Snippets", + addBtn: "Add snippet", + noSnippets: "No saved environment snippets yet. Click + to save your current environment configuration.", + nameRequired: "Please enter a name for the snippet", + modal: { + titleEdit: "Edit snippet", + titleSave: "Save snippet", + name: "Name", + namePlaceholder: "A descriptive name for this environment configuration", + description: "Description", + descPlaceholder: "Optional description", + envVars: "Environment variables", + envVarsPlaceholder: "KEY=VALUE format, one per line (export prefix supported)", + save: "Save", + update: "Update", + cancel: "Cancel" + } + }, + customContextLimits: { + name: "Custom Context Limits", + desc: "Set context window sizes for your custom models. Leave empty to use the default (200k tokens).", + invalid: "Invalid format. Use: 256k, 1m, or exact count (1000-10000000)." + }, + advanced: "Advanced", + show1MModel: { + name: "Enable Sonnet with 1M context window", + desc: "Replace standard Sonnet with Sonnet (1M) in the model selector. Same pricing under 200k tokens. Requires Max subscription." + }, + enableChrome: { + name: "Enable Chrome extension", + desc: "Allow Claude to interact with Chrome via the claude-in-chrome extension. Requires the extension to be installed. Requires session restart." + }, + maxTabs: { + name: "Maximum chat tabs", + desc: "Maximum number of concurrent chat tabs (3-10). Each tab uses a separate Claude session.", + warning: "More than 5 tabs may impact performance and memory usage." + }, + tabBarPosition: { + name: "Tab bar position", + desc: "Choose where to display tab badges and action buttons", + input: "Above input (default)", + header: "In header" + }, + enableAutoScroll: { + name: "Auto-scroll during streaming", + desc: "Automatically scroll to the bottom as Claude streams responses. Disable to stay at the top and read from the beginning." + }, + openInMainTab: { + name: "Open in main editor area", + desc: "Open chat panel as a main tab in the center editor area instead of the right sidebar" + }, + cliPath: { + name: "Claude CLI path", + desc: "Custom path to Claude Code CLI. Leave empty for auto-detection.", + descWindows: "For the native installer, use claude.exe. For npm/pnpm/yarn or other package manager installs, use the cli.js path (not claude.cmd).", + descUnix: 'Paste the output of "which claude" \u2014 works for both native and npm/pnpm/yarn installs.', + validation: { + notExist: "Path does not exist", + isDirectory: "Path is a directory, not a file" + } + }, + language: { + name: "Language", + desc: "Change the display language of the plugin interface" + } +}; +var en_default3 = { + common: common2, + settings: settings2 +}; + +// src/i18n/locales/es.json +var es_exports = {}; +__export(es_exports, { + common: () => common3, + default: () => es_default2, + settings: () => settings3 +}); +var common3 = { + save: "Guardar", + cancel: "Cancelar", + delete: "Eliminar", + edit: "Editar", + add: "Agregar", + remove: "Eliminar", + clear: "Limpiar", + clearAll: "Limpiar todo", + loading: "Cargando", + error: "Error", + success: "\xC9xito", + warning: "Advertencia", + confirm: "Confirmar", + settings: "Configuraci\xF3n", + advanced: "Avanzado", + enabled: "Habilitado", + disabled: "Deshabilitado", + platform: "Plataforma" +}; +var settings3 = { + title: "Configuraci\xF3n de Claudian", + customization: "Personalizaci\xF3n", + userName: { + name: "\xBFC\xF3mo deber\xEDa Claudian llamarte?", + desc: "Tu nombre para saludos personalizados (dejar vac\xEDo para saludos gen\xE9ricos)" + }, + excludedTags: { + name: "Etiquetas excluidas", + desc: "Las notas con estas etiquetas no se cargar\xE1n autom\xE1ticamente como contexto (una por l\xEDnea, sin #)" + }, + mediaFolder: { + name: "Carpeta de medios", + desc: "Carpeta que contiene archivos adjuntos/imagenes. Cuando las notas usan ![[image.jpg]], Claude buscar\xE1 aqu\xED. Dejar vac\xEDo para la ra\xEDz del dep\xF3sito." + }, + systemPrompt: { + name: "Prompt de sistema personalizado", + desc: "Instrucciones adicionales a\xF1adidas al prompt de sistema por defecto" + }, + autoTitle: { + name: "Generar autom\xE1ticamente t\xEDtulos de conversaci\xF3n", + desc: "Genera autom\xE1ticamente t\xEDtulos de conversaci\xF3n despu\xE9s del primer mensaje del usuario." + }, + titleModel: { + name: "Modelo de generaci\xF3n de t\xEDtulos", + desc: "Modelo utilizado para generar autom\xE1ticamente t\xEDtulos de conversaci\xF3n.", + auto: "Auto (Haiku)" + }, + navMappings: { + name: "Mapeos de navegaci\xF3n estilo Vim", + desc: 'Un mapeo por l\xEDnea. Formato: "map " (acciones: scrollUp, scrollDown, focusInput).' + }, + hotkeys: "Atajos de teclado", + inlineEditHotkey: { + name: "Edici\xF3n en l\xEDnea", + descWithKey: "Atajo actual: {hotkey}", + descNoKey: "Sin atajo configurado", + btnChange: "Cambiar", + btnSet: "Configurar" + }, + openChatHotkey: { + name: "Abrir chat", + descWithKey: "Atajo actual: {hotkey}", + descNoKey: "Sin atajo configurado", + btnChange: "Cambiar", + btnSet: "Configurar" + }, + newSessionHotkey: { + name: "Nueva sesi\xF3n", + descWithKey: "Atajo actual: {hotkey}", + descNoKey: "Sin atajo configurado", + btnChange: "Cambiar", + btnSet: "Configurar" + }, + newTabHotkey: { + name: "Nueva pesta\xF1a", + descWithKey: "Atajo actual: {hotkey}", + descNoKey: "Sin atajo configurado", + btnChange: "Cambiar", + btnSet: "Configurar" + }, + closeTabHotkey: { + name: "Cerrar pesta\xF1a", + descWithKey: "Atajo actual: {hotkey}", + descNoKey: "Sin atajo configurado", + btnChange: "Cambiar", + btnSet: "Configurar" + }, + slashCommands: { + name: "Comandos y habilidades", + desc: "Define comandos y habilidades personalizados activados por /nombre." + }, + hiddenSlashCommands: { + name: "Comandos ocultos", + desc: "Oculta comandos slash espec\xEDficos del men\xFA desplegable. \xDAtil para ocultar comandos de Claude Code que no son relevantes para Claudian. Ingresa nombres de comandos sin la barra inicial, uno por l\xEDnea.", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "Servidores MCP", + desc: "Configura servidores Model Context Protocol para extender las capacidades de Claude con herramientas y fuentes de datos externas. Los servidores con modo de guardado de contexto requieren @mention para activarse." + }, + plugins: { + name: "Plugins de Claude Code", + desc: "Habilita o deshabilita plugins de Claude Code descubiertos desde ~/.claude/plugins. Los plugins habilitados se almacenan por b\xF3veda." + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "Seguridad", + loadUserSettings: { + name: "Cargar configuraci\xF3n de usuario Claude", + desc: "Carga ~/.claude/settings.json. Cuando est\xE1 habilitado, las reglas de permisos del usuario pueden eludir el modo seguro." + }, + enableBlocklist: { + name: "Habilitar lista negra de comandos", + desc: "Bloquea comandos bash potencialmente peligrosos" + }, + blockedCommands: { + name: "Comandos bloqueados ({platform})", + desc: "Patrones a bloquear en {platform} (uno por l\xEDnea). Soporta expresiones regulares.", + unixName: "Comandos bloqueados (Unix/Git Bash)", + unixDesc: "Los patrones Unix tambi\xE9n se bloquean en Windows porque Git Bash puede invocarlos." + }, + exportPaths: { + name: "Rutas de exportaci\xF3n permitidas", + desc: "Rutas fuera del dep\xF3sito donde se pueden exportar archivos (una por l\xEDnea). Soporta ~ para el directorio home." + }, + environment: "Entorno", + customVariables: { + name: "Variables personalizadas", + desc: "Variables de entorno para Claude SDK (formato KEY=VALUE, una por l\xEDnea). Prefijo export soportado." + }, + envSnippets: { + name: "Snippets", + addBtn: "A\xF1adir fragmento", + noSnippets: "No hay fragmentos de entorno guardados. Haga clic en + para guardar su configuraci\xF3n actual.", + nameRequired: "Por favor ingrese un nombre para el fragmento", + modal: { + titleEdit: "Editar fragmento", + titleSave: "Guardar fragmento", + name: "Nombre", + namePlaceholder: "Un nombre descriptivo para esta configuraci\xF3n", + description: "Descripci\xF3n", + descPlaceholder: "Descripci\xF3n opcional", + envVars: "Variables de entorno", + envVarsPlaceholder: "Formato KEY=VALUE, una por l\xEDnea (prefijo export soportado)", + save: "Guardar", + update: "Actualizar", + cancel: "Cancelar" + } + }, + customContextLimits: { + name: "L\xEDmites de contexto personalizados", + desc: "Establezca tama\xF1os de ventana de contexto para sus modelos personalizados. Deje vac\xEDo para usar el valor predeterminado (200k tokens).", + invalid: "Formato inv\xE1lido. Use: 256k, 1m o n\xFAmero exacto (1000-10000000)." + }, + advanced: "Avanzado", + show1MModel: { + name: "Habilitar Sonnet con ventana de contexto de 1M", + desc: "Reemplazar Sonnet est\xE1ndar con Sonnet (1M) en el selector de modelos. Mismo precio bajo 200k tokens. Requiere suscripci\xF3n Max." + }, + enableChrome: { + name: "Habilitar extensi\xF3n de Chrome", + desc: "Permitir que Claude interact\xFAe con Chrome a trav\xE9s de la extensi\xF3n claude-in-chrome. Requiere que la extensi\xF3n est\xE9 instalada. Requiere reinicio de sesi\xF3n." + }, + maxTabs: { + name: "M\xE1ximo de pesta\xF1as de chat", + desc: "N\xFAmero m\xE1ximo de pesta\xF1as de chat simult\xE1neas (3-10). Cada pesta\xF1a usa una sesi\xF3n de Claude separada.", + warning: "M\xE1s de 5 pesta\xF1as puede afectar el rendimiento y el uso de memoria." + }, + tabBarPosition: { + name: "Posici\xF3n de la barra de pesta\xF1as", + desc: "Elige d\xF3nde mostrar las insignias de pesta\xF1as y los botones de acci\xF3n", + input: "Sobre el \xE1rea de entrada (predeterminado)", + header: "En el encabezado" + }, + enableAutoScroll: { + name: "Desplazamiento autom\xE1tico durante streaming", + desc: "Desplazarse autom\xE1ticamente hacia abajo mientras Claude transmite respuestas. Desactivar para quedarse arriba y leer desde el principio." + }, + openInMainTab: { + name: "Abrir en \xE1rea de editor principal", + desc: "Abrir el panel de chat como una pesta\xF1a principal en el \xE1rea de editor central en lugar de la barra lateral derecha" + }, + cliPath: { + name: "Ruta CLI Claude", + desc: "Ruta personalizada a Claude Code CLI. Dejar vac\xEDo para detecci\xF3n autom\xE1tica.", + descWindows: "Para el instalador nativo, use claude.exe. Para instalaciones con npm/pnpm/yarn u otros gestores de paquetes, use la ruta cli.js (no claude.cmd).", + descUnix: 'Pegue la salida de "which claude" \u2014 funciona tanto para instalaciones nativas como npm/pnpm/yarn.', + validation: { + notExist: "La ruta no existe", + isDirectory: "La ruta es un directorio, no un archivo" + } + }, + language: { + name: "Idioma", + desc: "Cambiar el idioma de visualizaci\xF3n de la interfaz del plugin" + } +}; +var es_default2 = { + common: common3, + settings: settings3 +}; + +// src/i18n/locales/fr.json +var fr_exports = {}; +__export(fr_exports, { + common: () => common4, + default: () => fr_default2, + settings: () => settings4 +}); +var common4 = { + save: "Enregistrer", + cancel: "Annuler", + delete: "Supprimer", + edit: "Modifier", + add: "Ajouter", + remove: "Supprimer", + clear: "Effacer", + clearAll: "Tout effacer", + loading: "Chargement", + error: "Erreur", + success: "Succ\xE8s", + warning: "Avertissement", + confirm: "Confirmer", + settings: "Param\xE8tres", + advanced: "Avanc\xE9", + enabled: "Activ\xE9", + disabled: "D\xE9sactiv\xE9", + platform: "Plateforme" +}; +var settings4 = { + title: "Param\xE8tres Claudian", + customization: "Personnalisation", + userName: { + name: "Comment Claudian doit-il vous appeler ?", + desc: "Votre nom pour les salutations personnalis\xE9es (laisser vide pour les salutations g\xE9n\xE9riques)" + }, + excludedTags: { + name: "Tags exclus", + desc: "Les notes avec ces tags ne seront pas charg\xE9es automatiquement comme contexte (un par ligne, sans #)" + }, + mediaFolder: { + name: "Dossier des m\xE9dias", + desc: "Dossier contenant les pi\xE8ces jointes/images. Lorsque les notes utilisent ![[image.jpg]], Claude cherchera ici. Laisser vide pour la racine du coffre." + }, + systemPrompt: { + name: "Prompt syst\xE8me personnalis\xE9", + desc: "Instructions suppl\xE9mentaires ajout\xE9es au prompt syst\xE8me par d\xE9faut" + }, + autoTitle: { + name: "G\xE9n\xE9rer automatiquement les titres de conversation", + desc: "G\xE9n\xE8re automatiquement les titres de conversation apr\xE8s le premier message de l'utilisateur." + }, + titleModel: { + name: "Mod\xE8le de g\xE9n\xE9ration de titre", + desc: "Mod\xE8le utilis\xE9 pour g\xE9n\xE9rer automatiquement les titres de conversation.", + auto: "Auto (Haiku)" + }, + navMappings: { + name: "Mappages de navigation style Vim", + desc: 'Un mappage par ligne. Format : "map " (actions : scrollUp, scrollDown, focusInput).' + }, + hotkeys: "Raccourcis clavier", + inlineEditHotkey: { + name: "\xC9dition en ligne", + descWithKey: "Raccourci actuel : {hotkey}", + descNoKey: "Aucun raccourci d\xE9fini", + btnChange: "Modifier", + btnSet: "D\xE9finir" + }, + openChatHotkey: { + name: "Ouvrir le chat", + descWithKey: "Raccourci actuel : {hotkey}", + descNoKey: "Aucun raccourci d\xE9fini", + btnChange: "Modifier", + btnSet: "D\xE9finir" + }, + newSessionHotkey: { + name: "Nouvelle session", + descWithKey: "Raccourci actuel : {hotkey}", + descNoKey: "Aucun raccourci d\xE9fini", + btnChange: "Modifier", + btnSet: "D\xE9finir" + }, + newTabHotkey: { + name: "Nouvel onglet", + descWithKey: "Raccourci actuel : {hotkey}", + descNoKey: "Aucun raccourci d\xE9fini", + btnChange: "Modifier", + btnSet: "D\xE9finir" + }, + closeTabHotkey: { + name: "Fermer l'onglet", + descWithKey: "Raccourci actuel : {hotkey}", + descNoKey: "Aucun raccourci d\xE9fini", + btnChange: "Modifier", + btnSet: "D\xE9finir" + }, + slashCommands: { + name: "Commandes et comp\xE9tences", + desc: "D\xE9finissez des commandes et comp\xE9tences personnalis\xE9es d\xE9clench\xE9es par /nom." + }, + hiddenSlashCommands: { + name: "Commandes masqu\xE9es", + desc: "Masquer des commandes slash sp\xE9cifiques du menu d\xE9roulant. Utile pour masquer les commandes Claude Code qui ne sont pas pertinentes pour Claudian. Entrez les noms de commandes sans le slash initial, un par ligne.", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "Serveurs MCP", + desc: "Configurez les serveurs Model Context Protocol pour \xE9tendre les capacit\xE9s de Claude avec des outils et sources de donn\xE9es externes. Les serveurs avec mode de sauvegarde de contexte n\xE9cessitent une @mention pour s'activer." + }, + plugins: { + name: "Plugins Claude Code", + desc: "Activez ou d\xE9sactivez les plugins Claude Code d\xE9couverts dans ~/.claude/plugins. Les plugins activ\xE9s sont stock\xE9s par coffre." + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "S\xE9curit\xE9", + loadUserSettings: { + name: "Charger les param\xE8tres utilisateur Claude", + desc: "Charge ~/.claude/settings.json. Lorsqu'activ\xE9, les r\xE8gles de permission de l'utilisateur peuvent contourner le mode s\xE9curis\xE9." + }, + enableBlocklist: { + name: "Activer la liste noire de commandes", + desc: "Bloque les commandes bash potentiellement dangereuses" + }, + blockedCommands: { + name: "Commandes bloqu\xE9es ({platform})", + desc: "Mod\xE8les \xE0 bloquer sur {platform} (un par ligne). Supporte les expressions r\xE9guli\xE8res.", + unixName: "Commandes bloqu\xE9es (Unix/Git Bash)", + unixDesc: "Les mod\xE8les Unix sont \xE9galement bloqu\xE9s sur Windows car Git Bash peut les appeler." + }, + exportPaths: { + name: "Chemins d'exportation autoris\xE9s", + desc: "Chemins en dehors du coffre o\xF9 les fichiers peuvent \xEAtre export\xE9s (un par ligne). Supporte ~ pour le r\xE9pertoire home." + }, + environment: "Environnement", + customVariables: { + name: "Variables personnalis\xE9es", + desc: "Variables d'environnement pour Claude SDK (format KEY=VALUE, une par ligne). Pr\xE9fixe export support\xE9." + }, + envSnippets: { + name: "Snippets", + addBtn: "Ajouter un extrait", + noSnippets: "Aucun extrait d'environnement enregistr\xE9. Cliquez sur + pour sauvegarder votre configuration actuelle.", + nameRequired: "Veuillez entrer un nom pour l'extrait", + modal: { + titleEdit: "Modifier l'extrait", + titleSave: "Sauvegarder l'extrait", + name: "Nom", + namePlaceholder: "Un nom descriptif pour cette configuration", + description: "Description", + descPlaceholder: "Description optionnelle", + envVars: "Variables d'environnement", + envVarsPlaceholder: "Format KEY=VALUE, une par ligne (pr\xE9fixe export support\xE9)", + save: "Enregistrer", + update: "Mettre \xE0 jour", + cancel: "Annuler" + } + }, + customContextLimits: { + name: "Limites de contexte personnalis\xE9es", + desc: "D\xE9finissez les tailles de fen\xEAtre de contexte pour vos mod\xE8les personnalis\xE9s. Laissez vide pour utiliser la valeur par d\xE9faut (200k tokens).", + invalid: "Format invalide. Utilisez : 256k, 1m ou nombre exact (1000-10000000)." + }, + advanced: "Avanc\xE9", + show1MModel: { + name: "Activer Sonnet avec fen\xEAtre de contexte de 1M", + desc: "Remplacer Sonnet standard par Sonnet (1M) dans le s\xE9lecteur de mod\xE8les. M\xEAme tarif sous 200k tokens. N\xE9cessite un abonnement Max." + }, + enableChrome: { + name: "Activer l'extension Chrome", + desc: "Permettre \xE0 Claude d'interagir avec Chrome via l'extension claude-in-chrome. L'extension doit \xEAtre install\xE9e. N\xE9cessite un red\xE9marrage de session." + }, + maxTabs: { + name: "Maximum d'onglets de chat", + desc: "Nombre maximum d'onglets de chat simultan\xE9s (3-10). Chaque onglet utilise une session Claude s\xE9par\xE9e.", + warning: "Plus de 5 onglets peut affecter les performances et l'utilisation de la m\xE9moire." + }, + tabBarPosition: { + name: "Position de la barre d'onglets", + desc: "Choisissez o\xF9 afficher les badges d'onglets et les boutons d'action", + input: "Au-dessus de la saisie (par d\xE9faut)", + header: "Dans l'en-t\xEAte" + }, + enableAutoScroll: { + name: "D\xE9filement automatique pendant le streaming", + desc: "D\xE9filer automatiquement vers le bas pendant que Claude diffuse les r\xE9ponses. D\xE9sactiver pour rester en haut et lire depuis le d\xE9but." + }, + openInMainTab: { + name: "Ouvrir dans la zone d'\xE9diteur principale", + desc: "Ouvrir le panneau de chat comme un onglet principal dans la zone d'\xE9diteur centrale au lieu de la barre lat\xE9rale droite" + }, + cliPath: { + name: "Chemin CLI Claude", + desc: "Chemin personnalis\xE9 vers Claude Code CLI. Laisser vide pour la d\xE9tection automatique.", + descWindows: "Pour l'installateur natif, utilisez claude.exe. Pour les installations npm/pnpm/yarn ou autres gestionnaires de paquets, utilisez le chemin cli.js (pas claude.cmd).", + descUnix: 'Collez la sortie de "which claude" \u2014 fonctionne pour les installations natives et npm/pnpm/yarn.', + validation: { + notExist: "Le chemin n'existe pas", + isDirectory: "Le chemin est un r\xE9pertoire, pas un fichier" + } + }, + language: { + name: "Langue", + desc: "Changer la langue d'affichage de l'interface du plugin" + } +}; +var fr_default2 = { + common: common4, + settings: settings4 +}; + +// src/i18n/locales/ja.json +var ja_exports = {}; +__export(ja_exports, { + common: () => common5, + default: () => ja_default2, + settings: () => settings5 +}); +var common5 = { + save: "\u4FDD\u5B58", + cancel: "\u30AD\u30E3\u30F3\u30BB\u30EB", + delete: "\u524A\u9664", + edit: "\u7DE8\u96C6", + add: "\u8FFD\u52A0", + remove: "\u524A\u9664", + clear: "\u30AF\u30EA\u30A2", + clearAll: "\u3059\u3079\u3066\u30AF\u30EA\u30A2", + loading: "\u8AAD\u307F\u8FBC\u307F\u4E2D", + error: "\u30A8\u30E9\u30FC", + success: "\u6210\u529F", + warning: "\u8B66\u544A", + confirm: "\u78BA\u8A8D", + settings: "\u8A2D\u5B9A", + advanced: "\u8A73\u7D30", + enabled: "\u6709\u52B9", + disabled: "\u7121\u52B9", + platform: "\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0" +}; +var settings5 = { + title: "Claudian \u8A2D\u5B9A", + customization: "\u30AB\u30B9\u30BF\u30DE\u30A4\u30BA", + userName: { + name: "Claudian \u306F\u3069\u306E\u3088\u3046\u306B\u547C\u3073\u307E\u3059\u304B\uFF1F", + desc: "\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u6328\u62F6\u306B\u4F7F\u7528\u3059\u308B\u540D\u524D\uFF08\u7A7A\u6B04\u3067\u4E00\u822C\u306E\u6328\u62F6\uFF09" + }, + excludedTags: { + name: "\u9664\u5916\u30BF\u30B0", + desc: "\u3053\u308C\u3089\u306E\u30BF\u30B0\u3092\u542B\u3080\u30CE\u30FC\u30C8\u306F\u81EA\u52D5\u7684\u306B\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3068\u3057\u3066\u8AAD\u307F\u8FBC\u307E\u308C\u307E\u305B\u3093\uFF081\u884C\u306B1\u3064\u3001#\u306A\u3057\uFF09" + }, + mediaFolder: { + name: "\u30E1\u30C7\u30A3\u30A2\u30D5\u30A9\u30EB\u30C0", + desc: "\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB/\u753B\u50CF\u3092\u683C\u7D0D\u3059\u308B\u30D5\u30A9\u30EB\u30C0\u3002\u30CE\u30FC\u30C8\u304C ![[image.jpg]] \u3092\u4F7F\u7528\u3059\u308B\u5834\u5408\u3001Claude \u306F\u3053\u3053\u3067\u63A2\u3057\u307E\u3059\u3002\u7A7A\u6B04\u3067\u30EA\u30DD\u30B8\u30C8\u30EA\u306E\u30EB\u30FC\u30C8\u3092\u4F7F\u7528\u3002" + }, + systemPrompt: { + name: "\u30AB\u30B9\u30BF\u30E0\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8", + desc: "\u30C7\u30D5\u30A9\u30EB\u30C8\u306E\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u306B\u8FFD\u52A0\u3055\u308C\u308B\u8FFD\u52A0\u6307\u793A" + }, + autoTitle: { + name: "\u4F1A\u8A71\u30BF\u30A4\u30C8\u30EB\u3092\u81EA\u52D5\u751F\u6210", + desc: "\u6700\u521D\u306E\u30E6\u30FC\u30B6\u30FC\u30E1\u30C3\u30BB\u30FC\u30B8\u9001\u4FE1\u5F8C\u306B\u4F1A\u8A71\u30BF\u30A4\u30C8\u30EB\u3092\u81EA\u52D5\u7684\u306B\u751F\u6210\u3057\u307E\u3059\u3002" + }, + titleModel: { + name: "\u30BF\u30A4\u30C8\u30EB\u751F\u6210\u30E2\u30C7\u30EB", + desc: "\u4F1A\u8A71\u30BF\u30A4\u30C8\u30EB\u3092\u81EA\u52D5\u751F\u6210\u3059\u308B\u305F\u3081\u306B\u4F7F\u7528\u3055\u308C\u308B\u30E2\u30C7\u30EB\u3002", + auto: "\u81EA\u52D5 (Haiku)" + }, + navMappings: { + name: "Vim\u30B9\u30BF\u30A4\u30EB\u30CA\u30D3\u30B2\u30FC\u30B7\u30E7\u30F3\u30DE\u30C3\u30D4\u30F3\u30B0", + desc: '1\u884C\u306B1\u3064\u306E\u30DE\u30C3\u30D4\u30F3\u30B0\u3002\u5F62\u5F0F\uFF1A"map <\u30AD\u30FC> <\u30A2\u30AF\u30B7\u30E7\u30F3>"\uFF08\u30A2\u30AF\u30B7\u30E7\u30F3\uFF1AscrollUp, scrollDown, focusInput\uFF09\u3002' + }, + hotkeys: "\u30DB\u30C3\u30C8\u30AD\u30FC", + inlineEditHotkey: { + name: "\u30A4\u30F3\u30E9\u30A4\u30F3\u7DE8\u96C6", + descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}", + descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A", + btnChange: "\u5909\u66F4", + btnSet: "\u8A2D\u5B9A" + }, + openChatHotkey: { + name: "\u30C1\u30E3\u30C3\u30C8\u3092\u958B\u304F", + descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}", + descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A", + btnChange: "\u5909\u66F4", + btnSet: "\u8A2D\u5B9A" + }, + newSessionHotkey: { + name: "\u65B0\u898F\u30BB\u30C3\u30B7\u30E7\u30F3", + descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}", + descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A", + btnChange: "\u5909\u66F4", + btnSet: "\u8A2D\u5B9A" + }, + newTabHotkey: { + name: "\u65B0\u898F\u30BF\u30D6", + descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}", + descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A", + btnChange: "\u5909\u66F4", + btnSet: "\u8A2D\u5B9A" + }, + closeTabHotkey: { + name: "\u30BF\u30D6\u3092\u9589\u3058\u308B", + descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}", + descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A", + btnChange: "\u5909\u66F4", + btnSet: "\u8A2D\u5B9A" + }, + slashCommands: { + name: "\u30B3\u30DE\u30F3\u30C9\u3068\u30B9\u30AD\u30EB", + desc: "/\u540D\u524D \u3067\u30C8\u30EA\u30AC\u30FC\u3055\u308C\u308B\u30AB\u30B9\u30BF\u30E0\u30B3\u30DE\u30F3\u30C9\u3068\u30B9\u30AD\u30EB\u3092\u5B9A\u7FA9\u3057\u307E\u3059\u3002" + }, + hiddenSlashCommands: { + name: "\u975E\u8868\u793A\u30B3\u30DE\u30F3\u30C9", + desc: "\u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3\u304B\u3089\u7279\u5B9A\u306E\u30B9\u30E9\u30C3\u30B7\u30E5\u30B3\u30DE\u30F3\u30C9\u3092\u975E\u8868\u793A\u306B\u3057\u307E\u3059\u3002Claudian \u306B\u95A2\u4FC2\u306E\u306A\u3044 Claude Code \u30B3\u30DE\u30F3\u30C9\u3092\u975E\u8868\u793A\u306B\u3059\u308B\u306E\u306B\u4FBF\u5229\u3067\u3059\u3002\u5148\u982D\u306E\u30B9\u30E9\u30C3\u30B7\u30E5\u306A\u3057\u3067\u30B3\u30DE\u30F3\u30C9\u540D\u30921\u884C\u306B1\u3064\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\u3002", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "MCP \u30B5\u30FC\u30D0\u30FC", + desc: "\u30E2\u30C7\u30EB\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30D7\u30ED\u30C8\u30B3\u30EB\u30B5\u30FC\u30D0\u30FC\u3092\u8A2D\u5B9A\u3057\u3001\u5916\u90E8\u30C4\u30FC\u30EB\u3084\u30C7\u30FC\u30BF\u30BD\u30FC\u30B9\u3067 Claude \u306E\u6A5F\u80FD\u3092\u62E1\u5F35\u3057\u307E\u3059\u3002\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4FDD\u5B58\u30E2\u30FC\u30C9\u306E\u30B5\u30FC\u30D0\u30FC\u306F @mention \u3067\u30A2\u30AF\u30C6\u30A3\u30D6\u306B\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002" + }, + plugins: { + name: "Claude Code \u30D7\u30E9\u30B0\u30A4\u30F3", + desc: "~/.claude/plugins \u304B\u3089\u691C\u51FA\u3055\u308C\u305F Claude Code \u30D7\u30E9\u30B0\u30A4\u30F3\u3092\u6709\u52B9\u5316\u307E\u305F\u306F\u7121\u52B9\u5316\u3057\u307E\u3059\u3002\u6709\u52B9\u5316\u3055\u308C\u305F\u30D7\u30E9\u30B0\u30A4\u30F3\u306F\u4FDD\u7BA1\u5EAB\u3054\u3068\u306B\u4FDD\u5B58\u3055\u308C\u307E\u3059\u3002" + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3", + loadUserSettings: { + name: "\u30E6\u30FC\u30B6\u30FCClaude\u8A2D\u5B9A\u3092\u8AAD\u307F\u8FBC\u3080", + desc: "~/.claude/settings.json \u3092\u8AAD\u307F\u8FBC\u307F\u307E\u3059\u3002\u6709\u52B9\u306B\u3059\u308B\u3068\u3001\u30E6\u30FC\u30B6\u30FC\u306E Claude Code \u8A31\u53EF\u30EB\u30FC\u30EB\u304C\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30E2\u30FC\u30C9\u3092\u30D0\u30A4\u30D1\u30B9\u3059\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002" + }, + enableBlocklist: { + name: "\u30B3\u30DE\u30F3\u30C9\u30D6\u30E9\u30C3\u30AF\u30EA\u30B9\u30C8\u3092\u6709\u52B9\u5316", + desc: "\u6F5C\u5728\u7684\u306B\u5371\u967A\u306Abash\u30B3\u30DE\u30F3\u30C9\u3092\u30D6\u30ED\u30C3\u30AF" + }, + blockedCommands: { + name: "\u30D6\u30ED\u30C3\u30AF\u3055\u308C\u305F\u30B3\u30DE\u30F3\u30C9 ({platform})", + desc: "{platform} \u3067\u30D6\u30ED\u30C3\u30AF\u3059\u308B\u30D1\u30BF\u30FC\u30F3\uFF081\u884C\u306B1\u3064\uFF09\u3002\u6B63\u898F\u8868\u73FE\u3092\u30B5\u30DD\u30FC\u30C8\u3002", + unixName: "\u30D6\u30ED\u30C3\u30AF\u3055\u308C\u305F\u30B3\u30DE\u30F3\u30C9 (Unix/Git Bash)", + unixDesc: "Git Bash\u304C\u547C\u3073\u51FA\u305B\u308B\u305F\u3081\u3001Unix\u30D1\u30BF\u30FC\u30F3\u3082Windows\u4E0A\u3067\u30D6\u30ED\u30C3\u30AF\u3055\u308C\u307E\u3059\u3002" + }, + exportPaths: { + name: "\u8A31\u53EF\u3055\u308C\u305F\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u30D1\u30B9", + desc: "\u30D5\u30A1\u30A4\u30EB\u3092\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8\u3067\u304D\u308B\u30EA\u30DD\u30B8\u30C8\u30EA\u5916\u306E\u30D1\u30B9\uFF081\u884C\u306B1\u3064\uFF09\u3002~ \u3067\u30DB\u30FC\u30E0\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3092\u30B5\u30DD\u30FC\u30C8\u3002" + }, + environment: "\u74B0\u5883", + customVariables: { + name: "\u30AB\u30B9\u30BF\u30E0\u5909\u6570", + desc: "Claude SDK\u306E\u74B0\u5883\u5909\u6570\uFF08KEY=VALUE\u5F62\u5F0F\u30011\u884C\u306B1\u3064\uFF09\u3002export\u30D7\u30EC\u30D5\u30A3\u30C3\u30AF\u30B9\u5BFE\u5FDC\u3002" + }, + envSnippets: { + name: "\u30B9\u30CB\u30DA\u30C3\u30C8", + addBtn: "\u30B9\u30CB\u30DA\u30C3\u30C8\u3092\u8FFD\u52A0", + noSnippets: "\u4FDD\u5B58\u3055\u308C\u305F\u74B0\u5883\u5909\u6570\u30B9\u30CB\u30DA\u30C3\u30C8\u306F\u3042\u308A\u307E\u305B\u3093\u3002+\u3092\u30AF\u30EA\u30C3\u30AF\u3057\u3066\u73FE\u5728\u306E\u8A2D\u5B9A\u3092\u4FDD\u5B58\u3057\u3066\u304F\u3060\u3055\u3044\u3002", + nameRequired: "\u30B9\u30CB\u30DA\u30C3\u30C8\u306E\u540D\u524D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044", + modal: { + titleEdit: "\u30B9\u30CB\u30DA\u30C3\u30C8\u3092\u7DE8\u96C6", + titleSave: "\u30B9\u30CB\u30DA\u30C3\u30C8\u3092\u4FDD\u5B58", + name: "\u540D\u524D", + namePlaceholder: "\u3053\u306E\u8A2D\u5B9A\u306E\u308F\u304B\u308A\u3084\u3059\u3044\u540D\u524D", + description: "\u8AAC\u660E", + descPlaceholder: "\u4EFB\u610F\u306E\u8AAC\u660E", + envVars: "\u74B0\u5883\u5909\u6570", + envVarsPlaceholder: "KEY=VALUE\u5F62\u5F0F\u30011\u884C\u306B1\u3064\uFF08export\u30D7\u30EC\u30D5\u30A3\u30C3\u30AF\u30B9\u5BFE\u5FDC\uFF09", + save: "\u4FDD\u5B58", + update: "\u66F4\u65B0", + cancel: "\u30AD\u30E3\u30F3\u30BB\u30EB" + } + }, + customContextLimits: { + name: "\u30AB\u30B9\u30BF\u30E0\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u5236\u9650", + desc: "\u30AB\u30B9\u30BF\u30E0\u30E2\u30C7\u30EB\u306E\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3057\u307E\u3059\u3002\u30C7\u30D5\u30A9\u30EB\u30C8\uFF08200k\u30C8\u30FC\u30AF\u30F3\uFF09\u3092\u4F7F\u7528\u3059\u308B\u5834\u5408\u306F\u7A7A\u6B04\u306E\u307E\u307E\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002", + invalid: "\u7121\u52B9\u306A\u5F62\u5F0F\u3067\u3059\u3002\u4F7F\u7528\uFF1A256k\u30011m\u3001\u307E\u305F\u306F\u6B63\u78BA\u306A\u6570\u5024\uFF081000-10000000\uFF09\u3002" + }, + advanced: "\u8A73\u7D30\u8A2D\u5B9A", + show1MModel: { + name: "1M\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6\u3092\u6301\u3064Sonnet\u3092\u6709\u52B9\u5316", + desc: "\u30E2\u30C7\u30EB\u30BB\u30EC\u30AF\u30BF\u30FC\u3067\u6A19\u6E96Sonnet\u3092 Sonnet (1M) \u306B\u7F6E\u304D\u63DB\u3048\u307E\u3059\u3002200k\u30C8\u30FC\u30AF\u30F3\u672A\u6E80\u3067\u306F\u540C\u3058\u4FA1\u683C\u3002Max\u30B5\u30D6\u30B9\u30AF\u30EA\u30D7\u30B7\u30E7\u30F3\u304C\u5FC5\u8981\u3067\u3059\u3002" + }, + enableChrome: { + name: "Chrome\u62E1\u5F35\u6A5F\u80FD\u3092\u6709\u52B9\u5316", + desc: "claude-in-chrome\u62E1\u5F35\u6A5F\u80FD\u3092\u901A\u3058\u3066Claude\u304CChrome\u3068\u9023\u643A\u3067\u304D\u308B\u3088\u3046\u306B\u3057\u307E\u3059\u3002\u62E1\u5F35\u6A5F\u80FD\u306E\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u304C\u5FC5\u8981\u3067\u3059\u3002\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u518D\u8D77\u52D5\u304C\u5FC5\u8981\u3067\u3059\u3002" + }, + maxTabs: { + name: "\u6700\u5927\u30C1\u30E3\u30C3\u30C8\u30BF\u30D6\u6570", + desc: "\u540C\u6642\u306B\u958B\u3051\u308B\u6700\u5927\u30C1\u30E3\u30C3\u30C8\u30BF\u30D6\u6570\uFF083-10\uFF09\u3002\u5404\u30BF\u30D6\u306F\u500B\u5225\u306E Claude \u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002", + warning: "5 \u30BF\u30D6\u3092\u8D85\u3048\u308B\u3068\u30D1\u30D5\u30A9\u30FC\u30DE\u30F3\u30B9\u3084\u30E1\u30E2\u30EA\u4F7F\u7528\u91CF\u306B\u5F71\u97FF\u3059\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002" + }, + tabBarPosition: { + name: "\u30BF\u30D6\u30D0\u30FC\u306E\u4F4D\u7F6E", + desc: "\u30BF\u30D6\u30D0\u30C3\u30B8\u3068\u30A2\u30AF\u30B7\u30E7\u30F3\u30DC\u30BF\u30F3\u306E\u8868\u793A\u4F4D\u7F6E\u3092\u9078\u629E", + input: "\u5165\u529B\u6B04\u306E\u4E0A\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF09", + header: "\u30D8\u30C3\u30C0\u30FC\u5185" + }, + enableAutoScroll: { + name: "\u30B9\u30C8\u30EA\u30FC\u30DF\u30F3\u30B0\u4E2D\u306E\u81EA\u52D5\u30B9\u30AF\u30ED\u30FC\u30EB", + desc: "Claude\u304C\u5FDC\u7B54\u3092\u30B9\u30C8\u30EA\u30FC\u30DF\u30F3\u30B0\u3057\u3066\u3044\u308B\u9593\u3001\u81EA\u52D5\u7684\u306B\u4E0B\u306B\u30B9\u30AF\u30ED\u30FC\u30EB\u3057\u307E\u3059\u3002\u7121\u52B9\u306B\u3059\u308B\u3068\u4E0A\u90E8\u306B\u7559\u307E\u308A\u3001\u6700\u521D\u304B\u3089\u8AAD\u3080\u3053\u3068\u304C\u3067\u304D\u307E\u3059\u3002" + }, + openInMainTab: { + name: "\u30E1\u30A4\u30F3\u30A8\u30C7\u30A3\u30BF\u9818\u57DF\u3067\u958B\u304F", + desc: "\u30C1\u30E3\u30C3\u30C8\u30D1\u30CD\u30EB\u3092\u53F3\u30B5\u30A4\u30C9\u30D0\u30FC\u3067\u306F\u306A\u304F\u3001\u4E2D\u592E\u30A8\u30C7\u30A3\u30BF\u9818\u57DF\u306E\u30E1\u30A4\u30F3\u30BF\u30D6\u3068\u3057\u3066\u958B\u304D\u307E\u3059" + }, + cliPath: { + name: "Claude CLI \u30D1\u30B9", + desc: "Claude Code CLI \u306E\u30AB\u30B9\u30BF\u30E0\u30D1\u30B9\u3002\u7A7A\u6B04\u3067\u81EA\u52D5\u691C\u51FA\u3092\u4F7F\u7528\u3002", + descWindows: "\u30CD\u30A4\u30C6\u30A3\u30D6\u30A4\u30F3\u30B9\u30C8\u30FC\u30E9\u30FC\u306E\u5834\u5408\u306F claude.exe \u3092\u4F7F\u7528\u3002npm/pnpm/yarn \u3084\u305D\u306E\u4ED6\u306E\u30D1\u30C3\u30B1\u30FC\u30B8\u30DE\u30CD\u30FC\u30B8\u30E3\u30FC\u3067\u306E\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u306E\u5834\u5408\u306F cli.js \u30D1\u30B9\u3092\u4F7F\u7528\uFF08claude.cmd \u3067\u306F\u306A\u3044\uFF09\u3002", + descUnix: '"which claude" \u306E\u51FA\u529B\u3092\u8CBC\u308A\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044 - \u30CD\u30A4\u30C6\u30A3\u30D6\u3068 npm/pnpm/yarn \u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u306E\u4E21\u65B9\u3067\u52D5\u4F5C\u3057\u307E\u3059\u3002', + validation: { + notExist: "\u30D1\u30B9\u304C\u5B58\u5728\u3057\u307E\u305B\u3093", + isDirectory: "\u30D1\u30B9\u306F\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3067\u30D5\u30A1\u30A4\u30EB\u3067\u306F\u3042\u308A\u307E\u305B\u3093" + } + }, + language: { + name: "\u8A00\u8A9E", + desc: "\u30D7\u30E9\u30B0\u30A4\u30F3\u30A4\u30F3\u30BF\u30FC\u30D5\u30A7\u30FC\u30B9\u306E\u8868\u793A\u8A00\u8A9E\u3092\u5909\u66F4" + } +}; +var ja_default2 = { + common: common5, + settings: settings5 +}; + +// src/i18n/locales/ko.json +var ko_exports = {}; +__export(ko_exports, { + common: () => common6, + default: () => ko_default2, + settings: () => settings6 +}); +var common6 = { + save: "\uC800\uC7A5", + cancel: "\uCDE8\uC18C", + delete: "\uC0AD\uC81C", + edit: "\uD3B8\uC9D1", + add: "\uCD94\uAC00", + remove: "\uC81C\uAC70", + clear: "\uC9C0\uC6B0\uAE30", + clearAll: "\uBAA8\uB450 \uC9C0\uC6B0\uAE30", + loading: "\uB85C\uB529 \uC911", + error: "\uC624\uB958", + success: "\uC131\uACF5", + warning: "\uACBD\uACE0", + confirm: "\uD655\uC778", + settings: "\uC124\uC815", + advanced: "\uACE0\uAE09", + enabled: "\uD65C\uC131\uD654", + disabled: "\uBE44\uD65C\uC131\uD654", + platform: "\uD50C\uB7AB\uD3FC" +}; +var settings6 = { + title: "Claudian \uC124\uC815", + customization: "\uC0AC\uC6A9\uC790 \uC815\uC758", + userName: { + name: "Claudian\uC774 \uB2F9\uC2E0\uC744 \uC5B4\uB5BB\uAC8C \uBD88\uB7EC\uC57C \uD569\uB2C8\uAE4C?", + desc: "\uAC1C\uC778\uD654\uB41C \uC778\uC0AC\uC5D0 \uC0AC\uC6A9\uD560 \uC774\uB984 (\uBE44\uC6CC\uB450\uBA74 \uC77C\uBC18 \uC778\uC0AC)" + }, + excludedTags: { + name: "\uC81C\uC678 \uD0DC\uADF8", + desc: "\uC774 \uD0DC\uADF8\uAC00 \uD3EC\uD568\uB41C \uB178\uD2B8\uB294 \uC790\uB3D9\uC73C\uB85C \uCEE8\uD14D\uC2A4\uD2B8\uB85C \uB85C\uB4DC\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4 (\uD55C \uC904\uC5D0 \uD558\uB098, # \uC81C\uC678)" + }, + mediaFolder: { + name: "\uBBF8\uB514\uC5B4 \uD3F4\uB354", + desc: "\uCCA8\uBD80 \uD30C\uC77C/\uC774\uBBF8\uC9C0\uB97C \uC800\uC7A5\uD560 \uD3F4\uB354. \uB178\uD2B8\uAC00 ![[image.jpg]]\uB97C \uC0AC\uC6A9\uD560 \uB54C Claude\uAC00 \uC5EC\uAE30\uC11C \uCC3E\uC2B5\uB2C8\uB2E4. \uBE44\uC6CC\uB450\uBA74 \uC800\uC7A5\uC18C \uB8E8\uD2B8 \uC0AC\uC6A9." + }, + systemPrompt: { + name: "\uCEE4\uC2A4\uD140 \uC2DC\uC2A4\uD15C \uD504\uB86C\uD504\uD2B8", + desc: "\uAE30\uBCF8 \uC2DC\uC2A4\uD15C \uD504\uB86C\uD504\uD2B8\uC5D0 \uCD94\uAC00\uB418\uB294 \uCD94\uAC00 \uC9C0\uCE68" + }, + autoTitle: { + name: "\uB300\uD654 \uC81C\uBAA9 \uC790\uB3D9 \uC0DD\uC131", + desc: "\uCCAB \uBC88\uC9F8 \uC0AC\uC6A9\uC790 \uBA54\uC2DC\uC9C0 \uC804\uC1A1 \uD6C4 \uC790\uB3D9\uC73C\uB85C \uB300\uD654 \uC81C\uBAA9\uC744 \uC0DD\uC131\uD569\uB2C8\uB2E4." + }, + titleModel: { + name: "\uC81C\uBAA9 \uC0DD\uC131 \uBAA8\uB378", + desc: "\uB300\uD654 \uC81C\uBAA9\uC744 \uC790\uB3D9 \uC0DD\uC131\uD558\uB294 \uB370 \uC0AC\uC6A9\uB418\uB294 \uBAA8\uB378.", + auto: "\uC790\uB3D9 (Haiku)" + }, + navMappings: { + name: "Vim \uC2A4\uD0C0\uC77C \uB124\uBE44\uAC8C\uC774\uC158 \uB9E4\uD551", + desc: '\uD55C \uC904\uC5D0 \uD558\uB098\uC758 \uB9E4\uD551. \uD615\uC2DD: "map <\uD0A4> <\uB3D9\uC791>" (\uB3D9\uC791: scrollUp, scrollDown, focusInput).' + }, + hotkeys: "\uB2E8\uCD95\uD0A4", + inlineEditHotkey: { + name: "\uC778\uB77C\uC778 \uD3B8\uC9D1", + descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}", + descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815", + btnChange: "\uBCC0\uACBD", + btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815" + }, + openChatHotkey: { + name: "\uCC44\uD305 \uC5F4\uAE30", + descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}", + descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815", + btnChange: "\uBCC0\uACBD", + btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815" + }, + newSessionHotkey: { + name: "\uC0C8 \uC138\uC158", + descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}", + descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815", + btnChange: "\uBCC0\uACBD", + btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815" + }, + newTabHotkey: { + name: "\uC0C8 \uD0ED", + descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}", + descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815", + btnChange: "\uBCC0\uACBD", + btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815" + }, + closeTabHotkey: { + name: "\uD0ED \uB2EB\uAE30", + descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}", + descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815", + btnChange: "\uBCC0\uACBD", + btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815" + }, + slashCommands: { + name: "\uBA85\uB839\uC5B4\uC640 \uC2A4\uD0AC", + desc: "/\uC774\uB984\uC73C\uB85C \uD2B8\uB9AC\uAC70\uB418\uB294 \uCEE4\uC2A4\uD140 \uBA85\uB839\uC5B4\uC640 \uC2A4\uD0AC\uC744 \uC815\uC758\uD569\uB2C8\uB2E4." + }, + hiddenSlashCommands: { + name: "\uC228\uACA8\uC9C4 \uBA85\uB839\uC5B4", + desc: "\uB4DC\uB86D\uB2E4\uC6B4\uC5D0\uC11C \uD2B9\uC815 \uC2AC\uB798\uC2DC \uBA85\uB839\uC5B4\uB97C \uC228\uAE41\uB2C8\uB2E4. Claudian\uACFC \uAD00\uB828 \uC5C6\uB294 Claude Code \uBA85\uB839\uC5B4\uB97C \uC228\uAE30\uB294 \uB370 \uC720\uC6A9\uD569\uB2C8\uB2E4. \uC55E\uC758 \uC2AC\uB798\uC2DC \uC5C6\uC774 \uD55C \uC904\uC5D0 \uD558\uB098\uC529 \uBA85\uB839\uC5B4 \uC774\uB984\uC744 \uC785\uB825\uD558\uC138\uC694.", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "MCP \uC11C\uBC84", + desc: "\uBAA8\uB378 \uCEE8\uD14D\uC2A4\uD2B8 \uD504\uB85C\uD1A0\uCF5C \uC11C\uBC84\uB97C \uC124\uC815\uD558\uC5EC \uC678\uBD80 \uB3C4\uAD6C\uC640 \uB370\uC774\uD130 \uC18C\uC2A4\uB85C Claude\uC758 \uAE30\uB2A5\uC744 \uD655\uC7A5\uD569\uB2C8\uB2E4. \uCEE8\uD14D\uC2A4\uD2B8 \uC800\uC7A5 \uBAA8\uB4DC \uC11C\uBC84\uB294 @mention\uC73C\uB85C \uD65C\uC131\uD654\uD574\uC57C \uD569\uB2C8\uB2E4." + }, + plugins: { + name: "Claude Code \uD50C\uB7EC\uADF8\uC778", + desc: "~/.claude/plugins\uC5D0\uC11C \uBC1C\uACAC\uB41C Claude Code \uD50C\uB7EC\uADF8\uC778\uC744 \uD65C\uC131\uD654 \uB610\uB294 \uBE44\uD65C\uC131\uD654\uD569\uB2C8\uB2E4. \uD65C\uC131\uD654\uB41C \uD50C\uB7EC\uADF8\uC778\uC740 \uBCFC\uD2B8\uBCC4\uB85C \uC800\uC7A5\uB429\uB2C8\uB2E4." + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "\uBCF4\uC548", + loadUserSettings: { + name: "\uC0AC\uC6A9\uC790 Claude \uC124\uC815 \uB85C\uB4DC", + desc: "~/.claude/settings.json\uC744 \uB85C\uB4DC\uD569\uB2C8\uB2E4. \uD65C\uC131\uD654\uD558\uBA74 \uC0AC\uC6A9\uC790\uC758 Claude Code \uD5C8\uC6A9 \uADDC\uCE59\uC774 \uBCF4\uC548 \uBAA8\uB4DC\uB97C \uC6B0\uD68C\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4." + }, + enableBlocklist: { + name: "\uBA85\uB839\uC5B4 \uBE14\uB799\uB9AC\uC2A4\uD2B8 \uD65C\uC131\uD654", + desc: "\uC7A0\uC7AC\uC801\uC73C\uB85C \uC704\uD5D8\uD55C bash \uBA85\uB839\uC5B4 \uCC28\uB2E8" + }, + blockedCommands: { + name: "\uCC28\uB2E8\uB41C \uBA85\uB839\uC5B4 ({platform})", + desc: "{platform}\uC5D0\uC11C \uCC28\uB2E8\uD560 \uD328\uD134 (\uD55C \uC904\uC5D0 \uD558\uB098). \uC815\uADDC\uC2DD \uC9C0\uC6D0.", + unixName: "\uCC28\uB2E8\uB41C \uBA85\uB839\uC5B4 (Unix/Git Bash)", + unixDesc: "Git Bash\uAC00 \uD638\uCD9C\uD560 \uC218 \uC788\uC73C\uBBC0\uB85C Unix \uD328\uD134\uB3C4 Windows\uC5D0\uC11C \uCC28\uB2E8\uB429\uB2C8\uB2E4." + }, + exportPaths: { + name: "\uD5C8\uC6A9\uB41C \uB0B4\uBCF4\uB0B4\uAE30 \uACBD\uB85C", + desc: "\uD30C\uC77C\uC744 \uB0B4\uBCF4\uB0BC \uC218 \uC788\uB294 \uC800\uC7A5\uC18C \uC678\uBD80 \uACBD\uB85C (\uD55C \uC904\uC5D0 \uD558\uB098). ~\uB85C \uD648 \uB514\uB809\uD1A0\uB9AC \uC9C0\uC6D0." + }, + environment: "\uD658\uACBD", + customVariables: { + name: "\uCEE4\uC2A4\uD140 \uBCC0\uC218", + desc: "Claude SDK \uD658\uACBD \uBCC0\uC218 (KEY=VALUE \uD615\uC2DD, \uD55C \uC904\uC5D0 \uD558\uB098). export \uC811\uB450\uC0AC \uC9C0\uC6D0." + }, + envSnippets: { + name: "\uC2A4\uB2C8\uD3AB", + addBtn: "\uC2A4\uB2C8\uD3AB \uCD94\uAC00", + noSnippets: "\uC800\uC7A5\uB41C \uD658\uACBD \uBCC0\uC218 \uC2A4\uB2C8\uD3AB\uC774 \uC5C6\uC2B5\uB2C8\uB2E4. +\uB97C \uD074\uB9AD\uD558\uC5EC \uD604\uC7AC \uAD6C\uC131\uC744 \uC800\uC7A5\uD558\uC138\uC694.", + nameRequired: "\uC2A4\uB2C8\uD3AB \uC774\uB984\uC744 \uC785\uB825\uD558\uC138\uC694", + modal: { + titleEdit: "\uC2A4\uB2C8\uD3AB \uD3B8\uC9D1", + titleSave: "\uC2A4\uB2C8\uD3AB \uC800\uC7A5", + name: "\uC774\uB984", + namePlaceholder: "\uC774 \uAD6C\uC131\uC5D0 \uB300\uD55C \uC124\uBA85\uC801\uC778 \uC774\uB984", + description: "\uC124\uBA85", + descPlaceholder: "\uC120\uD0DD\uC801 \uC124\uBA85", + envVars: "\uD658\uACBD \uBCC0\uC218", + envVarsPlaceholder: "KEY=VALUE \uD615\uC2DD, \uD55C \uC904\uC5D0 \uD558\uB098 (export \uC811\uB450\uC0AC \uC9C0\uC6D0)", + save: "\uC800\uC7A5", + update: "\uC5C5\uB370\uC774\uD2B8", + cancel: "\uCDE8\uC18C" + } + }, + customContextLimits: { + name: "\uC0AC\uC6A9\uC790 \uC815\uC758 \uCEE8\uD14D\uC2A4\uD2B8 \uC81C\uD55C", + desc: "\uC0AC\uC6A9\uC790 \uC815\uC758 \uBAA8\uB378\uC758 \uCEE8\uD14D\uC2A4\uD2B8 \uCC3D \uD06C\uAE30\uB97C \uC124\uC815\uD569\uB2C8\uB2E4. \uAE30\uBCF8\uAC12(200k \uD1A0\uD070)\uC744 \uC0AC\uC6A9\uD558\uB824\uBA74 \uBE44\uC6CC\uB450\uC138\uC694.", + invalid: "\uC798\uBABB\uB41C \uD615\uC2DD\uC785\uB2C8\uB2E4. \uC0AC\uC6A9: 256k, 1m \uB610\uB294 \uC815\uD655\uD55C \uC22B\uC790(1000-10000000)." + }, + advanced: "\uACE0\uAE09", + show1MModel: { + name: "1M \uCEE8\uD14D\uC2A4\uD2B8 \uCC3D\uC744 \uAC00\uC9C4 Sonnet \uD65C\uC131\uD654", + desc: "\uBAA8\uB378 \uC120\uD0DD\uAE30\uC5D0\uC11C \uD45C\uC900 Sonnet\uC744 Sonnet (1M)\uC73C\uB85C \uAD50\uCCB4\uD569\uB2C8\uB2E4. 200k \uD1A0\uD070 \uBBF8\uB9CC\uC5D0\uC11C\uB294 \uB3D9\uC77C\uD55C \uAC00\uACA9. Max \uAD6C\uB3C5\uC774 \uD544\uC694\uD569\uB2C8\uB2E4." + }, + enableChrome: { + name: "Chrome \uD655\uC7A5 \uD504\uB85C\uADF8\uB7A8 \uD65C\uC131\uD654", + desc: "claude-in-chrome \uD655\uC7A5 \uD504\uB85C\uADF8\uB7A8\uC744 \uD1B5\uD574 Claude\uAC00 Chrome\uACFC \uC0C1\uD638\uC791\uC6A9\uD560 \uC218 \uC788\uB3C4\uB85D \uD569\uB2C8\uB2E4. \uD655\uC7A5 \uD504\uB85C\uADF8\uB7A8\uC774 \uC124\uCE58\uB418\uC5B4 \uC788\uC5B4\uC57C \uD569\uB2C8\uB2E4. \uC138\uC158 \uC7AC\uC2DC\uC791\uC774 \uD544\uC694\uD569\uB2C8\uB2E4." + }, + maxTabs: { + name: "\uCD5C\uB300 \uCC44\uD305 \uD0ED \uC218", + desc: "\uB3D9\uC2DC\uC5D0 \uC5F4 \uC218 \uC788\uB294 \uCD5C\uB300 \uCC44\uD305 \uD0ED \uC218(3-10). \uAC01 \uD0ED\uC740 \uBCC4\uB3C4\uC758 Claude \uC138\uC158\uC744 \uC0AC\uC6A9\uD569\uB2C8\uB2E4.", + warning: "5\uAC1C \uD0ED\uC744 \uCD08\uACFC\uD558\uBA74 \uC131\uB2A5 \uBC0F \uBA54\uBAA8\uB9AC \uC0AC\uC6A9\uB7C9\uC5D0 \uC601\uD5A5\uC744 \uC904 \uC218 \uC788\uC2B5\uB2C8\uB2E4." + }, + tabBarPosition: { + name: "\uD0ED \uBC14 \uC704\uCE58", + desc: "\uD0ED \uBC30\uC9C0\uC640 \uC791\uC5C5 \uBC84\uD2BC\uC758 \uD45C\uC2DC \uC704\uCE58 \uC120\uD0DD", + input: "\uC785\uB825\uCC3D \uC704(\uAE30\uBCF8\uAC12)", + header: "\uD5E4\uB354\uC5D0" + }, + enableAutoScroll: { + name: "\uC2A4\uD2B8\uB9AC\uBC0D \uC911 \uC790\uB3D9 \uC2A4\uD06C\uB864", + desc: "Claude\uAC00 \uC751\uB2F5\uC744 \uC2A4\uD2B8\uB9AC\uBC0D\uD558\uB294 \uB3D9\uC548 \uC790\uB3D9\uC73C\uB85C \uC544\uB798\uB85C \uC2A4\uD06C\uB864\uD569\uB2C8\uB2E4. \uBE44\uD65C\uC131\uD654\uD558\uBA74 \uC0C1\uB2E8\uC5D0 \uBA38\uBB3C\uB7EC \uCC98\uC74C\uBD80\uD130 \uC77D\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4." + }, + openInMainTab: { + name: "\uBA54\uC778 \uD3B8\uC9D1\uAE30 \uC601\uC5ED\uC5D0\uC11C \uC5F4\uAE30", + desc: "\uCC44\uD305 \uD328\uB110\uC744 \uC624\uB978\uCABD \uC0AC\uC774\uB4DC\uBC14\uAC00 \uC544\uB2CC \uC911\uC559 \uD3B8\uC9D1\uAE30 \uC601\uC5ED\uC758 \uBA54\uC778 \uD0ED\uC73C\uB85C \uC5FD\uB2C8\uB2E4" + }, + cliPath: { + name: "Claude CLI \uACBD\uB85C", + desc: "Claude Code CLI\uC758 \uC0AC\uC6A9\uC790 \uC815\uC758 \uACBD\uB85C. \uBE44\uC6CC\uB450\uBA74 \uC790\uB3D9 \uAC10\uC9C0 \uC0AC\uC6A9.", + descWindows: "\uB124\uC774\uD2F0\uBE0C \uC124\uCE58 \uD504\uB85C\uADF8\uB7A8\uC758 \uACBD\uC6B0 claude.exe\uB97C \uC0AC\uC6A9\uD558\uC138\uC694. npm/pnpm/yarn \uB610\uB294 \uAE30\uD0C0 \uD328\uD0A4\uC9C0 \uAD00\uB9AC\uC790 \uC124\uCE58\uC758 \uACBD\uC6B0 cli.js \uACBD\uB85C\uB97C \uC0AC\uC6A9\uD558\uC138\uC694 (claude.cmd\uAC00 \uC544\uB2D8).", + descUnix: '"which claude"\uC758 \uCD9C\uB825\uC744 \uBD99\uC5EC\uB123\uC73C\uC138\uC694 - \uB124\uC774\uD2F0\uBE0C \uBC0F npm/pnpm/yarn \uC124\uCE58 \uBAA8\uB450\uC5D0\uC11C \uC791\uB3D9\uD569\uB2C8\uB2E4.', + validation: { + notExist: "\uACBD\uB85C\uAC00 \uC874\uC7AC\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4", + isDirectory: "\uACBD\uB85C\uAC00 \uB514\uB809\uD1A0\uB9AC\uC785\uB2C8\uB2E4 \uD30C\uC77C\uC774 \uC544\uB2D9\uB2C8\uB2E4" + } + }, + language: { + name: "\uC5B8\uC5B4", + desc: "\uD50C\uB7EC\uADF8\uC778 \uC778\uD130\uD398\uC774\uC2A4\uC758 \uD45C\uC2DC \uC5B8\uC5B4 \uBCC0\uACBD" + } +}; +var ko_default2 = { + common: common6, + settings: settings6 +}; + +// src/i18n/locales/pt.json +var pt_exports = {}; +__export(pt_exports, { + common: () => common7, + default: () => pt_default2, + settings: () => settings7 +}); +var common7 = { + save: "Salvar", + cancel: "Cancelar", + delete: "Excluir", + edit: "Editar", + add: "Adicionar", + remove: "Remover", + clear: "Limpar", + clearAll: "Limpar tudo", + loading: "Carregando", + error: "Erro", + success: "Sucesso", + warning: "Aviso", + confirm: "Confirmar", + settings: "Configura\xE7\xF5es", + advanced: "Avan\xE7ado", + enabled: "Ativado", + disabled: "Desativado", + platform: "Plataforma" +}; +var settings7 = { + title: "Configura\xE7\xF5es do Claudian", + customization: "Personaliza\xE7\xE3o", + userName: { + name: "Como o Claudian deve cham\xE1-lo?", + desc: "Seu nome para sauda\xE7\xF5es personalizadas (deixe vazio para sauda\xE7\xF5es gen\xE9ricas)" + }, + excludedTags: { + name: "Tags exclu\xEDdas", + desc: "Notas com estas tags n\xE3o ser\xE3o carregadas automaticamente como contexto (uma por linha, sem #)" + }, + mediaFolder: { + name: "Pasta de m\xEDdia", + desc: "Pasta contendo anexos/imagens. Quando notas usam ![[image.jpg]], Claude procurar\xE1 aqui. Deixe vazio para a raiz do reposit\xF3rio." + }, + systemPrompt: { + name: "Prompt de sistema personalizado", + desc: "Instru\xE7\xF5es adicionais anexadas ao prompt de sistema padr\xE3o" + }, + autoTitle: { + name: "Gerar automaticamente t\xEDtulos de conversa", + desc: "Gera automaticamente t\xEDtulos de conversa ap\xF3s a primeira mensagem do usu\xE1rio." + }, + titleModel: { + name: "Modelo de gera\xE7\xE3o de t\xEDtulo", + desc: "Modelo usado para gerar automaticamente t\xEDtulos de conversa.", + auto: "Auto (Haiku)" + }, + navMappings: { + name: "Mapeamentos de navega\xE7\xE3o estilo Vim", + desc: 'Um mapeamento por linha. Formato: "map " (a\xE7\xF5es: scrollUp, scrollDown, focusInput).' + }, + hotkeys: "Atalhos", + inlineEditHotkey: { + name: "Edi\xE7\xE3o em linha", + descWithKey: "Atalho atual: {hotkey}", + descNoKey: "Nenhum atalho definido", + btnChange: "Alterar", + btnSet: "Definir" + }, + openChatHotkey: { + name: "Abrir chat", + descWithKey: "Atalho atual: {hotkey}", + descNoKey: "Nenhum atalho definido", + btnChange: "Alterar", + btnSet: "Definir" + }, + newSessionHotkey: { + name: "Nova sess\xE3o", + descWithKey: "Atalho atual: {hotkey}", + descNoKey: "Nenhum atalho definido", + btnChange: "Alterar", + btnSet: "Definir" + }, + newTabHotkey: { + name: "Nova aba", + descWithKey: "Atalho atual: {hotkey}", + descNoKey: "Nenhum atalho definido", + btnChange: "Alterar", + btnSet: "Definir" + }, + closeTabHotkey: { + name: "Fechar aba", + descWithKey: "Atalho atual: {hotkey}", + descNoKey: "Nenhum atalho definido", + btnChange: "Alterar", + btnSet: "Definir" + }, + slashCommands: { + name: "Comandos e habilidades", + desc: "Defina comandos e habilidades personalizados acionados por /nome." + }, + hiddenSlashCommands: { + name: "Comandos ocultos", + desc: "Ocultar comandos slash espec\xEDficos do menu suspenso. \xDAtil para ocultar comandos do Claude Code que n\xE3o s\xE3o relevantes para o Claudian. Digite os nomes dos comandos sem a barra inicial, um por linha.", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "Servidores MCP", + desc: "Configure servidores Model Context Protocol para estender as capacidades do Claude com ferramentas e fontes de dados externas. Servidores com modo de salvamento de contexto exigem @mention para ativar." + }, + plugins: { + name: "Plugins do Claude Code", + desc: "Ative ou desative plugins do Claude Code descobertos em ~/.claude/plugins. Plugins ativados s\xE3o armazenados por cofre." + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "Seguran\xE7a", + loadUserSettings: { + name: "Carregar configura\xE7\xF5es do usu\xE1rio Claude", + desc: "Carrega ~/.claude/settings.json. Quando habilitado, as regras de permiss\xE3o do usu\xE1rio podem ignorar o modo seguro." + }, + enableBlocklist: { + name: "Habilitar lista negra de comandos", + desc: "Bloqueia comandos bash potencialmente perigosos" + }, + blockedCommands: { + name: "Comandos bloqueados ({platform})", + desc: "Padr\xF5es para bloquear em {platform} (um por linha). Suporta express\xF5es regulares.", + unixName: "Comandos bloqueados (Unix/Git Bash)", + unixDesc: "Padr\xF5es Unix tamb\xE9m bloqueados no Windows porque Git Bash pode invoc\xE1-los." + }, + exportPaths: { + name: "Caminhos de exporta\xE7\xE3o permitidos", + desc: "Caminhos fora do reposit\xF3rio onde arquivos podem ser exportados (um por linha). Suporta ~ para diret\xF3rio home." + }, + environment: "Ambiente", + customVariables: { + name: "Vari\xE1veis personalizadas", + desc: "Vari\xE1veis de ambiente para Claude SDK (formato KEY=VALUE, uma por linha). Prefixo export suportado." + }, + envSnippets: { + name: "Snippets", + addBtn: "Adicionar snippet", + noSnippets: "Nenhum snippet de ambiente salvo. Clique em + para salvar sua configura\xE7\xE3o atual.", + nameRequired: "Por favor, insira um nome para o snippet", + modal: { + titleEdit: "Editar snippet", + titleSave: "Salvar snippet", + name: "Nome", + namePlaceholder: "Um nome descritivo para esta configura\xE7\xE3o", + description: "Descri\xE7\xE3o", + descPlaceholder: "Descri\xE7\xE3o opcional", + envVars: "Vari\xE1veis de ambiente", + envVarsPlaceholder: "Formato KEY=VALUE, uma por linha (prefixo export suportado)", + save: "Salvar", + update: "Atualizar", + cancel: "Cancelar" + } + }, + customContextLimits: { + name: "Limites de contexto personalizados", + desc: "Defina tamanhos de janela de contexto para seus modelos personalizados. Deixe vazio para usar o padr\xE3o (200k tokens).", + invalid: "Formato inv\xE1lido. Use: 256k, 1m ou n\xFAmero exato (1000-10000000)." + }, + advanced: "Avan\xE7ado", + show1MModel: { + name: "Habilitar Sonnet com janela de contexto de 1M", + desc: "Substituir Sonnet padr\xE3o por Sonnet (1M) no seletor de modelos. Mesmo pre\xE7o abaixo de 200k tokens. Requer assinatura Max." + }, + enableChrome: { + name: "Habilitar extens\xE3o do Chrome", + desc: "Permitir que o Claude interaja com o Chrome atrav\xE9s da extens\xE3o claude-in-chrome. Requer que a extens\xE3o esteja instalada. Requer rein\xEDcio de sess\xE3o." + }, + maxTabs: { + name: "M\xE1ximo de abas de chat", + desc: "N\xFAmero m\xE1ximo de abas de chat simult\xE2neas (3-10). Cada aba usa uma sess\xE3o Claude separada.", + warning: "Mais de 5 abas pode afetar o desempenho e o uso de mem\xF3ria." + }, + tabBarPosition: { + name: "Posi\xE7\xE3o da barra de abas", + desc: "Escolha onde exibir os emblemas de abas e bot\xF5es de a\xE7\xE3o", + input: "Acima da entrada (padr\xE3o)", + header: "No cabe\xE7alho" + }, + enableAutoScroll: { + name: "Rolagem autom\xE1tica durante streaming", + desc: "Rolar automaticamente para baixo enquanto o Claude transmite respostas. Desativar para ficar no topo e ler desde o in\xEDcio." + }, + openInMainTab: { + name: "Abrir na \xE1rea do editor principal", + desc: "Abrir o painel de chat como uma aba principal na \xE1rea do editor central em vez da barra lateral direita" + }, + cliPath: { + name: "Caminho CLI Claude", + desc: "Caminho personalizado para Claude Code CLI. Deixe vazio para detec\xE7\xE3o autom\xE1tica.", + descWindows: "Para o instalador nativo, use claude.exe. Para instala\xE7\xF5es com npm/pnpm/yarn ou outros gerenciadores de pacotes, use o caminho cli.js (n\xE3o claude.cmd).", + descUnix: 'Cole a sa\xEDda de "which claude" \u2014 funciona tanto para instala\xE7\xF5es nativas quanto npm/pnpm/yarn.', + validation: { + notExist: "Caminho n\xE3o existe", + isDirectory: "Caminho \xE9 um diret\xF3rio, n\xE3o um arquivo" + } + }, + language: { + name: "Idioma", + desc: "Alterar o idioma de exibi\xE7\xE3o da interface do plugin" + } +}; +var pt_default2 = { + common: common7, + settings: settings7 +}; + +// src/i18n/locales/ru.json +var ru_exports = {}; +__export(ru_exports, { + common: () => common8, + default: () => ru_default2, + settings: () => settings8 +}); +var common8 = { + save: "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C", + cancel: "\u041E\u0442\u043C\u0435\u043D\u0430", + delete: "\u0423\u0434\u0430\u043B\u0438\u0442\u044C", + edit: "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C", + add: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C", + remove: "\u0423\u0434\u0430\u043B\u0438\u0442\u044C", + clear: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C", + clearAll: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0432\u0441\u0451", + loading: "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430", + error: "\u041E\u0448\u0438\u0431\u043A\u0430", + success: "\u0423\u0441\u043F\u0435\u0445", + warning: "\u041F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435", + confirm: "\u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u044C", + settings: "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438", + advanced: "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E", + enabled: "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E", + disabled: "\u041E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u043E", + platform: "\u041F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u0430" +}; +var settings8 = { + title: "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 Claudian", + customization: "\u041F\u0435\u0440\u0441\u043E\u043D\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u044F", + userName: { + name: "\u041A\u0430\u043A Claudian \u0434\u043E\u043B\u0436\u0435\u043D \u043E\u0431\u0440\u0430\u0449\u0430\u0442\u044C\u0441\u044F \u043A \u0432\u0430\u043C?", + desc: "\u0412\u0430\u0448\u0435 \u0438\u043C\u044F \u0434\u043B\u044F \u043F\u0435\u0440\u0441\u043E\u043D\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0445 \u043F\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0439 (\u043E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u043E\u0431\u0449\u0438\u0445 \u043F\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0439)" + }, + excludedTags: { + name: "\u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0435 \u0442\u0435\u0433\u0438", + desc: "\u0417\u0430\u043C\u0435\u0442\u043A\u0438 \u0441 \u044D\u0442\u0438\u043C\u0438 \u0442\u0435\u0433\u0430\u043C\u0438 \u043D\u0435 \u0431\u0443\u0434\u0443\u0442 \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u0437\u0430\u0433\u0440\u0443\u0436\u0430\u0442\u044C\u0441\u044F \u043A\u0430\u043A \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 (\u043F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435, \u0431\u0435\u0437 #)" + }, + mediaFolder: { + name: "\u041F\u0430\u043F\u043A\u0430 \u043C\u0435\u0434\u0438\u0430\u0444\u0430\u0439\u043B\u043E\u0432", + desc: "\u041F\u0430\u043F\u043A\u0430 \u0441 \u0432\u043B\u043E\u0436\u0435\u043D\u0438\u044F\u043C\u0438/\u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043C\u0438. \u041A\u043E\u0433\u0434\u0430 \u0437\u0430\u043C\u0435\u0442\u043A\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044E\u0442 ![[image.jpg]], Claude \u0431\u0443\u0434\u0435\u0442 \u0438\u0441\u043A\u0430\u0442\u044C \u0437\u0434\u0435\u0441\u044C. \u041E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u043A\u043E\u0440\u043D\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430." + }, + systemPrompt: { + name: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0439 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442", + desc: "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u0438, \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0435 \u043A \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u043E\u043C\u0443 \u043F\u0440\u043E\u043C\u043F\u0442\u0443 \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E" + }, + autoTitle: { + name: "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0438 \u0431\u0435\u0441\u0435\u0434", + desc: "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0438 \u0431\u0435\u0441\u0435\u0434 \u043F\u043E\u0441\u043B\u0435 \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F." + }, + titleModel: { + name: "\u041C\u043E\u0434\u0435\u043B\u044C \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u0438 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432", + desc: "\u041C\u043E\u0434\u0435\u043B\u044C, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C\u0430\u044F \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u0438 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432 \u0431\u0435\u0441\u0435\u0434.", + auto: "\u0410\u0432\u0442\u043E (Haiku)" + }, + navMappings: { + name: "\u0421\u043E\u043F\u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438 \u0432 \u0441\u0442\u0438\u043B\u0435 Vim", + desc: '\u041F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0441\u043E\u043F\u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044E \u0432 \u0441\u0442\u0440\u043E\u043A\u0435. \u0424\u043E\u0440\u043C\u0430\u0442: "map <\u043A\u043B\u044E\u0447> <\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435>" (\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F: scrollUp, scrollDown, focusInput).' + }, + hotkeys: "\u0413\u043E\u0440\u044F\u0447\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448\u0438", + inlineEditHotkey: { + name: "\u0418\u043D\u043B\u0430\u0439\u043D-\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435", + descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}", + descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430", + btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C", + btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C" + }, + openChatHotkey: { + name: "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0447\u0430\u0442", + descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}", + descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430", + btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C", + btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C" + }, + newSessionHotkey: { + name: "\u041D\u043E\u0432\u0430\u044F \u0441\u0435\u0441\u0441\u0438\u044F", + descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}", + descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430", + btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C", + btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C" + }, + newTabHotkey: { + name: "\u041D\u043E\u0432\u0430\u044F \u0432\u043A\u043B\u0430\u0434\u043A\u0430", + descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}", + descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430", + btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C", + btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C" + }, + closeTabHotkey: { + name: "\u0417\u0430\u043A\u0440\u044B\u0442\u044C \u0432\u043A\u043B\u0430\u0434\u043A\u0443", + descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}", + descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430", + btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C", + btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C" + }, + slashCommands: { + name: "\u041A\u043E\u043C\u0430\u043D\u0434\u044B \u0438 \u043D\u0430\u0432\u044B\u043A\u0438", + desc: "\u041E\u043F\u0440\u0435\u0434\u0435\u043B\u044F\u0439\u0442\u0435 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0438 \u043D\u0430\u0432\u044B\u043A\u0438, \u0437\u0430\u043F\u0443\u0441\u043A\u0430\u0435\u043C\u044B\u0435 \u0447\u0435\u0440\u0435\u0437 /\u0438\u043C\u044F." + }, + hiddenSlashCommands: { + name: "\u0421\u043A\u0440\u044B\u0442\u044B\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B", + desc: "\u0421\u043A\u0440\u044B\u0442\u044C \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0451\u043D\u043D\u044B\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0441\u043E \u0441\u043B\u044D\u0448\u0435\u043C \u0438\u0437 \u0432\u044B\u043F\u0430\u0434\u0430\u044E\u0449\u0435\u0433\u043E \u0441\u043F\u0438\u0441\u043A\u0430. \u041F\u043E\u043B\u0435\u0437\u043D\u043E \u0434\u043B\u044F \u0441\u043A\u0440\u044B\u0442\u0438\u044F \u043A\u043E\u043C\u0430\u043D\u0434 Claude Code, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u043D\u0435 \u0430\u043A\u0442\u0443\u0430\u043B\u044C\u043D\u044B \u0434\u043B\u044F Claudian. \u0412\u0432\u043E\u0434\u0438\u0442\u0435 \u0438\u043C\u0435\u043D\u0430 \u043A\u043E\u043C\u0430\u043D\u0434 \u0431\u0435\u0437 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0441\u043B\u044D\u0448\u0430, \u043F\u043E \u043E\u0434\u043D\u043E\u0439 \u043D\u0430 \u0441\u0442\u0440\u043E\u043A\u0443.", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "MCP \u0441\u0435\u0440\u0432\u0435\u0440\u044B", + desc: "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u0442\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u044B Model Context Protocol \u0434\u043B\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E\u0441\u0442\u0435\u0439 Claude \u0441 \u043F\u043E\u043C\u043E\u0449\u044C\u044E \u0432\u043D\u0435\u0448\u043D\u0438\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0438 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u043E\u0432 \u0434\u0430\u043D\u043D\u044B\u0445. \u0421\u0435\u0440\u0432\u0435\u0440\u044B \u0441 \u0440\u0435\u0436\u0438\u043C\u043E\u043C \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u0442\u0440\u0435\u0431\u0443\u044E\u0442 @mention \u0434\u043B\u044F \u0430\u043A\u0442\u0438\u0432\u0430\u0446\u0438\u0438." + }, + plugins: { + name: "\u041F\u043B\u0430\u0433\u0438\u043D\u044B Claude Code", + desc: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u0435 \u0438\u043B\u0438 \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u0435 \u043F\u043B\u0430\u0433\u0438\u043D\u044B Claude Code \u0438\u0437 ~/.claude/plugins. \u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0435 \u043F\u043B\u0430\u0433\u0438\u043D\u044B \u0441\u043E\u0445\u0440\u0430\u043D\u044F\u044E\u0442\u0441\u044F \u0434\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0433\u043E \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430." + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "\u0411\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u044C", + loadUserSettings: { + name: "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0442\u044C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 Claude", + desc: "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442 ~/.claude/settings.json. \u041F\u0440\u0438 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0438 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043F\u0440\u0430\u0432\u0438\u043B\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0439 Claude Code \u043C\u043E\u0433\u0443\u0442 \u043E\u0431\u0445\u043E\u0434\u0438\u0442\u044C \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C." + }, + enableBlocklist: { + name: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0447\u0435\u0440\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A \u043A\u043E\u043C\u0430\u043D\u0434", + desc: "\u0411\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043F\u043E\u0442\u0435\u043D\u0446\u0438\u0430\u043B\u044C\u043D\u043E \u043E\u043F\u0430\u0441\u043D\u044B\u0435 bash \u043A\u043E\u043C\u0430\u043D\u0434\u044B" + }, + blockedCommands: { + name: "\u0417\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B ({platform})", + desc: "\u0428\u0430\u0431\u043B\u043E\u043D\u044B \u0434\u043B\u044F \u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438 \u043D\u0430 {platform} (\u043F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435). \u041F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u044E\u0442\u0441\u044F \u0440\u0435\u0433\u0443\u043B\u044F\u0440\u043D\u044B\u0435 \u0432\u044B\u0440\u0430\u0436\u0435\u043D\u0438\u044F.", + unixName: "\u0417\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B (Unix/Git Bash)", + unixDesc: "Unix \u0448\u0430\u0431\u043B\u043E\u043D\u044B \u0442\u0430\u043A\u0436\u0435 \u0431\u043B\u043E\u043A\u0438\u0440\u0443\u044E\u0442\u0441\u044F \u043D\u0430 Windows, \u0442\u0430\u043A \u043A\u0430\u043A Git Bash \u043C\u043E\u0436\u0435\u0442 \u0438\u0445 \u0432\u044B\u0437\u044B\u0432\u0430\u0442\u044C." + }, + exportPaths: { + name: "\u0420\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u043D\u044B\u0435 \u043F\u0443\u0442\u0438 \u044D\u043A\u0441\u043F\u043E\u0440\u0442\u0430", + desc: "\u041F\u0443\u0442\u0438 \u0432\u043D\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430, \u043A\u0443\u0434\u0430 \u043C\u043E\u0436\u043D\u043E \u044D\u043A\u0441\u043F\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0444\u0430\u0439\u043B\u044B (\u043F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435). \u041F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442 ~ \u0434\u043B\u044F \u0434\u043E\u043C\u0430\u0448\u043D\u0435\u0433\u043E \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430." + }, + environment: "\u041E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u0435", + customVariables: { + name: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435", + desc: "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F \u0434\u043B\u044F Claude SDK (\u0444\u043E\u0440\u043C\u0430\u0442 KEY=VALUE, \u043F\u043E \u043E\u0434\u043D\u043E\u0439 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435). \u041F\u0440\u0435\u0444\u0438\u043A\u0441 export \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F." + }, + envSnippets: { + name: "\u0421\u043D\u0438\u043F\u043F\u0435\u0442\u044B", + addBtn: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u043D\u0438\u043F\u043F\u0435\u0442", + noSnippets: "\u041D\u0435\u0442 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043D\u044B\u0445 \u0441\u043D\u0438\u043F\u043F\u0435\u0442\u043E\u0432 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F. \u041D\u0430\u0436\u043C\u0438\u0442\u0435 +, \u0447\u0442\u043E\u0431\u044B \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0443\u044E \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044E.", + nameRequired: "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441\u043D\u0438\u043F\u043F\u0435\u0442\u0430", + modal: { + titleEdit: "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u043D\u0438\u043F\u043F\u0435\u0442", + titleSave: "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0441\u043D\u0438\u043F\u043F\u0435\u0442", + name: "\u0418\u043C\u044F", + namePlaceholder: "\u041E\u043F\u0438\u0441\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0434\u043B\u044F \u044D\u0442\u043E\u0439 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438", + description: "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435", + descPlaceholder: "\u041E\u043F\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u043E\u0435 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435", + envVars: "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F", + envVarsPlaceholder: "\u0424\u043E\u0440\u043C\u0430\u0442 KEY=VALUE, \u043F\u043E \u043E\u0434\u043D\u043E\u0439 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435 (\u043F\u0440\u0435\u0444\u0438\u043A\u0441 export \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F)", + save: "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C", + update: "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C", + cancel: "\u041E\u0442\u043C\u0435\u043D\u0430" + } + }, + customContextLimits: { + name: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043B\u0438\u043C\u0438\u0442\u044B \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430", + desc: "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u0440\u0430\u0437\u043C\u0435\u0440\u044B \u043E\u043A\u043D\u0430 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u0434\u043B\u044F \u0432\u0430\u0448\u0438\u0445 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445 \u043C\u043E\u0434\u0435\u043B\u0435\u0439. \u041E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E (200k \u0442\u043E\u043A\u0435\u043D\u043E\u0432).", + invalid: "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435: 256k, 1m \u0438\u043B\u0438 \u0442\u043E\u0447\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E (1000-10000000)." + }, + advanced: "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E", + show1MModel: { + name: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C Sonnet \u0441 \u043E\u043A\u043D\u043E\u043C \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 1M", + desc: "\u0417\u0430\u043C\u0435\u043D\u0438\u0442\u044C \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u044B\u0439 Sonnet \u043D\u0430 Sonnet (1M) \u0432 \u0432\u044B\u0431\u043E\u0440\u0435 \u043C\u043E\u0434\u0435\u043B\u0435\u0439. \u0422\u0430 \u0436\u0435 \u0446\u0435\u043D\u0430 \u0434\u043E 200k \u0442\u043E\u043A\u0435\u043D\u043E\u0432. \u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0430 Max." + }, + enableChrome: { + name: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 Chrome", + desc: "\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C Claude \u0432\u0437\u0430\u0438\u043C\u043E\u0434\u0435\u0439\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0441 Chrome \u0447\u0435\u0440\u0435\u0437 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 claude-in-chrome. \u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F. \u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A \u0441\u0435\u0441\u0441\u0438\u0438." + }, + maxTabs: { + name: "\u041C\u0430\u043A\u0441\u0438\u043C\u0443\u043C \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u0447\u0430\u0442\u0430", + desc: "\u041C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043E\u0434\u043D\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445 \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u0447\u0430\u0442\u0430 (3-10). \u041A\u0430\u0436\u0434\u0430\u044F \u0432\u043A\u043B\u0430\u0434\u043A\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442 \u043E\u0442\u0434\u0435\u043B\u044C\u043D\u0443\u044E \u0441\u0435\u0441\u0441\u0438\u044E Claude.", + warning: "\u0411\u043E\u043B\u0435\u0435 5 \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u043C\u043E\u0436\u0435\u0442 \u043F\u043E\u0432\u043B\u0438\u044F\u0442\u044C \u043D\u0430 \u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043F\u0430\u043C\u044F\u0442\u0438." + }, + tabBarPosition: { + name: "\u041F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u043F\u0430\u043D\u0435\u043B\u0438 \u0432\u043A\u043B\u0430\u0434\u043E\u043A", + desc: "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435, \u0433\u0434\u0435 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0430\u0442\u044C \u0437\u043D\u0430\u0447\u043A\u0438 \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u0438 \u043A\u043D\u043E\u043F\u043A\u0438 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439", + input: "\u041D\u0430\u0434 \u043F\u043E\u043B\u0435\u043C \u0432\u0432\u043E\u0434\u0430 (\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E)", + header: "\u0412 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0435" + }, + enableAutoScroll: { + name: "\u0410\u0432\u0442\u043E\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0430 \u0432\u043E \u0432\u0440\u0435\u043C\u044F \u043F\u043E\u0442\u043E\u043A\u043E\u0432\u043E\u0439 \u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438", + desc: "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043F\u0440\u043E\u043A\u0440\u0443\u0447\u0438\u0432\u0430\u0442\u044C \u0432\u043D\u0438\u0437, \u043F\u043E\u043A\u0430 Claude \u043F\u0435\u0440\u0435\u0434\u0430\u0435\u0442 \u043E\u0442\u0432\u0435\u0442\u044B. \u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u0435, \u0447\u0442\u043E\u0431\u044B \u043E\u0441\u0442\u0430\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430\u0432\u0435\u0440\u0445\u0443 \u0438 \u0447\u0438\u0442\u0430\u0442\u044C \u0441 \u043D\u0430\u0447\u0430\u043B\u0430." + }, + openInMainTab: { + name: "\u041E\u0442\u043A\u0440\u044B\u0432\u0430\u0442\u044C \u0432 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0430", + desc: "\u041E\u0442\u043A\u0440\u044B\u0432\u0430\u0442\u044C \u043F\u0430\u043D\u0435\u043B\u044C \u0447\u0430\u0442\u0430 \u0432 \u0432\u0438\u0434\u0435 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439 \u0432\u043A\u043B\u0430\u0434\u043A\u0438 \u0432 \u0446\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u043E\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0430 \u0432\u043C\u0435\u0441\u0442\u043E \u043F\u0440\u0430\u0432\u043E\u0439 \u0431\u043E\u043A\u043E\u0432\u043E\u0439 \u043F\u0430\u043D\u0435\u043B\u0438" + }, + cliPath: { + name: "\u041F\u0443\u0442\u044C \u043A CLI Claude", + desc: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0439 \u043F\u0443\u0442\u044C \u043A Claude Code CLI. \u041E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0433\u043E \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F.", + descWindows: "\u0414\u043B\u044F \u043D\u0430\u0442\u0438\u0432\u043D\u043E\u0433\u043E \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0449\u0438\u043A\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 claude.exe. \u0414\u043B\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043E\u043A \u0447\u0435\u0440\u0435\u0437 npm/pnpm/yarn \u0438\u043B\u0438 \u0434\u0440\u0443\u0433\u0438\u0435 \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u044B \u043F\u0430\u043A\u0435\u0442\u043E\u0432 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u043F\u0443\u0442\u044C \u043A cli.js (\u043D\u0435 claude.cmd).", + descUnix: '\u0412\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0432\u044B\u0432\u043E\u0434 \u043A\u043E\u043C\u0430\u043D\u0434\u044B "which claude" \u2014 \u0440\u0430\u0431\u043E\u0442\u0430\u0435\u0442 \u043A\u0430\u043A \u0434\u043B\u044F \u043D\u0430\u0442\u0438\u0432\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043E\u043A, \u0442\u0430\u043A \u0438 \u0434\u043B\u044F npm/pnpm/yarn.', + validation: { + notExist: "\u041F\u0443\u0442\u044C \u043D\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442", + isDirectory: "\u041F\u0443\u0442\u044C \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0435\u0439, \u0430 \u043D\u0435 \u0444\u0430\u0439\u043B\u043E\u043C" + } + }, + language: { + name: "\u042F\u0437\u044B\u043A", + desc: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u044F\u0437\u044B\u043A \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043F\u043B\u0430\u0433\u0438\u043D\u0430" + } +}; +var ru_default2 = { + common: common8, + settings: settings8 +}; + +// src/i18n/locales/zh-CN.json +var zh_CN_exports = {}; +__export(zh_CN_exports, { + common: () => common9, + default: () => zh_CN_default2, + settings: () => settings9 +}); +var common9 = { + save: "\u4FDD\u5B58", + cancel: "\u53D6\u6D88", + delete: "\u5220\u9664", + edit: "\u7F16\u8F91", + add: "\u6DFB\u52A0", + remove: "\u79FB\u9664", + clear: "\u6E05\u9664", + clearAll: "\u6E05\u9664\u5168\u90E8", + loading: "\u52A0\u8F7D\u4E2D", + error: "\u9519\u8BEF", + success: "\u6210\u529F", + warning: "\u8B66\u544A", + confirm: "\u786E\u8BA4", + settings: "\u8BBE\u7F6E", + advanced: "\u9AD8\u7EA7", + enabled: "\u5DF2\u542F\u7528", + disabled: "\u5DF2\u7981\u7528", + platform: "\u5E73\u53F0" +}; +var settings9 = { + title: "Claudian \u8BBE\u7F6E", + customization: "\u4E2A\u6027\u5316\u8BBE\u7F6E", + userName: { + name: "Claudian \u5E94\u8BE5\u5982\u4F55\u79F0\u547C\u4F60\uFF1F", + desc: "\u7528\u4E8E\u4E2A\u6027\u5316\u95EE\u5019\u7684\u7528\u6237\u540D\uFF08\u7559\u7A7A\u4F7F\u7528\u901A\u7528\u95EE\u5019\uFF09" + }, + excludedTags: { + name: "\u6392\u9664\u7684\u6807\u7B7E", + desc: "\u5305\u542B\u8FD9\u4E9B\u6807\u7B7E\u7684\u7B14\u8BB0\u4E0D\u4F1A\u81EA\u52A8\u52A0\u8F7D\u4E3A\u4E0A\u4E0B\u6587\uFF08\u6BCF\u884C\u4E00\u4E2A\uFF0C\u4E0D\u5E26 #\uFF09" + }, + mediaFolder: { + name: "\u5A92\u4F53\u6587\u4EF6\u5939", + desc: "\u5B58\u653E\u9644\u4EF6/\u56FE\u7247\u7684\u6587\u4EF6\u5939\u3002\u5F53\u7B14\u8BB0\u4F7F\u7528 ![[image.jpg]] \u65F6\uFF0CClaude \u4F1A\u5728\u6B64\u67E5\u627E\u3002\u7559\u7A7A\u4F7F\u7528\u4ED3\u5E93\u6839\u76EE\u5F55\u3002" + }, + systemPrompt: { + name: "\u81EA\u5B9A\u4E49\u7CFB\u7EDF\u63D0\u793A\u8BCD", + desc: "\u9644\u52A0\u5230\u9ED8\u8BA4\u7CFB\u7EDF\u63D0\u793A\u8BCD\u7684\u989D\u5916\u6307\u4EE4" + }, + autoTitle: { + name: "\u81EA\u52A8\u751F\u6210\u5BF9\u8BDD\u6807\u9898", + desc: "\u5728\u7528\u6237\u53D1\u9001\u9996\u6761\u6D88\u606F\u540E\u81EA\u52A8\u751F\u6210\u5BF9\u8BDD\u6807\u9898\u3002" + }, + titleModel: { + name: "\u6807\u9898\u751F\u6210\u6A21\u578B", + desc: "\u7528\u4E8E\u81EA\u52A8\u751F\u6210\u5BF9\u8BDD\u6807\u9898\u7684\u6A21\u578B\u3002", + auto: "\u81EA\u52A8 (Haiku)" + }, + navMappings: { + name: "Vim \u98CE\u683C\u5BFC\u822A\u6620\u5C04", + desc: '\u6BCF\u884C\u4E00\u4E2A\u6620\u5C04\u3002\u683C\u5F0F\uFF1A"map <\u952E> <\u52A8\u4F5C>"\uFF08\u52A8\u4F5C\uFF1AscrollUp, scrollDown, focusInput\uFF09\u3002' + }, + hotkeys: "\u5FEB\u6377\u952E", + inlineEditHotkey: { + name: "\u5185\u8054\u7F16\u8F91", + descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}", + descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E", + btnChange: "\u66F4\u6539", + btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E" + }, + openChatHotkey: { + name: "\u6253\u5F00\u804A\u5929", + descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}", + descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E", + btnChange: "\u66F4\u6539", + btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E" + }, + newSessionHotkey: { + name: "\u65B0\u4F1A\u8BDD", + descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}", + descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E", + btnChange: "\u66F4\u6539", + btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E" + }, + newTabHotkey: { + name: "\u65B0\u6807\u7B7E\u9875", + descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}", + descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E", + btnChange: "\u66F4\u6539", + btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E" + }, + closeTabHotkey: { + name: "\u5173\u95ED\u6807\u7B7E\u9875", + descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}", + descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E", + btnChange: "\u66F4\u6539", + btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E" + }, + slashCommands: { + name: "\u547D\u4EE4\u4E0E\u6280\u80FD", + desc: "\u5B9A\u4E49\u7531 /\u540D\u79F0 \u89E6\u53D1\u7684\u81EA\u5B9A\u4E49\u547D\u4EE4\u4E0E\u6280\u80FD\u3002" + }, + hiddenSlashCommands: { + name: "\u9690\u85CF\u547D\u4EE4", + desc: "\u4ECE\u4E0B\u62C9\u83DC\u5355\u4E2D\u9690\u85CF\u7279\u5B9A\u7684\u659C\u6760\u547D\u4EE4\u3002\u9002\u7528\u4E8E\u9690\u85CF\u4E0E Claudian \u65E0\u5173\u7684 Claude Code \u547D\u4EE4\u3002\u6BCF\u884C\u8F93\u5165\u4E00\u4E2A\u547D\u4EE4\u540D\u79F0\uFF0C\u65E0\u9700\u524D\u5BFC\u659C\u6760\u3002", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "MCP \u670D\u52A1\u5668", + desc: "\u914D\u7F6E\u6A21\u578B\u4E0A\u4E0B\u6587\u534F\u8BAE\u670D\u52A1\u5668\uFF0C\u901A\u8FC7\u5916\u90E8\u5DE5\u5177\u548C\u6570\u636E\u6E90\u6269\u5C55 Claude \u7684\u80FD\u529B\u3002\u542F\u7528\u4E0A\u4E0B\u6587\u4FDD\u5B58\u6A21\u5F0F\u7684\u670D\u52A1\u5668\u9700\u8981 @ \u63D0\u53CA\u624D\u80FD\u6FC0\u6D3B\u3002" + }, + plugins: { + name: "Claude Code \u63D2\u4EF6", + desc: "\u542F\u7528\u6216\u7981\u7528\u4ECE ~/.claude/plugins \u53D1\u73B0\u7684 Claude Code \u63D2\u4EF6\u3002\u542F\u7528\u7684\u63D2\u4EF6\u6309 Vault \u5B58\u50A8\u3002" + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "\u5B89\u5168", + loadUserSettings: { + name: "\u52A0\u8F7D\u7528\u6237 Claude \u8BBE\u7F6E", + desc: "\u52A0\u8F7D ~/.claude/settings.json\u3002\u542F\u7528\u540E\uFF0C\u7528\u6237\u7684 Claude Code \u6743\u9650\u89C4\u5219\u53EF\u80FD\u7ED5\u8FC7\u5B89\u5168\u6A21\u5F0F\u3002" + }, + enableBlocklist: { + name: "\u542F\u7528\u547D\u4EE4\u9ED1\u540D\u5355", + desc: "\u963B\u6B62\u6F5C\u5728\u5371\u9669\u7684 bash \u547D\u4EE4" + }, + blockedCommands: { + name: "\u963B\u6B62\u7684\u547D\u4EE4 ({platform})", + desc: "\u5728 {platform} \u4E0A\u963B\u6B62\u7684\u6A21\u5F0F\uFF08\u6BCF\u884C\u4E00\u4E2A\uFF09\u3002\u652F\u6301\u6B63\u5219\u8868\u8FBE\u5F0F\u3002", + unixName: "\u963B\u6B62\u7684\u547D\u4EE4 (Unix/Git Bash)", + unixDesc: "Unix \u6A21\u5F0F\u5728 Windows \u4E0A\u4E5F\u4F1A\u88AB\u963B\u6B62\uFF0C\u56E0\u4E3A Git Bash \u53EF\u4EE5\u8C03\u7528\u5B83\u4EEC\u3002" + }, + exportPaths: { + name: "\u5141\u8BB8\u7684\u5BFC\u51FA\u8DEF\u5F84", + desc: "\u5141\u8BB8\u5BFC\u51FA\u6587\u4EF6\u7684\u4ED3\u5E93\u5916\u90E8\u8DEF\u5F84\uFF08\u6BCF\u884C\u4E00\u4E2A\uFF09\u3002\u652F\u6301 ~ \u8868\u793A\u4E3B\u76EE\u5F55\u3002" + }, + environment: "\u73AF\u5883", + customVariables: { + name: "\u81EA\u5B9A\u4E49\u53D8\u91CF", + desc: "Claude SDK \u7684\u73AF\u5883\u53D8\u91CF\uFF08KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u4E2A\uFF09\u3002\u652F\u6301 export \u524D\u7F00\u3002" + }, + envSnippets: { + name: "\u7247\u6BB5", + addBtn: "\u6DFB\u52A0\u7247\u6BB5", + noSnippets: "\u5C1A\u65E0\u4FDD\u5B58\u7684\u73AF\u5883\u53D8\u91CF\u7247\u6BB5\u3002\u70B9\u51FB + \u4FDD\u5B58\u5F53\u524D\u914D\u7F6E\u3002", + nameRequired: "\u8BF7\u8F93\u5165\u7247\u6BB5\u540D\u79F0", + modal: { + titleEdit: "\u7F16\u8F91\u7247\u6BB5", + titleSave: "\u4FDD\u5B58\u7247\u6BB5", + name: "\u540D\u79F0", + namePlaceholder: "\u6B64\u914D\u7F6E\u7684\u63CF\u8FF0\u6027\u540D\u79F0", + description: "\u63CF\u8FF0", + descPlaceholder: "\u53EF\u9009\u63CF\u8FF0", + envVars: "\u73AF\u5883\u53D8\u91CF", + envVarsPlaceholder: "KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u4E2A\uFF08\u652F\u6301 export \u524D\u7F00\uFF09", + save: "\u4FDD\u5B58", + update: "\u66F4\u65B0", + cancel: "\u53D6\u6D88" + } + }, + customContextLimits: { + name: "\u81EA\u5B9A\u4E49\u4E0A\u4E0B\u6587\u9650\u5236", + desc: "\u4E3A\u60A8\u7684\u81EA\u5B9A\u4E49\u6A21\u578B\u8BBE\u7F6E\u4E0A\u4E0B\u6587\u7A97\u53E3\u5927\u5C0F\u3002\u7559\u7A7A\u4F7F\u7528\u9ED8\u8BA4\u503C\uFF08200k \u4EE4\u724C\uFF09\u3002", + invalid: "\u683C\u5F0F\u65E0\u6548\u3002\u4F7F\u7528\uFF1A256k\u30011m \u6216\u7CBE\u786E\u6570\u91CF\uFF081000-10000000\uFF09\u3002" + }, + advanced: "\u9AD8\u7EA7", + show1MModel: { + name: "\u542F\u7528\u5177\u6709 1M \u4E0A\u4E0B\u6587\u7A97\u53E3\u7684 Sonnet", + desc: "\u5728\u6A21\u578B\u9009\u62E9\u5668\u4E2D\u5C06\u6807\u51C6 Sonnet \u66FF\u6362\u4E3A Sonnet (1M)\u3002\u5728 200k \u4EE4\u724C\u4EE5\u4E0B\u4EF7\u683C\u76F8\u540C\u3002\u9700\u8981 Max \u8BA2\u9605\u3002" + }, + enableChrome: { + name: "\u542F\u7528 Chrome \u6269\u5C55", + desc: "\u5141\u8BB8 Claude \u901A\u8FC7 claude-in-chrome \u6269\u5C55\u4E0E Chrome \u4EA4\u4E92\u3002\u9700\u8981\u5B89\u88C5\u8BE5\u6269\u5C55\u3002\u9700\u8981\u91CD\u542F\u4F1A\u8BDD\u3002" + }, + maxTabs: { + name: "\u6700\u5927\u804A\u5929\u6807\u7B7E\u6570", + desc: "\u540C\u65F6\u5F00\u542F\u7684\u6700\u5927\u804A\u5929\u6807\u7B7E\u6570\uFF083-10\uFF09\u3002\u6BCF\u4E2A\u6807\u7B7E\u4F7F\u7528\u72EC\u7ACB\u7684 Claude \u4F1A\u8BDD\u3002", + warning: "\u8D85\u8FC7 5 \u4E2A\u6807\u7B7E\u53EF\u80FD\u4F1A\u5F71\u54CD\u6027\u80FD\u548C\u5185\u5B58\u4F7F\u7528\u3002" + }, + tabBarPosition: { + name: "\u6807\u7B7E\u680F\u4F4D\u7F6E", + desc: "\u9009\u62E9\u6807\u7B7E\u5FBD\u7AE0\u548C\u64CD\u4F5C\u6309\u94AE\u7684\u663E\u793A\u4F4D\u7F6E", + input: "\u8F93\u5165\u6846\u4E0A\u65B9\uFF08\u9ED8\u8BA4\uFF09", + header: "\u5728\u6807\u9898\u680F" + }, + enableAutoScroll: { + name: "\u6D41\u5F0F\u4F20\u8F93\u65F6\u81EA\u52A8\u6EDA\u52A8", + desc: "\u5728 Claude \u6D41\u5F0F\u4F20\u8F93\u54CD\u5E94\u65F6\u81EA\u52A8\u6EDA\u52A8\u5230\u5E95\u90E8\u3002\u7981\u7528\u540E\u5C06\u505C\u7559\u5728\u9876\u90E8\uFF0C\u4ECE\u5934\u5F00\u59CB\u9605\u8BFB\u3002" + }, + openInMainTab: { + name: "\u5728\u4E3B\u7F16\u8F91\u5668\u533A\u57DF\u6253\u5F00", + desc: "\u5728\u4E2D\u592E\u7F16\u8F91\u5668\u533A\u57DF\u4EE5\u4E3B\u6807\u7B7E\u9875\u5F62\u5F0F\u6253\u5F00\u804A\u5929\u9762\u677F\uFF0C\u800C\u4E0D\u662F\u5728\u53F3\u4FA7\u8FB9\u680F" + }, + cliPath: { + name: "Claude CLI \u8DEF\u5F84", + desc: "Claude Code CLI \u7684\u81EA\u5B9A\u4E49\u8DEF\u5F84\u3002\u7559\u7A7A\u4F7F\u7528\u81EA\u52A8\u68C0\u6D4B\u3002", + descWindows: "\u5BF9\u4E8E\u539F\u751F\u5B89\u88C5\u7A0B\u5E8F\uFF0C\u4F7F\u7528 claude.exe\u3002\u5BF9\u4E8E npm/pnpm/yarn \u6216\u5176\u4ED6\u5305\u7BA1\u7406\u5668\u5B89\u88C5\uFF0C\u4F7F\u7528 cli.js \u8DEF\u5F84\uFF08\u4E0D\u662F claude.cmd\uFF09\u3002", + descUnix: '\u7C98\u8D34 "which claude" \u7684\u8F93\u51FA - \u9002\u7528\u4E8E\u539F\u751F\u5B89\u88C5\u548C npm/pnpm/yarn \u5B89\u88C5\u3002', + validation: { + notExist: "\u8DEF\u5F84\u4E0D\u5B58\u5728", + isDirectory: "\u8DEF\u5F84\u662F\u76EE\u5F55\uFF0C\u4E0D\u662F\u6587\u4EF6" + } + }, + language: { + name: "\u8BED\u8A00", + desc: "\u66F4\u6539\u63D2\u4EF6\u754C\u9762\u7684\u663E\u793A\u8BED\u8A00" + } +}; +var zh_CN_default2 = { + common: common9, + settings: settings9 +}; + +// src/i18n/locales/zh-TW.json +var zh_TW_exports = {}; +__export(zh_TW_exports, { + common: () => common10, + default: () => zh_TW_default2, + settings: () => settings10 +}); +var common10 = { + save: "\u4FDD\u5B58", + cancel: "\u53D6\u6D88", + delete: "\u522A\u9664", + edit: "\u7DE8\u8F2F", + add: "\u6DFB\u52A0", + remove: "\u79FB\u9664", + clear: "\u6E05\u9664", + clearAll: "\u6E05\u9664\u5168\u90E8", + loading: "\u52A0\u8F09\u4E2D", + error: "\u932F\u8AA4", + success: "\u6210\u529F", + warning: "\u8B66\u544A", + confirm: "\u78BA\u8A8D", + settings: "\u8A2D\u7F6E", + advanced: "\u9AD8\u7D1A", + enabled: "\u5DF2\u555F\u7528", + disabled: "\u5DF2\u7981\u7528", + platform: "\u5E73\u53F0" +}; +var settings10 = { + title: "Claudian \u8A2D\u5B9A", + customization: "\u500B\u4EBA\u5316\u8A2D\u5B9A", + userName: { + name: "Claudian \u61C9\u8A72\u5982\u4F55\u7A31\u547C\u60A8\uFF1F", + desc: "\u7528\u65BC\u500B\u4EBA\u5316\u554F\u5019\u7684\u4F7F\u7528\u8005\u540D\u7A31\uFF08\u7559\u7A7A\u4F7F\u7528\u901A\u7528\u554F\u5019\uFF09" + }, + excludedTags: { + name: "\u6392\u9664\u7684\u6A19\u7C64", + desc: "\u5305\u542B\u9019\u4E9B\u6A19\u7C64\u7684\u7B46\u8A18\u4E0D\u6703\u81EA\u52D5\u8F09\u5165\u70BA\u4E0A\u4E0B\u6587\uFF08\u6BCF\u884C\u4E00\u500B\uFF0C\u4E0D\u5E36 #\uFF09" + }, + mediaFolder: { + name: "\u5A92\u9AD4\u8CC7\u6599\u593E", + desc: "\u5B58\u653E\u9644\u4EF6/\u5716\u7247\u7684\u8CC7\u6599\u593E\u3002\u7576\u7B46\u8A18\u4F7F\u7528 ![[image.jpg]] \u6642\uFF0CClaude \u6703\u5728\u6B64\u67E5\u627E\u3002\u7559\u7A7A\u4F7F\u7528\u5132\u5B58\u5EAB\u6839\u76EE\u9304\u3002" + }, + systemPrompt: { + name: "\u81EA\u8A02\u7CFB\u7D71\u63D0\u793A\u8A5E", + desc: "\u9644\u52A0\u5230\u9810\u8A2D\u7CFB\u7D71\u63D0\u793A\u8A5E\u7684\u984D\u5916\u6307\u4EE4" + }, + autoTitle: { + name: "\u81EA\u52D5\u751F\u6210\u5C0D\u8A71\u6A19\u984C", + desc: "\u5728\u4F7F\u7528\u8005\u9001\u51FA\u7B2C\u4E00\u5247\u8A0A\u606F\u5F8C\u81EA\u52D5\u751F\u6210\u5C0D\u8A71\u6A19\u984C\u3002" + }, + titleModel: { + name: "\u6A19\u984C\u751F\u6210\u6A21\u578B", + desc: "\u7528\u65BC\u81EA\u52D5\u751F\u6210\u5C0D\u8A71\u6A19\u984C\u7684\u6A21\u578B\u3002", + auto: "\u81EA\u52D5 (Haiku)" + }, + navMappings: { + name: "Vim \u98A8\u683C\u5C0E\u822A\u6620\u5C04", + desc: '\u6BCF\u884C\u4E00\u500B\u6620\u5C04\u3002\u683C\u5F0F\uFF1A"map <\u9375> <\u52D5\u4F5C>"\uFF08\u52D5\u4F5C\uFF1AscrollUp, scrollDown, focusInput\uFF09\u3002' + }, + hotkeys: "\u5FEB\u6377\u9375", + inlineEditHotkey: { + name: "\u5167\u5D4C\u7DE8\u8F2F", + descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}", + descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375", + btnChange: "\u8B8A\u66F4", + btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375" + }, + openChatHotkey: { + name: "\u958B\u555F\u804A\u5929", + descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}", + descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375", + btnChange: "\u8B8A\u66F4", + btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375" + }, + newSessionHotkey: { + name: "\u65B0\u5DE5\u4F5C\u968E\u6BB5", + descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}", + descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375", + btnChange: "\u8B8A\u66F4", + btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375" + }, + newTabHotkey: { + name: "\u65B0\u5206\u9801", + descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}", + descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375", + btnChange: "\u8B8A\u66F4", + btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375" + }, + closeTabHotkey: { + name: "\u95DC\u9589\u5206\u9801", + descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}", + descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375", + btnChange: "\u8B8A\u66F4", + btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375" + }, + slashCommands: { + name: "\u547D\u4EE4\u8207\u6280\u80FD", + desc: "\u5B9A\u7FA9\u7531 /\u540D\u7A31 \u89F8\u767C\u7684\u81EA\u8A02\u547D\u4EE4\u8207\u6280\u80FD\u3002" + }, + hiddenSlashCommands: { + name: "\u96B1\u85CF\u547D\u4EE4", + desc: "\u5F9E\u4E0B\u62C9\u9078\u55AE\u4E2D\u96B1\u85CF\u7279\u5B9A\u7684\u659C\u7DDA\u547D\u4EE4\u3002\u9069\u7528\u65BC\u96B1\u85CF\u8207 Claudian \u7121\u95DC\u7684 Claude Code \u547D\u4EE4\u3002\u6BCF\u884C\u8F38\u5165\u4E00\u500B\u547D\u4EE4\u540D\u7A31\uFF0C\u7121\u9700\u524D\u5C0E\u659C\u7DDA\u3002", + placeholder: "commit\nbuild\ntest" + }, + mcpServers: { + name: "MCP \u4F3A\u670D\u5668", + desc: "\u8A2D\u5B9A\u6A21\u578B\u4E0A\u4E0B\u6587\u5354\u5B9A\u4F3A\u670D\u5668\uFF0C\u900F\u904E\u5916\u90E8\u5DE5\u5177\u548C\u8CC7\u6599\u4F86\u6E90\u64F4\u5C55 Claude \u7684\u80FD\u529B\u3002\u555F\u7528\u4E0A\u4E0B\u6587\u4FDD\u5B58\u6A21\u5F0F\u7684\u4F3A\u670D\u5668\u9700\u8981 @ \u63D0\u53CA\u624D\u80FD\u555F\u7528\u3002" + }, + plugins: { + name: "Claude Code \u5916\u639B\u7A0B\u5F0F", + desc: "\u555F\u7528\u6216\u505C\u7528\u5F9E ~/.claude/plugins \u767C\u73FE\u7684 Claude Code \u5916\u639B\u7A0B\u5F0F\u3002\u5DF2\u555F\u7528\u7684\u5916\u639B\u7A0B\u5F0F\u6309\u5132\u5B58\u5EAB\u5132\u5B58\u3002" + }, + subagents: { + name: "Subagents", + desc: "Configure custom subagents that Claude can delegate to.", + noAgents: "No subagents configured. Click + to create one.", + deleteConfirm: 'Delete subagent "{name}"?', + saveFailed: "Failed to save subagent: {message}", + deleteFailed: "Failed to delete subagent: {message}", + renameCleanupFailed: 'Warning: could not remove old file for "{name}"', + saved: 'Subagent "{name}" {action}', + deleted: 'Subagent "{name}" deleted', + duplicateName: 'An agent named "{name}" already exists', + descriptionRequired: "Description is required", + promptRequired: "System prompt is required", + modal: { + titleEdit: "Edit Subagent", + titleAdd: "Add Subagent", + name: "Name", + nameDesc: "Lowercase letters, numbers, and hyphens only", + namePlaceholder: "code-reviewer", + description: "Description", + descriptionDesc: "Brief description of this agent", + descriptionPlaceholder: "Reviews code for bugs and style", + advancedOptions: "Advanced options", + model: "Model", + modelDesc: "Model override for this agent", + tools: "Tools", + toolsDesc: "Comma-separated list of allowed tools (empty = all)", + disallowedTools: "Disallowed tools", + disallowedToolsDesc: "Comma-separated list of tools to disallow", + skills: "Skills", + skillsDesc: "Comma-separated list of skills", + prompt: "System prompt", + promptDesc: "Instructions for the agent", + promptPlaceholder: "You are a code reviewer. Analyze the given code for..." + } + }, + safety: "\u5B89\u5168", + loadUserSettings: { + name: "\u8F09\u5165\u4F7F\u7528\u8005 Claude \u8A2D\u5B9A", + desc: "\u8F09\u5165 ~/.claude/settings.json\u3002\u555F\u7528\u5F8C\uFF0C\u4F7F\u7528\u8005\u7684 Claude Code \u6B0A\u9650\u898F\u5247\u53EF\u80FD\u7E5E\u904E\u5B89\u5168\u6A21\u5F0F\u3002" + }, + enableBlocklist: { + name: "\u555F\u7528\u547D\u4EE4\u9ED1\u540D\u55AE", + desc: "\u963B\u6B62\u6F5B\u5728\u5371\u96AA\u7684 bash \u547D\u4EE4" + }, + blockedCommands: { + name: "\u963B\u6B62\u7684\u547D\u4EE4 ({platform})", + desc: "\u5728 {platform} \u4E0A\u963B\u6B62\u7684\u6A21\u5F0F\uFF08\u6BCF\u884C\u4E00\u500B\uFF09\u3002\u652F\u63F4\u6B63\u5247\u8868\u793A\u5F0F\u3002", + unixName: "\u963B\u6B62\u7684\u547D\u4EE4 (Unix/Git Bash)", + unixDesc: "Unix \u6A21\u5F0F\u5728 Windows \u4E0A\u4E5F\u6703\u88AB\u963B\u6B62\uFF0C\u56E0\u70BA Git Bash \u53EF\u4EE5\u547C\u53EB\u5B83\u5011\u3002" + }, + exportPaths: { + name: "\u5141\u8A31\u7684\u532F\u51FA\u8DEF\u5F91", + desc: "\u5141\u8A31\u532F\u51FA\u6A94\u6848\u7684\u5132\u5B58\u5EAB\u5916\u90E8\u8DEF\u5F91\uFF08\u6BCF\u884C\u4E00\u500B\uFF09\u3002\u652F\u63F4 ~ \u8868\u793A\u4E3B\u76EE\u9304\u3002" + }, + environment: "\u74B0\u5883", + customVariables: { + name: "\u81EA\u8A02\u8B8A\u6578", + desc: "Claude SDK \u7684\u74B0\u5883\u8B8A\u6578\uFF08KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u500B\uFF09\u3002\u652F\u63F4 export \u524D\u7DB4\u3002" + }, + envSnippets: { + name: "\u7247\u6BB5", + addBtn: "\u65B0\u589E\u7247\u6BB5", + noSnippets: "\u5C1A\u7121\u4FDD\u5B58\u7684\u74B0\u5883\u8B8A\u6578\u7247\u6BB5\u3002\u9EDE\u64CA + \u4FDD\u5B58\u7576\u524D\u914D\u7F6E\u3002", + nameRequired: "\u8ACB\u8F38\u5165\u7247\u6BB5\u540D\u7A31", + modal: { + titleEdit: "\u7DE8\u8F2F\u7247\u6BB5", + titleSave: "\u4FDD\u5B58\u7247\u6BB5", + name: "\u540D\u7A31", + namePlaceholder: "\u6B64\u914D\u7F6E\u7684\u63CF\u8FF0\u6027\u540D\u7A31", + description: "\u63CF\u8FF0", + descPlaceholder: "\u53EF\u9078\u63CF\u8FF0", + envVars: "\u74B0\u5883\u8B8A\u6578", + envVarsPlaceholder: "KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u500B\uFF08\u652F\u63F4 export \u524D\u7DB4\uFF09", + save: "\u4FDD\u5B58", + update: "\u66F4\u65B0", + cancel: "\u53D6\u6D88" + } + }, + customContextLimits: { + name: "\u81EA\u8A02\u4E0A\u4E0B\u6587\u9650\u5236", + desc: "\u70BA\u60A8\u7684\u81EA\u8A02\u6A21\u578B\u8A2D\u5B9A\u4E0A\u4E0B\u6587\u8996\u7A97\u5927\u5C0F\u3002\u7559\u7A7A\u4F7F\u7528\u9810\u8A2D\u503C\uFF08200k \u6B0A\u6756\uFF09\u3002", + invalid: "\u683C\u5F0F\u7121\u6548\u3002\u4F7F\u7528\uFF1A256k\u30011m \u6216\u7CBE\u78BA\u6578\u91CF\uFF081000-10000000\uFF09\u3002" + }, + advanced: "\u9032\u968E", + show1MModel: { + name: "\u555F\u7528\u5177\u6709 1M \u4E0A\u4E0B\u6587\u8996\u7A97\u7684 Sonnet", + desc: "\u5728\u6A21\u578B\u9078\u64C7\u5668\u4E2D\u5C07\u6A19\u6E96 Sonnet \u66FF\u63DB\u70BA Sonnet (1M)\u3002\u5728 200k \u6B0A\u6756\u4EE5\u4E0B\u50F9\u683C\u76F8\u540C\u3002\u9700\u8981 Max \u8A02\u95B1\u3002" + }, + enableChrome: { + name: "\u555F\u7528 Chrome \u64F4\u5145\u529F\u80FD", + desc: "\u5141\u8A31 Claude \u900F\u904E claude-in-chrome \u64F4\u5145\u529F\u80FD\u8207 Chrome \u4E92\u52D5\u3002\u9700\u8981\u5B89\u88DD\u8A72\u64F4\u5145\u529F\u80FD\u3002\u9700\u8981\u91CD\u65B0\u555F\u52D5\u5DE5\u4F5C\u968E\u6BB5\u3002" + }, + maxTabs: { + name: "\u6700\u5927\u804A\u5929\u6A19\u7C64\u6578", + desc: "\u540C\u6642\u958B\u555F\u7684\u6700\u5927\u804A\u5929\u6A19\u7C64\u6578\uFF083-10\uFF09\u3002\u6BCF\u500B\u6A19\u7C64\u4F7F\u7528\u7368\u7ACB\u7684 Claude \u5C0D\u8A71\u3002", + warning: "\u8D85\u904E 5 \u500B\u6A19\u7C64\u53EF\u80FD\u6703\u5F71\u97FF\u6548\u80FD\u548C\u8A18\u61B6\u9AD4\u4F7F\u7528\u3002" + }, + tabBarPosition: { + name: "\u6A19\u7C64\u5217\u4F4D\u7F6E", + desc: "\u9078\u64C7\u6A19\u7C64\u5FBD\u7AE0\u548C\u64CD\u4F5C\u6309\u9215\u7684\u986F\u793A\u4F4D\u7F6E", + input: "\u8F38\u5165\u6846\u4E0A\u65B9\uFF08\u9810\u8A2D\uFF09", + header: "\u5728\u6A19\u984C\u5217" + }, + enableAutoScroll: { + name: "\u4E32\u6D41\u50B3\u8F38\u6642\u81EA\u52D5\u6372\u52D5", + desc: "\u5728 Claude \u4E32\u6D41\u50B3\u8F38\u56DE\u61C9\u6642\u81EA\u52D5\u6372\u52D5\u5230\u5E95\u90E8\u3002\u505C\u7528\u5F8C\u5C07\u505C\u7559\u5728\u9802\u90E8\uFF0C\u5F9E\u982D\u958B\u59CB\u95B1\u8B80\u3002" + }, + openInMainTab: { + name: "\u5728\u4E3B\u7DE8\u8F2F\u5668\u5340\u57DF\u958B\u555F", + desc: "\u5728\u4E2D\u592E\u7DE8\u8F2F\u5668\u5340\u57DF\u4EE5\u4E3B\u5206\u9801\u5F62\u5F0F\u958B\u555F\u804A\u5929\u9762\u677F\uFF0C\u800C\u4E0D\u662F\u5728\u53F3\u5074\u908A\u6B04" + }, + cliPath: { + name: "Claude CLI \u8DEF\u5F91", + desc: "Claude Code CLI \u7684\u81EA\u8A02\u8DEF\u5F91\u3002\u7559\u7A7A\u4F7F\u7528\u81EA\u52D5\u6AA2\u6E2C\u3002", + descWindows: "\u5C0D\u65BC\u539F\u751F\u5B89\u88DD\u7A0B\u5F0F\uFF0C\u4F7F\u7528 claude.exe\u3002\u5C0D\u65BC npm/pnpm/yarn \u6216\u5176\u4ED6\u5957\u4EF6\u7BA1\u7406\u5668\u5B89\u88DD\uFF0C\u4F7F\u7528 cli.js \u8DEF\u5F91\uFF08\u4E0D\u662F claude.cmd\uFF09\u3002", + descUnix: '\u8CBC\u4E0A "which claude" \u7684\u8F38\u51FA - \u9069\u7528\u65BC\u539F\u751F\u5B89\u88DD\u548C npm/pnpm/yarn \u5B89\u88DD\u3002', + validation: { + notExist: "\u8DEF\u5F91\u4E0D\u5B58\u5728", + isDirectory: "\u8DEF\u5F91\u662F\u76EE\u9304\uFF0C\u4E0D\u662F\u6A94\u6848" + } + }, + language: { + name: "\u8A9E\u8A00", + desc: "\u66F4\u6539\u63D2\u4EF6\u4ECB\u9762\u7684\u986F\u793A\u8A9E\u8A00" + } +}; +var zh_TW_default2 = { + common: common10, + settings: settings10 +}; + +// src/i18n/i18n.ts +var translations = { + en: en_exports, + "zh-CN": zh_CN_exports, + "zh-TW": zh_TW_exports, + ja: ja_exports, + ko: ko_exports, + de: de_exports, + fr: fr_exports, + es: es_exports, + ru: ru_exports, + pt: pt_exports +}; +var DEFAULT_LOCALE = "en"; +var currentLocale = DEFAULT_LOCALE; +function t(key, params) { + const dict = translations[currentLocale]; + const keys = key.split("."); + let value = dict; + for (const k of keys) { + if (value && typeof value === "object" && k in value) { + value = value[k]; + } else { + if (currentLocale !== DEFAULT_LOCALE) { + return tFallback(key, params); + } + return key; + } + } + if (typeof value !== "string") { + return key; + } + if (params) { + return value.replace(/\{(\w+)\}/g, (_, param) => { + var _a3, _b; + return (_b = (_a3 = params[param]) == null ? void 0 : _a3.toString()) != null ? _b : `{${param}}`; + }); + } + return value; +} +function tFallback(key, params) { + const dict = translations[DEFAULT_LOCALE]; + const keys = key.split("."); + let value = dict; + for (const k of keys) { + if (value && typeof value === "object" && k in value) { + value = value[k]; + } else { + return key; + } + } + if (typeof value !== "string") { + return key; + } + if (params) { + return value.replace(/\{(\w+)\}/g, (_, param) => { + var _a3, _b; + return (_b = (_a3 = params[param]) == null ? void 0 : _a3.toString()) != null ? _b : `{${param}}`; + }); + } + return value; +} +function setLocale(locale) { + if (!translations[locale]) { + return false; + } + currentLocale = locale; + return true; +} +function getAvailableLocales() { + return Object.keys(translations); +} +function getLocaleDisplayName(locale) { + const names = { + "en": "English", + "zh-CN": "\u7B80\u4F53\u4E2D\u6587", + "zh-TW": "\u7E41\u9AD4\u4E2D\u6587", + "ja": "\u65E5\u672C\u8A9E", + "ko": "\uD55C\uAD6D\uC5B4", + "de": "Deutsch", + "fr": "Fran\xE7ais", + "es": "Espa\xF1ol", + "ru": "\u0420\u0443\u0441\u0441\u043A\u0438\u0439", + "pt": "Portugu\xEAs" + }; + return names[locale] || locale; +} + +// src/features/settings/keyboardNavigation.ts +var NAV_ACTIONS = ["scrollUp", "scrollDown", "focusInput"]; +var buildNavMappingText = (settings11) => { + return [ + `map ${settings11.scrollUpKey} scrollUp`, + `map ${settings11.scrollDownKey} scrollDown`, + `map ${settings11.focusInputKey} focusInput` + ].join("\n"); +}; +var parseNavMappings = (value) => { + const parsed = {}; + const usedKeys = /* @__PURE__ */ new Map(); + const lines = value.split("\n"); + for (const rawLine of lines) { + const line = rawLine.trim(); + if (!line) continue; + const parts = line.split(/\s+/); + if (parts.length !== 3 || parts[0] !== "map") { + return { error: 'Each line must follow "map "' }; + } + const key = parts[1]; + const action = parts[2]; + if (!NAV_ACTIONS.includes(action)) { + return { error: `Unknown action: ${parts[2]}` }; + } + if (key.length !== 1) { + return { error: `Key must be a single character for ${action}` }; + } + const normalizedKey = key.toLowerCase(); + if (usedKeys.has(normalizedKey)) { + return { error: "Navigation keys must be unique" }; + } + if (parsed[action]) { + return { error: `Duplicate mapping for ${action}` }; + } + usedKeys.set(normalizedKey, action); + parsed[action] = key; + } + const missing = NAV_ACTIONS.filter((action) => !parsed[action]); + if (missing.length > 0) { + return { error: `Missing mapping for ${missing.join(", ")}` }; + } + return { settings: parsed }; +}; + +// src/features/settings/ui/AgentSettings.ts +var import_obsidian22 = require("obsidian"); + +// src/shared/modals/ConfirmModal.ts +var import_obsidian21 = require("obsidian"); +function confirmDelete(app, message) { + return new Promise((resolve4) => { + new ConfirmModal(app, message, resolve4).open(); + }); +} +var ConfirmModal = class extends import_obsidian21.Modal { + constructor(app, message, resolve4) { super(app); - this.state = "loading"; this.resolved = false; - // UI elements - this.contentSectionEl = null; - this.loadingEl = null; - this.clarificationEl = null; - this.confirmationEl = null; - this.buttonsEl = null; - // Clarification state - this.clarificationTextEl = null; - this.responseTextarea = null; - this.isSubmitting = false; - // Confirmation state - this.refinedInstruction = ""; - this.editTextarea = null; - this.isEditing = false; - this.refinedDisplayEl = null; - this.editContainerEl = null; - this.editBtnEl = null; - this.rawInstruction = rawInstruction; - this.callbacks = callbacks; + this.message = message; + this.resolve = resolve4; } onOpen() { - const { contentEl } = this; - contentEl.addClass("claudian-instruction-modal"); - this.setTitle("Add Custom Instruction"); - const inputSection = contentEl.createDiv({ cls: "claudian-instruction-section" }); - const inputLabel = inputSection.createDiv({ cls: "claudian-instruction-label" }); - inputLabel.setText("Your input:"); - const inputText = inputSection.createDiv({ cls: "claudian-instruction-original" }); - inputText.setText(this.rawInstruction); - this.contentSectionEl = contentEl.createDiv({ cls: "claudian-instruction-content-section" }); - this.loadingEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-loading" }); - this.loadingEl.createDiv({ cls: "claudian-instruction-spinner" }); - this.loadingEl.createSpan({ text: "Processing your instruction..." }); - this.clarificationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-clarification-section" }); - this.clarificationEl.style.display = "none"; - this.clarificationTextEl = this.clarificationEl.createDiv({ cls: "claudian-instruction-clarification" }); - const responseSection = this.clarificationEl.createDiv({ cls: "claudian-instruction-section" }); - const responseLabel = responseSection.createDiv({ cls: "claudian-instruction-label" }); - responseLabel.setText("Your response:"); - this.responseTextarea = new import_obsidian11.TextAreaComponent(responseSection); - this.responseTextarea.inputEl.addClass("claudian-instruction-response-textarea"); - this.responseTextarea.inputEl.rows = 3; - this.responseTextarea.inputEl.placeholder = "Provide more details..."; - this.responseTextarea.inputEl.addEventListener("keydown", (e) => { - if (e.key === "Enter" && !e.shiftKey && !this.isSubmitting) { - e.preventDefault(); - this.submitClarification(); - } - }); - this.confirmationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-confirmation-section" }); - this.confirmationEl.style.display = "none"; - const refinedSection = this.confirmationEl.createDiv({ cls: "claudian-instruction-section" }); - const refinedLabel = refinedSection.createDiv({ cls: "claudian-instruction-label" }); - refinedLabel.setText("Refined snippet:"); - this.refinedDisplayEl = refinedSection.createDiv({ cls: "claudian-instruction-refined" }); - this.editContainerEl = refinedSection.createDiv({ cls: "claudian-instruction-edit-container" }); - this.editContainerEl.style.display = "none"; - this.editTextarea = new import_obsidian11.TextAreaComponent(this.editContainerEl); - this.editTextarea.inputEl.addClass("claudian-instruction-edit-textarea"); - this.editTextarea.inputEl.rows = 4; - this.buttonsEl = contentEl.createDiv({ cls: "claudian-instruction-buttons" }); - this.updateButtons(); - this.showState("loading"); - } - /** Shows clarification question from agent. */ - showClarification(clarification) { - var _a; - if (this.clarificationTextEl) { - this.clarificationTextEl.setText(clarification); - } - if (this.responseTextarea) { - this.responseTextarea.setValue(""); - } - this.isSubmitting = false; - this.showState("clarification"); - (_a = this.responseTextarea) == null ? void 0 : _a.inputEl.focus(); - } - /** Shows confirmation with refined instruction. */ - showConfirmation(refinedInstruction) { - this.refinedInstruction = refinedInstruction; - if (this.refinedDisplayEl) { - this.refinedDisplayEl.setText(refinedInstruction); - } - if (this.editTextarea) { - this.editTextarea.setValue(refinedInstruction); - } - this.showState("confirmation"); - } - /** Shows error and closes modal. */ - showError(error2) { - this.resolved = true; - this.close(); - } - /** Updates the modal to show loading state during clarification submit. */ - showClarificationLoading() { - this.isSubmitting = true; - if (this.loadingEl) { - this.loadingEl.querySelector(".claudian-instruction-spinner"); - const text = this.loadingEl.querySelector("span"); - if (text) text.textContent = "Processing..."; - } - this.showState("loading"); - } - showState(state) { - this.state = state; - if (this.loadingEl) { - this.loadingEl.style.display = state === "loading" ? "flex" : "none"; - } - if (this.clarificationEl) { - this.clarificationEl.style.display = state === "clarification" ? "block" : "none"; - } - if (this.confirmationEl) { - this.confirmationEl.style.display = state === "confirmation" ? "block" : "none"; - } - this.updateButtons(); - } - updateButtons() { - if (!this.buttonsEl) return; - this.buttonsEl.empty(); - const cancelBtn = this.buttonsEl.createEl("button", { - text: "Cancel", - cls: "claudian-instruction-btn claudian-instruction-reject-btn", - attr: { "aria-label": "Cancel" } - }); - cancelBtn.addEventListener("click", () => this.handleReject()); - if (this.state === "clarification") { - const submitBtn = this.buttonsEl.createEl("button", { - text: "Submit", - cls: "claudian-instruction-btn claudian-instruction-accept-btn", - attr: { "aria-label": "Submit response" } - }); - submitBtn.addEventListener("click", () => this.submitClarification()); - } else if (this.state === "confirmation") { - this.editBtnEl = this.buttonsEl.createEl("button", { - text: "Edit", - cls: "claudian-instruction-btn claudian-instruction-edit-btn", - attr: { "aria-label": "Edit instruction" } - }); - this.editBtnEl.addEventListener("click", () => this.toggleEdit()); - const acceptBtn = this.buttonsEl.createEl("button", { - text: "Accept", - cls: "claudian-instruction-btn claudian-instruction-accept-btn", - attr: { "aria-label": "Accept instruction" } - }); - acceptBtn.addEventListener("click", () => this.handleAccept()); - acceptBtn.focus(); - } - } - async submitClarification() { - var _a; - const response = (_a = this.responseTextarea) == null ? void 0 : _a.getValue().trim(); - if (!response || this.isSubmitting) return; - this.showClarificationLoading(); - try { - await this.callbacks.onClarificationSubmit(response); - } catch (e) { - this.isSubmitting = false; - this.showState("clarification"); - } - } - toggleEdit() { - var _a, _b; - this.isEditing = !this.isEditing; - if (this.isEditing) { - if (this.refinedDisplayEl) this.refinedDisplayEl.style.display = "none"; - if (this.editContainerEl) this.editContainerEl.style.display = "block"; - if (this.editBtnEl) this.editBtnEl.setText("Preview"); - (_a = this.editTextarea) == null ? void 0 : _a.inputEl.focus(); - } else { - const edited = ((_b = this.editTextarea) == null ? void 0 : _b.getValue()) || this.refinedInstruction; - this.refinedInstruction = edited; - if (this.refinedDisplayEl) { - this.refinedDisplayEl.setText(edited); - this.refinedDisplayEl.style.display = "block"; - } - if (this.editContainerEl) this.editContainerEl.style.display = "none"; - if (this.editBtnEl) this.editBtnEl.setText("Edit"); - } - } - handleAccept() { - var _a; - if (this.resolved) return; - this.resolved = true; - const finalInstruction = this.isEditing ? ((_a = this.editTextarea) == null ? void 0 : _a.getValue()) || this.refinedInstruction : this.refinedInstruction; - this.callbacks.onAccept(finalInstruction); - this.close(); - } - handleReject() { - if (this.resolved) return; - this.resolved = true; - this.callbacks.onReject(); - this.close(); + this.setTitle(t("common.confirm")); + this.modalEl.addClass("claudian-confirm-modal"); + this.contentEl.createEl("p", { text: this.message }); + new import_obsidian21.Setting(this.contentEl).addButton( + (btn) => btn.setButtonText(t("common.cancel")).onClick(() => this.close()) + ).addButton( + (btn) => btn.setButtonText(t("common.delete")).setWarning().onClick(() => { + this.resolved = true; + this.resolve(true); + this.close(); + }) + ); } onClose() { if (!this.resolved) { - this.resolved = true; - this.callbacks.onReject(); + this.resolve(false); } this.contentEl.empty(); } }; -// src/ui/modals/McpServerModal.ts -var import_obsidian12 = require("obsidian"); -var McpServerModal = class extends import_obsidian12.Modal { +// src/features/settings/ui/AgentSettings.ts +var MODEL_OPTIONS = [ + { value: "inherit", label: "Inherit" }, + { value: "sonnet", label: "Sonnet" }, + { value: "opus", label: "Opus" }, + { value: "haiku", label: "Haiku" } +]; +var AgentModal = class extends import_obsidian22.Modal { + constructor(app, plugin, existingAgent, onSave) { + super(app); + this.plugin = plugin; + this.existingAgent = existingAgent; + this.onSave = onSave; + } + onOpen() { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j; + this.setTitle( + this.existingAgent ? t("settings.subagents.modal.titleEdit") : t("settings.subagents.modal.titleAdd") + ); + this.modalEl.addClass("claudian-sp-modal"); + const { contentEl } = this; + let nameInput; + let descInput; + let modelValue = (_b = (_a3 = this.existingAgent) == null ? void 0 : _a3.model) != null ? _b : "inherit"; + let toolsInput; + let disallowedToolsInput; + let skillsInput; + new import_obsidian22.Setting(contentEl).setName(t("settings.subagents.modal.name")).setDesc(t("settings.subagents.modal.nameDesc")).addText((text) => { + var _a4; + nameInput = text.inputEl; + text.setValue(((_a4 = this.existingAgent) == null ? void 0 : _a4.name) || "").setPlaceholder(t("settings.subagents.modal.namePlaceholder")); + }); + new import_obsidian22.Setting(contentEl).setName(t("settings.subagents.modal.description")).setDesc(t("settings.subagents.modal.descriptionDesc")).addText((text) => { + var _a4; + descInput = text.inputEl; + text.setValue(((_a4 = this.existingAgent) == null ? void 0 : _a4.description) || "").setPlaceholder(t("settings.subagents.modal.descriptionPlaceholder")); + }); + const details = contentEl.createEl("details", { cls: "claudian-sp-advanced-section" }); + details.createEl("summary", { + text: t("settings.subagents.modal.advancedOptions"), + cls: "claudian-sp-advanced-summary" + }); + if (((_c = this.existingAgent) == null ? void 0 : _c.model) && this.existingAgent.model !== "inherit" || ((_e = (_d = this.existingAgent) == null ? void 0 : _d.tools) == null ? void 0 : _e.length) || ((_g = (_f = this.existingAgent) == null ? void 0 : _f.disallowedTools) == null ? void 0 : _g.length) || ((_i = (_h = this.existingAgent) == null ? void 0 : _h.skills) == null ? void 0 : _i.length)) { + details.open = true; + } + new import_obsidian22.Setting(details).setName(t("settings.subagents.modal.model")).setDesc(t("settings.subagents.modal.modelDesc")).addDropdown((dropdown) => { + for (const opt of MODEL_OPTIONS) { + dropdown.addOption(opt.value, opt.label); + } + dropdown.setValue(modelValue).onChange((value) => { + modelValue = value; + }); + }); + new import_obsidian22.Setting(details).setName(t("settings.subagents.modal.tools")).setDesc(t("settings.subagents.modal.toolsDesc")).addText((text) => { + var _a4, _b2; + toolsInput = text.inputEl; + text.setValue(((_b2 = (_a4 = this.existingAgent) == null ? void 0 : _a4.tools) == null ? void 0 : _b2.join(", ")) || ""); + }); + new import_obsidian22.Setting(details).setName(t("settings.subagents.modal.disallowedTools")).setDesc(t("settings.subagents.modal.disallowedToolsDesc")).addText((text) => { + var _a4, _b2; + disallowedToolsInput = text.inputEl; + text.setValue(((_b2 = (_a4 = this.existingAgent) == null ? void 0 : _a4.disallowedTools) == null ? void 0 : _b2.join(", ")) || ""); + }); + new import_obsidian22.Setting(details).setName(t("settings.subagents.modal.skills")).setDesc(t("settings.subagents.modal.skillsDesc")).addText((text) => { + var _a4, _b2; + skillsInput = text.inputEl; + text.setValue(((_b2 = (_a4 = this.existingAgent) == null ? void 0 : _a4.skills) == null ? void 0 : _b2.join(", ")) || ""); + }); + new import_obsidian22.Setting(contentEl).setName(t("settings.subagents.modal.prompt")).setDesc(t("settings.subagents.modal.promptDesc")); + const contentArea = contentEl.createEl("textarea", { + cls: "claudian-sp-content-area", + attr: { + rows: "10", + placeholder: t("settings.subagents.modal.promptPlaceholder") + } + }); + contentArea.value = ((_j = this.existingAgent) == null ? void 0 : _j.prompt) || ""; + const buttonContainer = contentEl.createDiv({ cls: "claudian-sp-modal-buttons" }); + const cancelBtn = buttonContainer.createEl("button", { + text: t("common.cancel"), + cls: "claudian-cancel-btn" + }); + cancelBtn.addEventListener("click", () => this.close()); + const saveBtn = buttonContainer.createEl("button", { + text: t("common.save"), + cls: "claudian-save-btn" + }); + saveBtn.addEventListener("click", async () => { + var _a4, _b2, _c2; + const name = nameInput.value.trim(); + const nameError = validateAgentName(name); + if (nameError) { + new import_obsidian22.Notice(nameError); + return; + } + const description = descInput.value.trim(); + if (!description) { + new import_obsidian22.Notice(t("settings.subagents.descriptionRequired")); + return; + } + const prompt = contentArea.value; + if (!prompt.trim()) { + new import_obsidian22.Notice(t("settings.subagents.promptRequired")); + return; + } + const allAgents = this.plugin.agentManager.getAvailableAgents(); + const duplicate = allAgents.find( + (a) => { + var _a5; + return a.id.toLowerCase() === name.toLowerCase() && a.id !== ((_a5 = this.existingAgent) == null ? void 0 : _a5.id); + } + ); + if (duplicate) { + new import_obsidian22.Notice(t("settings.subagents.duplicateName", { name })); + return; + } + const parseList = (input) => { + const val = input.value.trim(); + if (!val) return void 0; + return val.split(",").map((s) => s.trim()).filter(Boolean); + }; + const agent = { + id: name, + name, + description, + prompt, + tools: parseList(toolsInput), + disallowedTools: parseList(disallowedToolsInput), + model: modelValue || "inherit", + source: "vault", + filePath: this.existingAgent && this.existingAgent.name === name ? this.existingAgent.filePath : void 0, + skills: parseList(skillsInput), + permissionMode: (_a4 = this.existingAgent) == null ? void 0 : _a4.permissionMode, + hooks: (_b2 = this.existingAgent) == null ? void 0 : _b2.hooks, + extraFrontmatter: (_c2 = this.existingAgent) == null ? void 0 : _c2.extraFrontmatter + }; + try { + await this.onSave(agent); + } catch (err) { + const message = err instanceof Error ? err.message : "Unknown error"; + new import_obsidian22.Notice(t("settings.subagents.saveFailed", { message })); + return; + } + this.close(); + }); + } + onClose() { + this.contentEl.empty(); + } +}; +var AgentSettings = class { + constructor(containerEl, plugin) { + this.containerEl = containerEl; + this.plugin = plugin; + this.render(); + } + render() { + this.containerEl.empty(); + const headerEl = this.containerEl.createDiv({ cls: "claudian-sp-header" }); + headerEl.createSpan({ text: t("settings.subagents.name"), cls: "claudian-sp-label" }); + const actionsEl = headerEl.createDiv({ cls: "claudian-sp-header-actions" }); + const addBtn = actionsEl.createEl("button", { + cls: "claudian-settings-action-btn", + attr: { "aria-label": t("common.add") } + }); + (0, import_obsidian22.setIcon)(addBtn, "plus"); + addBtn.addEventListener("click", () => this.openAgentModal(null)); + const allAgents = this.plugin.agentManager.getAvailableAgents(); + const vaultAgents = allAgents.filter((a) => a.source === "vault"); + if (vaultAgents.length === 0) { + const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" }); + emptyEl.setText(t("settings.subagents.noAgents")); + return; + } + const listEl = this.containerEl.createDiv({ cls: "claudian-sp-list" }); + for (const agent of vaultAgents) { + this.renderAgentItem(listEl, agent); + } + } + renderAgentItem(listEl, agent) { + const itemEl = listEl.createDiv({ cls: "claudian-sp-item" }); + const infoEl = itemEl.createDiv({ cls: "claudian-sp-info" }); + const headerRow = infoEl.createDiv({ cls: "claudian-sp-item-header" }); + const nameEl = headerRow.createSpan({ cls: "claudian-sp-item-name" }); + nameEl.setText(agent.name); + if (agent.description) { + const descEl = infoEl.createDiv({ cls: "claudian-sp-item-desc" }); + descEl.setText(agent.description); + } + const actionsEl = itemEl.createDiv({ cls: "claudian-sp-item-actions" }); + const editBtn = actionsEl.createEl("button", { + cls: "claudian-settings-action-btn", + attr: { "aria-label": t("common.edit") } + }); + (0, import_obsidian22.setIcon)(editBtn, "pencil"); + editBtn.addEventListener("click", () => this.openAgentModal(agent)); + const deleteBtn = actionsEl.createEl("button", { + cls: "claudian-settings-action-btn claudian-settings-delete-btn", + attr: { "aria-label": t("common.delete") } + }); + (0, import_obsidian22.setIcon)(deleteBtn, "trash-2"); + deleteBtn.addEventListener("click", async () => { + const confirmed = await confirmDelete( + this.plugin.app, + t("settings.subagents.deleteConfirm", { name: agent.name }) + ); + if (!confirmed) return; + try { + await this.deleteAgent(agent); + } catch (err) { + const message = err instanceof Error ? err.message : "Unknown error"; + new import_obsidian22.Notice(t("settings.subagents.deleteFailed", { message })); + } + }); + } + openAgentModal(existingAgent) { + new AgentModal( + this.plugin.app, + this.plugin, + existingAgent, + (agent) => this.saveAgent(agent, existingAgent) + ).open(); + } + async saveAgent(agent, existing) { + await this.plugin.storage.agents.save(agent); + if (existing && existing.name !== agent.name) { + try { + await this.plugin.storage.agents.delete(existing); + } catch (e2) { + new import_obsidian22.Notice(t("settings.subagents.renameCleanupFailed", { name: existing.name })); + } + } + try { + await this.plugin.agentManager.loadAgents(); + } catch (e2) { + } + this.render(); + const action = existing ? "updated" : "created"; + new import_obsidian22.Notice(t("settings.subagents.saved", { name: agent.name, action })); + } + async deleteAgent(agent) { + await this.plugin.storage.agents.delete(agent); + try { + await this.plugin.agentManager.loadAgents(); + } catch (e2) { + } + this.render(); + new import_obsidian22.Notice(t("settings.subagents.deleted", { name: agent.name })); + } +}; + +// src/features/settings/ui/EnvSnippetManager.ts +var import_obsidian23 = require("obsidian"); +var EnvSnippetModal = class extends import_obsidian23.Modal { + constructor(app, plugin, snippet, onSave) { + super(app); + this.plugin = plugin; + this.snippet = snippet; + this.onSave = onSave; + } + onOpen() { + const { contentEl } = this; + this.setTitle(this.snippet ? t("settings.envSnippets.modal.titleEdit") : t("settings.envSnippets.modal.titleSave")); + this.modalEl.addClass("claudian-env-snippet-modal"); + let nameEl; + let descEl; + let envVarsEl; + const contextLimitInputs = /* @__PURE__ */ new Map(); + let contextLimitsContainer = null; + const handleKeyDown = (e2) => { + if (e2.key === "Enter" && !e2.isComposing) { + e2.preventDefault(); + saveSnippet(); + } else if (e2.key === "Escape" && !e2.isComposing) { + e2.preventDefault(); + this.close(); + } + }; + const saveSnippet = () => { + var _a3; + const name = nameEl.value.trim(); + if (!name) { + new import_obsidian23.Notice(t("settings.envSnippets.nameRequired")); + return; + } + const contextLimits = {}; + for (const [modelId, input] of contextLimitInputs) { + const value = input.value.trim(); + if (value) { + const parsed = parseContextLimit(value); + if (parsed !== null) { + contextLimits[modelId] = parsed; + } + } + } + const snippet = { + id: ((_a3 = this.snippet) == null ? void 0 : _a3.id) || `snippet-${Date.now()}`, + name, + description: descEl.value.trim(), + envVars: envVarsEl.value, + contextLimits: Object.keys(contextLimits).length > 0 ? contextLimits : void 0 + }; + this.onSave(snippet); + this.close(); + }; + const renderContextLimitFields = () => { + var _a3, _b, _c; + if (!contextLimitsContainer) return; + contextLimitsContainer.empty(); + contextLimitInputs.clear(); + const envVars = parseEnvironmentVariables(envVarsEl.value); + const uniqueModelIds = getCustomModelIds(envVars); + if (uniqueModelIds.size === 0) { + contextLimitsContainer.style.display = "none"; + return; + } + contextLimitsContainer.style.display = "block"; + const existingLimits = (_c = (_b = (_a3 = this.snippet) == null ? void 0 : _a3.contextLimits) != null ? _b : this.plugin.settings.customContextLimits) != null ? _c : {}; + contextLimitsContainer.createEl("div", { + text: t("settings.customContextLimits.name"), + cls: "setting-item-name" + }); + contextLimitsContainer.createEl("div", { + text: t("settings.customContextLimits.desc"), + cls: "setting-item-description" + }); + for (const modelId of uniqueModelIds) { + const row = contextLimitsContainer.createDiv({ cls: "claudian-snippet-limit-row" }); + row.createSpan({ text: modelId, cls: "claudian-snippet-limit-model" }); + row.createSpan({ cls: "claudian-snippet-limit-spacer" }); + const input = row.createEl("input", { + type: "text", + placeholder: "200k", + cls: "claudian-snippet-limit-input" + }); + input.value = existingLimits[modelId] ? formatContextLimit(existingLimits[modelId]) : ""; + contextLimitInputs.set(modelId, input); + } + }; + new import_obsidian23.Setting(contentEl).setName(t("settings.envSnippets.modal.name")).setDesc(t("settings.envSnippets.modal.namePlaceholder")).addText((text) => { + var _a3; + nameEl = text.inputEl; + text.setValue(((_a3 = this.snippet) == null ? void 0 : _a3.name) || ""); + text.inputEl.addEventListener("keydown", handleKeyDown); + }); + new import_obsidian23.Setting(contentEl).setName(t("settings.envSnippets.modal.description")).setDesc(t("settings.envSnippets.modal.descPlaceholder")).addText((text) => { + var _a3; + descEl = text.inputEl; + text.setValue(((_a3 = this.snippet) == null ? void 0 : _a3.description) || ""); + text.inputEl.addEventListener("keydown", handleKeyDown); + }); + const envVarsSetting = new import_obsidian23.Setting(contentEl).setName(t("settings.envSnippets.modal.envVars")).setDesc(t("settings.envSnippets.modal.envVarsPlaceholder")).addTextArea((text) => { + var _a3, _b; + envVarsEl = text.inputEl; + const envVarsToShow = (_b = (_a3 = this.snippet) == null ? void 0 : _a3.envVars) != null ? _b : this.plugin.settings.environmentVariables; + text.setValue(envVarsToShow); + text.inputEl.rows = 8; + text.inputEl.addEventListener("blur", () => renderContextLimitFields()); + }); + envVarsSetting.settingEl.addClass("claudian-env-snippet-setting"); + envVarsSetting.controlEl.addClass("claudian-env-snippet-control"); + contextLimitsContainer = contentEl.createDiv({ cls: "claudian-snippet-context-limits" }); + renderContextLimitFields(); + const buttonContainer = contentEl.createDiv({ cls: "claudian-snippet-buttons" }); + const cancelBtn = buttonContainer.createEl("button", { + text: t("settings.envSnippets.modal.cancel"), + cls: "claudian-cancel-btn" + }); + cancelBtn.addEventListener("click", () => this.close()); + const saveBtn = buttonContainer.createEl("button", { + text: this.snippet ? t("settings.envSnippets.modal.update") : t("settings.envSnippets.modal.save"), + cls: "claudian-save-btn" + }); + saveBtn.addEventListener("click", () => saveSnippet()); + setTimeout(() => nameEl == null ? void 0 : nameEl.focus(), 50); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +}; +var EnvSnippetManager = class { + constructor(containerEl, plugin, onContextLimitsChange) { + this.containerEl = containerEl; + this.plugin = plugin; + this.onContextLimitsChange = onContextLimitsChange; + this.render(); + } + render() { + this.containerEl.empty(); + const headerEl = this.containerEl.createDiv({ cls: "claudian-snippet-header" }); + headerEl.createSpan({ text: t("settings.envSnippets.name"), cls: "claudian-snippet-label" }); + const saveBtn = headerEl.createEl("button", { + cls: "claudian-settings-action-btn", + attr: { "aria-label": t("settings.envSnippets.addBtn") } + }); + (0, import_obsidian23.setIcon)(saveBtn, "plus"); + saveBtn.addEventListener("click", () => this.saveCurrentEnv()); + const snippets = this.plugin.settings.envSnippets; + if (snippets.length === 0) { + const emptyEl = this.containerEl.createDiv({ cls: "claudian-snippet-empty" }); + emptyEl.setText(t("settings.envSnippets.noSnippets")); + return; + } + const listEl = this.containerEl.createDiv({ cls: "claudian-snippet-list" }); + for (const snippet of snippets) { + const itemEl = listEl.createDiv({ cls: "claudian-snippet-item" }); + const infoEl = itemEl.createDiv({ cls: "claudian-snippet-info" }); + const nameEl = infoEl.createDiv({ cls: "claudian-snippet-name" }); + nameEl.setText(snippet.name); + if (snippet.description) { + const descEl = infoEl.createDiv({ cls: "claudian-snippet-description" }); + descEl.setText(snippet.description); + } + const actionsEl = itemEl.createDiv({ cls: "claudian-snippet-actions" }); + const restoreBtn = actionsEl.createEl("button", { + cls: "claudian-settings-action-btn", + attr: { "aria-label": "Insert" } + }); + (0, import_obsidian23.setIcon)(restoreBtn, "clipboard-paste"); + restoreBtn.addEventListener("click", async () => { + try { + await this.insertSnippet(snippet); + } catch (e2) { + new import_obsidian23.Notice("Failed to insert snippet"); + } + }); + const editBtn = actionsEl.createEl("button", { + cls: "claudian-settings-action-btn", + attr: { "aria-label": "Edit" } + }); + (0, import_obsidian23.setIcon)(editBtn, "pencil"); + editBtn.addEventListener("click", () => { + this.editSnippet(snippet); + }); + const deleteBtn = actionsEl.createEl("button", { + cls: "claudian-settings-action-btn claudian-settings-delete-btn", + attr: { "aria-label": "Delete" } + }); + (0, import_obsidian23.setIcon)(deleteBtn, "trash-2"); + deleteBtn.addEventListener("click", async () => { + try { + if (confirm(`Delete environment snippet "${snippet.name}"?`)) { + await this.deleteSnippet(snippet); + } + } catch (e2) { + new import_obsidian23.Notice("Failed to delete snippet"); + } + }); + } + } + async saveCurrentEnv() { + const modal = new EnvSnippetModal( + this.plugin.app, + this.plugin, + null, + async (snippet) => { + this.plugin.settings.envSnippets.push(snippet); + await this.plugin.saveSettings(); + this.render(); + new import_obsidian23.Notice(`Environment snippet "${snippet.name}" saved`); + } + ); + modal.open(); + } + async insertSnippet(snippet) { + var _a3, _b; + const snippetContent = snippet.envVars.trim(); + const envTextarea = document.querySelector(".claudian-settings-env-textarea"); + if (envTextarea) { + envTextarea.value = snippetContent; + } else { + this.render(); + } + await this.plugin.applyEnvironmentVariables(snippetContent); + if (snippet.contextLimits) { + this.plugin.settings.customContextLimits = { + ...this.plugin.settings.customContextLimits, + ...snippet.contextLimits + }; + } + await this.plugin.saveSettings(); + (_a3 = this.onContextLimitsChange) == null ? void 0 : _a3.call(this); + const view = (_b = this.plugin.app.workspace.getLeavesOfType("claudian-view")[0]) == null ? void 0 : _b.view; + view == null ? void 0 : view.refreshModelSelector(); + } + editSnippet(snippet) { + const modal = new EnvSnippetModal( + this.plugin.app, + this.plugin, + snippet, + async (updatedSnippet) => { + const index = this.plugin.settings.envSnippets.findIndex((s) => s.id === snippet.id); + if (index !== -1) { + this.plugin.settings.envSnippets[index] = updatedSnippet; + await this.plugin.saveSettings(); + this.render(); + new import_obsidian23.Notice(`Environment snippet "${updatedSnippet.name}" updated`); + } + } + ); + modal.open(); + } + async deleteSnippet(snippet) { + this.plugin.settings.envSnippets = this.plugin.settings.envSnippets.filter((s) => s.id !== snippet.id); + await this.plugin.saveSettings(); + this.render(); + new import_obsidian23.Notice(`Environment snippet "${snippet.name}" deleted`); + } + refresh() { + this.render(); + } +}; + +// src/features/settings/ui/McpSettingsManager.ts +var import_obsidian26 = require("obsidian"); + +// src/features/settings/ui/McpServerModal.ts +var import_obsidian24 = require("obsidian"); +var McpServerModal = class extends import_obsidian24.Modal { constructor(app, plugin, existingServer, onSave, initialType, prefillConfig) { super(app); - // Form state this.serverName = ""; this.serverType = "stdio"; this.enabled = DEFAULT_MCP_SERVER.enabled; this.contextSaving = DEFAULT_MCP_SERVER.contextSaving; - // Stdio fields this.command = ""; - // Full command including args this.env = ""; - // SSE/HTTP fields this.url = ""; this.headers = ""; - // DOM references this.typeFieldsEl = null; this.nameInputEl = null; this.plugin = plugin; @@ -31366,7 +64258,6 @@ var McpServerModal = class extends import_obsidian12.Modal { this.serverType = initialType; } } - /** Initialize form fields from a config object. */ initFromConfig(config2) { const type = getMcpServerType(config2); if (type === "stdio") { @@ -31387,16 +64278,16 @@ var McpServerModal = class extends import_obsidian12.Modal { this.setTitle(this.existingServer ? "Edit MCP Server" : "Add MCP Server"); this.modalEl.addClass("claudian-mcp-modal"); const { contentEl } = this; - new import_obsidian12.Setting(contentEl).setName("Server name").setDesc("Unique identifier for this server").addText((text) => { + new import_obsidian24.Setting(contentEl).setName("Server name").setDesc("Unique identifier for this server").addText((text) => { this.nameInputEl = text.inputEl; text.setValue(this.serverName); text.setPlaceholder("my-mcp-server"); text.onChange((value) => { this.serverName = value; }); - text.inputEl.addEventListener("keydown", (e) => this.handleKeyDown(e)); + text.inputEl.addEventListener("keydown", (e2) => this.handleKeyDown(e2)); }); - new import_obsidian12.Setting(contentEl).setName("Type").setDesc("Server connection type").addDropdown((dropdown) => { + new import_obsidian24.Setting(contentEl).setName("Type").setDesc("Server connection type").addDropdown((dropdown) => { dropdown.addOption("stdio", "stdio (local command)"); dropdown.addOption("sse", "sse (Server-Sent Events)"); dropdown.addOption("http", "http (HTTP endpoint)"); @@ -31408,13 +64299,13 @@ var McpServerModal = class extends import_obsidian12.Modal { }); this.typeFieldsEl = contentEl.createDiv({ cls: "claudian-mcp-type-fields" }); this.renderTypeFields(); - new import_obsidian12.Setting(contentEl).setName("Enabled").setDesc("Whether this server is active").addToggle((toggle) => { + new import_obsidian24.Setting(contentEl).setName("Enabled").setDesc("Whether this server is active").addToggle((toggle) => { toggle.setValue(this.enabled); toggle.onChange((value) => { this.enabled = value; }); }); - new import_obsidian12.Setting(contentEl).setName("Context-saving mode").setDesc("Hide tools from agent unless @-mentioned (saves context window)").addToggle((toggle) => { + new import_obsidian24.Setting(contentEl).setName("Context-saving mode").setDesc("Hide tools from agent unless @-mentioned (saves context window)").addToggle((toggle) => { toggle.setValue(this.contextSaving); toggle.onChange((value) => { this.contextSaving = value; @@ -31443,7 +64334,7 @@ var McpServerModal = class extends import_obsidian12.Modal { } renderStdioFields() { if (!this.typeFieldsEl) return; - const cmdSetting = new import_obsidian12.Setting(this.typeFieldsEl).setName("Command").setDesc("Full command with arguments"); + const cmdSetting = new import_obsidian24.Setting(this.typeFieldsEl).setName("Command").setDesc("Full command with arguments"); cmdSetting.settingEl.addClass("claudian-mcp-cmd-setting"); const cmdTextarea = cmdSetting.controlEl.createEl("textarea", { cls: "claudian-mcp-cmd-textarea" @@ -31454,7 +64345,7 @@ var McpServerModal = class extends import_obsidian12.Modal { cmdTextarea.addEventListener("input", () => { this.command = cmdTextarea.value; }); - const envSetting = new import_obsidian12.Setting(this.typeFieldsEl).setName("Environment variables").setDesc("KEY=VALUE per line (optional)"); + const envSetting = new import_obsidian24.Setting(this.typeFieldsEl).setName("Environment variables").setDesc("KEY=VALUE per line (optional)"); envSetting.settingEl.addClass("claudian-mcp-env-setting"); const envTextarea = envSetting.controlEl.createEl("textarea", { cls: "claudian-mcp-env-textarea" @@ -31468,15 +64359,15 @@ var McpServerModal = class extends import_obsidian12.Modal { } renderUrlFields() { if (!this.typeFieldsEl) return; - new import_obsidian12.Setting(this.typeFieldsEl).setName("URL").setDesc(this.serverType === "sse" ? "SSE endpoint URL" : "HTTP endpoint URL").addText((text) => { + new import_obsidian24.Setting(this.typeFieldsEl).setName("URL").setDesc(this.serverType === "sse" ? "SSE endpoint URL" : "HTTP endpoint URL").addText((text) => { text.setValue(this.url); text.setPlaceholder("http://localhost:3000/sse"); text.onChange((value) => { this.url = value; }); - text.inputEl.addEventListener("keydown", (e) => this.handleKeyDown(e)); + text.inputEl.addEventListener("keydown", (e2) => this.handleKeyDown(e2)); }); - const headersSetting = new import_obsidian12.Setting(this.typeFieldsEl).setName("Headers").setDesc("HTTP headers (KEY=VALUE per line)"); + const headersSetting = new import_obsidian24.Setting(this.typeFieldsEl).setName("Headers").setDesc("HTTP headers (KEY=VALUE per line)"); headersSetting.settingEl.addClass("claudian-mcp-env-setting"); const headersTextarea = headersSetting.controlEl.createEl("textarea", { cls: "claudian-mcp-env-textarea" @@ -31488,25 +64379,25 @@ var McpServerModal = class extends import_obsidian12.Modal { this.headers = headersTextarea.value; }); } - handleKeyDown(e) { - if (e.key === "Enter" && !e.shiftKey) { - e.preventDefault(); + handleKeyDown(e2) { + if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing) { + e2.preventDefault(); this.save(); - } else if (e.key === "Escape") { - e.preventDefault(); + } else if (e2.key === "Escape" && !e2.isComposing) { + e2.preventDefault(); this.close(); } } save() { - var _a, _b, _c; + var _a3, _b, _c; const name = this.serverName.trim(); if (!name) { - new import_obsidian12.Notice("Please enter a server name"); - (_a = this.nameInputEl) == null ? void 0 : _a.focus(); + new import_obsidian24.Notice("Please enter a server name"); + (_a3 = this.nameInputEl) == null ? void 0 : _a3.focus(); return; } if (!/^[a-zA-Z0-9._-]+$/.test(name)) { - new import_obsidian12.Notice("Server name can only contain letters, numbers, dots, hyphens, and underscores"); + new import_obsidian24.Notice("Server name can only contain letters, numbers, dots, hyphens, and underscores"); (_b = this.nameInputEl) == null ? void 0 : _b.focus(); return; } @@ -31514,13 +64405,13 @@ var McpServerModal = class extends import_obsidian12.Modal { if (this.serverType === "stdio") { const fullCommand = this.command.trim(); if (!fullCommand) { - new import_obsidian12.Notice("Please enter a command"); + new import_obsidian24.Notice("Please enter a command"); return; } - const parts = this.parseCommandString(fullCommand); - const stdioConfig = { command: parts.command }; - if (parts.args.length > 0) { - stdioConfig.args = parts.args; + const { cmd, args } = parseCommand(fullCommand); + const stdioConfig = { command: cmd }; + if (args.length > 0) { + stdioConfig.args = args; } const env = this.parseEnvString(this.env); if (Object.keys(env).length > 0) { @@ -31528,20 +64419,20 @@ var McpServerModal = class extends import_obsidian12.Modal { } config2 = stdioConfig; } else { - const url = this.url.trim(); - if (!url) { - new import_obsidian12.Notice("Please enter a URL"); + const url2 = this.url.trim(); + if (!url2) { + new import_obsidian24.Notice("Please enter a URL"); return; } if (this.serverType === "sse") { - const sseConfig = { type: "sse", url }; + const sseConfig = { type: "sse", url: url2 }; const headers = this.parseEnvString(this.headers); if (Object.keys(headers).length > 0) { sseConfig.headers = headers; } config2 = sseConfig; } else { - const httpConfig = { type: "http", url }; + const httpConfig = { type: "http", url: url2 }; const headers = this.parseEnvString(this.headers); if (Object.keys(headers).length > 0) { httpConfig.headers = headers; @@ -31559,40 +64450,6 @@ var McpServerModal = class extends import_obsidian12.Modal { this.onSave(server); this.close(); } - /** Parse a command string into command and args, handling quoted strings. */ - parseCommandString(cmdStr) { - const parts = []; - let current = ""; - let inQuote = false; - let quoteChar = ""; - for (let i = 0; i < cmdStr.length; i++) { - const char = cmdStr[i]; - if ((char === '"' || char === "'") && !inQuote) { - inQuote = true; - quoteChar = char; - } else if (char === quoteChar && inQuote) { - inQuote = false; - quoteChar = ""; - } else if (/\s/.test(char) && !inQuote) { - if (current) { - parts.push(current); - current = ""; - } - } else { - current += char; - } - } - if (current) { - parts.push(current); - } - if (parts.length === 0) { - return { command: "", args: [] }; - } - return { - command: parts[0], - args: parts.slice(1) - }; - } parseEnvString(envStr) { const result = {}; if (!envStr.trim()) return result; @@ -31618,11 +64475,11 @@ var McpServerModal = class extends import_obsidian12.Modal { } }; -// src/ui/modals/McpTestModal.ts -var import_obsidian13 = require("obsidian"); -function formatToggleError(error2) { - if (!(error2 instanceof Error)) return "Failed to update tool setting"; - const msg = error2.message.toLowerCase(); +// src/features/settings/ui/McpTestModal.ts +var import_obsidian25 = require("obsidian"); +function formatToggleError(error48) { + if (!(error48 instanceof Error)) return "Failed to update tool setting"; + const msg = error48.message.toLowerCase(); if (msg.includes("permission") || msg.includes("eacces")) { return "Permission denied. Check .claude/ folder permissions."; } @@ -31632,9 +64489,9 @@ function formatToggleError(error2) { if (msg.includes("json") || msg.includes("syntax")) { return "Config file corrupted. Check .claude/mcp.json"; } - return error2.message || "Failed to update tool setting"; + return error48.message || "Failed to update tool setting"; } -var McpTestModal = class extends import_obsidian13.Modal { +var McpTestModal = class extends import_obsidian25.Modal { constructor(app, serverName, initialDisabledTools, onToolToggle, onBulkToggle) { super(app); this.result = null; @@ -31657,15 +64514,13 @@ var McpTestModal = class extends import_obsidian13.Modal { this.contentEl_ = this.contentEl; this.renderLoading(); } - /** Set the test result and update the display. */ setResult(result) { this.result = result; this.loading = false; this.render(); } - /** Set error state. */ - setError(error2) { - this.result = { success: false, tools: [], error: error2 }; + setError(error48) { + this.result = { success: false, tools: [], error: error48 }; this.loading = false; this.render(); } @@ -31689,10 +64544,10 @@ var McpTestModal = class extends import_obsidian13.Modal { const statusEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-status" }); const iconEl = statusEl.createSpan({ cls: "claudian-mcp-test-icon" }); if (this.result.success) { - (0, import_obsidian13.setIcon)(iconEl, "check-circle"); + (0, import_obsidian25.setIcon)(iconEl, "check-circle"); iconEl.addClass("success"); } else { - (0, import_obsidian13.setIcon)(iconEl, "x-circle"); + (0, import_obsidian25.setIcon)(iconEl, "x-circle"); iconEl.addClass("error"); } const textEl = statusEl.createSpan({ cls: "claudian-mcp-test-text" }); @@ -31744,7 +64599,7 @@ var McpTestModal = class extends import_obsidian13.Modal { const toolEl = container.createDiv({ cls: "claudian-mcp-test-tool" }); const headerEl = toolEl.createDiv({ cls: "claudian-mcp-test-tool-header" }); const iconEl = headerEl.createSpan({ cls: "claudian-mcp-test-tool-icon" }); - (0, import_obsidian13.setIcon)(iconEl, "wrench"); + (0, import_obsidian25.setIcon)(iconEl, "wrench"); const nameEl = headerEl.createSpan({ cls: "claudian-mcp-test-tool-name" }); nameEl.setText(tool.name); const toggleEl = headerEl.createDiv({ cls: "claudian-mcp-test-tool-toggle" }); @@ -31762,9 +64617,9 @@ var McpTestModal = class extends import_obsidian13.Modal { if (!this.onToolToggle) { checkbox.disabled = true; } else { - toggleContainer.addEventListener("click", (e) => { - e.preventDefault(); - e.stopPropagation(); + toggleContainer.addEventListener("click", (e2) => { + e2.preventDefault(); + e2.stopPropagation(); if (checkbox.disabled) return; checkbox.checked = !checkbox.checked; this.handleToolToggle(tool.name, checkbox, toggleContainer); @@ -31776,7 +64631,7 @@ var McpTestModal = class extends import_obsidian13.Modal { } } async handleToolToggle(toolName, checkbox, container) { - var _a; + var _a3; const toolEl = this.toolElements.get(toolName); if (!toolEl) return; const wasDisabled = this.disabledTools.has(toolName); @@ -31791,8 +64646,8 @@ var McpTestModal = class extends import_obsidian13.Modal { this.updateToggleAllButton(); checkbox.disabled = true; try { - await ((_a = this.onToolToggle) == null ? void 0 : _a.call(this, toolName, !nextDisabled)); - } catch (error2) { + await ((_a3 = this.onToolToggle) == null ? void 0 : _a3.call(this, toolName, !nextDisabled)); + } catch (error48) { if (nextDisabled) { this.disabledTools.delete(toolName); } else { @@ -31802,7 +64657,7 @@ var McpTestModal = class extends import_obsidian13.Modal { container.toggleClass("is-enabled", !wasDisabled); this.updateToolState(toolEl, !wasDisabled); this.updateToggleAllButton(); - new import_obsidian13.Notice(formatToggleError(error2)); + new import_obsidian25.Notice(formatToggleError(error48)); } finally { checkbox.disabled = false; } @@ -31826,7 +64681,7 @@ var McpTestModal = class extends import_obsidian13.Modal { if (!this.result || this.pendingToggle || !this.onBulkToggle) return; const allEnabled = this.disabledTools.size === 0; const previousDisabled = new Set(this.disabledTools); - const newDisabledTools = allEnabled ? this.result.tools.map((t) => t.name) : []; + const newDisabledTools = allEnabled ? this.result.tools.map((t2) => t2.name) : []; this.pendingToggle = true; if (this.toggleAllBtn) this.toggleAllBtn.disabled = true; for (const { checkbox } of this.toolToggles.values()) { @@ -31845,7 +64700,7 @@ var McpTestModal = class extends import_obsidian13.Modal { this.updateToggleAllButton(); try { await this.onBulkToggle(newDisabledTools); - } catch (error2) { + } catch (error48) { this.disabledTools = previousDisabled; for (const tool of this.result.tools) { const toggle = this.toolToggles.get(tool.name); @@ -31857,7 +64712,7 @@ var McpTestModal = class extends import_obsidian13.Modal { this.updateToolState(toolEl, isEnabled); } this.updateToggleAllButton(); - new import_obsidian13.Notice(formatToggleError(error2)); + new import_obsidian25.Notice(formatToggleError(error48)); } for (const { checkbox } of this.toolToggles.values()) { checkbox.disabled = false; @@ -31870,1929 +64725,7 @@ var McpTestModal = class extends import_obsidian13.Modal { } }; -// src/ui/renderers/AskUserQuestionRenderer.ts -var import_obsidian14 = require("obsidian"); -function parseAskUserQuestionInput(input) { - if (!input || typeof input !== "object") return null; - const questions = input.questions; - if (!Array.isArray(questions)) return null; - return { - questions, - answers: input.answers - }; -} -function formatAnswer(answer) { - if (Array.isArray(answer)) { - return answer.join(", "); - } - return answer; -} -function renderTreeQA(containerEl, questions, answers) { - const listEl = containerEl.createDiv({ cls: "claudian-ask-question-list" }); - const treeEl = listEl.createSpan({ cls: "claudian-ask-question-tree" }); - treeEl.setText("\u23BF "); - const alignedEl = listEl.createDiv({ cls: "claudian-ask-question-aligned" }); - questions.forEach((question) => { - const answer = answers[question.question]; - if (answer === void 0) return; - const itemEl = alignedEl.createDiv({ cls: "claudian-ask-question-item" }); - const qEl = itemEl.createDiv({ cls: "claudian-ask-question-q" }); - qEl.setText(`Q: ${question.question}`); - const aEl = itemEl.createDiv({ cls: "claudian-ask-question-a" }); - aEl.setText(`A: ${formatAnswer(answer)}`); - }); -} -function createAskUserQuestionBlock(parentEl, toolCall) { - const wrapperEl = parentEl.createDiv({ cls: "claudian-ask-question-block claudian-ask-question-pending" }); - wrapperEl.dataset.toolId = toolCall.id; - wrapperEl.style.display = "none"; - const headerEl = wrapperEl.createDiv({ cls: "claudian-ask-question-header" }); - const contentEl = wrapperEl.createDiv({ cls: "claudian-ask-question-content" }); - return { - wrapperEl, - contentEl, - headerEl, - toolId: toolCall.id - }; -} -function finalizeAskUserQuestionBlock(state, answers, isError, questions) { - const questionList = questions || []; - const questionCount = questionList.length; - state.wrapperEl.style.display = ""; - state.wrapperEl.removeClass("claudian-ask-question-pending"); - if (isError) { - state.wrapperEl.addClass("error"); - } else { - state.wrapperEl.addClass("done"); - } - state.headerEl.empty(); - state.headerEl.setAttribute("tabindex", "0"); - state.headerEl.setAttribute("role", "button"); - state.headerEl.setAttribute("aria-expanded", "false"); - const iconEl = state.headerEl.createDiv({ cls: "claudian-ask-question-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian14.setIcon)(iconEl, "help-circle"); - const labelEl = state.headerEl.createDiv({ cls: "claudian-ask-question-label" }); - labelEl.setText("Clarification"); - const countEl = state.headerEl.createDiv({ cls: "claudian-ask-question-count" }); - countEl.setText(questionCount === 1 ? "1 question" : `${questionCount} questions`); - const statusEl = state.headerEl.createDiv({ cls: `claudian-ask-question-status status-${isError ? "error" : "completed"}` }); - if (isError) { - (0, import_obsidian14.setIcon)(statusEl, "x"); - } else { - (0, import_obsidian14.setIcon)(statusEl, "check"); - } - state.contentEl.empty(); - state.contentEl.style.display = "none"; - if (isError || !answers) { - const errorEl = state.contentEl.createDiv({ cls: "claudian-ask-question-error" }); - errorEl.setText(isError ? "Failed to get response" : "No response received"); - } else { - renderTreeQA(state.contentEl, questionList, answers); - } - const toggleExpand = () => { - const expanded = state.wrapperEl.hasClass("expanded"); - if (expanded) { - state.wrapperEl.removeClass("expanded"); - state.contentEl.style.display = "none"; - state.headerEl.setAttribute("aria-expanded", "false"); - } else { - state.wrapperEl.addClass("expanded"); - state.contentEl.style.display = "block"; - state.headerEl.setAttribute("aria-expanded", "true"); - } - }; - state.headerEl.addEventListener("click", toggleExpand); - state.headerEl.addEventListener("keydown", (e) => { - if (e.key === "Enter" || e.key === " ") { - e.preventDefault(); - toggleExpand(); - } - }); -} -function renderStoredAskUserQuestion(parentEl, toolCall) { - const parsed = parseAskUserQuestionInput(toolCall.input); - const questions = (parsed == null ? void 0 : parsed.questions) || []; - const answers = parsed == null ? void 0 : parsed.answers; - const questionCount = questions.length; - const isError = toolCall.status === "error" || toolCall.status === "blocked"; - const isCompleted = toolCall.status === "completed"; - const wrapperEl = parentEl.createDiv({ cls: "claudian-ask-question-block" }); - wrapperEl.dataset.toolId = toolCall.id; - if (isCompleted) { - wrapperEl.addClass("done"); - } else if (isError) { - wrapperEl.addClass("error"); - } - const headerEl = wrapperEl.createDiv({ cls: "claudian-ask-question-header" }); - headerEl.setAttribute("tabindex", "0"); - headerEl.setAttribute("role", "button"); - headerEl.setAttribute("aria-expanded", "false"); - headerEl.setAttribute("aria-label", `Clarification - ${toolCall.status}`); - const iconEl = headerEl.createDiv({ cls: "claudian-ask-question-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian14.setIcon)(iconEl, "help-circle"); - const labelEl = headerEl.createDiv({ cls: "claudian-ask-question-label" }); - labelEl.setText("Clarification"); - const countEl = headerEl.createDiv({ cls: "claudian-ask-question-count" }); - countEl.setText(questionCount === 1 ? "1 question" : `${questionCount} questions`); - const statusEl = headerEl.createDiv({ cls: `claudian-ask-question-status status-${toolCall.status}` }); - statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`); - if (isCompleted) { - (0, import_obsidian14.setIcon)(statusEl, "check"); - } else if (isError) { - (0, import_obsidian14.setIcon)(statusEl, "x"); - } - const contentEl = wrapperEl.createDiv({ cls: "claudian-ask-question-content" }); - contentEl.style.display = "none"; - if (answers && Object.keys(answers).length > 0) { - renderTreeQA(contentEl, questions, answers); - } else if (isError) { - const errorEl = contentEl.createDiv({ cls: "claudian-ask-question-error" }); - errorEl.setText("Failed to get response"); - } else { - const noAnswerEl = contentEl.createDiv({ cls: "claudian-ask-question-error" }); - noAnswerEl.setText("No response recorded"); - } - const toggleExpand = () => { - const expanded = wrapperEl.hasClass("expanded"); - if (expanded) { - wrapperEl.removeClass("expanded"); - contentEl.style.display = "none"; - headerEl.setAttribute("aria-expanded", "false"); - } else { - wrapperEl.addClass("expanded"); - contentEl.style.display = "block"; - headerEl.setAttribute("aria-expanded", "true"); - } - }; - headerEl.addEventListener("click", toggleExpand); - headerEl.addEventListener("keydown", (e) => { - if (e.key === "Enter" || e.key === " ") { - e.preventDefault(); - toggleExpand(); - } - }); - return wrapperEl; -} - -// src/ui/renderers/DiffRenderer.ts -function computeLineDiff(oldText, newText) { - const oldLines = oldText.replace(/\r\n/g, "\n").split("\n"); - const newLines = newText.replace(/\r\n/g, "\n").split("\n"); - const m = oldLines.length; - const n = newLines.length; - const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0)); - for (let i2 = 1; i2 <= m; i2++) { - for (let j2 = 1; j2 <= n; j2++) { - dp[i2][j2] = oldLines[i2 - 1] === newLines[j2 - 1] ? dp[i2 - 1][j2 - 1] + 1 : Math.max(dp[i2 - 1][j2], dp[i2][j2 - 1]); - } - } - const result = []; - let i = m, j = n; - const temp = []; - while (i > 0 || j > 0) { - if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) { - temp.push({ type: "equal", text: oldLines[i - 1] }); - i--; - j--; - } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) { - temp.push({ type: "insert", text: newLines[j - 1] }); - j--; - } else { - temp.push({ type: "delete", text: oldLines[i - 1] }); - i--; - } - } - temp.reverse(); - let oldLineNum = 1; - let newLineNum = 1; - for (const line of temp) { - if (line.type === "equal") { - result.push({ ...line, oldLineNum: oldLineNum++, newLineNum: newLineNum++ }); - } else if (line.type === "delete") { - result.push({ ...line, oldLineNum: oldLineNum++ }); - } else { - result.push({ ...line, newLineNum: newLineNum++ }); - } - } - return result; -} -function countLineChanges(diffLines) { - let added = 0; - let removed = 0; - for (const line of diffLines) { - if (line.type === "insert") added++; - else if (line.type === "delete") removed++; - } - return { added, removed }; -} -function splitIntoHunks(diffLines, contextLines = 3) { - if (diffLines.length === 0) return []; - const changedIndices = []; - for (let i = 0; i < diffLines.length; i++) { - if (diffLines[i].type !== "equal") { - changedIndices.push(i); - } - } - if (changedIndices.length === 0) return []; - const ranges = []; - for (const idx of changedIndices) { - const start = Math.max(0, idx - contextLines); - const end = Math.min(diffLines.length - 1, idx + contextLines); - if (ranges.length > 0 && start <= ranges[ranges.length - 1].end + 1) { - ranges[ranges.length - 1].end = end; - } else { - ranges.push({ start, end }); - } - } - const hunks = []; - for (const range of ranges) { - const lines = diffLines.slice(range.start, range.end + 1); - let oldStart = 1; - let newStart = 1; - for (let i = 0; i < range.start; i++) { - const line = diffLines[i]; - if (line.type === "equal" || line.type === "delete") oldStart++; - if (line.type === "equal" || line.type === "insert") newStart++; - } - hunks.push({ lines, oldStart, newStart }); - } - return hunks; -} -function renderDiffContent(containerEl, diffLines, contextLines = 3) { - containerEl.empty(); - const hunks = splitIntoHunks(diffLines, contextLines); - if (hunks.length === 0) { - const noChanges = containerEl.createDiv({ cls: "claudian-diff-no-changes" }); - noChanges.setText("No changes"); - return; - } - hunks.forEach((hunk, hunkIndex) => { - if (hunkIndex > 0) { - const separator = containerEl.createDiv({ cls: "claudian-diff-separator" }); - separator.setText("..."); - } - const hunkEl = containerEl.createDiv({ cls: "claudian-diff-hunk" }); - for (const line of hunk.lines) { - const lineEl = hunkEl.createDiv({ cls: `claudian-diff-line claudian-diff-${line.type}` }); - const prefix = line.type === "insert" ? "+" : line.type === "delete" ? "-" : " "; - const prefixEl = lineEl.createSpan({ cls: "claudian-diff-prefix" }); - prefixEl.setText(prefix); - const contentEl = lineEl.createSpan({ cls: "claudian-diff-text" }); - contentEl.setText(line.text || " "); - } - }); -} -function isBinaryContent(content) { - const nonPrintable = content.match(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g); - if (nonPrintable && nonPrintable.length > content.length * 0.1) { - return true; - } - return content.includes("\0"); -} - -// src/ui/renderers/SubagentRenderer.ts -var import_obsidian16 = require("obsidian"); - -// src/ui/utils/collapsible.ts -function setupCollapsible(wrapperEl, headerEl, contentEl, state, options = {}) { - const { initiallyExpanded = false, onToggle, baseAriaLabel } = options; - const updateAriaLabel = (isExpanded) => { - if (baseAriaLabel) { - const action = isExpanded ? "click to collapse" : "click to expand"; - headerEl.setAttribute("aria-label", `${baseAriaLabel} - ${action}`); - } - }; - state.isExpanded = initiallyExpanded; - if (initiallyExpanded) { - wrapperEl.addClass("expanded"); - contentEl.style.display = "block"; - headerEl.setAttribute("aria-expanded", "true"); - } else { - contentEl.style.display = "none"; - headerEl.setAttribute("aria-expanded", "false"); - } - updateAriaLabel(initiallyExpanded); - const toggleExpand = () => { - state.isExpanded = !state.isExpanded; - if (state.isExpanded) { - wrapperEl.addClass("expanded"); - contentEl.style.display = "block"; - headerEl.setAttribute("aria-expanded", "true"); - } else { - wrapperEl.removeClass("expanded"); - contentEl.style.display = "none"; - headerEl.setAttribute("aria-expanded", "false"); - } - updateAriaLabel(state.isExpanded); - onToggle == null ? void 0 : onToggle(state.isExpanded); - }; - headerEl.addEventListener("click", toggleExpand); - headerEl.addEventListener("keydown", (e) => { - if (e.key === "Enter" || e.key === " ") { - e.preventDefault(); - toggleExpand(); - } - }); -} -function collapseElement(wrapperEl, headerEl, contentEl, state) { - state.isExpanded = false; - wrapperEl.removeClass("expanded"); - contentEl.style.display = "none"; - headerEl.setAttribute("aria-expanded", "false"); -} - -// src/ui/renderers/ToolCallRenderer.ts -var import_obsidian15 = require("obsidian"); -function setToolIcon(el, name) { - const icon = getToolIcon(name); - if (icon === MCP_ICON_MARKER) { - el.innerHTML = MCP_ICON_SVG; - } else { - (0, import_obsidian15.setIcon)(el, icon); - } -} -function getToolLabel(name, input) { - switch (name) { - case "Read": - return `Read: ${shortenPath(input.file_path) || "file"}`; - case "Write": - return `Write: ${shortenPath(input.file_path) || "file"}`; - case "Edit": - return `Edit: ${shortenPath(input.file_path) || "file"}`; - case "Bash": { - const cmd = input.command || "command"; - return `Bash: ${cmd.length > 40 ? cmd.substring(0, 40) + "..." : cmd}`; - } - case "Glob": - return `Glob: ${input.pattern || "files"}`; - case "Grep": - return `Grep: ${input.pattern || "pattern"}`; - case "WebSearch": { - const query2 = input.query || "search"; - return `WebSearch: ${query2.length > 40 ? query2.substring(0, 40) + "..." : query2}`; - } - case "WebFetch": { - const url = input.url || "url"; - return `WebFetch: ${url.length > 40 ? url.substring(0, 40) + "..." : url}`; - } - case "LS": - return `LS: ${shortenPath(input.path) || "."}`; - case "TodoWrite": { - const todos = input.todos; - if (todos && Array.isArray(todos)) { - const completed = todos.filter((t) => t.status === "completed").length; - return `Tasks (${completed}/${todos.length})`; - } - return "Tasks"; - } - case "Skill": { - const skillName = input.skill || "skill"; - return `Skill: ${skillName}`; - } - default: - return name; - } -} -function shortenPath(filePath) { - if (!filePath) return ""; - const normalized = filePath.replace(/\\/g, "/"); - const parts = normalized.split("/"); - if (parts.length <= 3) return normalized; - return ".../" + parts.slice(-2).join("/"); -} -function parseWebSearchResult(result) { - const linksMatch = result.match(/Links:\s*(\[[\s\S]*\])/); - if (!linksMatch) return null; - try { - const links = JSON.parse(linksMatch[1]); - if (!Array.isArray(links) || links.length === 0) return null; - return links; - } catch (e) { - return null; - } -} -function renderWebSearchResult(container, result, maxItems = 3) { - const links = parseWebSearchResult(result); - if (!links) return false; - container.empty(); - const displayItems = links.slice(0, maxItems); - displayItems.forEach((link) => { - const item = container.createSpan({ cls: "claudian-tool-result-bullet" }); - item.setText(`\u2022 ${link.title}`); - }); - if (links.length > maxItems) { - const more = container.createSpan({ cls: "claudian-tool-result-item" }); - more.setText(`${links.length - maxItems} more results`); - } - return true; -} -function renderReadResult(container, result) { - container.empty(); - const lines = result.split(/\r?\n/).filter((line) => line.trim() !== ""); - const item = container.createSpan({ cls: "claudian-tool-result-item" }); - item.setText(`${lines.length} lines read`); -} -function renderResultLines(container, result, maxLines = 3) { - container.empty(); - const lines = result.split(/\r?\n/); - const displayLines = lines.slice(0, maxLines); - displayLines.forEach((line) => { - const stripped = line.replace(/^\s*\d+→/, ""); - const item = container.createSpan({ cls: "claudian-tool-result-item" }); - item.setText(stripped); - }); - if (lines.length > maxLines) { - const more = container.createSpan({ cls: "claudian-tool-result-item" }); - more.setText(`${lines.length - maxLines} more lines`); - } -} -function isBlockedToolResult(content, isError) { - const lower = content.toLowerCase(); - if (lower.includes("blocked by blocklist")) return true; - if (lower.includes("outside the vault")) return true; - if (lower.includes("access denied")) return true; - if (lower.includes("user denied")) return true; - if (lower.includes("approval")) return true; - if (isError && lower.includes("deny")) return true; - return false; -} -function renderToolCall(parentEl, toolCall, toolCallElements) { - const toolEl = parentEl.createDiv({ cls: "claudian-tool-call" }); - toolEl.dataset.toolId = toolCall.id; - toolCallElements.set(toolCall.id, toolEl); - const header = toolEl.createDiv({ cls: "claudian-tool-header" }); - header.setAttribute("tabindex", "0"); - header.setAttribute("role", "button"); - const iconEl = header.createSpan({ cls: "claudian-tool-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - setToolIcon(iconEl, toolCall.name); - const labelEl = header.createSpan({ cls: "claudian-tool-label" }); - labelEl.setText(getToolLabel(toolCall.name, toolCall.input)); - const statusEl = header.createSpan({ cls: "claudian-tool-status" }); - statusEl.addClass(`status-${toolCall.status}`); - statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`); - if (toolCall.status === "running") { - statusEl.createSpan({ cls: "claudian-spinner" }); - } - const content = toolEl.createDiv({ cls: "claudian-tool-content" }); - const resultRow = content.createDiv({ cls: "claudian-tool-result-row" }); - const branch = resultRow.createSpan({ cls: "claudian-tool-branch" }); - branch.setText("\u2514\u2500"); - const resultText = resultRow.createSpan({ cls: "claudian-tool-result-text" }); - resultText.setText("Running..."); - const state = { isExpanded: false }; - toolCall.isExpanded = false; - setupCollapsible(toolEl, header, content, state, { - initiallyExpanded: false, - onToggle: (expanded) => { - toolCall.isExpanded = expanded; - }, - baseAriaLabel: getToolLabel(toolCall.name, toolCall.input) - }); - return toolEl; -} -function updateToolCallResult(toolId, toolCall, toolCallElements) { - const toolEl = toolCallElements.get(toolId); - if (!toolEl) return; - const statusEl = toolEl.querySelector(".claudian-tool-status"); - if (statusEl) { - statusEl.className = "claudian-tool-status"; - statusEl.addClass(`status-${toolCall.status}`); - statusEl.empty(); - if (toolCall.status === "completed") { - (0, import_obsidian15.setIcon)(statusEl, "check"); - } else if (toolCall.status === "error") { - (0, import_obsidian15.setIcon)(statusEl, "x"); - } else if (toolCall.status === "blocked") { - (0, import_obsidian15.setIcon)(statusEl, "shield-off"); - } - } - const resultText = toolEl.querySelector(".claudian-tool-result-text"); - if (resultText && toolCall.result) { - if (toolCall.name === "WebSearch") { - if (!renderWebSearchResult(resultText, toolCall.result, 3)) { - renderResultLines(resultText, toolCall.result, 3); - } - } else if (toolCall.name === "Read") { - renderReadResult(resultText, toolCall.result); - } else { - renderResultLines(resultText, toolCall.result, 3); - } - } -} -function renderStoredToolCall(parentEl, toolCall) { - const toolEl = parentEl.createDiv({ cls: "claudian-tool-call" }); - const header = toolEl.createDiv({ cls: "claudian-tool-header" }); - header.setAttribute("tabindex", "0"); - header.setAttribute("role", "button"); - const iconEl = header.createSpan({ cls: "claudian-tool-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - setToolIcon(iconEl, toolCall.name); - const labelEl = header.createSpan({ cls: "claudian-tool-label" }); - labelEl.setText(getToolLabel(toolCall.name, toolCall.input)); - const statusEl = header.createSpan({ cls: "claudian-tool-status" }); - statusEl.addClass(`status-${toolCall.status}`); - statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`); - if (toolCall.status === "completed") { - (0, import_obsidian15.setIcon)(statusEl, "check"); - } else if (toolCall.status === "error") { - (0, import_obsidian15.setIcon)(statusEl, "x"); - } else if (toolCall.status === "blocked") { - (0, import_obsidian15.setIcon)(statusEl, "shield-off"); - } - const content = toolEl.createDiv({ cls: "claudian-tool-content" }); - const resultRow = content.createDiv({ cls: "claudian-tool-result-row" }); - const branch = resultRow.createSpan({ cls: "claudian-tool-branch" }); - branch.setText("\u2514\u2500"); - const resultText = resultRow.createSpan({ cls: "claudian-tool-result-text" }); - if (toolCall.result) { - if (toolCall.name === "WebSearch") { - if (!renderWebSearchResult(resultText, toolCall.result, 3)) { - renderResultLines(resultText, toolCall.result, 3); - } - } else if (toolCall.name === "Read") { - renderReadResult(resultText, toolCall.result); - } else { - renderResultLines(resultText, toolCall.result, 3); - } - } else { - resultText.setText("No result"); - } - const state = { isExpanded: false }; - setupCollapsible(toolEl, header, content, state, { - initiallyExpanded: false, - baseAriaLabel: getToolLabel(toolCall.name, toolCall.input) - }); - return toolEl; -} - -// src/ui/renderers/SubagentRenderer.ts -function extractTaskDescription(input) { - return input.description || "Subagent task"; -} -function truncateDescription(description, maxLength = 40) { - if (description.length <= maxLength) return description; - return description.substring(0, maxLength) + "..."; -} -function truncateResult(result) { - const lines = result.split(/\r?\n/).filter((line) => line.trim()); - if (lines.length <= 2) { - return lines.join("\n"); - } - return lines.slice(0, 2).join("\n") + "..."; -} -function createSubagentBlock(parentEl, taskToolId, taskInput) { - const description = extractTaskDescription(taskInput); - const info = { - id: taskToolId, - description, - status: "running", - toolCalls: [], - isExpanded: false - // Collapsed by default - }; - const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); - wrapperEl.dataset.subagentId = taskToolId; - const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); - headerEl.setAttribute("tabindex", "0"); - headerEl.setAttribute("role", "button"); - headerEl.setAttribute("aria-expanded", "false"); - headerEl.setAttribute("aria-label", `Subagent task: ${truncateDescription(description)} - click to expand`); - const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian16.setIcon)(iconEl, "bot"); - const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); - labelEl.setText(truncateDescription(description)); - const countEl = headerEl.createDiv({ cls: "claudian-subagent-count" }); - countEl.setText("0 tool uses"); - const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" }); - statusEl.setAttribute("aria-label", "Status: running"); - const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); - setupCollapsible(wrapperEl, headerEl, contentEl, info); - return { - wrapperEl, - contentEl, - headerEl, - labelEl, - countEl, - statusEl, - info, - currentToolEl: null, - currentResultEl: null - }; -} -function addSubagentToolCall(state, toolCall) { - state.info.toolCalls.push(toolCall); - const toolCount = state.info.toolCalls.length; - state.countEl.setText(`${toolCount} tool uses`); - state.contentEl.empty(); - state.currentResultEl = null; - const itemEl = state.contentEl.createDiv({ - cls: `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}` - }); - itemEl.dataset.toolId = toolCall.id; - state.currentToolEl = itemEl; - const toolRowEl = itemEl.createDiv({ cls: "claudian-subagent-tool-row" }); - const branchEl = toolRowEl.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const labelEl = toolRowEl.createDiv({ cls: "claudian-subagent-tool-text" }); - labelEl.setText(getToolLabel(toolCall.name, toolCall.input)); -} -function updateSubagentToolResult(state, toolId, toolCall) { - const idx = state.info.toolCalls.findIndex((tc) => tc.id === toolId); - if (idx !== -1) { - state.info.toolCalls[idx] = toolCall; - } - if (state.currentToolEl && state.currentToolEl.dataset.toolId === toolId) { - state.currentToolEl.className = `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}`; - if (toolCall.result) { - if (!state.currentResultEl) { - state.currentResultEl = state.currentToolEl.createDiv({ cls: "claudian-subagent-tool-result" }); - const branchEl = state.currentResultEl.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = state.currentResultEl.createDiv({ cls: "claudian-subagent-result-text" }); - textEl.setText(truncateResult(toolCall.result)); - } else { - const textEl = state.currentResultEl.querySelector(".claudian-subagent-result-text"); - if (textEl) { - textEl.setText(truncateResult(toolCall.result)); - } - } - } - } -} -function finalizeSubagentBlock(state, result, isError) { - state.info.status = isError ? "error" : "completed"; - state.info.result = result; - state.labelEl.setText(truncateDescription(state.info.description)); - const toolCount = state.info.toolCalls.length; - state.countEl.setText(`${toolCount} tool uses`); - state.statusEl.className = "claudian-subagent-status"; - state.statusEl.addClass(`status-${state.info.status}`); - state.statusEl.empty(); - if (state.info.status === "completed") { - (0, import_obsidian16.setIcon)(state.statusEl, "check"); - } else { - (0, import_obsidian16.setIcon)(state.statusEl, "x"); - } - if (state.info.status === "completed") { - state.wrapperEl.addClass("done"); - } else if (state.info.status === "error") { - state.wrapperEl.addClass("error"); - } - state.contentEl.empty(); - state.currentToolEl = null; - state.currentResultEl = null; - const doneEl = state.contentEl.createDiv({ cls: "claudian-subagent-done" }); - const branchEl = doneEl.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = doneEl.createDiv({ cls: "claudian-subagent-done-text" }); - textEl.setText(isError ? "ERROR" : "DONE"); -} -function renderStoredSubagent(parentEl, subagent) { - const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); - if (subagent.status === "completed") { - wrapperEl.addClass("done"); - } else if (subagent.status === "error") { - wrapperEl.addClass("error"); - } - wrapperEl.dataset.subagentId = subagent.id; - const toolCount = subagent.toolCalls.length; - const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); - headerEl.setAttribute("tabindex", "0"); - headerEl.setAttribute("role", "button"); - headerEl.setAttribute("aria-label", `Subagent task: ${truncateDescription(subagent.description)} - ${toolCount} tool uses - Status: ${subagent.status}`); - const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian16.setIcon)(iconEl, "bot"); - const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); - labelEl.setText(truncateDescription(subagent.description)); - const countEl = headerEl.createDiv({ cls: "claudian-subagent-count" }); - countEl.setText(`${toolCount} tool uses`); - const statusEl = headerEl.createDiv({ cls: `claudian-subagent-status status-${subagent.status}` }); - statusEl.setAttribute("aria-label", `Status: ${subagent.status}`); - if (subagent.status === "completed") { - (0, import_obsidian16.setIcon)(statusEl, "check"); - } else if (subagent.status === "error") { - (0, import_obsidian16.setIcon)(statusEl, "x"); - } else { - statusEl.createSpan({ cls: "claudian-spinner" }); - } - const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); - if (subagent.status === "completed" || subagent.status === "error") { - const doneEl = contentEl.createDiv({ cls: "claudian-subagent-done" }); - const branchEl = doneEl.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = doneEl.createDiv({ cls: "claudian-subagent-done-text" }); - textEl.setText(subagent.status === "error" ? "ERROR" : "DONE"); - } else { - const lastTool = subagent.toolCalls[subagent.toolCalls.length - 1]; - if (lastTool) { - const itemEl = contentEl.createDiv({ - cls: `claudian-subagent-tool-item claudian-subagent-tool-${lastTool.status}` - }); - const toolRowEl = itemEl.createDiv({ cls: "claudian-subagent-tool-row" }); - const branchEl = toolRowEl.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const toolLabelEl = toolRowEl.createDiv({ cls: "claudian-subagent-tool-text" }); - toolLabelEl.setText(getToolLabel(lastTool.name, lastTool.input)); - if (lastTool.result) { - const resultEl = itemEl.createDiv({ cls: "claudian-subagent-tool-result" }); - const resultBranchEl = resultEl.createDiv({ cls: "claudian-subagent-branch" }); - resultBranchEl.setText("\u2514\u2500"); - const textEl = resultEl.createDiv({ cls: "claudian-subagent-result-text" }); - textEl.setText(truncateResult(lastTool.result)); - } - } - } - const state = { isExpanded: false }; - setupCollapsible(wrapperEl, headerEl, contentEl, state); - return wrapperEl; -} -function setAsyncWrapperStatus(wrapperEl, status) { - const classes = ["pending", "running", "awaiting", "completed", "error", "orphaned", "async"]; - classes.forEach((cls) => wrapperEl.removeClass(cls)); - wrapperEl.addClass("async"); - wrapperEl.addClass(status); -} -function getAsyncDisplayStatus(asyncStatus) { - if (asyncStatus === "completed") return "completed"; - if (asyncStatus === "error") return "error"; - if (asyncStatus === "orphaned") return "orphaned"; - return "running"; -} -function getAsyncStatusText(asyncStatus) { - const display = getAsyncDisplayStatus(asyncStatus); - if (display === "completed") return "Completed"; - if (display === "error") return "Error"; - if (display === "orphaned") return "Orphaned"; - return "Running"; -} -function updateAsyncLabel(state, _displayStatus) { - state.labelEl.setText(truncateDescription(state.info.description)); -} -function createAsyncSubagentBlock(parentEl, taskToolId, taskInput) { - const description = taskInput.description || "Background task"; - const info = { - id: taskToolId, - description, - mode: "async", - status: "running", - toolCalls: [], - isExpanded: false, - // Collapsed by default for async - asyncStatus: "pending" - }; - const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); - setAsyncWrapperStatus(wrapperEl, "pending"); - wrapperEl.dataset.asyncSubagentId = taskToolId; - const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); - headerEl.setAttribute("tabindex", "0"); - headerEl.setAttribute("role", "button"); - headerEl.setAttribute("aria-expanded", "false"); - headerEl.setAttribute("aria-label", `Background task: ${description} - Status: running`); - const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian16.setIcon)(iconEl, "bot"); - const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); - labelEl.setText(truncateDescription(description)); - const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" }); - statusTextEl.setText("Running"); - const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" }); - statusEl.setAttribute("aria-label", "Status: running"); - const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); - const statusRow = contentEl.createDiv({ cls: "claudian-subagent-done" }); - const branchEl = statusRow.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = statusRow.createDiv({ cls: "claudian-subagent-done-text" }); - textEl.setText("run in background"); - setupCollapsible(wrapperEl, headerEl, contentEl, info); - return { - wrapperEl, - contentEl, - headerEl, - labelEl, - statusTextEl, - statusEl, - info - }; -} -function updateAsyncSubagentRunning(state, agentId) { - state.info.asyncStatus = "running"; - state.info.agentId = agentId; - setAsyncWrapperStatus(state.wrapperEl, "running"); - updateAsyncLabel(state, "running"); - state.statusTextEl.setText("Running"); - state.contentEl.empty(); - const statusRow = state.contentEl.createDiv({ cls: "claudian-subagent-done" }); - const branchEl = statusRow.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = statusRow.createDiv({ cls: "claudian-subagent-done-text claudian-async-agent-id" }); - const shortId = agentId.length > 12 ? agentId.substring(0, 12) + "..." : agentId; - textEl.setText(`run in background (${shortId})`); -} -function finalizeAsyncSubagent(state, result, isError) { - state.info.asyncStatus = isError ? "error" : "completed"; - state.info.status = isError ? "error" : "completed"; - state.info.result = result; - setAsyncWrapperStatus(state.wrapperEl, isError ? "error" : "completed"); - updateAsyncLabel(state, isError ? "error" : "completed"); - state.statusTextEl.setText(isError ? "Error" : "Completed"); - state.statusEl.className = "claudian-subagent-status"; - state.statusEl.addClass(`status-${isError ? "error" : "completed"}`); - state.statusEl.empty(); - if (isError) { - (0, import_obsidian16.setIcon)(state.statusEl, "x"); - } else { - (0, import_obsidian16.setIcon)(state.statusEl, "check"); - } - if (isError) { - state.wrapperEl.addClass("error"); - } else { - state.wrapperEl.addClass("done"); - } - state.contentEl.empty(); - const resultEl = state.contentEl.createDiv({ cls: "claudian-subagent-done" }); - const branchEl = resultEl.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = resultEl.createDiv({ cls: "claudian-subagent-done-text" }); - if (isError && result) { - const truncated = result.length > 80 ? result.substring(0, 80) + "..." : result; - textEl.setText(`ERROR: ${truncated}`); - } else { - textEl.setText(isError ? "ERROR" : "DONE"); - } -} -function markAsyncSubagentOrphaned(state) { - state.info.asyncStatus = "orphaned"; - state.info.status = "error"; - state.info.result = "Conversation ended before task completed"; - setAsyncWrapperStatus(state.wrapperEl, "orphaned"); - updateAsyncLabel(state, "orphaned"); - state.statusTextEl.setText("Orphaned"); - state.statusEl.className = "claudian-subagent-status status-error"; - state.statusEl.empty(); - (0, import_obsidian16.setIcon)(state.statusEl, "alert-circle"); - state.wrapperEl.addClass("error"); - state.wrapperEl.addClass("orphaned"); - state.contentEl.empty(); - const orphanEl = state.contentEl.createDiv({ cls: "claudian-subagent-done claudian-async-orphaned" }); - const branchEl = orphanEl.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = orphanEl.createDiv({ cls: "claudian-subagent-done-text" }); - textEl.setText("\u26A0\uFE0F Task orphaned"); -} -function renderStoredAsyncSubagent(parentEl, subagent) { - const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" }); - const statusClass = getAsyncDisplayStatus(subagent.asyncStatus); - setAsyncWrapperStatus(wrapperEl, statusClass); - if (subagent.asyncStatus === "completed") { - wrapperEl.addClass("done"); - } else if (subagent.asyncStatus === "error" || subagent.asyncStatus === "orphaned") { - wrapperEl.addClass("error"); - } - wrapperEl.dataset.asyncSubagentId = subagent.id; - const displayStatus = getAsyncDisplayStatus(subagent.asyncStatus); - const statusText = getAsyncStatusText(subagent.asyncStatus); - const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" }); - headerEl.setAttribute("tabindex", "0"); - headerEl.setAttribute("role", "button"); - headerEl.setAttribute("aria-label", `Background task: ${subagent.description} - Status: ${statusText}`); - const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian16.setIcon)(iconEl, "bot"); - const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" }); - labelEl.setText(truncateDescription(subagent.description)); - const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" }); - statusTextEl.setText(statusText); - const statusIconClass = displayStatus === "error" || displayStatus === "orphaned" ? "status-error" : displayStatus === "completed" ? "status-completed" : "status-running"; - const statusEl = headerEl.createDiv({ cls: `claudian-subagent-status ${statusIconClass}` }); - statusEl.setAttribute("aria-label", `Status: ${statusText}`); - if (subagent.asyncStatus === "completed") { - (0, import_obsidian16.setIcon)(statusEl, "check"); - } else if (subagent.asyncStatus === "error" || subagent.asyncStatus === "orphaned") { - (0, import_obsidian16.setIcon)(statusEl, subagent.asyncStatus === "orphaned" ? "alert-circle" : "x"); - } - const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" }); - const statusRow = contentEl.createDiv({ cls: "claudian-subagent-done" }); - const branchEl = statusRow.createDiv({ cls: "claudian-subagent-branch" }); - branchEl.setText("\u2514\u2500"); - const textEl = statusRow.createDiv({ cls: "claudian-subagent-done-text" }); - if (subagent.asyncStatus === "completed") { - textEl.setText("DONE"); - } else if (subagent.asyncStatus === "error") { - textEl.setText("ERROR"); - } else if (subagent.asyncStatus === "orphaned") { - textEl.setText("\u26A0\uFE0F Task orphaned"); - } else if (subagent.agentId) { - const shortId = subagent.agentId.length > 12 ? subagent.agentId.substring(0, 12) + "..." : subagent.agentId; - textEl.setText(`run in background (${shortId})`); - } else { - textEl.setText("run in background"); - } - const state = { isExpanded: false }; - setupCollapsible(wrapperEl, headerEl, contentEl, state); - return wrapperEl; -} - -// src/ui/renderers/ThinkingBlockRenderer.ts -function createThinkingBlock(parentEl, renderContent) { - const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" }); - const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" }); - header.setAttribute("tabindex", "0"); - header.setAttribute("role", "button"); - header.setAttribute("aria-expanded", "false"); - header.setAttribute("aria-label", "Extended thinking - click to expand"); - const labelEl = header.createSpan({ cls: "claudian-thinking-label" }); - const startTime = Date.now(); - labelEl.setText("Thinking 0s..."); - const timerInterval = setInterval(() => { - const elapsed = Math.floor((Date.now() - startTime) / 1e3); - labelEl.setText(`Thinking ${elapsed}s...`); - }, 1e3); - const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" }); - const state = { - wrapperEl, - contentEl, - labelEl, - content: "", - startTime, - timerInterval, - isExpanded: false - }; - setupCollapsible(wrapperEl, header, contentEl, state); - return state; -} -async function appendThinkingContent(state, content, renderContent) { - state.content += content; - await renderContent(state.contentEl, state.content); -} -function finalizeThinkingBlock(state) { - if (state.timerInterval) { - clearInterval(state.timerInterval); - state.timerInterval = null; - } - const durationSeconds = Math.floor((Date.now() - state.startTime) / 1e3); - state.labelEl.setText(`Thought for ${durationSeconds}s`); - const header = state.wrapperEl.querySelector(".claudian-thinking-header"); - if (header) { - collapseElement(state.wrapperEl, header, state.contentEl, state); - } - return durationSeconds; -} -function cleanupThinkingBlock(state) { - if (state == null ? void 0 : state.timerInterval) { - clearInterval(state.timerInterval); - } -} -function renderStoredThinkingBlock(parentEl, content, durationSeconds, renderContent) { - const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" }); - const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" }); - header.setAttribute("tabindex", "0"); - header.setAttribute("role", "button"); - header.setAttribute("aria-label", "Extended thinking - click to expand"); - const labelEl = header.createSpan({ cls: "claudian-thinking-label" }); - const labelText = durationSeconds !== void 0 ? `Thought for ${durationSeconds}s` : "Thinking"; - labelEl.setText(labelText); - const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" }); - renderContent(contentEl, content); - const state = { isExpanded: false }; - setupCollapsible(wrapperEl, header, contentEl, state); - return wrapperEl; -} - -// src/ui/renderers/TodoListRenderer.ts -function isValidTodoItem(item) { - if (typeof item !== "object" || item === null) return false; - const record2 = item; - return typeof record2.content === "string" && record2.content.length > 0 && typeof record2.activeForm === "string" && record2.activeForm.length > 0 && typeof record2.status === "string" && ["pending", "in_progress", "completed"].includes(record2.status); -} -function parseTodoInput(input) { - if (!input.todos || !Array.isArray(input.todos)) { - return null; - } - const validTodos = []; - const invalidItems = []; - for (const item of input.todos) { - if (isValidTodoItem(item)) { - validTodos.push(item); - } else { - invalidItems.push(item); - } - } - if (invalidItems.length > 0) { - console.warn("[TodoListRenderer] Dropped invalid todo items:", { - dropped: invalidItems.length, - total: input.todos.length, - sample: invalidItems.slice(0, 3) - }); - } - return validTodos.length > 0 ? validTodos : null; -} -function extractLastTodosFromMessages(messages) { - for (let i = messages.length - 1; i >= 0; i--) { - const msg = messages[i]; - if (msg.role === "assistant" && msg.toolCalls) { - for (let j = msg.toolCalls.length - 1; j >= 0; j--) { - const toolCall = msg.toolCalls[j]; - if (toolCall.name === TOOL_TODO_WRITE) { - const todos = parseTodoInput(toolCall.input); - if (!todos) { - console.warn("[TodoListRenderer] Failed to parse TodoWrite from saved conversation", { - messageIndex: i, - toolCallIndex: j, - inputKeys: Object.keys(toolCall.input) - }); - } - return todos; - } - } - } - } - return null; -} - -// src/ui/renderers/WriteEditRenderer.ts -var import_obsidian17 = require("obsidian"); -function shortenPath2(filePath, maxLength = 40) { - if (!filePath) return "file"; - const normalized = filePath.replace(/\\/g, "/"); - if (normalized.length <= maxLength) return normalized; - const parts = normalized.split("/"); - if (parts.length <= 2) { - return "..." + normalized.slice(-maxLength + 3); - } - const filename = parts[parts.length - 1]; - const firstDir = parts[0]; - const available = maxLength - firstDir.length - filename.length - 5; - if (available < 0) { - return "..." + filename.slice(-maxLength + 3); - } - return `${firstDir}/.../${filename}`; -} -function createWriteEditBlock(parentEl, toolCall) { - const filePath = toolCall.input.file_path || "file"; - const toolName = toolCall.name; - const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" }); - wrapperEl.dataset.toolId = toolCall.id; - const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" }); - headerEl.setAttribute("tabindex", "0"); - headerEl.setAttribute("role", "button"); - headerEl.setAttribute("aria-label", `${toolName}: ${shortenPath2(filePath)} - click to expand`); - const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian17.setIcon)(iconEl, toolName === TOOL_EDIT ? "file-pen" : "file-plus"); - const labelEl = headerEl.createDiv({ cls: "claudian-write-edit-label" }); - labelEl.setText(`${toolName}: ${shortenPath2(filePath)}`); - const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" }); - const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status status-running" }); - statusEl.setAttribute("aria-label", "Status: running"); - statusEl.createSpan({ cls: "claudian-spinner" }); - const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" }); - const loadingRow = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); - const loadingEl = loadingRow.createDiv({ cls: "claudian-write-edit-loading" }); - loadingEl.setText("Writing..."); - const state = { - wrapperEl, - contentEl, - headerEl, - labelEl, - statsEl, - statusEl, - toolCall, - isExpanded: false - }; - setupCollapsible(wrapperEl, headerEl, contentEl, state); - return state; -} -function updateWriteEditWithDiff(state, diffData) { - state.statsEl.empty(); - state.contentEl.empty(); - if (diffData.skippedReason === "too_large") { - const row2 = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); - const skipEl = row2.createDiv({ cls: "claudian-write-edit-binary" }); - skipEl.setText("Diff skipped: file too large"); - return; - } - if (diffData.skippedReason === "unavailable" || diffData.originalContent === void 0 || diffData.newContent === void 0) { - const row2 = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); - const skipEl = row2.createDiv({ cls: "claudian-write-edit-binary" }); - skipEl.setText("Diff unavailable"); - return; - } - const { originalContent, newContent } = diffData; - if (isBinaryContent(originalContent) || isBinaryContent(newContent)) { - const row2 = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); - const binaryEl = row2.createDiv({ cls: "claudian-write-edit-binary" }); - binaryEl.setText("Binary file"); - return; - } - const diffLines = computeLineDiff(originalContent, newContent); - state.diffLines = diffLines; - const stats = countLineChanges(diffLines); - if (stats.added > 0) { - const addedEl = state.statsEl.createSpan({ cls: "added" }); - addedEl.setText(`+${stats.added}`); - } - if (stats.removed > 0) { - if (stats.added > 0) { - state.statsEl.createSpan({ text: " " }); - } - const removedEl = state.statsEl.createSpan({ cls: "removed" }); - removedEl.setText(`-${stats.removed}`); - } - const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); - const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" }); - renderDiffContent(diffEl, diffLines); -} -function finalizeWriteEditBlock(state, isError) { - state.statusEl.className = "claudian-write-edit-status"; - state.statusEl.empty(); - if (isError) { - state.statusEl.addClass("status-error"); - (0, import_obsidian17.setIcon)(state.statusEl, "x"); - state.statusEl.setAttribute("aria-label", "Status: error"); - if (!state.diffLines) { - state.contentEl.empty(); - const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); - const errorEl = row.createDiv({ cls: "claudian-write-edit-error" }); - errorEl.setText(state.toolCall.result || "Error"); - } - } - if (isError) { - state.wrapperEl.addClass("error"); - } else { - state.wrapperEl.addClass("done"); - } -} -function renderStoredWriteEdit(parentEl, toolCall) { - const filePath = toolCall.input.file_path || "file"; - const toolName = toolCall.name; - const isError = toolCall.status === "error" || toolCall.status === "blocked"; - const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" }); - if (isError) { - wrapperEl.addClass("error"); - } else if (toolCall.status === "completed") { - wrapperEl.addClass("done"); - } - wrapperEl.dataset.toolId = toolCall.id; - const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" }); - headerEl.setAttribute("tabindex", "0"); - headerEl.setAttribute("role", "button"); - const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" }); - iconEl.setAttribute("aria-hidden", "true"); - (0, import_obsidian17.setIcon)(iconEl, toolName === TOOL_EDIT ? "file-pen" : "file-plus"); - const labelEl = headerEl.createDiv({ cls: "claudian-write-edit-label" }); - labelEl.setText(`${toolName}: ${shortenPath2(filePath)}`); - const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" }); - if (toolCall.diffData && !toolCall.diffData.skippedReason && toolCall.diffData.originalContent !== void 0 && toolCall.diffData.newContent !== void 0) { - const diffLines = computeLineDiff(toolCall.diffData.originalContent, toolCall.diffData.newContent); - const stats = countLineChanges(diffLines); - if (stats.added > 0) { - const addedEl = statsEl.createSpan({ cls: "added" }); - addedEl.setText(`+${stats.added}`); - } - if (stats.removed > 0) { - if (stats.added > 0) { - statsEl.createSpan({ text: " " }); - } - const removedEl = statsEl.createSpan({ cls: "removed" }); - removedEl.setText(`-${stats.removed}`); - } - } - const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status" }); - if (isError) { - statusEl.addClass("status-error"); - (0, import_obsidian17.setIcon)(statusEl, "x"); - } - const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" }); - const row = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" }); - if (toolCall.diffData) { - if (toolCall.diffData.skippedReason === "too_large") { - const skipEl = row.createDiv({ cls: "claudian-write-edit-binary" }); - skipEl.setText("Diff skipped: file too large"); - } else if (toolCall.diffData.skippedReason === "unavailable" || toolCall.diffData.originalContent === void 0 || toolCall.diffData.newContent === void 0) { - const skipEl = row.createDiv({ cls: "claudian-write-edit-binary" }); - skipEl.setText("Diff unavailable"); - } else { - const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" }); - const diffLines = computeLineDiff(toolCall.diffData.originalContent, toolCall.diffData.newContent); - renderDiffContent(diffEl, diffLines); - } - } else if (isError && toolCall.result) { - const errorEl = row.createDiv({ cls: "claudian-write-edit-error" }); - errorEl.setText(toolCall.result); - } else { - const doneEl = row.createDiv({ cls: "claudian-write-edit-done-text" }); - doneEl.setText(isError ? "ERROR" : "DONE"); - } - const state = { isExpanded: false }; - setupCollapsible(wrapperEl, headerEl, contentEl, state); - return wrapperEl; -} - -// src/ui/settings/EnvSnippetManager.ts -var import_obsidian18 = require("obsidian"); -var EnvSnippetModal = class extends import_obsidian18.Modal { - constructor(app, plugin, snippet, onSave) { - super(app); - this.plugin = plugin; - this.snippet = snippet; - this.onSave = onSave; - } - onOpen() { - const { contentEl } = this; - this.setTitle(this.snippet ? "Edit snippet" : "Save snippet"); - this.modalEl.addClass("claudian-env-snippet-modal"); - let nameEl; - let descEl; - let envVarsEl; - const handleKeyDown = (e) => { - if (e.key === "Enter") { - e.preventDefault(); - saveSnippet(); - } else if (e.key === "Escape") { - e.preventDefault(); - this.close(); - } - }; - const saveSnippet = () => { - var _a; - const name = nameEl.value.trim(); - if (!name) { - new import_obsidian18.Notice("Please enter a name for the snippet"); - return; - } - const snippet = { - id: ((_a = this.snippet) == null ? void 0 : _a.id) || `snippet-${Date.now()}`, - name, - description: descEl.value.trim(), - envVars: envVarsEl.value - }; - this.onSave(snippet); - this.close(); - }; - new import_obsidian18.Setting(contentEl).setName("Name").setDesc("A descriptive name for this environment configuration").addText((text) => { - var _a; - nameEl = text.inputEl; - text.setValue(((_a = this.snippet) == null ? void 0 : _a.name) || ""); - text.inputEl.addEventListener("keydown", handleKeyDown); - }); - new import_obsidian18.Setting(contentEl).setName("Description").setDesc("Optional description").addText((text) => { - var _a; - descEl = text.inputEl; - text.setValue(((_a = this.snippet) == null ? void 0 : _a.description) || ""); - text.inputEl.addEventListener("keydown", handleKeyDown); - }); - const envVarsSetting = new import_obsidian18.Setting(contentEl).setName("Environment variables").setDesc("KEY=VALUE format, one per line").addTextArea((text) => { - var _a, _b; - envVarsEl = text.inputEl; - const envVarsToShow = (_b = (_a = this.snippet) == null ? void 0 : _a.envVars) != null ? _b : this.plugin.settings.environmentVariables; - text.setValue(envVarsToShow); - text.inputEl.rows = 8; - }); - envVarsSetting.settingEl.addClass("claudian-env-snippet-setting"); - envVarsSetting.controlEl.addClass("claudian-env-snippet-control"); - const buttonContainer = contentEl.createDiv({ cls: "claudian-snippet-buttons" }); - const cancelBtn = buttonContainer.createEl("button", { - text: "Cancel", - cls: "claudian-cancel-btn" - }); - cancelBtn.addEventListener("click", () => this.close()); - const saveBtn = buttonContainer.createEl("button", { - text: this.snippet ? "Update" : "Save", - cls: "claudian-save-btn" - }); - saveBtn.addEventListener("click", () => saveSnippet()); - } - onClose() { - const { contentEl } = this; - contentEl.empty(); - } -}; -var EnvSnippetManager = class { - constructor(containerEl, plugin) { - this.containerEl = containerEl; - this.plugin = plugin; - this.render(); - } - render() { - this.containerEl.empty(); - const headerEl = this.containerEl.createDiv({ cls: "claudian-snippet-header" }); - headerEl.createSpan({ text: "Snippets", cls: "claudian-snippet-label" }); - const saveBtn = headerEl.createEl("button", { - cls: "claudian-settings-action-btn", - attr: { "aria-label": "Save current" } - }); - (0, import_obsidian18.setIcon)(saveBtn, "plus"); - saveBtn.addEventListener("click", () => this.saveCurrentEnv()); - const snippets = this.plugin.settings.envSnippets; - if (snippets.length === 0) { - const emptyEl = this.containerEl.createDiv({ cls: "claudian-snippet-empty" }); - emptyEl.setText('No saved environment snippets yet. Click "Save Current" to save your current environment configuration.'); - return; - } - const sortedSnippets = snippets; - const listEl = this.containerEl.createDiv({ cls: "claudian-snippet-list" }); - for (const snippet of sortedSnippets) { - const itemEl = listEl.createDiv({ cls: "claudian-snippet-item" }); - const infoEl = itemEl.createDiv({ cls: "claudian-snippet-info" }); - const nameEl = infoEl.createDiv({ cls: "claudian-snippet-name" }); - nameEl.setText(snippet.name); - if (snippet.description) { - const descEl = infoEl.createDiv({ cls: "claudian-snippet-description" }); - descEl.setText(snippet.description); - } - const actionsEl = itemEl.createDiv({ cls: "claudian-snippet-actions" }); - const restoreBtn = actionsEl.createEl("button", { - cls: "claudian-settings-action-btn", - attr: { "aria-label": "Insert" } - }); - (0, import_obsidian18.setIcon)(restoreBtn, "clipboard-paste"); - restoreBtn.addEventListener("click", async () => { - await this.insertSnippet(snippet); - }); - const editBtn = actionsEl.createEl("button", { - cls: "claudian-settings-action-btn", - attr: { "aria-label": "Edit" } - }); - (0, import_obsidian18.setIcon)(editBtn, "pencil"); - editBtn.addEventListener("click", () => { - this.editSnippet(snippet); - }); - const deleteBtn = actionsEl.createEl("button", { - cls: "claudian-settings-action-btn claudian-settings-delete-btn", - attr: { "aria-label": "Delete" } - }); - (0, import_obsidian18.setIcon)(deleteBtn, "trash-2"); - deleteBtn.addEventListener("click", async () => { - if (confirm(`Delete environment snippet "${snippet.name}"?`)) { - await this.deleteSnippet(snippet); - } - }); - } - } - async saveCurrentEnv() { - const modal = new EnvSnippetModal( - this.plugin.app, - this.plugin, - null, - async (snippet) => { - this.plugin.settings.envSnippets.push(snippet); - await this.plugin.saveSettings(); - this.render(); - new import_obsidian18.Notice(`Environment snippet "${snippet.name}" saved`); - } - ); - modal.open(); - } - async insertSnippet(snippet) { - var _a, _b; - const envTextarea = document.querySelector(".claudian-settings-env-textarea"); - if (envTextarea) { - const snippetContent = snippet.envVars.trim(); - envTextarea.value = snippetContent; - await this.plugin.applyEnvironmentVariables(snippetContent); - const view = (_a = this.plugin.app.workspace.getLeavesOfType("claudian-view")[0]) == null ? void 0 : _a.view; - if (view == null ? void 0 : view.modelSelector) { - view.modelSelector.updateDisplay(); - view.modelSelector.renderOptions(); - } - } else { - await this.plugin.applyEnvironmentVariables(snippet.envVars); - this.render(); - const view = (_b = this.plugin.app.workspace.getLeavesOfType("claudian-view")[0]) == null ? void 0 : _b.view; - if (view == null ? void 0 : view.modelSelector) { - view.modelSelector.updateDisplay(); - view.modelSelector.renderOptions(); - } - } - } - editSnippet(snippet) { - const modal = new EnvSnippetModal( - this.plugin.app, - this.plugin, - snippet, - async (updatedSnippet) => { - const index = this.plugin.settings.envSnippets.findIndex((s) => s.id === snippet.id); - if (index !== -1) { - this.plugin.settings.envSnippets[index] = updatedSnippet; - await this.plugin.saveSettings(); - this.render(); - new import_obsidian18.Notice(`Environment snippet "${updatedSnippet.name}" updated`); - } - } - ); - modal.open(); - } - async deleteSnippet(snippet) { - this.plugin.settings.envSnippets = this.plugin.settings.envSnippets.filter((s) => s.id !== snippet.id); - await this.plugin.saveSettings(); - this.render(); - new import_obsidian18.Notice(`Environment snippet "${snippet.name}" deleted`); - } - refresh() { - this.render(); - } -}; - -// src/ui/settings/McpSettingsManager.ts -var import_obsidian19 = require("obsidian"); - -// src/features/mcp/McpTester.ts -var import_child_process3 = require("child_process"); -var http = __toESM(require("http")); -var https = __toESM(require("https")); -async function testMcpServer(server) { - const type = getMcpServerType(server.config); - try { - if (type === "stdio") { - return await testStdioServer(server); - } else if (type === "sse") { - return await testSseServer(server); - } else { - return await testHttpServer(server); - } - } catch (error2) { - return { - success: false, - tools: [], - error: error2 instanceof Error ? error2.message : "Unknown error" - }; - } -} -async function testStdioServer(server) { - const config2 = server.config; - const { cmd, args } = parseCommand(config2.command, config2.args); - return new Promise((resolve7) => { - var _a, _b, _c, _d; - let child = null; - let stdout = ""; - let stderr = ""; - let resolved = false; - let initReceived = false; - let serverInfo = {}; - const cleanup = () => { - if (child && !child.killed) { - child.kill(); - } - }; - const timeout = setTimeout(() => { - if (!resolved) { - resolved = true; - cleanup(); - resolve7({ - success: false, - tools: [], - error: "Connection timeout (10s)" - }); - } - }, 1e4); - try { - if (!cmd) { - clearTimeout(timeout); - resolve7({ - success: false, - tools: [], - error: "Missing command" - }); - return; - } - child = (0, import_child_process3.spawn)(cmd, args, { - env: { ...process.env, ...config2.env, PATH: getEnhancedPath((_a = config2.env) == null ? void 0 : _a.PATH) }, - stdio: ["pipe", "pipe", "pipe"] - }); - (_b = child.stdout) == null ? void 0 : _b.on("data", (data) => { - var _a2, _b2, _c2, _d2, _e; - stdout += data.toString(); - const lines = stdout.split("\n"); - stdout = lines.pop() || ""; - for (const line of lines) { - if (!line.trim()) continue; - try { - const msg = JSON.parse(line); - if (msg.id === 1) { - if (msg.error) { - if (!resolved) { - resolved = true; - clearTimeout(timeout); - cleanup(); - resolve7({ - success: false, - tools: [], - error: msg.error.message || "Initialize failed" - }); - } - return; - } - if (msg.result) { - initReceived = true; - serverInfo = { - name: (_a2 = msg.result.serverInfo) == null ? void 0 : _a2.name, - version: (_b2 = msg.result.serverInfo) == null ? void 0 : _b2.version - }; - const initializedNotification = { - jsonrpc: "2.0", - method: "notifications/initialized" - }; - (_c2 = child == null ? void 0 : child.stdin) == null ? void 0 : _c2.write(JSON.stringify(initializedNotification) + "\n"); - const toolsRequest = { - jsonrpc: "2.0", - id: 2, - method: "tools/list", - params: {} - }; - (_d2 = child == null ? void 0 : child.stdin) == null ? void 0 : _d2.write(JSON.stringify(toolsRequest) + "\n"); - } - } - if (msg.id === 2) { - if (!resolved) { - resolved = true; - clearTimeout(timeout); - cleanup(); - if (msg.error) { - resolve7({ - success: true, - serverName: serverInfo.name, - serverVersion: serverInfo.version, - tools: [] - }); - return; - } - const tools = (((_e = msg.result) == null ? void 0 : _e.tools) || []).map( - (t) => ({ - name: t.name, - description: t.description, - inputSchema: t.inputSchema - }) - ); - resolve7({ - success: true, - serverName: serverInfo.name, - serverVersion: serverInfo.version, - tools - }); - } - return; - } - } catch (e) { - } - } - }); - (_c = child.stderr) == null ? void 0 : _c.on("data", (data) => { - stderr += data.toString(); - }); - child.on("error", (error2) => { - if (!resolved) { - resolved = true; - clearTimeout(timeout); - resolve7({ - success: false, - tools: [], - error: `Failed to start: ${error2.message}` - }); - } - }); - child.on("close", (code) => { - if (!resolved) { - resolved = true; - clearTimeout(timeout); - if (initReceived) { - resolve7({ - success: true, - serverName: serverInfo.name, - serverVersion: serverInfo.version, - tools: [] - }); - } else if (code !== 0) { - resolve7({ - success: false, - tools: [], - error: stderr || `Process exited with code ${code}` - }); - } - } - }); - const initRequest = { - jsonrpc: "2.0", - id: 1, - method: "initialize", - params: { - protocolVersion: "2024-11-05", - capabilities: {}, - clientInfo: { name: "claudian-tester", version: "1.0.0" } - } - }; - (_d = child.stdin) == null ? void 0 : _d.write(JSON.stringify(initRequest) + "\n"); - } catch (error2) { - resolved = true; - clearTimeout(timeout); - resolve7({ - success: false, - tools: [], - error: error2 instanceof Error ? error2.message : "Failed to spawn process" - }); - } - }); -} -function httpRequest(url, headers, body) { - return new Promise((resolve7, reject) => { - const isHttps = url.protocol === "https:"; - const httpModule = isHttps ? https : http; - const req = httpModule.request( - { - hostname: url.hostname, - port: url.port || (isHttps ? 443 : 80), - path: url.pathname + url.search, - method: "POST", - headers: { - ...headers, - "Content-Length": Buffer.byteLength(body) - } - }, - (res) => { - let data = ""; - res.on("data", (chunk) => { - data += chunk; - }); - res.on("end", () => { - resolve7({ statusCode: res.statusCode || 0, data }); - }); - } - ); - req.on("error", reject); - req.write(body); - req.end(); - }); -} -async function testHttpServer(server) { - const config2 = server.config; - return new Promise((resolve7) => { - const timeout = setTimeout(() => { - resolve7({ - success: false, - tools: [], - error: "Connection timeout (10s)" - }); - }, 1e4); - (async () => { - var _a, _b; - try { - const url = new URL(config2.url); - const headers = { - "Content-Type": "application/json", - Accept: "application/json, text/event-stream", - ...config2.headers - }; - const initRequest = JSON.stringify({ - jsonrpc: "2.0", - id: 1, - method: "initialize", - params: { - protocolVersion: "2024-11-05", - capabilities: {}, - clientInfo: { name: "claudian-tester", version: "1.0.0" } - } - }); - const initResponse = await httpRequest(url, headers, initRequest); - let serverName; - let serverVersion; - try { - const initResult = JSON.parse(initResponse.data); - if (initResult.error) { - clearTimeout(timeout); - resolve7({ - success: false, - tools: [], - error: initResult.error.message || "Server error" - }); - return; - } - if ((_a = initResult.result) == null ? void 0 : _a.serverInfo) { - serverName = initResult.result.serverInfo.name; - serverVersion = initResult.result.serverInfo.version; - } - } catch (e) { - clearTimeout(timeout); - resolve7({ - success: false, - tools: [], - error: `Invalid JSON response: ${initResponse.data.slice(0, 200)}` - }); - return; - } - const initializedNotification = JSON.stringify({ - jsonrpc: "2.0", - method: "notifications/initialized" - }); - httpRequest(url, headers, initializedNotification).catch(() => { - }); - const toolsRequest = JSON.stringify({ - jsonrpc: "2.0", - id: 2, - method: "tools/list", - params: {} - }); - const toolsResponse = await httpRequest(url, headers, toolsRequest); - try { - const toolsResult = JSON.parse(toolsResponse.data); - clearTimeout(timeout); - if (toolsResult.error) { - resolve7({ - success: true, - serverName, - serverVersion, - tools: [] - }); - return; - } - const tools = (((_b = toolsResult.result) == null ? void 0 : _b.tools) || []).map( - (t) => ({ - name: t.name, - description: t.description, - inputSchema: t.inputSchema - }) - ); - resolve7({ - success: true, - serverName, - serverVersion, - tools - }); - } catch (e) { - clearTimeout(timeout); - resolve7({ - success: true, - serverName, - serverVersion, - tools: [] - }); - } - } catch (error2) { - clearTimeout(timeout); - resolve7({ - success: false, - tools: [], - error: error2 instanceof Error ? error2.message : "Request failed" - }); - } - })(); - }); -} -async function testSseServer(server) { - var _a, _b, _c, _d, _e; - const config2 = server.config; - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 1e4); - try { - const sseUrl = new URL(config2.url); - const headers = { - Accept: "text/event-stream", - ...config2.headers - }; - const response = await fetch(sseUrl.toString(), { - method: "GET", - headers, - signal: controller.signal - }); - if (!response.ok || !response.body) { - clearTimeout(timeout); - return { - success: false, - tools: [], - error: `HTTP ${response.status}: ${response.statusText}` - }; - } - let endpointResolved = false; - let resolveEndpoint = null; - const endpointPromise = new Promise((resolve7) => { - resolveEndpoint = resolve7; - }); - const pending = /* @__PURE__ */ new Map(); - const streamPromise = consumeSseStream(response.body, (event) => { - if (!endpointResolved) { - const candidate = resolveSseEndpoint(event.data, sseUrl); - if (candidate) { - endpointResolved = true; - resolveEndpoint == null ? void 0 : resolveEndpoint(candidate); - } - } - const payload = tryParseJson(event.data); - if (payload && typeof payload === "object") { - const record2 = payload; - const id = parseRpcId(record2.id); - if (id !== null) { - const handler = pending.get(id); - if (handler) { - handler(record2); - } - } - } - }).catch(() => { - }); - let endpointTimeout = null; - const endpointTimeoutPromise = new Promise((_, reject) => { - endpointTimeout = setTimeout(() => reject(new Error("SSE endpoint not advertised")), 5e3); - }); - let postUrl; - try { - postUrl = await Promise.race([endpointPromise, endpointTimeoutPromise]); - } finally { - if (endpointTimeout) clearTimeout(endpointTimeout); - } - const postOptions = { signal: controller.signal, timeoutMs: 8e3 }; - const initRequest = { - jsonrpc: "2.0", - id: 1, - method: "initialize", - params: { - protocolVersion: "2024-11-05", - capabilities: {}, - clientInfo: { name: "claudian-tester", version: "1.0.0" } - } - }; - const initResponsePromise = waitForRpcResponse(pending, 1, 8e3); - initResponsePromise.catch(() => { - }); - const initPost = await postJsonRpc(postUrl, (_a = config2.headers) != null ? _a : {}, initRequest, postOptions); - if (initPost.status >= 400) { - initResponsePromise.catch(() => { - }); - clearTimeout(timeout); - controller.abort(); - return { - success: false, - tools: [], - error: `HTTP ${initPost.status}: ${initPost.statusText}` - }; - } - const initResponse = await initResponsePromise; - const initError = initResponse.error; - if (initError) { - clearTimeout(timeout); - controller.abort(); - return { - success: false, - tools: [], - error: initError.message || "Initialize failed" - }; - } - const serverInfo = initResponse.result; - const serverName = (_b = serverInfo == null ? void 0 : serverInfo.serverInfo) == null ? void 0 : _b.name; - const serverVersion = (_c = serverInfo == null ? void 0 : serverInfo.serverInfo) == null ? void 0 : _c.version; - await postJsonRpc(postUrl, (_d = config2.headers) != null ? _d : {}, { - jsonrpc: "2.0", - method: "notifications/initialized" - }, postOptions).catch(() => { - }); - const toolsResponsePromise = waitForRpcResponse(pending, 2, 8e3); - toolsResponsePromise.catch(() => { - }); - await postJsonRpc(postUrl, (_e = config2.headers) != null ? _e : {}, { - jsonrpc: "2.0", - id: 2, - method: "tools/list", - params: {} - }, postOptions); - let tools = []; - try { - const toolsResponse = await toolsResponsePromise; - const toolsError = toolsResponse.error; - if (!toolsError) { - const result = toolsResponse.result; - tools = ((result == null ? void 0 : result.tools) || []).map( - (t) => ({ - name: t.name, - description: t.description, - inputSchema: t.inputSchema - }) - ); - } - } catch (e) { - } - clearTimeout(timeout); - controller.abort(); - await streamPromise; - return { - success: true, - serverName, - serverVersion, - tools - }; - } catch (error2) { - clearTimeout(timeout); - controller.abort(); - return { - success: false, - tools: [], - error: error2 instanceof Error ? error2.message : "Request failed" - }; - } -} - -// src/ui/settings/McpSettingsManager.ts +// src/features/settings/ui/McpSettingsManager.ts var McpSettingsManager = class { constructor(containerEl, plugin) { this.servers = []; @@ -33800,6 +64733,19 @@ var McpSettingsManager = class { this.plugin = plugin; this.loadAndRender(); } + /** + * Broadcasts MCP reload to all open Claudian views. + * With multiple views open (split workspace), each view's tabs need to reload MCP config. + */ + async broadcastMcpReloadToAllViews() { + var _a3; + const views = this.plugin.getAllViews(); + for (const view of views) { + await ((_a3 = view.getTabManager()) == null ? void 0 : _a3.broadcastToAllTabs( + (service) => service.reloadMcpServers() + )); + } + } async loadAndRender() { this.servers = await this.plugin.storage.mcp.load(); this.render(); @@ -33813,31 +64759,31 @@ var McpSettingsManager = class { cls: "claudian-settings-action-btn", attr: { "aria-label": "Add" } }); - (0, import_obsidian19.setIcon)(addBtn, "plus"); + (0, import_obsidian26.setIcon)(addBtn, "plus"); const dropdown = addContainer.createDiv({ cls: "claudian-mcp-add-dropdown" }); const stdioOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" }); - (0, import_obsidian19.setIcon)(stdioOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "terminal"); + (0, import_obsidian26.setIcon)(stdioOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "terminal"); stdioOption.createSpan({ text: "stdio (local command)" }); stdioOption.addEventListener("click", () => { dropdown.removeClass("is-visible"); this.openModal(null, "stdio"); }); const httpOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" }); - (0, import_obsidian19.setIcon)(httpOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "globe"); + (0, import_obsidian26.setIcon)(httpOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "globe"); httpOption.createSpan({ text: "http / sse (remote)" }); httpOption.addEventListener("click", () => { dropdown.removeClass("is-visible"); this.openModal(null, "http"); }); const importOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" }); - (0, import_obsidian19.setIcon)(importOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "clipboard-paste"); + (0, import_obsidian26.setIcon)(importOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "clipboard-paste"); importOption.createSpan({ text: "Import from clipboard" }); importOption.addEventListener("click", () => { dropdown.removeClass("is-visible"); this.importFromClipboard(); }); - addBtn.addEventListener("click", (e) => { - e.stopPropagation(); + addBtn.addEventListener("click", (e2) => { + e2.stopPropagation(); dropdown.toggleClass("is-visible", !dropdown.hasClass("is-visible")); }); document.addEventListener("click", () => { @@ -33885,25 +64831,25 @@ var McpSettingsManager = class { cls: "claudian-mcp-action-btn", attr: { "aria-label": "Verify (show tools)" } }); - (0, import_obsidian19.setIcon)(testBtn, "zap"); + (0, import_obsidian26.setIcon)(testBtn, "zap"); testBtn.addEventListener("click", () => this.testServer(server)); const toggleBtn = actionsEl.createEl("button", { cls: "claudian-mcp-action-btn", attr: { "aria-label": server.enabled ? "Disable" : "Enable" } }); - (0, import_obsidian19.setIcon)(toggleBtn, server.enabled ? "toggle-right" : "toggle-left"); + (0, import_obsidian26.setIcon)(toggleBtn, server.enabled ? "toggle-right" : "toggle-left"); toggleBtn.addEventListener("click", () => this.toggleServer(server)); const editBtn = actionsEl.createEl("button", { cls: "claudian-mcp-action-btn", attr: { "aria-label": "Edit" } }); - (0, import_obsidian19.setIcon)(editBtn, "pencil"); + (0, import_obsidian26.setIcon)(editBtn, "pencil"); editBtn.addEventListener("click", () => this.openModal(server)); const deleteBtn = actionsEl.createEl("button", { cls: "claudian-mcp-action-btn claudian-mcp-delete-btn", attr: { "aria-label": "Delete" } }); - (0, import_obsidian19.setIcon)(deleteBtn, "trash-2"); + (0, import_obsidian26.setIcon)(deleteBtn, "trash-2"); deleteBtn.addEventListener("click", () => this.deleteServer(server)); } async testServer(server) { @@ -33922,33 +64868,29 @@ var McpSettingsManager = class { try { const result = await testMcpServer(server); modal.setResult(result); - } catch (error2) { - modal.setError(error2 instanceof Error ? error2.message : "Verification failed"); + } catch (error48) { + modal.setError(error48 instanceof Error ? error48.message : "Verification failed"); } } - /** - * Helper to update server.disabledTools with save and reload. - * Rolls back on save failure; warns on reload failure (since save succeeded). - */ + /** Rolls back on save failure; warns on reload failure (since save succeeded). */ async updateServerDisabledTools(server, newDisabledTools) { const previous = server.disabledTools ? [...server.disabledTools] : void 0; server.disabledTools = newDisabledTools; try { await this.plugin.storage.mcp.save(this.servers); - } catch (error2) { + } catch (error48) { server.disabledTools = previous; - throw error2; + throw error48; } try { - await this.plugin.agentService.reloadMcpServers(); - } catch (error2) { - console.warn("[Claudian] MCP reload failed after save:", error2); - new import_obsidian19.Notice("Setting saved but reload failed. Changes will apply on next session."); + await this.broadcastMcpReloadToAllViews(); + } catch (e2) { + new import_obsidian26.Notice("Setting saved but reload failed. Changes will apply on next session."); } } async updateDisabledTool(server, toolName, enabled) { - var _a; - const disabledTools = new Set((_a = server.disabledTools) != null ? _a : []); + var _a3; + const disabledTools = new Set((_a3 = server.disabledTools) != null ? _a3 : []); if (enabled) { disabledTools.delete(toolName); } else { @@ -33966,10 +64908,10 @@ var McpSettingsManager = class { ); } getServerPreview(server, type) { - var _a; + var _a3; if (type === "stdio") { const config2 = server.config; - const args = ((_a = config2.args) == null ? void 0 : _a.join(" ")) || ""; + const args = ((_a3 = config2.args) == null ? void 0 : _a3.join(" ")) || ""; return args ? `${config2.command} ${args}` : config2.command; } else { const config2 = server.config; @@ -33992,12 +64934,12 @@ var McpSettingsManager = class { try { const text = await navigator.clipboard.readText(); if (!text.trim()) { - new import_obsidian19.Notice("Clipboard is empty"); + new import_obsidian26.Notice("Clipboard is empty"); return; } const parsed = McpStorage.tryParseClipboardConfig(text); if (!parsed || parsed.servers.length === 0) { - new import_obsidian19.Notice("No valid MCP configuration found in clipboard"); + new import_obsidian26.Notice("No valid MCP configuration found in clipboard"); return; } if (parsed.needsName || parsed.servers.length === 1) { @@ -34016,13 +64958,13 @@ var McpSettingsManager = class { ); modal.open(); if (parsed.needsName) { - new import_obsidian19.Notice("Enter a name for the server"); + new import_obsidian26.Notice("Enter a name for the server"); } return; } await this.importServers(parsed.servers); - } catch (e) { - new import_obsidian19.Notice("Failed to read clipboard"); + } catch (e2) { + new import_obsidian26.Notice("Failed to read clipboard"); } } async saveServer(server, existing) { @@ -34032,7 +64974,7 @@ var McpSettingsManager = class { if (server.name !== existing.name) { const conflict = this.servers.find((s) => s.name === server.name); if (conflict) { - new import_obsidian19.Notice(`Server "${server.name}" already exists`); + new import_obsidian26.Notice(`Server "${server.name}" already exists`); return; } } @@ -34041,15 +64983,15 @@ var McpSettingsManager = class { } else { const conflict = this.servers.find((s) => s.name === server.name); if (conflict) { - new import_obsidian19.Notice(`Server "${server.name}" already exists`); + new import_obsidian26.Notice(`Server "${server.name}" already exists`); return; } this.servers.push(server); } await this.plugin.storage.mcp.save(this.servers); - await this.plugin.agentService.reloadMcpServers(); + await this.broadcastMcpReloadToAllViews(); this.render(); - new import_obsidian19.Notice(existing ? `MCP server "${server.name}" updated` : `MCP server "${server.name}" added`); + new import_obsidian26.Notice(existing ? `MCP server "${server.name}" updated` : `MCP server "${server.name}" added`); } async importServers(servers) { const added = []; @@ -34074,24 +65016,24 @@ var McpSettingsManager = class { added.push(name); } if (added.length === 0) { - new import_obsidian19.Notice("No new MCP servers imported"); + new import_obsidian26.Notice("No new MCP servers imported"); return; } await this.plugin.storage.mcp.save(this.servers); - await this.plugin.agentService.reloadMcpServers(); + await this.broadcastMcpReloadToAllViews(); this.render(); let message = `Imported ${added.length} MCP server${added.length > 1 ? "s" : ""}`; if (skipped.length > 0) { message += ` (${skipped.length} skipped)`; } - new import_obsidian19.Notice(message); + new import_obsidian26.Notice(message); } async toggleServer(server) { server.enabled = !server.enabled; await this.plugin.storage.mcp.save(this.servers); - await this.plugin.agentService.reloadMcpServers(); + await this.broadcastMcpReloadToAllViews(); this.render(); - new import_obsidian19.Notice(`MCP server "${server.name}" ${server.enabled ? "enabled" : "disabled"}`); + new import_obsidian26.Notice(`MCP server "${server.name}" ${server.enabled ? "enabled" : "disabled"}`); } async deleteServer(server) { if (!confirm(`Delete MCP server "${server.name}"?`)) { @@ -34099,9 +65041,9 @@ var McpSettingsManager = class { } this.servers = this.servers.filter((s) => s.name !== server.name); await this.plugin.storage.mcp.save(this.servers); - await this.plugin.agentService.reloadMcpServers(); + await this.broadcastMcpReloadToAllViews(); this.render(); - new import_obsidian19.Notice(`MCP server "${server.name}" deleted`); + new import_obsidian26.Notice(`MCP server "${server.name}" deleted`); } /** Refresh the server list (call after external changes). */ refresh() { @@ -34109,9 +65051,130 @@ var McpSettingsManager = class { } }; -// src/ui/settings/SlashCommandSettings.ts -var import_obsidian20 = require("obsidian"); -var SlashCommandModal = class extends import_obsidian20.Modal { +// src/features/settings/ui/PluginSettingsManager.ts +var import_obsidian27 = require("obsidian"); +var PluginSettingsManager = class { + constructor(containerEl, plugin) { + this.containerEl = containerEl; + this.plugin = plugin; + this.render(); + } + render() { + this.containerEl.empty(); + const headerEl = this.containerEl.createDiv({ cls: "claudian-plugin-header" }); + headerEl.createSpan({ text: "Claude Code Plugins", cls: "claudian-plugin-label" }); + const refreshBtn = headerEl.createEl("button", { + cls: "claudian-settings-action-btn", + attr: { "aria-label": "Refresh" } + }); + (0, import_obsidian27.setIcon)(refreshBtn, "refresh-cw"); + refreshBtn.addEventListener("click", () => this.refreshPlugins()); + const plugins = this.plugin.pluginManager.getPlugins(); + if (plugins.length === 0) { + const emptyEl = this.containerEl.createDiv({ cls: "claudian-plugin-empty" }); + emptyEl.setText("No Claude Code plugins found. Enable plugins via the Claude CLI."); + return; + } + const projectPlugins = plugins.filter((p2) => p2.scope === "project"); + const userPlugins = plugins.filter((p2) => p2.scope === "user"); + const listEl = this.containerEl.createDiv({ cls: "claudian-plugin-list" }); + if (projectPlugins.length > 0) { + const sectionHeader = listEl.createDiv({ cls: "claudian-plugin-section-header" }); + sectionHeader.setText("Project Plugins"); + for (const plugin of projectPlugins) { + this.renderPluginItem(listEl, plugin); + } + } + if (userPlugins.length > 0) { + const sectionHeader = listEl.createDiv({ cls: "claudian-plugin-section-header" }); + sectionHeader.setText("User Plugins"); + for (const plugin of userPlugins) { + this.renderPluginItem(listEl, plugin); + } + } + } + renderPluginItem(listEl, plugin) { + const itemEl = listEl.createDiv({ cls: "claudian-plugin-item" }); + if (!plugin.enabled) { + itemEl.addClass("claudian-plugin-item-disabled"); + } + const statusEl = itemEl.createDiv({ cls: "claudian-plugin-status" }); + if (plugin.enabled) { + statusEl.addClass("claudian-plugin-status-enabled"); + } else { + statusEl.addClass("claudian-plugin-status-disabled"); + } + const infoEl = itemEl.createDiv({ cls: "claudian-plugin-info" }); + const nameRow = infoEl.createDiv({ cls: "claudian-plugin-name-row" }); + const nameEl = nameRow.createSpan({ cls: "claudian-plugin-name" }); + nameEl.setText(plugin.name); + const actionsEl = itemEl.createDiv({ cls: "claudian-plugin-actions" }); + const toggleBtn = actionsEl.createEl("button", { + cls: "claudian-plugin-action-btn", + attr: { "aria-label": plugin.enabled ? "Disable" : "Enable" } + }); + (0, import_obsidian27.setIcon)(toggleBtn, plugin.enabled ? "toggle-right" : "toggle-left"); + toggleBtn.addEventListener("click", () => this.togglePlugin(plugin.id)); + } + async togglePlugin(pluginId) { + var _a3; + const plugin = this.plugin.pluginManager.getPlugins().find((p2) => p2.id === pluginId); + const wasEnabled = (_a3 = plugin == null ? void 0 : plugin.enabled) != null ? _a3 : false; + try { + await this.plugin.pluginManager.togglePlugin(pluginId); + await this.plugin.agentManager.loadAgents(); + const view = this.plugin.getView(); + const tabManager = view == null ? void 0 : view.getTabManager(); + if (tabManager) { + try { + await tabManager.broadcastToAllTabs( + async (service) => { + await service.ensureReady({ force: true }); + } + ); + } catch (e2) { + new import_obsidian27.Notice("Plugin toggled, but some tabs failed to restart."); + } + } + new import_obsidian27.Notice(`Plugin "${pluginId}" ${wasEnabled ? "disabled" : "enabled"}`); + } catch (err) { + await this.plugin.pluginManager.togglePlugin(pluginId); + const message = err instanceof Error ? err.message : "Unknown error"; + new import_obsidian27.Notice(`Failed to toggle plugin: ${message}`); + } finally { + this.render(); + } + } + async refreshPlugins() { + try { + await this.plugin.pluginManager.loadPlugins(); + await this.plugin.agentManager.loadAgents(); + new import_obsidian27.Notice("Plugin list refreshed"); + } catch (err) { + const message = err instanceof Error ? err.message : "Unknown error"; + new import_obsidian27.Notice(`Failed to refresh plugins: ${message}`); + } finally { + this.render(); + } + } + refresh() { + this.render(); + } +}; + +// src/features/settings/ui/SlashCommandSettings.ts +var import_obsidian28 = require("obsidian"); +function resolveAllowedTools(inputValue, parsedTools) { + const trimmed = inputValue.trim(); + if (trimmed) { + return trimmed.split(",").map((s) => s.trim()).filter(Boolean); + } + if (parsedTools && parsedTools.length > 0) { + return parsedTools; + } + return void 0; +} +var SlashCommandModal = class extends import_obsidian28.Modal { constructor(app, plugin, existingCmd, onSave) { super(app); this.plugin = plugin; @@ -34119,42 +65182,102 @@ var SlashCommandModal = class extends import_obsidian20.Modal { this.onSave = onSave; } onOpen() { - this.setTitle(this.existingCmd ? "Edit Slash Command" : "Add Slash Command"); - this.modalEl.addClass("claudian-slash-modal"); + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m; + const existingIsSkill = this.existingCmd ? isSkill(this.existingCmd) : false; + let selectedType = existingIsSkill ? "skill" : "command"; + const typeLabel = () => selectedType === "skill" ? "Skill" : "Slash Command"; + this.setTitle(this.existingCmd ? `Edit ${typeLabel()}` : `Add ${typeLabel()}`); + this.modalEl.addClass("claudian-sp-modal"); const { contentEl } = this; let nameInput; let descInput; let hintInput; let modelInput; let toolsInput; - new import_obsidian20.Setting(contentEl).setName("Command name").setDesc('The name used after / (e.g., "review" for /review)').addText((text) => { - var _a; + let disableModelToggle = (_b = (_a3 = this.existingCmd) == null ? void 0 : _a3.disableModelInvocation) != null ? _b : false; + let disableUserInvocation = ((_c = this.existingCmd) == null ? void 0 : _c.userInvocable) === false; + let contextValue = (_e = (_d = this.existingCmd) == null ? void 0 : _d.context) != null ? _e : ""; + let agentInput; + let disableUserSetting; + let disableUserToggle; + const updateSkillOnlyFields = () => { + const isSkillType = selectedType === "skill"; + disableUserSetting.settingEl.style.display = isSkillType ? "" : "none"; + if (!isSkillType) { + disableUserInvocation = false; + disableUserToggle.setValue(false); + } + }; + new import_obsidian28.Setting(contentEl).setName("Type").setDesc("Command or skill").addDropdown((dropdown) => { + dropdown.addOption("command", "Command").addOption("skill", "Skill").setValue(selectedType).onChange((value) => { + selectedType = value; + this.setTitle(this.existingCmd ? `Edit ${typeLabel()}` : `Add ${typeLabel()}`); + updateSkillOnlyFields(); + }); + if (this.existingCmd) { + dropdown.setDisabled(true); + } + }); + new import_obsidian28.Setting(contentEl).setName("Command name").setDesc('The name used after / (e.g., "review" for /review)').addText((text) => { + var _a4; nameInput = text.inputEl; - text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.name) || "").setPlaceholder("review-code"); + text.setValue(((_a4 = this.existingCmd) == null ? void 0 : _a4.name) || "").setPlaceholder("review-code"); }); - new import_obsidian20.Setting(contentEl).setName("Description").setDesc("Optional description shown in dropdown").addText((text) => { - var _a; + new import_obsidian28.Setting(contentEl).setName("Description").setDesc("Optional description shown in dropdown").addText((text) => { + var _a4; descInput = text.inputEl; - text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.description) || ""); + text.setValue(((_a4 = this.existingCmd) == null ? void 0 : _a4.description) || ""); }); - new import_obsidian20.Setting(contentEl).setName("Argument hint").setDesc('Placeholder text for arguments (e.g., "[file] [focus]")').addText((text) => { - var _a; + const details = contentEl.createEl("details", { cls: "claudian-sp-advanced-section" }); + details.createEl("summary", { + text: "Advanced options", + cls: "claudian-sp-advanced-summary" + }); + if (((_f = this.existingCmd) == null ? void 0 : _f.argumentHint) || ((_g = this.existingCmd) == null ? void 0 : _g.model) || ((_i = (_h = this.existingCmd) == null ? void 0 : _h.allowedTools) == null ? void 0 : _i.length) || ((_j = this.existingCmd) == null ? void 0 : _j.disableModelInvocation) || ((_k = this.existingCmd) == null ? void 0 : _k.userInvocable) === false || ((_l = this.existingCmd) == null ? void 0 : _l.context) || ((_m = this.existingCmd) == null ? void 0 : _m.agent)) { + details.open = true; + } + new import_obsidian28.Setting(details).setName("Argument hint").setDesc('Placeholder text for arguments (e.g., "[file] [focus]")').addText((text) => { + var _a4; hintInput = text.inputEl; - text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.argumentHint) || ""); + text.setValue(((_a4 = this.existingCmd) == null ? void 0 : _a4.argumentHint) || ""); }); - new import_obsidian20.Setting(contentEl).setName("Model override").setDesc("Optional model to use for this command").addText((text) => { - var _a; + new import_obsidian28.Setting(details).setName("Model override").setDesc("Optional model to use for this command").addText((text) => { + var _a4; modelInput = text.inputEl; - text.setValue(((_a = this.existingCmd) == null ? void 0 : _a.model) || "").setPlaceholder("claude-sonnet-4-5"); + text.setValue(((_a4 = this.existingCmd) == null ? void 0 : _a4.model) || "").setPlaceholder("claude-sonnet-4-5"); }); - new import_obsidian20.Setting(contentEl).setName("Allowed tools").setDesc("Comma-separated list of tools to allow (empty = all)").addText((text) => { - var _a, _b; + new import_obsidian28.Setting(details).setName("Allowed tools").setDesc("Comma-separated list of tools to allow (empty = all)").addText((text) => { + var _a4, _b2; toolsInput = text.inputEl; - text.setValue(((_b = (_a = this.existingCmd) == null ? void 0 : _a.allowedTools) == null ? void 0 : _b.join(", ")) || ""); + text.setValue(((_b2 = (_a4 = this.existingCmd) == null ? void 0 : _a4.allowedTools) == null ? void 0 : _b2.join(", ")) || ""); }); - new import_obsidian20.Setting(contentEl).setName("Prompt template").setDesc("Use $ARGUMENTS, $1, $2, @file, !`bash`"); + new import_obsidian28.Setting(details).setName("Disable model invocation").setDesc("Prevent the model from invoking this command itself").addToggle((toggle) => { + toggle.setValue(disableModelToggle).onChange((value) => { + disableModelToggle = value; + }); + }); + disableUserSetting = new import_obsidian28.Setting(details).setName("Disable user invocation").setDesc("Prevent the user from invoking this skill directly").addToggle((toggle) => { + disableUserToggle = toggle; + toggle.setValue(disableUserInvocation).onChange((value) => { + disableUserInvocation = value; + }); + }); + updateSkillOnlyFields(); + new import_obsidian28.Setting(details).setName("Context").setDesc("Run in a subagent (fork)").addToggle((toggle) => { + toggle.setValue(contextValue === "fork").onChange((value) => { + contextValue = value ? "fork" : ""; + agentSetting.settingEl.style.display = value ? "" : "none"; + }); + }); + const agentSetting = new import_obsidian28.Setting(details).setName("Agent").setDesc("Subagent type when context is fork").addText((text) => { + var _a4; + agentInput = text.inputEl; + text.setValue(((_a4 = this.existingCmd) == null ? void 0 : _a4.agent) || "").setPlaceholder("code-reviewer"); + }); + agentSetting.settingEl.style.display = contextValue === "fork" ? "" : "none"; + new import_obsidian28.Setting(contentEl).setName("Prompt template").setDesc("Use $ARGUMENTS, $1, $2, @file, !`bash`"); const contentArea = contentEl.createEl("textarea", { - cls: "claudian-slash-content-area", + cls: "claudian-sp-content-area", attr: { rows: "10", placeholder: "Review this code for:\n$ARGUMENTS\n\n@$1" @@ -34162,7 +65285,7 @@ var SlashCommandModal = class extends import_obsidian20.Modal { }); const initialContent = this.existingCmd ? parseSlashCommandContent(this.existingCmd.content).promptContent : ""; contentArea.value = initialContent; - const buttonContainer = contentEl.createDiv({ cls: "claudian-slash-modal-buttons" }); + const buttonContainer = contentEl.createDiv({ cls: "claudian-sp-modal-buttons" }); const cancelBtn = buttonContainer.createEl("button", { text: "Cancel", cls: "claudian-cancel-btn" @@ -34173,48 +65296,58 @@ var SlashCommandModal = class extends import_obsidian20.Modal { cls: "claudian-save-btn" }); saveBtn.addEventListener("click", async () => { - var _a; + var _a4; const name = nameInput.value.trim(); - if (!name) { - new import_obsidian20.Notice("Command name is required"); + const nameError = validateCommandName(name); + if (nameError) { + new import_obsidian28.Notice(nameError); return; } const content = contentArea.value; if (!content.trim()) { - new import_obsidian20.Notice("Prompt template is required"); - return; - } - if (!/^[a-zA-Z0-9_/-]+$/.test(name)) { - new import_obsidian20.Notice("Command name can only contain letters, numbers, hyphens, underscores, and slashes"); + new import_obsidian28.Notice("Prompt template is required"); return; } const existing = this.plugin.settings.slashCommands.find( - (c) => { - var _a2; - return c.name.toLowerCase() === name.toLowerCase() && c.id !== ((_a2 = this.existingCmd) == null ? void 0 : _a2.id); + (c3) => { + var _a5; + return c3.name.toLowerCase() === name.toLowerCase() && c3.id !== ((_a5 = this.existingCmd) == null ? void 0 : _a5.id); } ); if (existing) { - new import_obsidian20.Notice(`A command named "/${name}" already exists`); + new import_obsidian28.Notice(`A command named "/${name}" already exists`); return; } const parsed = parseSlashCommandContent(content); const promptContent = parsed.promptContent; + const isSkillType = selectedType === "skill"; + const id = ((_a4 = this.existingCmd) == null ? void 0 : _a4.id) || (isSkillType ? `skill-${name}` : `cmd-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`); const cmd = { - id: ((_a = this.existingCmd) == null ? void 0 : _a.id) || `cmd-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`, + id, name, description: descInput.value.trim() || parsed.description || void 0, argumentHint: hintInput.value.trim() || parsed.argumentHint || void 0, model: modelInput.value.trim() || parsed.model || void 0, - allowedTools: toolsInput.value.trim() ? toolsInput.value.split(",").map((s) => s.trim()).filter(Boolean) : parsed.allowedTools && parsed.allowedTools.length > 0 ? parsed.allowedTools : void 0, - content: promptContent + allowedTools: resolveAllowedTools(toolsInput.value, parsed.allowedTools), + content: promptContent, + source: isSkillType ? "user" : void 0, + disableModelInvocation: disableModelToggle || void 0, + userInvocable: disableUserInvocation ? false : void 0, + context: contextValue || void 0, + agent: contextValue === "fork" ? agentInput.value.trim() || void 0 : void 0 }; - this.onSave(cmd); + try { + await this.onSave(cmd); + } catch (e2) { + const label = isSkillType ? "skill" : "slash command"; + new import_obsidian28.Notice(`Failed to save ${label}`); + return; + } this.close(); }); - const handleKeyDown = (e) => { - if (e.key === "Escape") { - e.preventDefault(); + const handleKeyDown = (e2) => { + if (e2.key === "Escape") { + e2.preventDefault(); this.close(); } }; @@ -34232,66 +65365,76 @@ var SlashCommandSettings = class { } render() { this.containerEl.empty(); - const headerEl = this.containerEl.createDiv({ cls: "claudian-slash-header" }); - headerEl.createSpan({ text: "Slash Commands", cls: "claudian-slash-label" }); - const actionsEl = headerEl.createDiv({ cls: "claudian-slash-header-actions" }); - const importBtn = actionsEl.createEl("button", { - cls: "claudian-settings-action-btn", - attr: { "aria-label": "Import" } - }); - (0, import_obsidian20.setIcon)(importBtn, "download"); - importBtn.addEventListener("click", () => this.importCommands()); - const exportBtn = actionsEl.createEl("button", { - cls: "claudian-settings-action-btn", - attr: { "aria-label": "Export" } - }); - (0, import_obsidian20.setIcon)(exportBtn, "upload"); - exportBtn.addEventListener("click", () => this.exportCommands()); + const headerEl = this.containerEl.createDiv({ cls: "claudian-sp-header" }); + headerEl.createSpan({ text: t("settings.slashCommands.name"), cls: "claudian-sp-label" }); + const actionsEl = headerEl.createDiv({ cls: "claudian-sp-header-actions" }); const addBtn = actionsEl.createEl("button", { cls: "claudian-settings-action-btn", attr: { "aria-label": "Add" } }); - (0, import_obsidian20.setIcon)(addBtn, "plus"); + (0, import_obsidian28.setIcon)(addBtn, "plus"); addBtn.addEventListener("click", () => this.openCommandModal(null)); const commands = this.plugin.settings.slashCommands; if (commands.length === 0) { - const emptyEl = this.containerEl.createDiv({ cls: "claudian-slash-empty-state" }); - emptyEl.setText('No slash commands configured. Click "Add" to create one.'); + const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" }); + emptyEl.setText("No commands or skills configured. Click + to create one."); return; } - const listEl = this.containerEl.createDiv({ cls: "claudian-slash-list" }); + const listEl = this.containerEl.createDiv({ cls: "claudian-sp-list" }); for (const cmd of commands) { this.renderCommandItem(listEl, cmd); } } renderCommandItem(listEl, cmd) { - const itemEl = listEl.createDiv({ cls: "claudian-slash-item-settings" }); - const infoEl = itemEl.createDiv({ cls: "claudian-slash-info" }); - const headerRow = infoEl.createDiv({ cls: "claudian-slash-item-header" }); - const nameEl = headerRow.createSpan({ cls: "claudian-slash-item-name" }); + const itemEl = listEl.createDiv({ cls: "claudian-sp-item" }); + const infoEl = itemEl.createDiv({ cls: "claudian-sp-info" }); + const headerRow = infoEl.createDiv({ cls: "claudian-sp-item-header" }); + const nameEl = headerRow.createSpan({ cls: "claudian-sp-item-name" }); nameEl.setText(`/${cmd.name}`); + if (isSkill(cmd)) { + headerRow.createSpan({ text: "skill", cls: "claudian-slash-item-badge" }); + } if (cmd.argumentHint) { const hintEl = headerRow.createSpan({ cls: "claudian-slash-item-hint" }); hintEl.setText(cmd.argumentHint); } if (cmd.description) { - const descEl = infoEl.createDiv({ cls: "claudian-slash-item-desc" }); + const descEl = infoEl.createDiv({ cls: "claudian-sp-item-desc" }); descEl.setText(cmd.description); } - const actionsEl = itemEl.createDiv({ cls: "claudian-slash-item-actions" }); + const actionsEl = itemEl.createDiv({ cls: "claudian-sp-item-actions" }); const editBtn = actionsEl.createEl("button", { cls: "claudian-settings-action-btn", attr: { "aria-label": "Edit" } }); - (0, import_obsidian20.setIcon)(editBtn, "pencil"); + (0, import_obsidian28.setIcon)(editBtn, "pencil"); editBtn.addEventListener("click", () => this.openCommandModal(cmd)); + if (!isSkill(cmd)) { + const convertBtn = actionsEl.createEl("button", { + cls: "claudian-settings-action-btn", + attr: { "aria-label": "Convert to skill" } + }); + (0, import_obsidian28.setIcon)(convertBtn, "package"); + convertBtn.addEventListener("click", async () => { + try { + await this.transformToSkill(cmd); + } catch (e2) { + new import_obsidian28.Notice("Failed to convert to skill"); + } + }); + } const deleteBtn = actionsEl.createEl("button", { cls: "claudian-settings-action-btn claudian-settings-delete-btn", attr: { "aria-label": "Delete" } }); - (0, import_obsidian20.setIcon)(deleteBtn, "trash-2"); + (0, import_obsidian28.setIcon)(deleteBtn, "trash-2"); deleteBtn.addEventListener("click", async () => { - await this.deleteCommand(cmd); + try { + await this.deleteCommand(cmd); + } catch (e2) { + const label = isSkill(cmd) ? "skill" : "slash command"; + new import_obsidian28.Notice(`Failed to delete ${label}`); + } }); } openCommandModal(existingCmd) { @@ -34305,4288 +65448,57 @@ var SlashCommandSettings = class { ); modal.open(); } + storageFor(cmd) { + return isSkill(cmd) ? this.plugin.storage.skills : this.plugin.storage.commands; + } async saveCommand(cmd, existing) { - await this.plugin.storage.commands.save(cmd); + await this.storageFor(cmd).save(cmd); if (existing && existing.name !== cmd.name) { - await this.plugin.storage.commands.delete(existing.id); + await this.storageFor(existing).delete(existing.id); } await this.reloadCommands(); this.render(); - new import_obsidian20.Notice(`Slash command "/${cmd.name}" ${existing ? "updated" : "created"}`); + const label = isSkill(cmd) ? "Skill" : "Slash command"; + new import_obsidian28.Notice(`${label} "/${cmd.name}" ${existing ? "updated" : "created"}`); } async deleteCommand(cmd) { + await this.storageFor(cmd).delete(cmd.id); + await this.reloadCommands(); + this.render(); + const label = isSkill(cmd) ? "Skill" : "Slash command"; + new import_obsidian28.Notice(`${label} "/${cmd.name}" deleted`); + } + async transformToSkill(cmd) { + const skillName = cmd.name.toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, 64); + const existingSkill = this.plugin.settings.slashCommands.find( + (c3) => isSkill(c3) && c3.name === skillName + ); + if (existingSkill) { + new import_obsidian28.Notice(`A skill named "/${skillName}" already exists`); + return; + } + const description = cmd.description || extractFirstParagraph(cmd.content); + const skill = { + ...cmd, + id: `skill-${skillName}`, + name: skillName, + description, + source: "user" + }; + await this.plugin.storage.skills.save(skill); await this.plugin.storage.commands.delete(cmd.id); await this.reloadCommands(); this.render(); - new import_obsidian20.Notice(`Slash command "/${cmd.name}" deleted`); + new import_obsidian28.Notice(`Converted "/${cmd.name}" to skill`); } - /** Reload commands from storage and update in-memory settings. */ async reloadCommands() { - const commands = await this.plugin.storage.commands.loadAll(); - this.plugin.settings.slashCommands = commands; - } - exportCommands() { - const commands = this.plugin.settings.slashCommands; - if (commands.length === 0) { - new import_obsidian20.Notice("No slash commands to export"); - return; - } - const json = JSON.stringify(commands, null, 2); - const blob = new Blob([json], { type: "application/json" }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = "claudian-slash-commands.json"; - a.click(); - URL.revokeObjectURL(url); - new import_obsidian20.Notice(`Exported ${commands.length} slash command(s)`); - } - importCommands() { - const input = document.createElement("input"); - input.type = "file"; - input.accept = ".json"; - input.addEventListener("change", async (e) => { - var _a; - const file = (_a = e.target.files) == null ? void 0 : _a[0]; - if (!file) return; - try { - const text = await file.text(); - const commands = JSON.parse(text); - if (!Array.isArray(commands)) { - throw new Error("Invalid format: expected an array"); - } - const existingCommands = await this.plugin.storage.commands.loadAll(); - const existingNames = new Set(existingCommands.map((c) => c.name.toLowerCase())); - let imported = 0; - for (const cmd of commands) { - if (!cmd.name || !cmd.content) { - continue; - } - if (typeof cmd.name !== "string" || typeof cmd.content !== "string") { - continue; - } - if (!/^[a-zA-Z0-9_/-]+$/.test(cmd.name)) { - continue; - } - cmd.id = `cmd-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`; - if (cmd.allowedTools && !Array.isArray(cmd.allowedTools)) { - cmd.allowedTools = void 0; - } - if (Array.isArray(cmd.allowedTools)) { - cmd.allowedTools = cmd.allowedTools.filter((t) => typeof t === "string" && t.trim().length > 0); - if (cmd.allowedTools.length === 0) { - cmd.allowedTools = void 0; - } - } - if (cmd.description && typeof cmd.description !== "string") { - cmd.description = void 0; - } - if (cmd.argumentHint && typeof cmd.argumentHint !== "string") { - cmd.argumentHint = void 0; - } - if (cmd.model && typeof cmd.model !== "string") { - cmd.model = void 0; - } - const parsed = parseSlashCommandContent(cmd.content); - cmd.description = cmd.description || parsed.description; - cmd.argumentHint = cmd.argumentHint || parsed.argumentHint; - cmd.model = cmd.model || parsed.model; - cmd.allowedTools = cmd.allowedTools || parsed.allowedTools; - cmd.content = parsed.promptContent; - if (existingNames.has(cmd.name.toLowerCase())) { - continue; - } - await this.plugin.storage.commands.save(cmd); - existingNames.add(cmd.name.toLowerCase()); - imported++; - } - await this.reloadCommands(); - this.render(); - new import_obsidian20.Notice(`Imported ${imported} slash command(s)`); - } catch (e2) { - new import_obsidian20.Notice("Failed to import slash commands. Check file format."); - } - }); - input.click(); + this.plugin.settings.slashCommands = await this.plugin.storage.loadAllSlashCommands(); } refresh() { this.render(); } }; -// src/features/chat/controllers/ConversationController.ts -var import_obsidian21 = require("obsidian"); -var ConversationController = class { - constructor(deps, callbacks = {}) { - this.deps = deps; - this.callbacks = callbacks; - } - // ============================================ - // Conversation Lifecycle - // ============================================ - /** Creates a new conversation, or switches to an existing empty one. */ - async createNew() { - var _a, _b, _c, _d, _e, _f, _g; - const { plugin, state, asyncSubagentManager } = this.deps; - if (state.isStreaming) return; - if (state.messages.length > 0) { - await this.save(); - } - asyncSubagentManager.orphanAllActive(); - state.asyncSubagentStates.clear(); - const emptyConv = plugin.findEmptyConversation(); - const conversation = emptyConv ? (_a = await plugin.switchConversation(emptyConv.id)) != null ? _a : await plugin.createConversation() : await plugin.createConversation(); - state.currentConversationId = conversation.id; - state.clearMessages(); - state.usage = null; - state.currentTodos = null; - this.deps.setApprovedPlan(null); - this.deps.hidePlanBanner(); - state.pendingPlanContent = null; - this.restorePlanModeState(); - const messagesEl = this.deps.getMessagesEl(); - messagesEl.empty(); - (_b = this.deps.getTodoPanel()) == null ? void 0 : _b.remount(); - const welcomeEl = messagesEl.createDiv({ cls: "claudian-welcome" }); - welcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: this.getGreeting() }); - this.deps.setWelcomeEl(welcomeEl); - this.deps.getInputEl().value = ""; - const fileCtx = this.deps.getFileContextManager(); - fileCtx == null ? void 0 : fileCtx.resetForNewConversation(); - fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile(); - (_c = this.deps.getImageContextManager()) == null ? void 0 : _c.clearImages(); - (_d = this.deps.getMcpServerSelector()) == null ? void 0 : _d.clearEnabled(); - (_e = this.deps.getContextPathSelector()) == null ? void 0 : _e.clearContextPaths(); - this.deps.clearQueuedMessage(); - (_g = (_f = this.callbacks).onNewConversation) == null ? void 0 : _g.call(_f); - } - /** Loads the active conversation or creates a new one. */ - async loadActive() { - var _a, _b, _c, _d; - const { plugin, state, renderer } = this.deps; - let conversation = plugin.getActiveConversation(); - const isNewConversation = !conversation; - if (!conversation) { - conversation = await plugin.createConversation(); - } - state.currentConversationId = conversation.id; - state.messages = [...conversation.messages]; - state.usage = (_a = conversation.usage) != null ? _a : null; - plugin.agentService.setSessionId(conversation.sessionId); - if (conversation.approvedPlan) { - this.deps.setApprovedPlan(conversation.approvedPlan); - this.deps.showPlanBanner(conversation.approvedPlan); - } else { - this.deps.setApprovedPlan(null); - this.deps.hidePlanBanner(); - } - state.pendingPlanContent = (_b = conversation.pendingPlanContent) != null ? _b : null; - this.restorePlanModeState(); - const hasMessages = state.messages.length > 0; - const fileCtx = this.deps.getFileContextManager(); - fileCtx == null ? void 0 : fileCtx.resetForLoadedConversation(hasMessages); - if (conversation.currentNote) { - fileCtx == null ? void 0 : fileCtx.setCurrentNote(conversation.currentNote); - } else if (isNewConversation || !hasMessages) { - fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile(); - } - const contextPathSelector = this.deps.getContextPathSelector(); - if (conversation.sessionContextPaths && conversation.sessionContextPaths.length > 0) { - contextPathSelector == null ? void 0 : contextPathSelector.setContextPaths(conversation.sessionContextPaths); - } else { - contextPathSelector == null ? void 0 : contextPathSelector.clearContextPaths(); - } - const welcomeEl = renderer.renderMessages( - state.messages, - () => this.getGreeting() - ); - this.deps.setWelcomeEl(welcomeEl); - this.updateWelcomeVisibility(); - state.currentTodos = extractLastTodosFromMessages(state.messages); - (_d = (_c = this.callbacks).onConversationLoaded) == null ? void 0 : _d.call(_c); - if (conversation.pendingPlanContent && !conversation.approvedPlan) { - this.deps.triggerPendingPlanApproval(conversation.pendingPlanContent); - } - } - /** Switches to a different conversation. */ - async switchTo(id) { - var _a, _b, _c, _d, _e, _f; - const { plugin, state, renderer, asyncSubagentManager } = this.deps; - if (id === state.currentConversationId) return; - if (state.isStreaming) return; - await this.save(); - asyncSubagentManager.orphanAllActive(); - state.asyncSubagentStates.clear(); - const conversation = await plugin.switchConversation(id); - if (!conversation) return; - state.currentConversationId = conversation.id; - state.messages = [...conversation.messages]; - state.usage = (_a = conversation.usage) != null ? _a : null; - if (conversation.approvedPlan) { - this.deps.setApprovedPlan(conversation.approvedPlan); - this.deps.showPlanBanner(conversation.approvedPlan); - } else { - this.deps.setApprovedPlan(null); - this.deps.hidePlanBanner(); - } - state.pendingPlanContent = (_b = conversation.pendingPlanContent) != null ? _b : null; - this.restorePlanModeState(); - this.deps.getInputEl().value = ""; - this.deps.clearQueuedMessage(); - const fileCtx = this.deps.getFileContextManager(); - fileCtx == null ? void 0 : fileCtx.resetForLoadedConversation(state.messages.length > 0); - if (conversation.currentNote) { - fileCtx == null ? void 0 : fileCtx.setCurrentNote(conversation.currentNote); - } - const contextPathSelector = this.deps.getContextPathSelector(); - if (conversation.sessionContextPaths && conversation.sessionContextPaths.length > 0) { - contextPathSelector == null ? void 0 : contextPathSelector.setContextPaths(conversation.sessionContextPaths); - } else { - contextPathSelector == null ? void 0 : contextPathSelector.clearContextPaths(); - } - (_c = this.deps.getMcpServerSelector()) == null ? void 0 : _c.clearEnabled(); - const welcomeEl = renderer.renderMessages( - state.messages, - () => this.getGreeting() - ); - this.deps.setWelcomeEl(welcomeEl); - state.currentTodos = extractLastTodosFromMessages(state.messages); - (_d = this.deps.getHistoryDropdown()) == null ? void 0 : _d.removeClass("visible"); - this.updateWelcomeVisibility(); - (_f = (_e = this.callbacks).onConversationSwitched) == null ? void 0 : _f.call(_e); - if (conversation.pendingPlanContent && !conversation.approvedPlan) { - this.deps.triggerPendingPlanApproval(conversation.pendingPlanContent); - } - } - /** Saves the current conversation. */ - async save(updateLastResponse = false) { - var _a, _b, _c, _d, _e; - const { plugin, state } = this.deps; - if (!state.currentConversationId) return; - const sessionId = plugin.agentService.getSessionId(); - const fileCtx = this.deps.getFileContextManager(); - const currentNote = (fileCtx == null ? void 0 : fileCtx.getCurrentNotePath()) || void 0; - const contextPathSelector = this.deps.getContextPathSelector(); - const sessionContextPaths = (_a = contextPathSelector == null ? void 0 : contextPathSelector.getContextPaths()) != null ? _a : []; - const approvedPlan = this.deps.getApprovedPlan(); - const updates = { - messages: state.getPersistedMessages(), - sessionId, - currentNote, - sessionContextPaths: sessionContextPaths.length > 0 ? sessionContextPaths : void 0, - usage: (_b = state.usage) != null ? _b : void 0, - approvedPlan: approvedPlan != null ? approvedPlan : void 0, - pendingPlanContent: (_c = state.pendingPlanContent) != null ? _c : void 0, - isInPlanMode: (_e = (_d = state.planModeState) == null ? void 0 : _d.isActive) != null ? _e : void 0 - }; - if (updateLastResponse) { - updates.lastResponseAt = Date.now(); - } - await plugin.updateConversation(state.currentConversationId, updates); - } - /** - * Restores plan mode state based on current permission mode. - * Resets transient flags and sets up planModeState appropriately. - */ - restorePlanModeState() { - var _a, _b; - const { plugin, state } = this.deps; - state.planModeRequested = false; - state.planModeActivationPending = false; - const isPlanMode = plugin.settings.permissionMode === "plan"; - if (isPlanMode) { - const wasAgentInitiated = (_b = (_a = state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false; - state.planModeState = { - isActive: true, - planFilePath: null, - planContent: null, - originalQuery: null, - agentInitiated: wasAgentInitiated - }; - } else { - state.resetPlanModeState(); - } - this.deps.setPlanModeActive(isPlanMode); - } - // ============================================ - // History Dropdown - // ============================================ - /** Toggles the history dropdown visibility. */ - toggleHistoryDropdown() { - const dropdown = this.deps.getHistoryDropdown(); - if (!dropdown) return; - const isVisible = dropdown.hasClass("visible"); - if (isVisible) { - dropdown.removeClass("visible"); - } else { - this.updateHistoryDropdown(); - dropdown.addClass("visible"); - } - } - /** Updates the history dropdown content. */ - updateHistoryDropdown() { - var _a; - const dropdown = this.deps.getHistoryDropdown(); - if (!dropdown) return; - const { plugin, state } = this.deps; - dropdown.empty(); - const dropdownHeader = dropdown.createDiv({ cls: "claudian-history-header" }); - dropdownHeader.createSpan({ text: "Conversations" }); - const list = dropdown.createDiv({ cls: "claudian-history-list" }); - const allConversations = plugin.getConversationList(); - if (allConversations.length === 0) { - list.createDiv({ cls: "claudian-history-empty", text: "No conversations" }); - return; - } - const conversations = [...allConversations].sort((a, b) => { - var _a2, _b; - return ((_a2 = b.lastResponseAt) != null ? _a2 : b.createdAt) - ((_b = a.lastResponseAt) != null ? _b : a.createdAt); - }); - for (const conv of conversations) { - const isCurrent = conv.id === state.currentConversationId; - const item = list.createDiv({ - cls: `claudian-history-item${isCurrent ? " active" : ""}` - }); - const iconEl = item.createDiv({ cls: "claudian-history-item-icon" }); - (0, import_obsidian21.setIcon)(iconEl, isCurrent ? "message-square-dot" : "message-square"); - const content = item.createDiv({ cls: "claudian-history-item-content" }); - const titleEl = content.createDiv({ cls: "claudian-history-item-title", text: conv.title }); - titleEl.setAttribute("title", conv.title); - content.createDiv({ - cls: "claudian-history-item-date", - text: isCurrent ? "Current session" : this.formatDate((_a = conv.lastResponseAt) != null ? _a : conv.createdAt) - }); - if (!isCurrent) { - content.addEventListener("click", async (e) => { - e.stopPropagation(); - await this.switchTo(conv.id); - }); - } - const actions = item.createDiv({ cls: "claudian-history-item-actions" }); - if (conv.titleGenerationStatus === "pending") { - const loadingEl = actions.createEl("span", { cls: "claudian-action-btn claudian-action-loading" }); - (0, import_obsidian21.setIcon)(loadingEl, "loader-2"); - loadingEl.setAttribute("aria-label", "Generating title..."); - } else if (conv.titleGenerationStatus === "failed") { - const regenerateBtn = actions.createEl("button", { cls: "claudian-action-btn" }); - (0, import_obsidian21.setIcon)(regenerateBtn, "refresh-cw"); - regenerateBtn.setAttribute("aria-label", "Regenerate title"); - regenerateBtn.addEventListener("click", async (e) => { - e.stopPropagation(); - try { - await this.regenerateTitle(conv.id); - } catch (error2) { - console.error("[ConversationController] Failed to regenerate title:", error2); - } - }); - } - const renameBtn = actions.createEl("button", { cls: "claudian-action-btn" }); - (0, import_obsidian21.setIcon)(renameBtn, "pencil"); - renameBtn.setAttribute("aria-label", "Rename"); - renameBtn.addEventListener("click", (e) => { - e.stopPropagation(); - this.showRenameInput(item, conv.id, conv.title); - }); - const deleteBtn = actions.createEl("button", { cls: "claudian-action-btn claudian-delete-btn" }); - (0, import_obsidian21.setIcon)(deleteBtn, "trash-2"); - deleteBtn.setAttribute("aria-label", "Delete"); - deleteBtn.addEventListener("click", async (e) => { - e.stopPropagation(); - if (state.isStreaming) return; - await plugin.deleteConversation(conv.id); - this.updateHistoryDropdown(); - if (conv.id === state.currentConversationId) { - await this.loadActive(); - } - }); - } - } - /** Shows inline rename input for a conversation. */ - showRenameInput(item, convId, currentTitle) { - const titleEl = item.querySelector(".claudian-history-item-title"); - if (!titleEl) return; - const input = document.createElement("input"); - input.type = "text"; - input.className = "claudian-rename-input"; - input.value = currentTitle; - titleEl.replaceWith(input); - input.focus(); - input.select(); - const finishRename = async () => { - const newTitle = input.value.trim() || currentTitle; - await this.deps.plugin.renameConversation(convId, newTitle); - this.updateHistoryDropdown(); - }; - input.addEventListener("blur", finishRename); - input.addEventListener("keydown", async (e) => { - if (e.key === "Enter") { - input.blur(); - } else if (e.key === "Escape") { - input.value = currentTitle; - input.blur(); - } - }); - } - // ============================================ - // Welcome & Greeting - // ============================================ - /** Generates a dynamic greeting based on time/day. */ - getGreeting() { - var _a; - const now = /* @__PURE__ */ new Date(); - const hour = now.getHours(); - const day = now.getDay(); - const name = (_a = this.deps.plugin.settings.userName) == null ? void 0 : _a.trim(); - const dayGreetings = name ? { - 0: [`Happy Sunday, ${name}`, "Sunday session?", "Welcome to the weekend"], - 1: [`Happy Monday, ${name}`, `Back at it, ${name}`], - 2: [`Happy Tuesday, ${name}`], - 3: [`Happy Wednesday, ${name}`], - 4: [`Happy Thursday, ${name}`], - 5: [`Happy Friday, ${name}`, `That Friday feeling, ${name}`], - 6: [`Happy Saturday, ${name}`, `Welcome to the weekend, ${name}`] - } : { - 0: ["Happy Sunday", "Sunday session?", "Welcome to the weekend"], - 1: ["Happy Monday", "Back at it!"], - 2: ["Happy Tuesday"], - 3: ["Happy Wednesday"], - 4: ["Happy Thursday"], - 5: ["Happy Friday", "That Friday feeling"], - 6: ["Happy Saturday!", "Welcome to the weekend"] - }; - const getTimeGreetings = () => { - if (hour >= 5 && hour < 12) { - return name ? [`Good morning, ${name}`, "Coffee and Claudian time?"] : ["Good morning", "Coffee and Claudian time?"]; - } else if (hour >= 12 && hour < 18) { - return name ? [`Good afternoon, ${name}`, `Hey there, ${name}`, `How's it going, ${name}?`] : ["Good afternoon", "Hey there", "How's it going?"]; - } else if (hour >= 18 && hour < 22) { - return name ? [`Good evening, ${name}`, `Evening, ${name}`, `How was your day, ${name}?`] : ["Good evening", "Evening", "How was your day?"]; - } else { - return name ? ["Hello, night owl", `Evening, ${name}`] : ["Hello, night owl", "Evening"]; - } - }; - const generalGreetings = name ? [ - `Hey there, ${name}`, - `Hi ${name}, how are you?`, - `How's it going, ${name}?`, - `Welcome Back!, ${name}`, - `What's new, ${name}?`, - `${name} returns!` - ] : [ - "Hey there", - "Hi, how are you?", - "How's it going?", - "Welcome Back!", - "What's new?" - ]; - const allGreetings = [ - ...dayGreetings[day] || [], - ...getTimeGreetings(), - ...generalGreetings - ]; - return allGreetings[Math.floor(Math.random() * allGreetings.length)]; - } - /** Updates welcome element visibility based on message count. */ - updateWelcomeVisibility() { - const welcomeEl = this.deps.getWelcomeEl(); - if (!welcomeEl) return; - if (this.deps.state.messages.length === 0) { - welcomeEl.style.display = ""; - } else { - welcomeEl.style.display = "none"; - } - } - // ============================================ - // Utilities - // ============================================ - /** Generates a fallback title from the first message (used when AI fails). */ - generateFallbackTitle(firstMessage) { - const firstSentence = firstMessage.split(/[.!?\n]/)[0].trim(); - const autoTitle = firstSentence.substring(0, 50); - const suffix = firstSentence.length > 50 ? "..." : ""; - return `${autoTitle}${suffix}`; - } - /** Regenerates AI title for a conversation. */ - async regenerateTitle(conversationId) { - var _a; - const { plugin } = this.deps; - if (!plugin.settings.enableAutoTitleGeneration) return; - const titleService = this.deps.getTitleGenerationService(); - if (!titleService) return; - const fullConv = plugin.getConversationById(conversationId); - if (!fullConv || fullConv.messages.length < 2) return; - const firstUserMsg = fullConv.messages.find((m) => m.role === "user"); - const firstAssistantMsg = fullConv.messages.find((m) => m.role === "assistant"); - if (!firstUserMsg || !firstAssistantMsg) return; - const userContent = firstUserMsg.displayContent || firstUserMsg.content; - const assistantText = firstAssistantMsg.content || ((_a = firstAssistantMsg.contentBlocks) == null ? void 0 : _a.filter((b) => b.type === "text").map((b) => b.content).join("\n")) || ""; - if (!assistantText) return; - const isPlan = fullConv.title.startsWith("[Plan]"); - const expectedTitle = fullConv.title; - await plugin.updateConversation(conversationId, { titleGenerationStatus: "pending" }); - this.updateHistoryDropdown(); - await titleService.generateTitle( - conversationId, - userContent, - assistantText, - async (convId, result) => { - const currentConv = plugin.getConversationById(convId); - if (!currentConv) return; - const userManuallyRenamed = currentConv.title !== expectedTitle; - if (result.success && result.title && !userManuallyRenamed) { - const newTitle = isPlan ? `[Plan] ${result.title}` : result.title; - await plugin.renameConversation(convId, newTitle); - await plugin.updateConversation(convId, { titleGenerationStatus: "success" }); - } else if (!userManuallyRenamed) { - await plugin.updateConversation(convId, { titleGenerationStatus: "failed" }); - } else { - await plugin.updateConversation(convId, { titleGenerationStatus: void 0 }); - } - this.updateHistoryDropdown(); - } - ); - } - /** Formats a timestamp for display. */ - formatDate(timestamp) { - const date3 = new Date(timestamp); - const now = /* @__PURE__ */ new Date(); - if (date3.toDateString() === now.toDateString()) { - return date3.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", hour12: false }); - } - return date3.toLocaleDateString(void 0, { month: "short", day: "numeric" }); - } -}; - -// src/features/chat/controllers/InputController.ts -var import_obsidian22 = require("obsidian"); - -// src/utils/editor.ts -function findNearestNonEmptyLine(getLine, lineCount, startLine, direction) { - const step = direction === "before" ? -1 : 1; - for (let i = startLine + step; i >= 0 && i < lineCount; i += step) { - const content = getLine(i); - if (content.trim().length > 0) { - return content; - } - } - return ""; -} -function buildCursorContext(getLine, lineCount, line, column) { - const lineContent = getLine(line); - const beforeCursor = lineContent.substring(0, column); - const afterCursor = lineContent.substring(column); - const lineIsEmpty = lineContent.trim().length === 0; - const nothingBefore = beforeCursor.trim().length === 0; - const nothingAfter = afterCursor.trim().length === 0; - const isInbetween = lineIsEmpty || nothingBefore && nothingAfter; - let contextBefore = beforeCursor; - let contextAfter = afterCursor; - if (isInbetween) { - contextBefore = findNearestNonEmptyLine(getLine, lineCount, line, "before"); - contextAfter = findNearestNonEmptyLine(getLine, lineCount, line, "after"); - } - return { beforeCursor: contextBefore, afterCursor: contextAfter, isInbetween, line, column }; -} -function formatEditorContext(context) { - if (context.mode === "selection" && context.selectedText) { - const lineAttr = context.startLine && context.lineCount ? ` lines="${context.startLine}-${context.startLine + context.lineCount - 1}"` : ""; - return ` -${context.selectedText} -`; - } else if (context.mode === "cursor" && context.cursorContext) { - const ctx = context.cursorContext; - let content; - if (ctx.isInbetween) { - const parts = []; - if (ctx.beforeCursor) parts.push(ctx.beforeCursor); - parts.push("| #inbetween"); - if (ctx.afterCursor) parts.push(ctx.afterCursor); - content = parts.join("\n"); - } else { - content = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`; - } - return ` -${content} -`; - } - return ""; -} -function prependEditorContext(prompt, context) { - const formatted = formatEditorContext(context); - return formatted ? `${formatted} - -${prompt}` : prompt; -} - -// src/utils/markdown.ts -function appendMarkdownSnippet(existingPrompt, snippet) { - const trimmedSnippet = snippet.trim(); - if (!trimmedSnippet) { - return existingPrompt; - } - if (!existingPrompt.trim()) { - return trimmedSnippet; - } - const separator = existingPrompt.endsWith("\n\n") ? "" : existingPrompt.endsWith("\n") ? "\n" : "\n\n"; - return existingPrompt + separator + trimmedSnippet; -} - -// src/features/chat/controllers/InputController.ts -var PLAN_MODE_REQUEST_PREFIX = "User requested plan mode. Call EnterPlanMode before responding."; -var InputController = class { - constructor(deps) { - this.deps = deps; - } - // ============================================ - // Message Sending - // ============================================ - /** Sends a message with optional editor context override. */ - async sendMessage(options) { - var _a, _b, _c; - const { plugin, state, renderer, streamController, selectionController, conversationController } = this.deps; - const inputEl = this.deps.getInputEl(); - const imageContextManager = this.deps.getImageContextManager(); - const fileContextManager = this.deps.getFileContextManager(); - const slashCommandManager = this.deps.getSlashCommandManager(); - const mcpServerSelector = this.deps.getMcpServerSelector(); - const contentOverride = options == null ? void 0 : options.content; - const shouldUseInput = contentOverride === void 0; - let content = (contentOverride != null ? contentOverride : inputEl.value).trim(); - const hasImages = (_a = imageContextManager == null ? void 0 : imageContextManager.hasImages()) != null ? _a : false; - if (!content && !hasImages) return; - if (state.isStreaming) { - const images2 = hasImages ? [...(imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || []] : void 0; - const editorContext2 = selectionController.getContext(); - const promptPrefix = options == null ? void 0 : options.promptPrefix; - if (state.queuedMessage) { - state.queuedMessage.content += "\n\n" + content; - if (images2 && images2.length > 0) { - state.queuedMessage.images = [...state.queuedMessage.images || [], ...images2]; - } - state.queuedMessage.editorContext = editorContext2; - state.queuedMessage.hidden = state.queuedMessage.hidden || (options == null ? void 0 : options.hidden); - if (promptPrefix) { - state.queuedMessage.promptPrefix = (_b = state.queuedMessage.promptPrefix) != null ? _b : promptPrefix; - } - } else { - state.queuedMessage = { - content, - images: images2, - editorContext: editorContext2, - hidden: options == null ? void 0 : options.hidden, - promptPrefix - }; - } - if (shouldUseInput) { - inputEl.value = ""; - } - imageContextManager == null ? void 0 : imageContextManager.clearImages(); - this.updateQueueIndicator(); - return; - } - if (shouldUseInput) { - inputEl.value = ""; - } - state.isStreaming = true; - state.cancelRequested = false; - state.ignoreUsageUpdates = false; - state.subagentsSpawnedThisStream = 0; - const welcomeEl = this.deps.getWelcomeEl(); - if (welcomeEl) { - welcomeEl.style.display = "none"; - } - fileContextManager == null ? void 0 : fileContextManager.startSession(); - const displayContent = content; - let queryOptions; - if (content && slashCommandManager) { - slashCommandManager.setCommands(plugin.settings.slashCommands); - const detected = slashCommandManager.detectCommand(content); - if (detected) { - const cmd = plugin.settings.slashCommands.find( - (c) => c.name.toLowerCase() === detected.commandName.toLowerCase() - ); - if (cmd) { - const result = await slashCommandManager.expandCommand(cmd, detected.args, { - bash: { - enabled: true, - shouldBlockCommand: (bashCommand) => isCommandBlocked( - bashCommand, - getBashToolBlockedCommands(plugin.settings.blockedCommands), - plugin.settings.enableBlocklist - ), - requestApproval: plugin.settings.permissionMode !== "yolo" ? (bashCommand) => this.requestInlineBashApproval(bashCommand) : void 0 - } - }); - content = result.expandedPrompt; - if (result.errors.length > 0) { - new import_obsidian22.Notice(formatSlashCommandWarnings(result.errors)); - } - if (result.allowedTools || result.model) { - queryOptions = { - allowedTools: result.allowedTools, - model: result.model - }; - } - } - } - } - if (content && imageContextManager) { - const result = await imageContextManager.handleImagePathInText(content); - if (result.imageLoaded) { - content = result.text; - } - } - const images = (imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || []; - const imagesForMessage = images.length > 0 ? [...images] : void 0; - if (shouldUseInput) { - imageContextManager == null ? void 0 : imageContextManager.clearImages(); - } - const currentNotePath = (fileContextManager == null ? void 0 : fileContextManager.getCurrentNotePath()) || null; - const shouldSendCurrentNote = (_c = fileContextManager == null ? void 0 : fileContextManager.shouldSendCurrentNote(currentNotePath)) != null ? _c : false; - const editorContextOverride = options == null ? void 0 : options.editorContextOverride; - const editorContext = editorContextOverride !== void 0 ? editorContextOverride : selectionController.getContext(); - let promptToSend = ` -${content} -`; - let currentNoteForMessage; - if (editorContext) { - promptToSend = prependEditorContext(promptToSend, editorContext); - } - if (shouldSendCurrentNote && currentNotePath) { - promptToSend = prependCurrentNote(promptToSend, currentNotePath); - currentNoteForMessage = currentNotePath; - } - if (options == null ? void 0 : options.promptPrefix) { - promptToSend = `${options.promptPrefix} - -${promptToSend}`; - } - // --- Claude Code SDK /compact passthrough --- -const trimmedInput = (content || "").trimStart(); -if (/^\/(compact|comact)(\s|$)/.test(trimmedInput)) { - promptToSend = trimmedInput.replace(/^\/comact(\s|$)/, "/compact$1"); -} -// --- end passthrough --- - - fileContextManager == null ? void 0 : fileContextManager.markCurrentNoteSent(); - const userMsg = { - id: this.deps.generateId(), - role: "user", - content, - displayContent: displayContent !== content ? displayContent : void 0, - timestamp: Date.now(), - currentNote: currentNoteForMessage, - images: imagesForMessage, - hidden: options == null ? void 0 : options.hidden - }; - state.addMessage(userMsg); - if (!(options == null ? void 0 : options.hidden)) { - renderer.addMessage(userMsg); - } - const assistantMsg = { - id: this.deps.generateId(), - role: "assistant", - content: "", - timestamp: Date.now(), - toolCalls: [], - contentBlocks: [] - }; - state.addMessage(assistantMsg); - const msgEl = renderer.addMessage(assistantMsg); - const contentEl = msgEl.querySelector(".claudian-message-content"); - state.toolCallElements.clear(); - state.currentContentEl = contentEl; - state.currentTextEl = null; - state.currentTextContent = ""; - streamController.showThinkingIndicator(contentEl); - const mcpMentions = plugin.mcpService.extractMentions(promptToSend); - promptToSend = plugin.mcpService.transformMentions(promptToSend); - const enabledMcpServers = mcpServerSelector == null ? void 0 : mcpServerSelector.getEnabledServers(); - if (mcpMentions.size > 0 || enabledMcpServers && enabledMcpServers.size > 0) { - queryOptions = { - ...queryOptions, - mcpMentions, - enabledMcpServers - }; - } - let wasInterrupted = false; - try { - for await (const chunk of plugin.agentService.query(promptToSend, imagesForMessage, state.messages, queryOptions)) { - if (state.cancelRequested) { - wasInterrupted = true; - break; - } - await streamController.handleStreamChunk(chunk, assistantMsg); - } - } catch (error2) { - const errorMsg = error2 instanceof Error ? error2.message : "Unknown error"; - await streamController.appendText(` - -**Error:** ${errorMsg}`); - } finally { - if (wasInterrupted) { - await streamController.appendText('\n\nInterrupted \xB7 What should Claudian do instead?'); - } - streamController.hideThinkingIndicator(); - state.isStreaming = false; - state.cancelRequested = false; - state.currentContentEl = null; - streamController.finalizeCurrentThinkingBlock(assistantMsg); - streamController.finalizeCurrentTextBlock(assistantMsg); - state.activeSubagents.clear(); - await conversationController.save(true); - await this.activatePendingPlanMode(); - await this.triggerTitleGeneration(); - this.processQueuedMessage(); - } - } - // ============================================ - // Plan Mode - // ============================================ - setPlanModeRequested(active) { - const { state } = this.deps; - if (state.planModeRequested === active) { - return; - } - state.planModeRequested = active; - this.deps.setPlanModeActive(active); - } - ensurePlanModeState(agentInitiated) { - var _a; - const { state, plugin } = this.deps; - if (plugin.settings.permissionMode !== "plan") { - return; - } - if ((_a = state.planModeState) == null ? void 0 : _a.isActive) { - if (!state.planModeState.agentInitiated && agentInitiated) { - state.planModeState.agentInitiated = true; - } - return; - } - state.planModeState = { - isActive: true, - planFilePath: null, - planContent: null, - originalQuery: null, - agentInitiated - }; - } - async activatePendingPlanMode() { - const { plugin, state } = this.deps; - if (!state.planModeActivationPending) { - return; - } - state.planModeActivationPending = false; - if (plugin.settings.permissionMode !== "plan") { - plugin.settings.lastNonPlanPermissionMode = plugin.settings.permissionMode; - plugin.settings.permissionMode = "plan"; - await plugin.saveSettings(); - } - state.planModeRequested = false; - this.ensurePlanModeState(true); - plugin.agentService.setCurrentPlanFilePath(null); - this.deps.setPlanModeActive(true); - } - async exitPlanPermissionMode() { - var _a; - const { plugin, state } = this.deps; - const restored = (_a = plugin.settings.lastNonPlanPermissionMode) != null ? _a : "yolo"; - if (plugin.settings.permissionMode === "plan") { - plugin.settings.permissionMode = restored; - plugin.settings.lastNonPlanPermissionMode = restored; - await plugin.saveSettings(); - } - state.resetPlanModeState(); - state.planModeRequested = false; - state.planModeActivationPending = false; - this.deps.setPlanModeActive(false); - } - /** Sends a message in plan mode (read-only exploration). */ - async sendPlanModeMessage() { - var _a, _b; - const { state, plugin } = this.deps; - const inputEl = this.deps.getInputEl(); - const content = inputEl.value.trim(); - if (!content) return; - if (state.isStreaming) { - new import_obsidian22.Notice("Cannot request plan mode while agent is working"); - return; - } - if (plugin.settings.permissionMode === "plan") { - plugin.agentService.setCurrentPlanFilePath(null); - const wasAgentInitiated = (_b = (_a = state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false; - this.ensurePlanModeState(wasAgentInitiated); - state.planModeState = { - isActive: true, - planFilePath: null, - planContent: null, - originalQuery: content, - agentInitiated: wasAgentInitiated - }; - inputEl.value = ""; - await this.sendMessageWithPlanMode({ content }); - return; - } - await this.sendMessage({ promptPrefix: PLAN_MODE_REQUEST_PREFIX }); - } - /** - * Handles agent-initiated EnterPlanMode tool call. - * Sets up state for re-sending with plan mode after current stream ends. - */ - async handleEnterPlanMode() { - const { state, plugin } = this.deps; - if (plugin.settings.permissionMode === "plan") { - this.ensurePlanModeState(true); - return; - } - state.planModeActivationPending = true; - } - /** Internal: sends message with plan mode options. */ - async sendMessageWithPlanMode(options) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; - const { plugin, state, renderer, streamController, selectionController, conversationController } = this.deps; - const inputEl = this.deps.getInputEl(); - const imageContextManager = this.deps.getImageContextManager(); - const fileContextManager = this.deps.getFileContextManager(); - const mcpServerSelector = this.deps.getMcpServerSelector(); - if (plugin.settings.permissionMode !== "plan") { - await this.sendMessage({ promptPrefix: PLAN_MODE_REQUEST_PREFIX }); - return; - } - this.ensurePlanModeState((_b = (_a = state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false); - const content = ((_c = options == null ? void 0 : options.content) != null ? _c : inputEl.value).trim(); - if (!content) return; - const skipUserMessage = (_d = options == null ? void 0 : options.skipUserMessage) != null ? _d : false; - if ((options == null ? void 0 : options.content) === void 0) { - inputEl.value = ""; - } - state.isStreaming = true; - state.cancelRequested = false; - state.ignoreUsageUpdates = false; - state.subagentsSpawnedThisStream = 0; - const welcomeEl = this.deps.getWelcomeEl(); - if (welcomeEl) { - welcomeEl.style.display = "none"; - } - fileContextManager == null ? void 0 : fileContextManager.startSession(); - const images = skipUserMessage ? (_e = options == null ? void 0 : options.images) != null ? _e : [] : (_f = options == null ? void 0 : options.images) != null ? _f : (imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || []; - const imagesForMessage = images.length > 0 ? [...images] : void 0; - if (!skipUserMessage && !(options == null ? void 0 : options.images)) { - imageContextManager == null ? void 0 : imageContextManager.clearImages(); - } - let currentNote = null; - let shouldSendCurrentNote = false; - let currentNoteForMessage; - if (skipUserMessage || (options == null ? void 0 : options.currentNote)) { - currentNote = (options == null ? void 0 : options.currentNote) || null; - } else { - currentNote = (fileContextManager == null ? void 0 : fileContextManager.getCurrentNotePath()) || null; - } - shouldSendCurrentNote = (_g = fileContextManager == null ? void 0 : fileContextManager.shouldSendCurrentNote(currentNote)) != null ? _g : false; - if (shouldSendCurrentNote && currentNote) { - currentNoteForMessage = currentNote; - } - const editorContext = (_h = options == null ? void 0 : options.editorContext) != null ? _h : selectionController.getContext(); - let promptToSend = `[Plan Mode] -Explore the codebase and create an implementation plan. Call the ExitPlanMode tool when the plan is ready for user approval. - - -${content} -`; - if (editorContext) { - promptToSend = prependEditorContext(promptToSend, editorContext); - } - if (shouldSendCurrentNote && currentNote) { - promptToSend = prependCurrentNote(promptToSend, currentNote); - currentNoteForMessage = currentNote; - } - fileContextManager == null ? void 0 : fileContextManager.markCurrentNoteSent(); - if (!skipUserMessage) { - const displayContent = (_i = options == null ? void 0 : options.displayContent) != null ? _i : content; - const userMsg = { - id: this.deps.generateId(), - role: "user", - content, - displayContent: displayContent !== content ? displayContent : void 0, - timestamp: Date.now(), - currentNote: currentNoteForMessage, - images: imagesForMessage, - hidden: options == null ? void 0 : options.hidden - }; - state.addMessage(userMsg); - if (!(options == null ? void 0 : options.hidden)) { - renderer.addMessage(userMsg); - } - } - const assistantMsg = { - id: this.deps.generateId(), - role: "assistant", - content: "", - timestamp: Date.now(), - toolCalls: [], - contentBlocks: [] - }; - state.addMessage(assistantMsg); - const msgEl = renderer.addMessage(assistantMsg); - const contentEl = msgEl.querySelector(".claudian-message-content"); - state.toolCallElements.clear(); - state.currentContentEl = contentEl; - state.currentTextEl = null; - state.currentTextContent = ""; - streamController.showThinkingIndicator(contentEl); - const mcpMentions = plugin.mcpService.extractMentions(promptToSend); - promptToSend = plugin.mcpService.transformMentions(promptToSend); - const enabledMcpServers = mcpServerSelector == null ? void 0 : mcpServerSelector.getEnabledServers(); - const queryOptions = { - ...options == null ? void 0 : options.queryOptions, - planMode: true, - mcpMentions, - enabledMcpServers - }; - let wasInterrupted = false; - try { - for await (const chunk of plugin.agentService.query(promptToSend, imagesForMessage, state.messages, queryOptions)) { - if (state.cancelRequested) { - wasInterrupted = true; - break; - } - await streamController.handleStreamChunk(chunk, assistantMsg); - } - } catch (error2) { - const errorMsg = error2 instanceof Error ? error2.message : "Unknown error"; - await streamController.appendText(` - -**Error:** ${errorMsg}`); - } finally { - if (wasInterrupted) { - await streamController.appendText('\n\nPlan mode interrupted'); - plugin.agentService.setCurrentPlanFilePath(null); - } - streamController.hideThinkingIndicator(); - state.isStreaming = false; - state.cancelRequested = false; - state.currentContentEl = null; - streamController.finalizeCurrentThinkingBlock(assistantMsg); - streamController.finalizeCurrentTextBlock(assistantMsg); - state.activeSubagents.clear(); - await conversationController.save(true); - await this.activatePendingPlanMode(); - await this.triggerTitleGeneration({ isPlanMode: true }); - this.processQueuedMessage(); - } - } - // ============================================ - // Queue Management - // ============================================ - /** Updates the queue indicator UI. */ - updateQueueIndicator() { - var _a, _b; - const { state } = this.deps; - if (!state.queueIndicatorEl) return; - if (state.queuedMessage) { - const rawContent = state.queuedMessage.content.trim(); - const preview = rawContent.length > 40 ? rawContent.slice(0, 40) + "..." : rawContent; - const hasImages = ((_b = (_a = state.queuedMessage.images) == null ? void 0 : _a.length) != null ? _b : 0) > 0; - let display = preview; - if (hasImages) { - display = display ? `${display} [images]` : "[images]"; - } - state.queueIndicatorEl.setText(`\u2319 Queued: ${display}`); - state.queueIndicatorEl.style.display = "block"; - } else { - state.queueIndicatorEl.style.display = "none"; - } - } - /** Clears the queued message. */ - clearQueuedMessage() { - const { state } = this.deps; - state.queuedMessage = null; - this.updateQueueIndicator(); - } - /** Processes the queued message. */ - processQueuedMessage() { - var _a; - const { state } = this.deps; - if (!state.queuedMessage) return; - const { content, images, editorContext, hidden, promptPrefix } = state.queuedMessage; - state.queuedMessage = null; - this.updateQueueIndicator(); - const isPlanMode = this.deps.plugin.settings.permissionMode === "plan"; - if (isPlanMode) { - setTimeout( - () => this.sendMessageWithPlanMode({ content, images, editorContext, hidden }), - 0 - ); - return; - } - const inputEl = this.deps.getInputEl(); - inputEl.value = content; - if (images && images.length > 0) { - (_a = this.deps.getImageContextManager()) == null ? void 0 : _a.setImages(images); - } - setTimeout(() => this.sendMessage({ editorContextOverride: editorContext, hidden, promptPrefix }), 0); - } - // ============================================ - // Title Generation - // ============================================ - /** - * Triggers AI title generation after first exchange. - * Handles setting fallback title, firing async generation, and updating UI. - */ - async triggerTitleGeneration(options = {}) { - var _a; - const { plugin, state, conversationController } = this.deps; - const { isPlanMode = false } = options; - if (state.messages.length !== 2 || !state.currentConversationId) { - return; - } - const firstUserMsg = state.messages.find((m) => m.role === "user"); - const firstAssistantMsg = state.messages.find((m) => m.role === "assistant"); - if (!firstUserMsg || !firstAssistantMsg) { - return; - } - const userContent = firstUserMsg.displayContent || firstUserMsg.content; - const assistantText = firstAssistantMsg.content || ((_a = firstAssistantMsg.contentBlocks) == null ? void 0 : _a.filter((b) => b.type === "text").map((b) => b.content).join("\n")) || ""; - const fallbackTitle = conversationController.generateFallbackTitle(userContent); - const displayTitle = isPlanMode ? `[Plan] ${fallbackTitle}` : fallbackTitle; - await plugin.renameConversation(state.currentConversationId, displayTitle); - if (!plugin.settings.enableAutoTitleGeneration) { - return; - } - const titleService = this.deps.getTitleGenerationService(); - if (!titleService || !assistantText) { - return; - } - await plugin.updateConversation(state.currentConversationId, { titleGenerationStatus: "pending" }); - conversationController.updateHistoryDropdown(); - const convId = state.currentConversationId; - const expectedTitle = displayTitle; - titleService.generateTitle( - convId, - userContent, - assistantText, - async (conversationId, result) => { - const currentConv = plugin.getConversationById(conversationId); - if (!currentConv) return; - const userManuallyRenamed = currentConv.title !== expectedTitle; - if (result.success && !userManuallyRenamed) { - const newTitle = isPlanMode ? `[Plan] ${result.title}` : result.title; - await plugin.renameConversation(conversationId, newTitle); - await plugin.updateConversation(conversationId, { titleGenerationStatus: "success" }); - } else if (!userManuallyRenamed) { - await plugin.updateConversation(conversationId, { titleGenerationStatus: "failed" }); - } else { - await plugin.updateConversation(conversationId, { titleGenerationStatus: void 0 }); - } - conversationController.updateHistoryDropdown(); - } - ).catch((error2) => { - console.error("[InputController] Title generation failed:", error2 instanceof Error ? error2.message : error2); - }); - } - // ============================================ - // Streaming Control - // ============================================ - /** Cancels the current streaming operation. */ - cancelStreaming() { - const { plugin, state, streamController } = this.deps; - if (!state.isStreaming) return; - state.cancelRequested = true; - this.clearQueuedMessage(); - plugin.agentService.cancel(); - streamController.hideThinkingIndicator(); - } - // ============================================ - // Instruction Mode - // ============================================ - /** Handles instruction mode submission. */ - async handleInstructionSubmit(rawInstruction) { - const { plugin } = this.deps; - const instructionRefineService = this.deps.getInstructionRefineService(); - const instructionModeManager = this.deps.getInstructionModeManager(); - if (!instructionRefineService) return; - const existingPrompt = plugin.settings.systemPrompt; - let modal = null; - let wasCancelled = false; - try { - modal = new InstructionModal( - plugin.app, - rawInstruction, - { - onAccept: async (finalInstruction) => { - const currentPrompt = plugin.settings.systemPrompt; - plugin.settings.systemPrompt = appendMarkdownSnippet(currentPrompt, finalInstruction); - await plugin.saveSettings(); - new import_obsidian22.Notice("Instruction added to custom system prompt"); - instructionModeManager == null ? void 0 : instructionModeManager.clear(); - }, - onReject: () => { - wasCancelled = true; - instructionRefineService.cancel(); - instructionModeManager == null ? void 0 : instructionModeManager.clear(); - }, - onClarificationSubmit: async (response) => { - const result2 = await instructionRefineService.continueConversation(response); - if (wasCancelled) { - return; - } - if (!result2.success) { - if (result2.error === "Cancelled") { - return; - } - new import_obsidian22.Notice(result2.error || "Failed to process response"); - modal == null ? void 0 : modal.showError(result2.error || "Failed to process response"); - return; - } - if (result2.clarification) { - modal == null ? void 0 : modal.showClarification(result2.clarification); - } else if (result2.refinedInstruction) { - modal == null ? void 0 : modal.showConfirmation(result2.refinedInstruction); - } - } - } - ); - modal.open(); - instructionRefineService.resetConversation(); - const result = await instructionRefineService.refineInstruction( - rawInstruction, - existingPrompt - ); - if (wasCancelled) { - return; - } - if (!result.success) { - if (result.error === "Cancelled") { - instructionModeManager == null ? void 0 : instructionModeManager.clear(); - return; - } - new import_obsidian22.Notice(result.error || "Failed to refine instruction"); - modal.showError(result.error || "Failed to refine instruction"); - instructionModeManager == null ? void 0 : instructionModeManager.clear(); - return; - } - if (result.clarification) { - modal.showClarification(result.clarification); - } else if (result.refinedInstruction) { - modal.showConfirmation(result.refinedInstruction); - } else { - new import_obsidian22.Notice("No instruction received"); - modal.showError("No instruction received"); - instructionModeManager == null ? void 0 : instructionModeManager.clear(); - } - } catch (error2) { - const errorMsg = error2 instanceof Error ? error2.message : "Unknown error"; - new import_obsidian22.Notice(`Error: ${errorMsg}`); - modal == null ? void 0 : modal.showError(errorMsg); - instructionModeManager == null ? void 0 : instructionModeManager.clear(); - } - } - // ============================================ - // Approval Dialogs - // ============================================ - /** Handles tool approval requests. */ - async handleApprovalRequest(toolName, input, description) { - const { plugin } = this.deps; - return new Promise((resolve7) => { - const modal = new ApprovalModal(plugin.app, toolName, input, description, resolve7); - modal.open(); - }); - } - /** Requests approval for inline bash commands. */ - async requestInlineBashApproval(command) { - const { plugin } = this.deps; - const description = `Execute inline bash command: -${command}`; - return new Promise((resolve7) => { - const modal = new ApprovalModal( - plugin.app, - TOOL_BASH, - { command }, - description, - (decision) => resolve7(decision === "allow" || decision === "allow-always"), - { showAlwaysAllow: false, title: "Inline bash execution" } - ); - modal.open(); - }); - } - /** Handles AskUserQuestion tool calls by showing a floating panel. */ - async handleAskUserQuestion(input) { - const { plugin } = this.deps; - const messagesEl = this.deps.getMessagesEl(); - const containerEl = messagesEl.parentElement; - if (!containerEl) { - return null; - } - return showAskUserQuestionPanel(plugin.app, containerEl, input); - } - // ============================================ - // Plan Mode Approval - // ============================================ - /** Handles ExitPlanMode tool by showing plan approval panel. */ - async handleExitPlanMode(planContent) { - const { state, renderer, conversationController, streamController } = this.deps; - const messagesEl = this.deps.getMessagesEl(); - const containerEl = messagesEl.parentElement; - if (!containerEl) { - return { decision: "cancel" }; - } - if (state.planModeState) { - state.planModeState.planContent = planContent; - } - streamController.hideThinkingIndicator(); - const planMsg = { - id: this.deps.generateId(), - role: "assistant", - content: planContent, - timestamp: Date.now(), - isPlanMessage: true - }; - state.addMessage(planMsg); - renderer.addMessage(planMsg); - const lastMsgEl = messagesEl.lastElementChild; - if (lastMsgEl) { - lastMsgEl.classList.add("claudian-message-plan"); - const contentEl = lastMsgEl.querySelector(".claudian-message-content"); - if (contentEl) { - const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); - await renderer.renderContent(textEl, planContent); - state.currentContentEl = contentEl; - state.currentTextEl = null; - state.currentTextContent = ""; - state.currentThinkingState = null; - } - } - renderer.scrollToBottom(); - state.pendingPlanContent = planContent; - await conversationController.save(); - return this.showApprovalPanelAndHandleDecision(planContent, containerEl); - } - /** - * Restores pending plan approval panel when loading a conversation. - * Called when a conversation with pendingPlanContent is loaded. - */ - restorePendingPlanApproval(planContent) { - const messagesEl = this.deps.getMessagesEl(); - const containerEl = messagesEl.parentElement; - if (!containerEl) { - return; - } - void this.showApprovalPanelAndHandleDecision(planContent, containerEl); - } - /** Shows approval panel and handles the decision. */ - async showApprovalPanelAndHandleDecision(planContent, containerEl) { - const { plugin, state, conversationController } = this.deps; - const result = await showPlanApprovalPanel( - plugin.app, - containerEl, - planContent, - this.deps.getComponent() - ); - state.pendingPlanContent = null; - if (result.decision === "approve") { - this.addApprovalIndicator("approve"); - plugin.agentService.setApprovedPlanContent(planContent); - const planBanner = this.deps.getPlanBanner(); - if (planBanner) { - void planBanner.show(planContent); - } - await this.exitPlanPermissionMode(); - plugin.agentService.setCurrentPlanFilePath(null); - await conversationController.save(); - setTimeout( - () => this.sendMessage({ hidden: true, content: "Please implement the approved plan." }), - 100 - ); - return { decision: "approve" }; - } else if (result.decision === "approve_new_session") { - this.addApprovalIndicator("approve_new_session"); - const planBanner = this.deps.getPlanBanner(); - if (planBanner) { - void planBanner.show(planContent); - } - await this.exitPlanPermissionMode(); - plugin.agentService.setCurrentPlanFilePath(null); - plugin.agentService.resetSession(); - plugin.agentService.setApprovedPlanContent(planContent); - state.ignoreUsageUpdates = true; - state.usage = null; - this.deps.resetContextMeter(); - await conversationController.save(); - setTimeout( - () => this.sendMessage({ hidden: true, content: "Please implement the approved plan." }), - 100 - ); - return { decision: "approve_new_session" }; - } else if (result.decision === "revise") { - this.addApprovalIndicator("revise", result.feedback); - await conversationController.save(); - plugin.agentService.setCurrentPlanFilePath(null); - setTimeout( - () => this.sendMessageWithPlanMode({ content: result.feedback, hidden: true, images: [] }), - 100 - ); - return { decision: "revise", feedback: result.feedback }; - } else { - plugin.agentService.setCurrentPlanFilePath(null); - await conversationController.save(); - return { decision: "cancel" }; - } - } - /** Hides the plan banner. */ - hidePlanBanner() { - const planBanner = this.deps.getPlanBanner(); - if (planBanner) { - planBanner.hide(); - } - } - /** Adds an approval indicator message to the chat. */ - addApprovalIndicator(type, feedback) { - const { state, renderer } = this.deps; - const indicatorMsg = { - id: `indicator-${Date.now()}`, - role: "user", - content: "", - // Empty content, rendered via approvalIndicator - timestamp: Date.now(), - approvalIndicator: { - type, - feedback - } - }; - state.addMessage(indicatorMsg); - renderer.addMessage(indicatorMsg); - renderer.scrollToBottom(); - } -}; - -// src/features/chat/controllers/NavigationController.ts -var SCROLL_SPEED = 8; -var NavigationController = class { - constructor(deps) { - this.scrollDirection = null; - this.animationFrameId = null; - this.initialized = false; - this.disposed = false; - this.scrollLoop = () => { - if (this.scrollDirection === null || this.disposed) return; - const messagesEl = this.deps.getMessagesEl(); - if (!messagesEl) { - this.stopScrolling(); - return; - } - const scrollAmount = this.scrollDirection === "up" ? -SCROLL_SPEED : SCROLL_SPEED; - messagesEl.scrollTop += scrollAmount; - this.animationFrameId = requestAnimationFrame(this.scrollLoop); - }; - this.deps = deps; - this.boundMessagesKeydown = this.handleMessagesKeydown.bind(this); - this.boundKeyup = this.handleKeyup.bind(this); - this.boundInputKeydown = this.handleInputKeydown.bind(this); - } - // ============================================ - // Lifecycle - // ============================================ - /** Initializes navigation by making messagesEl focusable and attaching listeners. */ - initialize() { - if (this.initialized || this.disposed) return; - const messagesEl = this.deps.getMessagesEl(); - const inputEl = this.deps.getInputEl(); - if (!messagesEl || !inputEl) return; - messagesEl.setAttribute("tabindex", "0"); - messagesEl.addClass("claudian-messages-focusable"); - messagesEl.addEventListener("keydown", this.boundMessagesKeydown); - document.addEventListener("keyup", this.boundKeyup); - inputEl.addEventListener("keydown", this.boundInputKeydown, { capture: true }); - this.initialized = true; - } - /** Cleans up event listeners and animation frames. */ - dispose() { - if (this.disposed) return; - this.disposed = true; - this.stopScrolling(); - document.removeEventListener("keyup", this.boundKeyup); - const messagesEl = this.deps.getMessagesEl(); - messagesEl == null ? void 0 : messagesEl.removeEventListener("keydown", this.boundMessagesKeydown); - messagesEl == null ? void 0 : messagesEl.removeClass("claudian-messages-focusable"); - const inputEl = this.deps.getInputEl(); - inputEl == null ? void 0 : inputEl.removeEventListener("keydown", this.boundInputKeydown, { capture: true }); - } - // ============================================ - // Messages Panel Keyboard Handling - // ============================================ - handleMessagesKeydown(e) { - if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return; - const settings = this.deps.getSettings(); - const key = e.key.toLowerCase(); - if (key === settings.scrollUpKey.toLowerCase()) { - e.preventDefault(); - this.startScrolling("up"); - return; - } - if (key === settings.scrollDownKey.toLowerCase()) { - e.preventDefault(); - this.startScrolling("down"); - return; - } - if (key === settings.focusInputKey.toLowerCase()) { - e.preventDefault(); - this.deps.getInputEl().focus(); - return; - } - } - handleKeyup(e) { - const settings = this.deps.getSettings(); - const key = e.key.toLowerCase(); - if (key === settings.scrollUpKey.toLowerCase() || key === settings.scrollDownKey.toLowerCase()) { - this.stopScrolling(); - } - } - // ============================================ - // Input Keyboard Handling (Escape) - // ============================================ - handleInputKeydown(e) { - var _a, _b; - if (e.key !== "Escape") return; - if (this.deps.isStreaming()) { - return; - } - try { - if ((_b = (_a = this.deps).shouldSkipEscapeHandling) == null ? void 0 : _b.call(_a)) { - return; - } - } catch (e2) { - } - e.preventDefault(); - e.stopPropagation(); - this.deps.getInputEl().blur(); - this.deps.getMessagesEl().focus(); - } - // ============================================ - // Continuous Scrolling with requestAnimationFrame - // ============================================ - startScrolling(direction) { - if (this.scrollDirection === direction) { - return; - } - this.scrollDirection = direction; - this.scrollLoop(); - } - stopScrolling() { - this.scrollDirection = null; - if (this.animationFrameId !== null) { - cancelAnimationFrame(this.animationFrameId); - this.animationFrameId = null; - } - } - // ============================================ - // Public API - // ============================================ - /** Focuses the messages panel. */ - focusMessages() { - this.deps.getMessagesEl().focus(); - } - /** Focuses the input. */ - focusInput() { - this.deps.getInputEl().focus(); - } -}; - -// src/features/chat/controllers/SelectionController.ts -var import_obsidian23 = require("obsidian"); -var SELECTION_POLL_INTERVAL = 250; -var SelectionController = class { - constructor(app, indicatorEl, inputEl) { - this.storedSelection = null; - this.pollInterval = null; - this.app = app; - this.indicatorEl = indicatorEl; - this.inputEl = inputEl; - } - // ============================================ - // Lifecycle - // ============================================ - /** Starts polling for editor selection changes. */ - start() { - if (this.pollInterval) return; - this.pollInterval = setInterval(() => this.poll(), SELECTION_POLL_INTERVAL); - } - /** Stops polling and clears state. */ - stop() { - if (this.pollInterval) { - clearInterval(this.pollInterval); - this.pollInterval = null; - } - this.clear(); - } - /** Cleans up resources. Same as stop(). */ - dispose() { - this.stop(); - } - // ============================================ - // Selection Polling - // ============================================ - /** Polls editor selection and updates stored selection. */ - poll() { - var _a, _b, _c, _d; - const view = this.app.workspace.getActiveViewOfType(import_obsidian23.MarkdownView); - if (!view) return; - const editor = view.editor; - const editorView = editor.cm; - if (!editorView) return; - const selectedText = editor.getSelection(); - if (selectedText.trim()) { - const fromPos = editor.getCursor("from"); - const toPos = editor.getCursor("to"); - const from = editor.posToOffset(fromPos); - const to = editor.posToOffset(toPos); - const startLine = fromPos.line + 1; - const notePath = ((_a = view.file) == null ? void 0 : _a.path) || "unknown"; - const lineCount = selectedText.split(/\r?\n/).length; - const sameRange = this.storedSelection && this.storedSelection.editorView === editorView && this.storedSelection.from === from && this.storedSelection.to === to && this.storedSelection.notePath === notePath; - const sameText = sameRange && ((_b = this.storedSelection) == null ? void 0 : _b.selectedText) === selectedText; - const sameLineCount = sameRange && ((_c = this.storedSelection) == null ? void 0 : _c.lineCount) === lineCount; - const sameStartLine = sameRange && ((_d = this.storedSelection) == null ? void 0 : _d.startLine) === startLine; - if (!sameRange || !sameText || !sameLineCount || !sameStartLine) { - if (this.storedSelection && !sameRange) { - this.clearHighlight(); - } - this.storedSelection = { notePath, selectedText, lineCount, startLine, from, to, editorView }; - this.updateIndicator(); - } - } else if (document.activeElement !== this.inputEl) { - this.clearHighlight(); - this.storedSelection = null; - this.updateIndicator(); - } - } - // ============================================ - // Highlight Management - // ============================================ - /** Shows the selection highlight in the editor. */ - showHighlight() { - if (!this.storedSelection) return; - const { from, to, editorView } = this.storedSelection; - showSelectionHighlight(editorView, from, to); - } - /** Clears the selection highlight from the editor. */ - clearHighlight() { - if (!this.storedSelection) return; - hideSelectionHighlight(this.storedSelection.editorView); - } - // ============================================ - // Indicator - // ============================================ - /** Updates selection indicator based on stored selection. */ - updateIndicator() { - if (!this.indicatorEl) return; - if (this.storedSelection) { - const lineText = this.storedSelection.lineCount === 1 ? "line" : "lines"; - this.indicatorEl.textContent = `${this.storedSelection.lineCount} ${lineText} selected`; - this.indicatorEl.style.display = "block"; - } else { - this.indicatorEl.style.display = "none"; - } - } - // ============================================ - // Context Access - // ============================================ - /** Returns stored selection as EditorSelectionContext, or null if none. */ - getContext() { - if (!this.storedSelection) return null; - return { - notePath: this.storedSelection.notePath, - mode: "selection", - selectedText: this.storedSelection.selectedText, - lineCount: this.storedSelection.lineCount, - startLine: this.storedSelection.startLine - }; - } - /** Checks if there is a stored selection. */ - hasSelection() { - return this.storedSelection !== null; - } - // ============================================ - // Clear - // ============================================ - /** Clears the stored selection and highlight. */ - clear() { - this.clearHighlight(); - this.storedSelection = null; - this.updateIndicator(); - } -}; - -// src/features/chat/controllers/StreamController.ts -var StreamController = class { - constructor(deps) { - this.deps = deps; - } - // ============================================ - // Stream Chunk Handling - // ============================================ - /** Processes a stream chunk and updates the message. */ - async handleStreamChunk(chunk, msg) { - var _a; - const { state, plugin } = this.deps; - if ("parentToolUseId" in chunk && chunk.parentToolUseId) { - await this.handleSubagentChunk(chunk, msg); - this.scrollToBottom(); - return; - } - switch (chunk.type) { - case "thinking": - if (state.currentTextEl) { - this.finalizeCurrentTextBlock(msg); - } - await this.appendThinking(chunk.content, msg); - break; - case "text": - if (state.currentThinkingState) { - this.finalizeCurrentThinkingBlock(msg); - } - msg.content += chunk.content; - await this.appendText(chunk.content); - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - break; - case "tool_use": { - if (state.currentThinkingState) { - this.finalizeCurrentThinkingBlock(msg); - } - this.finalizeCurrentTextBlock(msg); - if (chunk.name === TOOL_TASK) { - state.subagentsSpawnedThisStream++; - const isAsync2 = this.deps.asyncSubagentManager.isAsyncTask(chunk.input); - if (isAsync2) { - await this.handleAsyncTaskToolUse(chunk, msg); - } else { - await this.handleTaskToolUse(chunk, msg); - } - break; - } - if (chunk.name === TOOL_AGENT_OUTPUT) { - this.handleAgentOutputToolUse(chunk, msg); - break; - } - if (chunk.name === TOOL_ASK_USER_QUESTION) { - this.handleAskUserQuestionToolUse(chunk, msg); - break; - } - if (isPlanModeTool(chunk.name)) { - break; - } - this.handleRegularToolUse(chunk, msg); - break; - } - case "tool_result": { - this.handleToolResult(chunk, msg); - break; - } - case "blocked": - await this.appendText(` - -\u26A0\uFE0F **Blocked:** ${chunk.content}`); - break; - case "error": - await this.appendText(` - -\u274C **Error:** ${chunk.content}`); - break; - case "done": - break; - case "usage": { - const currentSessionId = plugin.agentService.getSessionId(); - const chunkSessionId = (_a = chunk.sessionId) != null ? _a : null; - if (chunkSessionId && currentSessionId && chunkSessionId !== currentSessionId || chunkSessionId && !currentSessionId) { - break; - } - if (state.subagentsSpawnedThisStream > 0) { - break; - } - if (!state.ignoreUsageUpdates) { - state.usage = chunk.usage; - } - break; - } - } - this.scrollToBottom(); - } - // ============================================ - // Tool Use Handling - // ============================================ - /** Handles regular tool_use chunks. */ - handleRegularToolUse(chunk, msg) { - const { plugin, state } = this.deps; - const isPlanMode = plugin.settings.permissionMode === "plan"; - if (isPlanMode && isWriteEditTool(chunk.name)) { - return; - } - const toolCall = { - id: chunk.id, - name: chunk.name, - input: chunk.input, - status: "running", - isExpanded: false - }; - msg.toolCalls = msg.toolCalls || []; - msg.toolCalls.push(toolCall); - if (chunk.name === TOOL_TODO_WRITE) { - const todos = parseTodoInput(chunk.input); - if (todos) { - this.deps.state.currentTodos = todos; - } else { - console.warn("[StreamController] TodoWrite input parsing failed", { - toolId: chunk.id, - inputKeys: Object.keys(chunk.input) - }); - if (state.currentContentEl) { - msg.contentBlocks = msg.contentBlocks || []; - msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id }); - renderToolCall(state.currentContentEl, toolCall, state.toolCallElements); - } - } - } else { - msg.contentBlocks = msg.contentBlocks || []; - msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id }); - if (isWriteEditTool(chunk.name)) { - const writeEditState = createWriteEditBlock(state.currentContentEl, toolCall); - state.writeEditStates.set(chunk.id, writeEditState); - state.toolCallElements.set(chunk.id, writeEditState.wrapperEl); - } else { - renderToolCall(state.currentContentEl, toolCall, state.toolCallElements); - } - } - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - } - /** Handles AskUserQuestion tool_use chunks. */ - handleAskUserQuestionToolUse(chunk, msg) { - const { state } = this.deps; - if (!state.currentContentEl) return; - const toolCall = { - id: chunk.id, - name: chunk.name, - input: chunk.input, - status: "running", - isExpanded: false - }; - msg.toolCalls = msg.toolCalls || []; - msg.toolCalls.push(toolCall); - msg.contentBlocks = msg.contentBlocks || []; - msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id }); - const askQuestionState = createAskUserQuestionBlock(state.currentContentEl, toolCall); - state.askUserQuestionStates.set(chunk.id, askQuestionState); - state.toolCallElements.set(chunk.id, askQuestionState.wrapperEl); - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - } - /** Handles tool_result chunks. */ - handleToolResult(chunk, msg) { - var _a; - const { plugin, state } = this.deps; - const subagentState = state.activeSubagents.get(chunk.id); - if (subagentState) { - this.finalizeSubagent(chunk, msg, subagentState); - return; - } - if (this.handleAsyncTaskToolResult(chunk, msg)) { - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - return; - } - if (this.handleAgentOutputToolResult(chunk, msg)) { - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - return; - } - const existingToolCall = (_a = msg.toolCalls) == null ? void 0 : _a.find((tc) => tc.id === chunk.id); - const askQuestionState = state.askUserQuestionStates.get(chunk.id); - if ((existingToolCall == null ? void 0 : existingToolCall.name) === TOOL_ASK_USER_QUESTION || askQuestionState) { - const isBlocked2 = isBlockedToolResult(chunk.content, chunk.isError); - if (existingToolCall) { - existingToolCall.status = isBlocked2 ? "blocked" : chunk.isError ? "error" : "completed"; - existingToolCall.result = chunk.content; - } - const storedAnswers = plugin.agentService.getAskUserQuestionAnswers(chunk.id); - const parsed = existingToolCall ? parseAskUserQuestionInput(existingToolCall.input) : null; - const answers = storedAnswers || (parsed == null ? void 0 : parsed.answers); - if (existingToolCall && answers) { - existingToolCall.input = { ...existingToolCall.input, answers }; - } - if (askQuestionState && existingToolCall) { - finalizeAskUserQuestionBlock( - askQuestionState, - answers, - chunk.isError || isBlocked2, - parsed == null ? void 0 : parsed.questions - ); - } - if (askQuestionState) { - state.askUserQuestionStates.delete(chunk.id); - } - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - return; - } - const isBlocked = isBlockedToolResult(chunk.content, chunk.isError); - if (existingToolCall) { - existingToolCall.status = isBlocked ? "blocked" : chunk.isError ? "error" : "completed"; - existingToolCall.result = chunk.content; - const writeEditState = state.writeEditStates.get(chunk.id); - if (writeEditState && isWriteEditTool(existingToolCall.name)) { - if (!chunk.isError && !isBlocked) { - const diffData = plugin.agentService.getDiffData(chunk.id); - if (diffData) { - existingToolCall.diffData = diffData; - updateWriteEditWithDiff(writeEditState, diffData); - } - } - finalizeWriteEditBlock(writeEditState, chunk.isError || isBlocked); - } else { - updateToolCallResult(chunk.id, existingToolCall, state.toolCallElements); - } - } - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - } - // ============================================ - // Text Block Management - // ============================================ - /** Appends text to the current text block. */ - async appendText(text) { - const { state, renderer } = this.deps; - if (!state.currentContentEl) return; - if (!state.currentTextEl) { - state.currentTextEl = state.currentContentEl.createDiv({ cls: "claudian-text-block" }); - state.currentTextContent = ""; - } - state.currentTextContent += text; - await renderer.renderContent(state.currentTextEl, state.currentTextContent); - } - /** Finalizes the current text block. */ - finalizeCurrentTextBlock(msg) { - const { state } = this.deps; - if (msg && state.currentTextContent) { - msg.contentBlocks = msg.contentBlocks || []; - msg.contentBlocks.push({ type: "text", content: state.currentTextContent }); - } - state.currentTextEl = null; - state.currentTextContent = ""; - } - // ============================================ - // Thinking Block Management - // ============================================ - /** Appends thinking content. */ - async appendThinking(content, msg) { - const { state, renderer } = this.deps; - if (!state.currentContentEl) return; - this.hideThinkingIndicator(); - if (!state.currentThinkingState) { - state.currentThinkingState = createThinkingBlock( - state.currentContentEl, - (el, md) => renderer.renderContent(el, md) - ); - } - await appendThinkingContent(state.currentThinkingState, content, (el, md) => renderer.renderContent(el, md)); - } - /** Finalizes the current thinking block. */ - finalizeCurrentThinkingBlock(msg) { - const { state } = this.deps; - if (!state.currentThinkingState) return; - const durationSeconds = finalizeThinkingBlock(state.currentThinkingState); - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - if (msg && state.currentThinkingState.content) { - msg.contentBlocks = msg.contentBlocks || []; - msg.contentBlocks.push({ - type: "thinking", - content: state.currentThinkingState.content, - durationSeconds - }); - } - state.currentThinkingState = null; - } - // ============================================ - // Sync Subagent Handling - // ============================================ - /** Handles Task tool_use by creating a sync subagent block. */ - async handleTaskToolUse(chunk, msg) { - const { state } = this.deps; - if (!state.currentContentEl) return; - const subagentState = createSubagentBlock(state.currentContentEl, chunk.id, chunk.input); - state.activeSubagents.set(chunk.id, subagentState); - msg.subagents = msg.subagents || []; - msg.subagents.push(subagentState.info); - msg.contentBlocks = msg.contentBlocks || []; - msg.contentBlocks.push({ type: "subagent", subagentId: chunk.id }); - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - } - /** Routes chunks from subagents. */ - async handleSubagentChunk(chunk, msg) { - if (!("parentToolUseId" in chunk) || !chunk.parentToolUseId) { - return; - } - const parentToolUseId = chunk.parentToolUseId; - const { state } = this.deps; - const subagentState = state.activeSubagents.get(parentToolUseId); - if (!subagentState) { - return; - } - switch (chunk.type) { - case "tool_use": { - const toolCall = { - id: chunk.id, - name: chunk.name, - input: chunk.input, - status: "running", - isExpanded: false - }; - addSubagentToolCall(subagentState, toolCall); - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - break; - } - case "tool_result": { - const toolCall = subagentState.info.toolCalls.find((tc) => tc.id === chunk.id); - if (toolCall) { - const isBlocked = isBlockedToolResult(chunk.content, chunk.isError); - toolCall.status = isBlocked ? "blocked" : chunk.isError ? "error" : "completed"; - toolCall.result = chunk.content; - updateSubagentToolResult(subagentState, chunk.id, toolCall); - this.deps.plugin.agentService.getDiffData(chunk.id); - } - break; - } - case "text": - case "thinking": - break; - } - } - /** Finalizes a sync subagent when its Task tool_result is received. */ - finalizeSubagent(chunk, msg, subagentState) { - var _a; - const { state } = this.deps; - const isError = chunk.isError || false; - finalizeSubagentBlock(subagentState, chunk.content, isError); - const subagentInfo = (_a = msg.subagents) == null ? void 0 : _a.find((s) => s.id === chunk.id); - if (subagentInfo) { - subagentInfo.status = isError ? "error" : "completed"; - subagentInfo.result = chunk.content; - } - state.activeSubagents.delete(chunk.id); - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - } - // ============================================ - // Async Subagent Handling - // ============================================ - /** Handles async Task tool_use (run_in_background=true). */ - async handleAsyncTaskToolUse(chunk, msg) { - const { state, asyncSubagentManager } = this.deps; - if (!state.currentContentEl) return; - const subagentInfo = asyncSubagentManager.createAsyncSubagent(chunk.id, chunk.input); - const asyncState = createAsyncSubagentBlock(state.currentContentEl, chunk.id, chunk.input); - state.asyncSubagentStates.set(chunk.id, asyncState); - msg.subagents = msg.subagents || []; - msg.subagents.push(subagentInfo); - msg.contentBlocks = msg.contentBlocks || []; - msg.contentBlocks.push({ type: "subagent", subagentId: chunk.id, mode: "async" }); - if (state.currentContentEl) { - this.showThinkingIndicator(state.currentContentEl); - } - } - /** Handles AgentOutputTool tool_use (invisible, links to async subagent). */ - handleAgentOutputToolUse(chunk, _msg) { - const toolCall = { - id: chunk.id, - name: chunk.name, - input: chunk.input, - status: "running", - isExpanded: false - }; - this.deps.asyncSubagentManager.handleAgentOutputToolUse(toolCall); - } - /** Handles async Task tool_result to extract agent_id. */ - handleAsyncTaskToolResult(chunk, _msg) { - const { asyncSubagentManager } = this.deps; - if (!asyncSubagentManager.isPendingAsyncTask(chunk.id)) { - return false; - } - asyncSubagentManager.handleTaskToolResult(chunk.id, chunk.content, chunk.isError); - return true; - } - /** Handles AgentOutputTool result to finalize async subagent. */ - handleAgentOutputToolResult(chunk, _msg) { - const { asyncSubagentManager } = this.deps; - const isLinked = asyncSubagentManager.isLinkedAgentOutputTool(chunk.id); - const handled = asyncSubagentManager.handleAgentOutputToolResult( - chunk.id, - chunk.content, - chunk.isError || false - ); - return isLinked || handled !== void 0; - } - /** Callback from AsyncSubagentManager when state changes. */ - onAsyncSubagentStateChange(subagent) { - const { state } = this.deps; - let asyncState = state.asyncSubagentStates.get(subagent.id); - if (!asyncState) { - for (const s of state.asyncSubagentStates.values()) { - if (s.info.agentId === subagent.agentId) { - asyncState = s; - break; - } - } - if (!asyncState) return; - } - this.updateAsyncSubagentUI(asyncState, subagent); - } - /** Updates async subagent UI based on state. */ - updateAsyncSubagentUI(asyncState, subagent) { - asyncState.info = subagent; - switch (subagent.asyncStatus) { - case "running": - updateAsyncSubagentRunning(asyncState, subagent.agentId || ""); - break; - case "completed": - case "error": - finalizeAsyncSubagent(asyncState, subagent.result || "", subagent.asyncStatus === "error"); - break; - case "orphaned": - markAsyncSubagentOrphaned(asyncState); - break; - } - this.updateSubagentInMessages(subagent); - this.scrollToBottom(); - } - /** Updates subagent info in messages array. */ - updateSubagentInMessages(subagent) { - const { state } = this.deps; - for (let i = state.messages.length - 1; i >= 0; i--) { - const msg = state.messages[i]; - if (msg.role === "assistant" && msg.subagents) { - const idx = msg.subagents.findIndex((s) => s.id === subagent.id); - if (idx !== -1) { - msg.subagents[idx] = subagent; - return; - } - } - } - } - // ============================================ - // Thinking Indicator - // ============================================ - /** Shows the thinking indicator. */ - showThinkingIndicator(parentEl) { - const { state } = this.deps; - if (state.thinkingEl) { - parentEl.appendChild(state.thinkingEl); - this.deps.updateQueueIndicator(); - return; - } - state.thinkingEl = parentEl.createDiv({ cls: "claudian-thinking" }); - const randomText = FLAVOR_TEXTS[Math.floor(Math.random() * FLAVOR_TEXTS.length)]; - state.thinkingEl.createSpan({ text: randomText }); - state.thinkingEl.createSpan({ text: " (esc to interrupt)", cls: "claudian-thinking-hint" }); - state.queueIndicatorEl = state.thinkingEl.createDiv({ cls: "claudian-queue-indicator" }); - this.deps.updateQueueIndicator(); - } - /** Hides the thinking indicator. */ - hideThinkingIndicator() { - const { state } = this.deps; - if (state.thinkingEl) { - state.thinkingEl.remove(); - state.thinkingEl = null; - } - state.queueIndicatorEl = null; - } - // ============================================ - // Utilities - // ============================================ - /** Scrolls messages to bottom. */ - scrollToBottom() { - const messagesEl = this.deps.getMessagesEl(); - messagesEl.scrollTop = messagesEl.scrollHeight; - } - /** Resets streaming state after completion. */ - resetStreamingState() { - const { state } = this.deps; - this.hideThinkingIndicator(); - state.currentContentEl = null; - state.currentTextEl = null; - state.currentTextContent = ""; - state.currentThinkingState = null; - state.activeSubagents.clear(); - } -}; - -// src/features/chat/rendering/MessageRenderer.ts -var import_obsidian24 = require("obsidian"); -var MessageRenderer = class { - constructor(app, component, messagesEl) { - this.app = app; - this.component = component; - this.messagesEl = messagesEl; - } - /** Sets the messages container element. */ - setMessagesEl(el) { - this.messagesEl = el; - } - // ============================================ - // Streaming Message Rendering - // ============================================ - /** - * Adds a new message to the chat during streaming. - * Returns the message element for content updates. - */ - addMessage(msg) { - var _a, _b; - if (msg.hidden) { - this.ensureTodoPanelAtBottom(); - this.scrollToBottom(); - const lastChild = this.messagesEl.lastElementChild; - return lastChild != null ? lastChild : this.messagesEl; - } - if (msg.approvalIndicator) { - const indicatorEl = this.renderApprovalIndicator(msg.approvalIndicator); - this.ensureTodoPanelAtBottom(); - this.scrollToBottom(); - return indicatorEl; - } - if (msg.role === "user" && msg.images && msg.images.length > 0) { - this.renderMessageImages(this.messagesEl, msg.images); - } - if (msg.role === "user") { - const textToShow = (_a = msg.displayContent) != null ? _a : msg.content; - if (!textToShow) { - this.ensureTodoPanelAtBottom(); - this.scrollToBottom(); - const lastChild = this.messagesEl.lastElementChild; - return lastChild != null ? lastChild : this.messagesEl; - } - } - const msgEl = this.messagesEl.createDiv({ - cls: `claudian-message claudian-message-${msg.role}` - }); - const contentEl = msgEl.createDiv({ cls: "claudian-message-content" }); - if (msg.role === "user") { - const textToShow = (_b = msg.displayContent) != null ? _b : msg.content; - if (textToShow) { - const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); - void this.renderContent(textEl, textToShow); - } - } - this.ensureTodoPanelAtBottom(); - this.scrollToBottom(); - return msgEl; - } - // ============================================ - // Stored Message Rendering (Batch/Replay) - // ============================================ - /** - * Renders all messages for conversation load/switch. - * @param messages Array of messages to render - * @param getGreeting Function to get greeting text - * @returns The newly created welcome element - */ - renderMessages(messages, getGreeting) { - const existingTodoPanel = this.messagesEl.querySelector(".claudian-todo-panel"); - this.messagesEl.empty(); - const newWelcomeEl = this.messagesEl.createDiv({ cls: "claudian-welcome" }); - newWelcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: getGreeting() }); - for (const msg of messages) { - this.renderStoredMessage(msg); - } - this.ensureTodoPanelAtBottom(existingTodoPanel); - this.scrollToBottom(); - return newWelcomeEl; - } - /** - * Renders a persisted message from history. - */ - renderStoredMessage(msg) { - var _a, _b; - if (msg.hidden) { - return; - } - if (msg.approvalIndicator) { - this.renderApprovalIndicator(msg.approvalIndicator); - return; - } - if (msg.role === "user" && msg.images && msg.images.length > 0) { - this.renderMessageImages(this.messagesEl, msg.images); - } - if (msg.role === "user") { - const textToShow = (_a = msg.displayContent) != null ? _a : msg.content; - if (!textToShow) { - return; - } - } - const msgEl = this.messagesEl.createDiv({ - cls: `claudian-message claudian-message-${msg.role}` - }); - if (msg.isPlanMessage) { - msgEl.classList.add("claudian-message-plan"); - } - const contentEl = msgEl.createDiv({ cls: "claudian-message-content" }); - if (msg.role === "user") { - const textToShow = (_b = msg.displayContent) != null ? _b : msg.content; - if (textToShow) { - const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); - void this.renderContent(textEl, textToShow); - } - } else if (msg.role === "assistant") { - this.renderAssistantContent(msg, contentEl); - } - } - /** - * Renders an approval indicator for plan mode decisions. - */ - renderApprovalIndicator(indicator) { - const indicatorEl = this.messagesEl.createDiv({ - cls: "claudian-approval-indicator" - }); - const iconEl = indicatorEl.createSpan({ cls: "claudian-approval-indicator-icon" }); - const textEl = indicatorEl.createSpan({ cls: "claudian-approval-indicator-text" }); - switch (indicator.type) { - case "approve": - indicatorEl.classList.add("claudian-approval-indicator-approve"); - (0, import_obsidian24.setIcon)(iconEl, "check"); - textEl.textContent = "User approved plan."; - break; - case "approve_new_session": - indicatorEl.classList.add("claudian-approval-indicator-approve"); - (0, import_obsidian24.setIcon)(iconEl, "check"); - textEl.textContent = "User approved plan, implement in new session."; - break; - case "revise": - indicatorEl.classList.add("claudian-approval-indicator-revise"); - (0, import_obsidian24.setIcon)(iconEl, "x"); - textEl.textContent = indicator.feedback || "User requested revision."; - break; - } - return indicatorEl; - } - /** - * Renders assistant message content (content blocks or fallback). - */ - renderAssistantContent(msg, contentEl) { - var _a, _b; - if (msg.contentBlocks && msg.contentBlocks.length > 0) { - for (const block of msg.contentBlocks) { - if (block.type === "thinking") { - renderStoredThinkingBlock( - contentEl, - block.content, - block.durationSeconds, - (el, md) => this.renderContent(el, md) - ); - } else if (block.type === "text") { - const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); - void this.renderContent(textEl, block.content); - } else if (block.type === "tool_use") { - const toolCall = (_a = msg.toolCalls) == null ? void 0 : _a.find((tc) => tc.id === block.toolId); - if (toolCall) { - this.renderToolCall(contentEl, toolCall); - } - } else if (block.type === "subagent") { - const subagent = (_b = msg.subagents) == null ? void 0 : _b.find((s) => s.id === block.subagentId); - if (subagent) { - const mode = block.mode || subagent.mode || "sync"; - if (mode === "async") { - renderStoredAsyncSubagent(contentEl, subagent); - } else { - renderStoredSubagent(contentEl, subagent); - } - } - } - } - } else { - if (msg.content) { - const textEl = contentEl.createDiv({ cls: "claudian-text-block" }); - void this.renderContent(textEl, msg.content); - } - if (msg.toolCalls) { - for (const toolCall of msg.toolCalls) { - this.renderToolCall(contentEl, toolCall); - } - } - } - } - /** - * Renders a tool call with special handling for Write/Edit, and AskUserQuestion. - * TodoWrite is not rendered inline - it only shows in the bottom panel. - */ - renderToolCall(contentEl, toolCall) { - if (toolCall.name === TOOL_TODO_WRITE) { - return; - } else if (toolCall.name === TOOL_ASK_USER_QUESTION) { - renderStoredAskUserQuestion(contentEl, toolCall); - } else if (isWriteEditTool(toolCall.name)) { - renderStoredWriteEdit(contentEl, toolCall); - } else { - renderStoredToolCall(contentEl, toolCall); - } - } - // ============================================ - // Image Rendering - // ============================================ - /** - * Renders image attachments above a message. - */ - renderMessageImages(containerEl, images) { - const imagesEl = containerEl.createDiv({ cls: "claudian-message-images" }); - for (const image of images) { - const imageWrapper = imagesEl.createDiv({ cls: "claudian-message-image" }); - const imgEl = imageWrapper.createEl("img", { - attr: { - alt: image.name - } - }); - void this.setImageSrc(imgEl, image); - imgEl.addEventListener("click", () => { - void this.showFullImage(image); - }); - } - } - /** - * Shows full-size image in modal overlay. - */ - async showFullImage(image) { - const dataUri = getImageAttachmentDataUri(this.app, image); - if (!dataUri) return; - const overlay = document.body.createDiv({ cls: "claudian-image-modal-overlay" }); - const modal = overlay.createDiv({ cls: "claudian-image-modal" }); - modal.createEl("img", { - attr: { - src: dataUri, - alt: image.name - } - }); - const closeBtn = modal.createDiv({ cls: "claudian-image-modal-close" }); - closeBtn.setText("\xD7"); - const handleEsc = (e) => { - if (e.key === "Escape") { - close(); - } - }; - const close = () => { - document.removeEventListener("keydown", handleEsc); - overlay.remove(); - }; - closeBtn.addEventListener("click", close); - overlay.addEventListener("click", (e) => { - if (e.target === overlay) close(); - }); - document.addEventListener("keydown", handleEsc); - } - /** - * Sets image src from attachment data. - */ - async setImageSrc(imgEl, image) { - const dataUri = getImageAttachmentDataUri(this.app, image); - if (dataUri) { - imgEl.setAttribute("src", dataUri); - } else { - imgEl.setAttribute("alt", `${image.name} (missing)`); - } - } - // ============================================ - // Content Rendering - // ============================================ - /** - * Renders markdown content with code block enhancements. - */ - async renderContent(el, markdown) { - el.empty(); - await import_obsidian24.MarkdownRenderer.renderMarkdown(markdown, el, "", this.component); - el.querySelectorAll("pre").forEach((pre) => { - var _a, _b; - if ((_a = pre.parentElement) == null ? void 0 : _a.classList.contains("claudian-code-wrapper")) return; - const wrapper = createEl("div", { cls: "claudian-code-wrapper" }); - (_b = pre.parentElement) == null ? void 0 : _b.insertBefore(wrapper, pre); - wrapper.appendChild(pre); - const code = pre.querySelector('code[class*="language-"]'); - if (code) { - const match = code.className.match(/language-(\w+)/); - if (match) { - wrapper.classList.add("has-language"); - const label = createEl("span", { - cls: "claudian-code-lang-label", - text: match[1] - }); - wrapper.appendChild(label); - label.addEventListener("click", async () => { - await navigator.clipboard.writeText(code.textContent || ""); - label.setText("copied!"); - setTimeout(() => label.setText(match[1]), 1500); - }); - } - } - const copyBtn = pre.querySelector(".copy-code-button"); - if (copyBtn) { - wrapper.appendChild(copyBtn); - } - }); - } - // ============================================ - // Utilities - // ============================================ - /** Scrolls messages container to bottom. */ - scrollToBottom() { - this.messagesEl.scrollTop = this.messagesEl.scrollHeight; - } - /** Scrolls to bottom if already near bottom (within threshold). */ - scrollToBottomIfNeeded(threshold = 100) { - const { scrollTop, scrollHeight, clientHeight } = this.messagesEl; - const isNearBottom = scrollHeight - scrollTop - clientHeight < threshold; - if (isNearBottom) { - requestAnimationFrame(() => { - this.messagesEl.scrollTop = this.messagesEl.scrollHeight; - }); - } - } - /** Keeps the persistent todo panel pinned to the bottom of the messages container. */ - ensureTodoPanelAtBottom(panelEl) { - const todoPanel = panelEl != null ? panelEl : this.messagesEl.querySelector(".claudian-todo-panel"); - if (todoPanel) { - this.messagesEl.appendChild(todoPanel); - } - } -}; - -// src/features/chat/services/AsyncSubagentManager.ts -var AsyncSubagentManager = class { - constructor(onStateChange) { - this.activeAsyncSubagents = /* @__PURE__ */ new Map(); - this.pendingAsyncSubagents = /* @__PURE__ */ new Map(); - this.taskIdToAgentId = /* @__PURE__ */ new Map(); - this.outputToolIdToAgentId = /* @__PURE__ */ new Map(); - this.onStateChange = onStateChange; - } - /** Checks if a Task tool input indicates async mode (run_in_background=true). */ - isAsyncTask(taskInput) { - return taskInput.run_in_background === true; - } - /** Creates an async subagent in pending state. */ - createAsyncSubagent(taskToolId, taskInput) { - const description = taskInput.description || "Background task"; - const subagent = { - id: taskToolId, - description, - mode: "async", - isExpanded: false, - status: "running", - toolCalls: [], - asyncStatus: "pending" - }; - this.pendingAsyncSubagents.set(taskToolId, subagent); - return subagent; - } - /** Handles Task tool_result to extract agent_id. Transitions: pending → running/error. */ - handleTaskToolResult(taskToolId, result, isError) { - const subagent = this.pendingAsyncSubagents.get(taskToolId); - if (!subagent) { - return; - } - if (isError) { - subagent.asyncStatus = "error"; - subagent.status = "error"; - subagent.result = result || "Task failed to start"; - subagent.completedAt = Date.now(); - this.pendingAsyncSubagents.delete(taskToolId); - this.onStateChange(subagent); - return; - } - const agentId = this.parseAgentId(result); - if (!agentId) { - subagent.asyncStatus = "error"; - subagent.status = "error"; - const truncatedResult = result.length > 100 ? result.substring(0, 100) + "..." : result; - subagent.result = `Failed to parse agent_id. Result: ${truncatedResult}`; - subagent.completedAt = Date.now(); - this.pendingAsyncSubagents.delete(taskToolId); - this.onStateChange(subagent); - return; - } - subagent.asyncStatus = "running"; - subagent.agentId = agentId; - subagent.startedAt = Date.now(); - this.pendingAsyncSubagents.delete(taskToolId); - this.activeAsyncSubagents.set(agentId, subagent); - this.taskIdToAgentId.set(taskToolId, agentId); - this.onStateChange(subagent); - } - /** Links AgentOutputTool to its async subagent for result routing. */ - handleAgentOutputToolUse(toolCall) { - const agentId = this.extractAgentIdFromInput(toolCall.input); - if (!agentId) { - return; - } - const subagent = this.activeAsyncSubagents.get(agentId); - if (!subagent) { - return; - } - subagent.outputToolId = toolCall.id; - this.outputToolIdToAgentId.set(toolCall.id, agentId); - } - /** Handles AgentOutputTool result. Transitions: running → completed/error (if done). */ - handleAgentOutputToolResult(toolId, result, isError) { - let agentId = this.outputToolIdToAgentId.get(toolId); - let subagent = agentId ? this.activeAsyncSubagents.get(agentId) : void 0; - if (!subagent) { - const inferredAgentId = this.inferAgentIdFromResult(result); - if (inferredAgentId) { - agentId = inferredAgentId; - subagent = this.activeAsyncSubagents.get(inferredAgentId); - } - } - if (!subagent) { - return void 0; - } - if (agentId) { - subagent.agentId = subagent.agentId || agentId; - this.outputToolIdToAgentId.set(toolId, agentId); - } - const validStates = ["running"]; - if (!validStates.includes(subagent.asyncStatus)) { - return void 0; - } - const stillRunning = this.isStillRunningResult(result, isError); - if (stillRunning) { - this.outputToolIdToAgentId.delete(toolId); - return subagent; - } - const extractedResult = this.extractAgentResult(result, agentId != null ? agentId : ""); - subagent.asyncStatus = isError ? "error" : "completed"; - subagent.status = isError ? "error" : "completed"; - subagent.result = extractedResult; - subagent.completedAt = Date.now(); - if (agentId) this.activeAsyncSubagents.delete(agentId); - this.outputToolIdToAgentId.delete(toolId); - this.onStateChange(subagent); - return subagent; - } - /** Checks if AgentOutputTool result indicates the task is still running. */ - isStillRunningResult(result, isError) { - const trimmed = (result == null ? void 0 : result.trim()) || ""; - const unwrapTextPayload = (raw) => { - try { - const parsed = JSON.parse(raw); - if (Array.isArray(parsed)) { - const textBlock = parsed.find((b) => b && typeof b.text === "string"); - if (textBlock == null ? void 0 : textBlock.text) return textBlock.text; - } else if (parsed && typeof parsed === "object" && typeof parsed.text === "string") { - return parsed.text; - } - } catch (e) { - } - return raw; - }; - const payload = unwrapTextPayload(trimmed); - if (isError) { - return false; - } - if (!trimmed) { - return false; - } - try { - const parsed = JSON.parse(payload); - const status = parsed.retrieval_status || parsed.status; - const hasAgents = parsed.agents && Object.keys(parsed.agents).length > 0; - if (status === "not_ready" || status === "running" || status === "pending") { - return true; - } - if (hasAgents) { - const agentStatuses = Object.values(parsed.agents).map((a) => a && typeof a.status === "string" ? a.status.toLowerCase() : ""); - const anyRunning = agentStatuses.some( - (s) => s === "running" || s === "pending" || s === "not_ready" - ); - if (anyRunning) return true; - return false; - } - if (status === "success" || status === "completed") { - return false; - } - return false; - } catch (e) { - } - const lowerResult = payload.toLowerCase(); - if (lowerResult.includes("not_ready") || lowerResult.includes("not ready")) { - return true; - } - return false; - } - /** Extracts the actual result content from AgentOutputTool response. */ - extractAgentResult(result, agentId) { - const unwrap = (raw) => { - try { - const parsed = JSON.parse(raw); - if (Array.isArray(parsed)) { - const textBlock = parsed.find((b) => b && typeof b.text === "string"); - if (textBlock == null ? void 0 : textBlock.text) return textBlock.text; - } else if (parsed && typeof parsed === "object" && typeof parsed.text === "string") { - return parsed.text; - } - } catch (e) { - } - return raw; - }; - const payload = unwrap(result); - try { - const parsed = JSON.parse(payload); - if (parsed.agents && agentId && parsed.agents[agentId]) { - const agentData = parsed.agents[agentId]; - if (agentData.result) { - return agentData.result; - } - return JSON.stringify(agentData, null, 2); - } - if (parsed.agents) { - const agentIds = Object.keys(parsed.agents); - if (agentIds.length > 0) { - const firstAgent = parsed.agents[agentIds[0]]; - if (firstAgent.result) { - return firstAgent.result; - } - return JSON.stringify(firstAgent, null, 2); - } - } - } catch (e) { - } - return payload; - } - /** Orphans all active async subagents when conversation ends. */ - orphanAllActive() { - const orphaned = []; - for (const subagent of this.pendingAsyncSubagents.values()) { - subagent.asyncStatus = "orphaned"; - subagent.status = "error"; - subagent.result = "Conversation ended before task completed"; - subagent.completedAt = Date.now(); - orphaned.push(subagent); - this.onStateChange(subagent); - } - for (const subagent of this.activeAsyncSubagents.values()) { - if (subagent.asyncStatus === "running") { - subagent.asyncStatus = "orphaned"; - subagent.status = "error"; - subagent.result = "Conversation ended before task completed"; - subagent.completedAt = Date.now(); - orphaned.push(subagent); - this.onStateChange(subagent); - } - } - this.pendingAsyncSubagents.clear(); - this.activeAsyncSubagents.clear(); - this.outputToolIdToAgentId.clear(); - return orphaned; - } - /** Clears all state for a new conversation. */ - clear() { - this.pendingAsyncSubagents.clear(); - this.activeAsyncSubagents.clear(); - this.taskIdToAgentId.clear(); - this.outputToolIdToAgentId.clear(); - } - /** Gets async subagent by agent_id. */ - getByAgentId(agentId) { - return this.activeAsyncSubagents.get(agentId); - } - /** Gets async subagent by task tool_use_id. */ - getByTaskId(taskToolId) { - const pending = this.pendingAsyncSubagents.get(taskToolId); - if (pending) return pending; - const agentId = this.taskIdToAgentId.get(taskToolId); - if (agentId) { - return this.activeAsyncSubagents.get(agentId); - } - return void 0; - } - /** Checks if a task tool_id is a pending async subagent. */ - isPendingAsyncTask(taskToolId) { - return this.pendingAsyncSubagents.has(taskToolId); - } - /** Checks if a tool_id is an AgentOutputTool linked to an async subagent. */ - isLinkedAgentOutputTool(toolId) { - return this.outputToolIdToAgentId.has(toolId); - } - /** Gets all active async subagents (pending + running). */ - getAllActive() { - return [ - ...this.pendingAsyncSubagents.values(), - ...this.activeAsyncSubagents.values() - ]; - } - /** Checks if there are any active async subagents. */ - hasActiveAsync() { - return this.pendingAsyncSubagents.size > 0 || this.activeAsyncSubagents.size > 0; - } - /** Parses agent_id from Task tool_result. */ - parseAgentId(result) { - var _a; - const regexPatterns = [ - /"agent_id"\s*:\s*"([^"]+)"/, - // JSON style: "agent_id": "value" - /"agentId"\s*:\s*"([^"]+)"/, - // camelCase JSON - /agent_id[=:]\s*"?([a-zA-Z0-9_-]+)"?/i, - // Flexible format - /agentId[=:]\s*"?([a-zA-Z0-9_-]+)"?/i, - // camelCase flexible - /\b([a-f0-9]{8})\b/ - // Short hex ID (8 chars) - ]; - for (const pattern of regexPatterns) { - const match = result.match(pattern); - if (match && match[1]) { - return match[1]; - } - } - try { - const parsed = JSON.parse(result); - const agentId = parsed.agent_id || parsed.agentId; - if (typeof agentId === "string" && agentId.length > 0) { - return agentId; - } - if ((_a = parsed.data) == null ? void 0 : _a.agent_id) { - return parsed.data.agent_id; - } - if (parsed.id && typeof parsed.id === "string") { - return parsed.id; - } - } catch (e) { - } - return null; - } - /** Infers agent_id from AgentOutputTool result payload. */ - inferAgentIdFromResult(result) { - try { - const parsed = JSON.parse(result); - if (parsed.agents && typeof parsed.agents === "object") { - const keys = Object.keys(parsed.agents); - if (keys.length > 0) { - return keys[0]; - } - } - } catch (e) { - } - return null; - } - /** Extracts agentId from AgentOutputTool input. */ - extractAgentIdFromInput(input) { - const agentId = input.agentId || input.agent_id; - return agentId || null; - } -}; - -// src/core/prompts/instructionRefine.ts -function buildRefineSystemPrompt(existingInstructions) { - const existingSection = existingInstructions.trim() ? ` - -EXISTING INSTRUCTIONS (already in the user's system prompt): -\`\`\` -${existingInstructions.trim()} -\`\`\` - -When refining the new instruction: -- Consider how it fits with existing instructions -- Avoid duplicating existing instructions -- If the new instruction conflicts with an existing one, refine it to be complementary or note the conflict -- Match the format of existing instructions (section, heading, bullet points, style, etc.)` : ""; - return `You are an expert Prompt Engineer. You help users craft precise, effective system instructions for their AI assistant. - -**Your Goal**: Transform vague or simple user requests into **high-quality, actionable, and non-conflicting** system prompt instructions. - -**Process**: -1. **Analyze Intent**: What behavior does the user want to enforce or change? -2. **Check Context**: Does this conflict with existing instructions? - - *No Conflict*: Add as new. - - *Conflict*: Propose a **merged instruction** that resolves the contradiction (or ask if unsure). -3. **Refine**: Draft a clear, positive instruction (e.g., "Do X" instead of "Don't do Y"). -4. **Format**: Return *only* the Markdown snippet wrapped in \`\` tags. - -**Guidelines**: -- **Clarity**: Use precise language. Avoid ambiguity. -- **Scope**: Keep it focused. Don't add unrelated rules. -- **Format**: Valid Markdown (bullets \`-\` or sections \`##\`). -- **No Header**: Do NOT include a top-level header like \`# Custom Instructions\`. -- **Conflict Handling**: If the new rule directly contradicts an existing one, rewrite the *new* one to override specific cases or ask for clarification. - -**Output Format**: -- **Success**: \`...markdown content...\` -- **Ambiguity**: Plain text question. - -${existingSection} - -**Examples**: - -Input: "typescript for code" -Output: - **Code Language**: Always use TypeScript for code examples. Include proper type annotations and interfaces. - -Input: "be concise" -Output: - **Conciseness**: Provide brief, direct responses. Omit conversational filler and unnecessary explanations. - -Input: "organize coding style rules" -Output: ## Coding Standards - -- **Language**: Use TypeScript. -- **Style**: Prefer functional patterns. -- **Review**: Keep diffs small. - -Input: "use that thing from before" -Output: I'm not sure what you're referring to. Could you please clarify?`; -} - -// src/features/chat/services/InstructionRefineService.ts -var READ_ONLY_TOOLS2 = [TOOL_READ, TOOL_GREP, TOOL_GLOB]; -var InstructionRefineService = class { - constructor(plugin) { - this.abortController = null; - this.resolvedClaudePath = null; - this.sessionId = null; - this.existingInstructions = ""; - this.plugin = plugin; - } - /** Resets conversation state for a new refinement session. */ - resetConversation() { - this.sessionId = null; - } - findClaudeCLI() { - return findClaudeCLIPath(); - } - /** Refines a raw instruction from user input. */ - async refineInstruction(rawInstruction, existingInstructions, onProgress) { - this.sessionId = null; - this.existingInstructions = existingInstructions; - const prompt = `Please refine this instruction: "${rawInstruction}"`; - return this.sendMessage(prompt, onProgress); - } - /** Continues conversation with a follow-up message (for clarifications). */ - async continueConversation(message, onProgress) { - if (!this.sessionId) { - return { success: false, error: "No active conversation to continue" }; - } - return this.sendMessage(message, onProgress); - } - /** Cancels any ongoing query. */ - cancel() { - if (this.abortController) { - this.abortController.abort(); - this.abortController = null; - } - } - async sendMessage(prompt, onProgress) { - var _a; - const vaultPath = getVaultPath(this.plugin.app); - if (!vaultPath) { - return { success: false, error: "Could not determine vault path" }; - } - if (!this.resolvedClaudePath) { - this.resolvedClaudePath = this.findClaudeCLI(); - } - if (!this.resolvedClaudePath) { - return { success: false, error: "Claude CLI not found. Please install Claude Code CLI." }; - } - this.abortController = new AbortController(); - const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables()); - const options = { - cwd: vaultPath, - systemPrompt: buildRefineSystemPrompt(this.existingInstructions), - model: this.plugin.settings.model, - abortController: this.abortController, - pathToClaudeCodeExecutable: this.resolvedClaudePath, - env: { - ...process.env, - ...customEnv, - PATH: getEnhancedPath(customEnv.PATH) - }, - allowedTools: [...READ_ONLY_TOOLS2], - permissionMode: "bypassPermissions", - allowDangerouslySkipPermissions: true, - hooks: { - PreToolUse: [ - this.createReadOnlyHook(), - this.createVaultRestrictionHook(vaultPath) - ] - } - }; - if (this.sessionId) { - options.resume = this.sessionId; - } - const budgetSetting = this.plugin.settings.thinkingBudget; - const budgetConfig = THINKING_BUDGETS.find((b) => b.value === budgetSetting); - if (budgetConfig && budgetConfig.tokens > 0) { - options.maxThinkingTokens = budgetConfig.tokens; - } - try { - const response = query({ prompt, options }); - let responseText = ""; - for await (const message of response) { - if ((_a = this.abortController) == null ? void 0 : _a.signal.aborted) { - await response.interrupt(); - return { success: false, error: "Cancelled" }; - } - if (message.type === "system" && message.subtype === "init" && message.session_id) { - this.sessionId = message.session_id; - } - const text = this.extractTextFromMessage(message); - if (text) { - responseText += text; - if (onProgress) { - const partialResult = this.parseResponse(responseText); - onProgress(partialResult); - } - } - } - return this.parseResponse(responseText); - } catch (error2) { - const msg = error2 instanceof Error ? error2.message : "Unknown error"; - return { success: false, error: msg }; - } finally { - this.abortController = null; - } - } - /** Parses response text for tag. */ - parseResponse(responseText) { - const instructionMatch = responseText.match(/([\s\S]*?)<\/instruction>/); - if (instructionMatch) { - return { success: true, refinedInstruction: instructionMatch[1].trim() }; - } - const trimmed = responseText.trim(); - if (trimmed) { - return { success: true, clarification: trimmed }; - } - return { success: false, error: "Empty response" }; - } - /** Extracts text content from SDK message. */ - extractTextFromMessage(message) { - var _a; - if (message.type !== "assistant" || !((_a = message.message) == null ? void 0 : _a.content)) { - return ""; - } - return message.message.content.filter((block) => block.type === "text" && !!block.text).map((block) => block.text).join(""); - } - /** Creates PreToolUse hook to enforce read-only mode. */ - createReadOnlyHook() { - return { - hooks: [ - async (hookInput) => { - const input = hookInput; - const toolName = input.tool_name; - if (READ_ONLY_TOOLS2.includes(toolName)) { - return { continue: true }; - } - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Instruction refine mode: tool "${toolName}" is not allowed (read-only)` - } - }; - } - ] - }; - } - /** Creates PreToolUse hook to restrict file access to vault. */ - createVaultRestrictionHook(vaultPath) { - return { - hooks: [ - async (hookInput) => { - const input = hookInput; - const toolName = input.tool_name; - const toolInput = input.tool_input; - if (toolName === "Read" || toolName === "Glob" || toolName === "Grep") { - const filePath = toolName === "Read" ? toolInput.file_path || "" : toolInput.path || toolInput.pattern || ""; - if (filePath && !isPathWithinVault(filePath, vaultPath)) { - return { - continue: false, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: `Access denied: "${filePath}" is outside the vault` - } - }; - } - } - return { continue: true }; - } - ] - }; - } -}; - -// src/core/prompts/titleGeneration.ts -var TITLE_GENERATION_SYSTEM_PROMPT = `You are a specialist in summarizing intent. - -**Task**: Generate a **concise, descriptive title** (max 50 chars) for this conversation based on the first interaction. - -**Rules**: -1. **Format**: Sentence case. No periods/quotes. -2. **Structure**: Start with a **strong verb** (e.g., Create, Fix, Debug, Explain, Analyze). -3. **Forbidden**: "Conversation with...", "Help me...", "Question about...", "I need...". -4. **Tech Context**: Detect and include the primary language/framework if code is present (e.g., "Debug Python script", "Refactor React hook"). - -**Output**: Return ONLY the raw title text.`; - -// src/features/chat/services/TitleGenerationService.ts -var TitleGenerationService = class { - constructor(plugin) { - this.resolvedClaudePath = null; - /** Map of conversationId to AbortController for concurrent generation support. */ - this.activeGenerations = /* @__PURE__ */ new Map(); - this.plugin = plugin; - } - /** - * Generates a title for a conversation based on first messages. - * Non-blocking: calls callback when complete. - */ - async generateTitle(conversationId, userMessage, assistantResponse, callback) { - const vaultPath = getVaultPath(this.plugin.app); - if (!vaultPath) { - console.warn("[TitleGeneration] Could not determine vault path"); - await this.safeCallback(callback, conversationId, { - success: false, - error: "Could not determine vault path" - }); - return; - } - if (!this.resolvedClaudePath) { - this.resolvedClaudePath = findClaudeCLIPath(); - } - if (!this.resolvedClaudePath) { - console.warn("[TitleGeneration] Claude CLI not found"); - await this.safeCallback(callback, conversationId, { - success: false, - error: "Claude CLI not found" - }); - return; - } - const envVars = parseEnvironmentVariables( - this.plugin.getActiveEnvironmentVariables() - ); - const titleModel = this.plugin.settings.titleGenerationModel || envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL || "claude-haiku-4-5"; - const existingController = this.activeGenerations.get(conversationId); - if (existingController) { - existingController.abort(); - } - const abortController = new AbortController(); - this.activeGenerations.set(conversationId, abortController); - const truncatedUser = this.truncateText(userMessage, 500); - const truncatedAssistant = this.truncateText(assistantResponse, 500); - const prompt = `User's first message: -""" -${truncatedUser} -""" - -AI's response: -""" -${truncatedAssistant} -""" - -Generate a title for this conversation:`; - const customEnv = parseEnvironmentVariables( - this.plugin.getActiveEnvironmentVariables() - ); - const options = { - cwd: vaultPath, - systemPrompt: TITLE_GENERATION_SYSTEM_PROMPT, - model: titleModel, - abortController, - pathToClaudeCodeExecutable: this.resolvedClaudePath, - env: { - ...process.env, - ...customEnv, - PATH: getEnhancedPath(customEnv.PATH) - }, - allowedTools: [], - // No tools needed for title generation - permissionMode: "bypassPermissions", - allowDangerouslySkipPermissions: true - }; - try { - const response = query({ prompt, options }); - let responseText = ""; - for await (const message of response) { - if (abortController.signal.aborted) { - await this.safeCallback(callback, conversationId, { - success: false, - error: "Cancelled" - }); - return; - } - const text = this.extractTextFromMessage(message); - if (text) { - responseText += text; - } - } - const title = this.parseTitle(responseText); - if (title) { - await this.safeCallback(callback, conversationId, { success: true, title }); - } else { - console.warn("[TitleGeneration] Failed to parse title from response"); - await this.safeCallback(callback, conversationId, { - success: false, - error: "Failed to parse title from response" - }); - } - } catch (error2) { - if (error2 instanceof Error && error2.name !== "AbortError") { - console.error("[TitleGeneration] Error generating title:", error2.message); - } - const msg = error2 instanceof Error ? error2.message : "Unknown error"; - await this.safeCallback(callback, conversationId, { success: false, error: msg }); - } finally { - this.activeGenerations.delete(conversationId); - } - } - /** Cancels all ongoing title generations. */ - cancel() { - for (const controller of this.activeGenerations.values()) { - controller.abort(); - } - this.activeGenerations.clear(); - } - /** Truncates text to a maximum length with ellipsis. */ - truncateText(text, maxLength) { - if (text.length <= maxLength) return text; - return text.substring(0, maxLength) + "..."; - } - /** Extracts text content from SDK message. */ - extractTextFromMessage(message) { - var _a; - if (message.type !== "assistant" || !((_a = message.message) == null ? void 0 : _a.content)) { - return ""; - } - return message.message.content.filter( - (block) => block.type === "text" && !!block.text - ).map((block) => block.text).join(""); - } - /** Parses and cleans the title from response. */ - parseTitle(responseText) { - const trimmed = responseText.trim(); - if (!trimmed) return null; - let title = trimmed; - if (title.startsWith('"') && title.endsWith('"') || title.startsWith("'") && title.endsWith("'")) { - title = title.slice(1, -1); - } - title = title.replace(/[.!?:;,]+$/, ""); - if (title.length > 50) { - title = title.substring(0, 47) + "..."; - } - return title || null; - } - /** Safely invokes callback with try-catch to prevent unhandled errors. */ - async safeCallback(callback, conversationId, result) { - try { - await callback(conversationId, result); - } catch (error2) { - console.error("[TitleGeneration] Error in callback:", error2 instanceof Error ? error2.message : error2); - } - } -}; - -// src/features/chat/state/ChatState.ts -function createInitialState() { - return { - messages: [], - isStreaming: false, - cancelRequested: false, - currentConversationId: null, - queuedMessage: null, - currentContentEl: null, - currentTextEl: null, - currentTextContent: "", - currentThinkingState: null, - thinkingEl: null, - queueIndicatorEl: null, - toolCallElements: /* @__PURE__ */ new Map(), - activeSubagents: /* @__PURE__ */ new Map(), - asyncSubagentStates: /* @__PURE__ */ new Map(), - writeEditStates: /* @__PURE__ */ new Map(), - askUserQuestionStates: /* @__PURE__ */ new Map(), - usage: null, - ignoreUsageUpdates: false, - subagentsSpawnedThisStream: 0, - planModeState: null, - planModeRequested: false, - planModeActivationPending: false, - pendingPlanContent: null, - currentTodos: null - }; -} -var ChatState = class { - constructor(callbacks = {}) { - this.state = createInitialState(); - this.callbacks = callbacks; - } - // ============================================ - // Messages - // ============================================ - get messages() { - return this.state.messages; - } - set messages(value) { - var _a, _b; - this.state.messages = value; - (_b = (_a = this.callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a); - } - addMessage(msg) { - var _a, _b; - this.state.messages.push(msg); - (_b = (_a = this.callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a); - } - clearMessages() { - var _a, _b; - this.state.messages = []; - (_b = (_a = this.callbacks).onMessagesChanged) == null ? void 0 : _b.call(_a); - } - // ============================================ - // Streaming Control - // ============================================ - get isStreaming() { - return this.state.isStreaming; - } - set isStreaming(value) { - var _a, _b; - this.state.isStreaming = value; - (_b = (_a = this.callbacks).onStreamingStateChanged) == null ? void 0 : _b.call(_a, value); - } - get cancelRequested() { - return this.state.cancelRequested; - } - set cancelRequested(value) { - this.state.cancelRequested = value; - } - // ============================================ - // Conversation - // ============================================ - get currentConversationId() { - return this.state.currentConversationId; - } - set currentConversationId(value) { - var _a, _b; - this.state.currentConversationId = value; - (_b = (_a = this.callbacks).onConversationChanged) == null ? void 0 : _b.call(_a, value); - } - // ============================================ - // Queued Message - // ============================================ - get queuedMessage() { - return this.state.queuedMessage; - } - set queuedMessage(value) { - this.state.queuedMessage = value; - } - // ============================================ - // Streaming DOM State - // ============================================ - get currentContentEl() { - return this.state.currentContentEl; - } - set currentContentEl(value) { - this.state.currentContentEl = value; - } - get currentTextEl() { - return this.state.currentTextEl; - } - set currentTextEl(value) { - this.state.currentTextEl = value; - } - get currentTextContent() { - return this.state.currentTextContent; - } - set currentTextContent(value) { - this.state.currentTextContent = value; - } - get currentThinkingState() { - return this.state.currentThinkingState; - } - set currentThinkingState(value) { - this.state.currentThinkingState = value; - } - get thinkingEl() { - return this.state.thinkingEl; - } - set thinkingEl(value) { - this.state.thinkingEl = value; - } - get queueIndicatorEl() { - return this.state.queueIndicatorEl; - } - set queueIndicatorEl(value) { - this.state.queueIndicatorEl = value; - } - // ============================================ - // Tool and Subagent Tracking Maps - // ============================================ - get toolCallElements() { - return this.state.toolCallElements; - } - get activeSubagents() { - return this.state.activeSubagents; - } - get asyncSubagentStates() { - return this.state.asyncSubagentStates; - } - get writeEditStates() { - return this.state.writeEditStates; - } - get askUserQuestionStates() { - return this.state.askUserQuestionStates; - } - // ============================================ - // Usage State - // ============================================ - get usage() { - return this.state.usage; - } - set usage(value) { - var _a, _b; - this.state.usage = value; - (_b = (_a = this.callbacks).onUsageChanged) == null ? void 0 : _b.call(_a, value); - } - get ignoreUsageUpdates() { - return this.state.ignoreUsageUpdates; - } - set ignoreUsageUpdates(value) { - this.state.ignoreUsageUpdates = value; - } - get subagentsSpawnedThisStream() { - return this.state.subagentsSpawnedThisStream; - } - set subagentsSpawnedThisStream(value) { - this.state.subagentsSpawnedThisStream = value; - } - // ============================================ - // Plan Mode State - // ============================================ - get planModeState() { - return this.state.planModeState; - } - set planModeState(value) { - this.state.planModeState = value; - } - /** Resets plan mode state. */ - resetPlanModeState() { - this.state.planModeState = null; - } - get planModeRequested() { - return this.state.planModeRequested; - } - set planModeRequested(value) { - this.state.planModeRequested = value; - } - get planModeActivationPending() { - return this.state.planModeActivationPending; - } - set planModeActivationPending(value) { - this.state.planModeActivationPending = value; - } - // ============================================ - // Pending Plan Content (for approval persistence) - // ============================================ - get pendingPlanContent() { - return this.state.pendingPlanContent; - } - set pendingPlanContent(value) { - this.state.pendingPlanContent = value; - } - // ============================================ - // Current Todos (for persistent bottom panel) - // ============================================ - get currentTodos() { - return this.state.currentTodos; - } - set currentTodos(value) { - var _a, _b; - const normalizedValue = value && value.length > 0 ? value : null; - this.state.currentTodos = normalizedValue; - (_b = (_a = this.callbacks).onTodosChanged) == null ? void 0 : _b.call(_a, normalizedValue); - } - // ============================================ - // Reset Methods - // ============================================ - /** Resets streaming-related state. */ - resetStreamingState() { - this.state.currentContentEl = null; - this.state.currentTextEl = null; - this.state.currentTextContent = ""; - this.state.currentThinkingState = null; - this.state.isStreaming = false; - this.state.cancelRequested = false; - } - /** Clears all maps for a new conversation. */ - clearMaps() { - this.state.toolCallElements.clear(); - this.state.activeSubagents.clear(); - this.state.asyncSubagentStates.clear(); - this.state.writeEditStates.clear(); - this.state.askUserQuestionStates.clear(); - } - /** Resets all state for a new conversation. */ - resetForNewConversation() { - this.clearMessages(); - this.resetStreamingState(); - this.clearMaps(); - this.state.queuedMessage = null; - this.state.planModeRequested = false; - this.state.planModeActivationPending = false; - this.usage = null; - this.currentTodos = null; - } - /** Gets persisted messages (strips image data). */ - getPersistedMessages() { - return this.state.messages.map((msg) => { - var _a; - return { - ...msg, - images: (_a = msg.images) == null ? void 0 : _a.map((img) => { - const { data, ...rest } = img; - return { ...rest }; - }) - }; - }); - } -}; - -// src/features/chat/ClaudianView.ts -var ClaudianView = class extends import_obsidian25.ItemView { - constructor(leaf, plugin) { - super(leaf); - // Controllers - this.selectionController = null; - this.conversationController = null; - this.streamController = null; - this.inputController = null; - this.navigationController = null; - // Rendering - this.renderer = null; - this.instructionRefineService = null; - this.titleGenerationService = null; - // DOM Elements - this.messagesEl = null; - this.inputEl = null; - this.inputWrapper = null; - this.historyDropdown = null; - this.welcomeEl = null; - this.selectionIndicatorEl = null; - // UI Components - this.fileContextManager = null; - this.imageContextManager = null; - this.modelSelector = null; - this.thinkingBudgetSelector = null; - this.contextPathSelector = null; - this.mcpServerSelector = null; - this.permissionToggle = null; - this.slashCommandManager = null; - this.slashCommandDropdown = null; - this.instructionModeManager = null; - this.contextUsageMeter = null; - this.planBanner = null; - this.todoPanel = null; - this.plugin = plugin; - this.state = new ChatState({ - onUsageChanged: (usage) => { - var _a; - return (_a = this.contextUsageMeter) == null ? void 0 : _a.update(usage); - }, - onTodosChanged: (todos) => { - var _a; - return (_a = this.todoPanel) == null ? void 0 : _a.updateTodos(todos); - } - }); - this.asyncSubagentManager = new AsyncSubagentManager( - (subagent) => { - var _a; - return (_a = this.streamController) == null ? void 0 : _a.onAsyncSubagentStateChange(subagent); - } - ); - } - getViewType() { - return VIEW_TYPE_CLAUDIAN; - } - getDisplayText() { - return "Claudian"; - } - getIcon() { - return "bot"; - } - async onOpen() { - var _a, _b; - const container = this.containerEl.children[1]; - container.empty(); - container.addClass("claudian-container"); - const header = container.createDiv({ cls: "claudian-header" }); - this.buildHeader(header); - this.planBanner = new PlanBanner({ - app: this.plugin.app, - component: this - }); - this.planBanner.mount(container); - this.messagesEl = container.createDiv({ cls: "claudian-messages" }); - this.welcomeEl = this.messagesEl.createDiv({ cls: "claudian-welcome" }); - this.todoPanel = new TodoPanel(); - this.todoPanel.mount(this.messagesEl); - const inputContainerEl = container.createDiv({ cls: "claudian-input-container" }); - this.buildInputArea(inputContainerEl); - this.renderer = new MessageRenderer( - this.plugin.app, - this, - this.messagesEl - ); - this.initializeControllers(); - this.wireEventHandlers(); - (_a = this.selectionController) == null ? void 0 : _a.start(); - await ((_b = this.conversationController) == null ? void 0 : _b.loadActive()); - } - async onClose() { - var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; - (_a = this.selectionController) == null ? void 0 : _a.stop(); - (_b = this.selectionController) == null ? void 0 : _b.clear(); - (_c = this.navigationController) == null ? void 0 : _c.dispose(); - cleanupThinkingBlock(this.state.currentThinkingState); - this.state.currentThinkingState = null; - this.plugin.agentService.setApprovalCallback(null); - this.plugin.agentService.setAskUserQuestionCallback(null); - (_d = this.fileContextManager) == null ? void 0 : _d.destroy(); - (_e = this.slashCommandDropdown) == null ? void 0 : _e.destroy(); - this.slashCommandDropdown = null; - this.slashCommandManager = null; - (_f = this.instructionModeManager) == null ? void 0 : _f.destroy(); - this.instructionModeManager = null; - (_g = this.instructionRefineService) == null ? void 0 : _g.cancel(); - this.instructionRefineService = null; - (_h = this.titleGenerationService) == null ? void 0 : _h.cancel(); - this.titleGenerationService = null; - (_i = this.todoPanel) == null ? void 0 : _i.destroy(); - this.todoPanel = null; - this.asyncSubagentManager.orphanAllActive(); - this.state.asyncSubagentStates.clear(); - await ((_j = this.conversationController) == null ? void 0 : _j.save()); - } - // ============================================ - // UI Building - // ============================================ - buildHeader(header) { - const titleContainer = header.createDiv({ cls: "claudian-title" }); - const logoEl = titleContainer.createSpan({ cls: "claudian-logo" }); - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - svg.setAttribute("viewBox", LOGO_SVG.viewBox); - svg.setAttribute("width", LOGO_SVG.width); - svg.setAttribute("height", LOGO_SVG.height); - svg.setAttribute("fill", "none"); - const path12 = document.createElementNS("http://www.w3.org/2000/svg", "path"); - path12.setAttribute("d", LOGO_SVG.path); - path12.setAttribute("fill", LOGO_SVG.fill); - svg.appendChild(path12); - logoEl.appendChild(svg); - titleContainer.createEl("h4", { text: "Claudian" }); - const headerActions = header.createDiv({ cls: "claudian-header-actions" }); - const historyContainer = headerActions.createDiv({ cls: "claudian-history-container" }); - const trigger = historyContainer.createDiv({ cls: "claudian-header-btn" }); - (0, import_obsidian25.setIcon)(trigger, "history"); - trigger.setAttribute("aria-label", "Chat history"); - this.historyDropdown = historyContainer.createDiv({ cls: "claudian-history-menu" }); - trigger.addEventListener("click", (e) => { - var _a; - e.stopPropagation(); - (_a = this.conversationController) == null ? void 0 : _a.toggleHistoryDropdown(); - }); - const newBtn = headerActions.createDiv({ cls: "claudian-header-btn" }); - (0, import_obsidian25.setIcon)(newBtn, "plus"); - newBtn.setAttribute("aria-label", "New conversation"); - newBtn.addEventListener("click", () => { - var _a; - return (_a = this.conversationController) == null ? void 0 : _a.createNew(); - }); - } - buildInputArea(inputContainerEl) { - this.inputWrapper = inputContainerEl.createDiv({ cls: "claudian-input-wrapper" }); - this.selectionIndicatorEl = this.inputWrapper.createDiv({ cls: "claudian-selection-indicator" }); - this.selectionIndicatorEl.style.display = "none"; - this.inputEl = this.inputWrapper.createEl("textarea", { - cls: "claudian-input", - attr: { - placeholder: "How can I help you today?", - rows: "3" - } - }); - this.fileContextManager = new FileContextManager( - this.plugin.app, - inputContainerEl, - this.inputEl, - { - getExcludedTags: () => this.plugin.settings.excludedTags, - onChipsChanged: () => { - var _a; - return (_a = this.renderer) == null ? void 0 : _a.scrollToBottomIfNeeded(); - }, - getContextPaths: () => { - var _a; - return ((_a = this.contextPathSelector) == null ? void 0 : _a.getContextPaths()) || []; - } - } - ); - this.fileContextManager.setMcpService(this.plugin.mcpService); - this.imageContextManager = new ImageContextManager( - this.plugin.app, - inputContainerEl, - this.inputEl, - { - onImagesChanged: () => { - var _a; - return (_a = this.renderer) == null ? void 0 : _a.scrollToBottomIfNeeded(); - }, - getMediaFolder: () => this.plugin.settings.mediaFolder - } - ); - const vaultPath = getVaultPath(this.plugin.app); - if (vaultPath) { - this.slashCommandManager = new SlashCommandManager(this.plugin.app, vaultPath); - this.slashCommandManager.setCommands(this.plugin.settings.slashCommands); - this.slashCommandDropdown = new SlashCommandDropdown( - inputContainerEl, - this.inputEl, - { - onSelect: () => { - }, - onHide: () => { - }, - getCommands: () => this.plugin.settings.slashCommands - } - ); - } - this.instructionRefineService = new InstructionRefineService(this.plugin); - this.titleGenerationService = new TitleGenerationService(this.plugin); - this.instructionModeManager = new InstructionModeManager( - this.inputEl, - { - onSubmit: async (rawInstruction) => { - var _a; - await ((_a = this.inputController) == null ? void 0 : _a.handleInstructionSubmit(rawInstruction)); - }, - getInputWrapper: () => this.inputWrapper - } - ); - const inputToolbar = this.inputWrapper.createDiv({ cls: "claudian-input-toolbar" }); - const toolbarComponents = createInputToolbar(inputToolbar, { - getSettings: () => ({ - model: this.plugin.settings.model, - thinkingBudget: this.plugin.settings.thinkingBudget, - permissionMode: this.plugin.settings.permissionMode, - lastNonPlanPermissionMode: this.plugin.settings.lastNonPlanPermissionMode - }), - getEnvironmentVariables: () => this.plugin.getActiveEnvironmentVariables(), - isAgentInitiatedPlanMode: () => { - var _a, _b; - return (_b = (_a = this.state.planModeState) == null ? void 0 : _a.agentInitiated) != null ? _b : false; - }, - isPlanModeRequested: () => this.state.planModeRequested, - onModelChange: async (model) => { - var _a, _b, _c; - this.plugin.settings.model = model; - const isDefaultModel = DEFAULT_CLAUDE_MODELS.find((m) => m.value === model); - if (isDefaultModel) { - this.plugin.settings.thinkingBudget = DEFAULT_THINKING_BUDGET[model]; - this.plugin.settings.lastClaudeModel = model; - } else { - this.plugin.settings.lastCustomModel = model; - } - await this.plugin.saveSettings(); - (_a = this.thinkingBudgetSelector) == null ? void 0 : _a.updateDisplay(); - (_b = this.modelSelector) == null ? void 0 : _b.updateDisplay(); - (_c = this.modelSelector) == null ? void 0 : _c.renderOptions(); - }, - onThinkingBudgetChange: async (budget) => { - this.plugin.settings.thinkingBudget = budget; - await this.plugin.saveSettings(); - }, - onPermissionModeChange: async (mode) => { - var _a; - const current = this.plugin.settings.permissionMode; - if (mode === "plan") { - if (current !== "plan") { - this.plugin.settings.lastNonPlanPermissionMode = current; - } - } else { - this.plugin.settings.lastNonPlanPermissionMode = mode; - } - this.plugin.settings.permissionMode = mode; - await this.plugin.saveSettings(); - if (mode === "plan") { - if (!((_a = this.state.planModeState) == null ? void 0 : _a.isActive)) { - this.state.planModeState = { - isActive: true, - planFilePath: null, - planContent: null, - originalQuery: null, - agentInitiated: true - }; - } - } else { - this.state.resetPlanModeState(); - } - this.updatePlanModeUiState(); - } - }); - this.modelSelector = toolbarComponents.modelSelector; - this.thinkingBudgetSelector = toolbarComponents.thinkingBudgetSelector; - this.contextUsageMeter = toolbarComponents.contextUsageMeter; - this.contextPathSelector = toolbarComponents.contextPathSelector; - this.mcpServerSelector = toolbarComponents.mcpServerSelector; - this.permissionToggle = toolbarComponents.permissionToggle; - this.mcpServerSelector.setMcpService(this.plugin.mcpService); - this.fileContextManager.setOnMcpMentionChange((servers) => { - var _a; - (_a = this.mcpServerSelector) == null ? void 0 : _a.addMentionedServers(servers); - }); - this.contextPathSelector.setOnChange(() => { - var _a; - (_a = this.fileContextManager) == null ? void 0 : _a.preScanContextPaths(); - }); - } - // ============================================ - // Controller Initialization - // ============================================ - initializeControllers() { - var _a; - this.selectionController = new SelectionController( - this.plugin.app, - this.selectionIndicatorEl, - this.inputEl - ); - this.streamController = new StreamController({ - plugin: this.plugin, - state: this.state, - renderer: this.renderer, - asyncSubagentManager: this.asyncSubagentManager, - getMessagesEl: () => this.messagesEl, - getFileContextManager: () => this.fileContextManager, - updateQueueIndicator: () => { - var _a2; - return (_a2 = this.inputController) == null ? void 0 : _a2.updateQueueIndicator(); - }, - setPlanModeActive: (_active) => { - this.updatePlanModeUiState(); - } - }); - this.conversationController = new ConversationController( - { - plugin: this.plugin, - state: this.state, - renderer: this.renderer, - asyncSubagentManager: this.asyncSubagentManager, - getHistoryDropdown: () => this.historyDropdown, - getWelcomeEl: () => this.welcomeEl, - setWelcomeEl: (el) => { - this.welcomeEl = el; - }, - getMessagesEl: () => this.messagesEl, - getInputEl: () => this.inputEl, - getFileContextManager: () => this.fileContextManager, - getImageContextManager: () => this.imageContextManager, - getMcpServerSelector: () => this.mcpServerSelector, - getContextPathSelector: () => this.contextPathSelector, - clearQueuedMessage: () => { - var _a2; - return (_a2 = this.inputController) == null ? void 0 : _a2.clearQueuedMessage(); - }, - getApprovedPlan: () => this.plugin.agentService.getApprovedPlanContent(), - setApprovedPlan: (plan) => this.plugin.agentService.setApprovedPlanContent(plan), - showPlanBanner: (content) => { - var _a2; - void ((_a2 = this.planBanner) == null ? void 0 : _a2.show(content)); - }, - hidePlanBanner: () => { - var _a2; - return (_a2 = this.planBanner) == null ? void 0 : _a2.hide(); - }, - triggerPendingPlanApproval: (content) => { - var _a2; - return (_a2 = this.inputController) == null ? void 0 : _a2.restorePendingPlanApproval(content); - }, - getTitleGenerationService: () => this.titleGenerationService, - setPlanModeActive: (_active) => { - this.updatePlanModeUiState(); - }, - getTodoPanel: () => this.todoPanel - }, - {} - ); - this.inputController = new InputController({ - plugin: this.plugin, - state: this.state, - renderer: this.renderer, - streamController: this.streamController, - selectionController: this.selectionController, - conversationController: this.conversationController, - getInputEl: () => this.inputEl, - getWelcomeEl: () => this.welcomeEl, - getMessagesEl: () => this.messagesEl, - getFileContextManager: () => this.fileContextManager, - getImageContextManager: () => this.imageContextManager, - getSlashCommandManager: () => this.slashCommandManager, - getMcpServerSelector: () => this.mcpServerSelector, - getInstructionModeManager: () => this.instructionModeManager, - getInstructionRefineService: () => this.instructionRefineService, - getTitleGenerationService: () => this.titleGenerationService, - getComponent: () => this, - setPlanModeActive: (_active) => { - this.updatePlanModeUiState(); - }, - getPlanBanner: () => this.planBanner, - generateId: () => this.generateId(), - resetContextMeter: () => { - var _a2; - return (_a2 = this.contextUsageMeter) == null ? void 0 : _a2.update(null); - } - }); - (_a = this.permissionToggle) == null ? void 0 : _a.setOnPlanModeToggle((active) => { - var _a2; - (_a2 = this.inputController) == null ? void 0 : _a2.setPlanModeRequested(active); - }); - this.plugin.agentService.setApprovalCallback( - (toolName, input, description) => this.inputController.handleApprovalRequest(toolName, input, description) - ); - this.plugin.agentService.setAskUserQuestionCallback( - (input) => this.inputController.handleAskUserQuestion(input) - ); - this.plugin.agentService.setExitPlanModeCallback( - (planFilePath) => this.inputController.handleExitPlanMode(planFilePath) - ); - this.plugin.agentService.setEnterPlanModeCallback( - () => this.inputController.handleEnterPlanMode() - ); - this.navigationController = new NavigationController({ - getMessagesEl: () => this.messagesEl, - getInputEl: () => this.inputEl, - getSettings: () => this.plugin.settings.keyboardNavigation, - isStreaming: () => this.state.isStreaming, - shouldSkipEscapeHandling: () => { - var _a2, _b, _c; - if ((_a2 = this.instructionModeManager) == null ? void 0 : _a2.isActive()) return true; - if ((_b = this.slashCommandDropdown) == null ? void 0 : _b.isVisible()) return true; - if ((_c = this.fileContextManager) == null ? void 0 : _c.isMentionDropdownVisible()) return true; - return false; - } - }); - this.navigationController.initialize(); - } - // ============================================ - // Event Wiring - // ============================================ - wireEventHandlers() { - this.registerDomEvent(document, "click", () => { - var _a; - (_a = this.historyDropdown) == null ? void 0 : _a.removeClass("visible"); - }); - this.registerDomEvent(document, "keydown", (e) => { - var _a; - if (e.key === "Escape" && this.state.isStreaming) { - e.preventDefault(); - (_a = this.inputController) == null ? void 0 : _a.cancelStreaming(); - } - }); - this.registerEvent(this.plugin.app.vault.on("create", () => { - var _a; - return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty(); - })); - this.registerEvent(this.plugin.app.vault.on("delete", () => { - var _a; - return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty(); - })); - this.registerEvent(this.plugin.app.vault.on("rename", () => { - var _a; - return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty(); - })); - this.registerEvent(this.plugin.app.vault.on("modify", () => { - var _a; - return (_a = this.fileContextManager) == null ? void 0 : _a.markFilesCacheDirty(); - })); - this.registerEvent( - this.plugin.app.workspace.on("file-open", (file) => { - var _a; - if (file) { - (_a = this.fileContextManager) == null ? void 0 : _a.handleFileOpen(file); - } - }) - ); - this.registerDomEvent(document, "click", (e) => { - var _a, _b; - if (!((_a = this.fileContextManager) == null ? void 0 : _a.containsElement(e.target)) && e.target !== this.inputEl) { - (_b = this.fileContextManager) == null ? void 0 : _b.hideMentionDropdown(); - } - }); - this.inputEl.addEventListener("keydown", (e) => { - var _a; - if (e.key === "Tab" && e.shiftKey && !this.state.isStreaming) { - e.preventDefault(); - e.stopPropagation(); - (_a = this.permissionToggle) == null ? void 0 : _a.togglePlanMode(); - } - }, { capture: true }); - this.inputEl.addEventListener("keydown", (e) => { - var _a, _b, _c, _d, _e, _f, _g, _h; - if ((_a = this.instructionModeManager) == null ? void 0 : _a.handleTriggerKey(e)) { - return; - } - if ((_b = this.instructionModeManager) == null ? void 0 : _b.handleKeydown(e)) { - return; - } - if ((_c = this.slashCommandDropdown) == null ? void 0 : _c.handleKeydown(e)) { - return; - } - if ((_d = this.fileContextManager) == null ? void 0 : _d.handleMentionKeydown(e)) { - return; - } - if (e.key === "Escape" && this.state.isStreaming) { - e.preventDefault(); - (_e = this.inputController) == null ? void 0 : _e.cancelStreaming(); - return; - } - if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { - e.preventDefault(); - if ((_f = this.permissionToggle) == null ? void 0 : _f.isPlanModeActive()) { - void ((_g = this.inputController) == null ? void 0 : _g.sendPlanModeMessage()); - } else { - void ((_h = this.inputController) == null ? void 0 : _h.sendMessage()); - } - } - }); - this.inputEl.addEventListener("input", () => { - var _a, _b; - (_a = this.fileContextManager) == null ? void 0 : _a.handleInputChange(); - (_b = this.instructionModeManager) == null ? void 0 : _b.handleInputChange(); - }); - this.inputEl.addEventListener("focus", () => { - var _a; - (_a = this.selectionController) == null ? void 0 : _a.showHighlight(); - }); - } - // ============================================ - // Utilities - // ============================================ - generateId() { - return `msg-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`; - } - updatePlanModeUiState() { - var _a; - const isPlanMode = this.plugin.settings.permissionMode === "plan"; - const isPlanModeRequested = this.state.planModeRequested; - (_a = this.permissionToggle) == null ? void 0 : _a.setPlanModeActive(isPlanMode || isPlanModeRequested); - } -}; - -// src/core/mcp/McpServerManager.ts -var McpServerManager = class { - constructor(storage) { - this.servers = []; - this.storage = storage; - } - /** Load servers from storage. */ - async loadServers() { - this.servers = await this.storage.load(); - } - /** Get all loaded servers. */ - getServers() { - return this.servers; - } - /** Get enabled servers count. */ - getEnabledCount() { - return this.servers.filter((s) => s.enabled).length; - } - /** - * Get servers to include in SDK options. - * - * A server is included if: - * - It is enabled AND - * - Either context-saving is disabled OR the server is @-mentioned - * - * @param mentionedNames Set of server names that were @-mentioned in the prompt - */ - getActiveServers(mentionedNames) { - const result = {}; - for (const server of this.servers) { - if (!server.enabled) continue; - if (server.contextSaving && !mentionedNames.has(server.name)) { - continue; - } - result[server.name] = server.config; - } - return result; - } - /** - * Get disabled MCP tools formatted for SDK disallowedTools option. - * - * Only returns disabled tools from servers that would be active (same filter as getActiveServers). - * - * @param mentionedNames Set of server names that were @-mentioned in the prompt - */ - getDisallowedMcpTools(mentionedNames) { - const disallowed = /* @__PURE__ */ new Set(); - for (const server of this.servers) { - if (!server.enabled) continue; - if (server.contextSaving && !mentionedNames.has(server.name)) { - continue; - } - if (!server.disabledTools || server.disabledTools.length === 0) continue; - for (const tool of server.disabledTools) { - const normalized = tool.trim(); - if (!normalized) continue; - disallowed.add(`mcp__${server.name}__${normalized}`); - } - } - return Array.from(disallowed); - } - /** Check if any MCP servers are configured. */ - hasServers() { - return this.servers.length > 0; - } -}; - -// src/features/mcp/McpService.ts -var McpService = class { - constructor(plugin) { - this.manager = new McpServerManager(plugin.storage.mcp); - } - // ============================================ - // Delegated to McpServerManager (core) - // ============================================ - /** Load servers from storage. */ - async loadServers() { - return this.manager.loadServers(); - } - /** Get all loaded servers. */ - getServers() { - return this.manager.getServers(); - } - /** Get enabled servers count. */ - getEnabledCount() { - return this.manager.getEnabledCount(); - } - /** Get servers to include in SDK options. */ - getActiveServers(mentionedNames) { - return this.manager.getActiveServers(mentionedNames); - } - /** Check if any MCP servers are configured. */ - hasServers() { - return this.manager.hasServers(); - } - // ============================================ - // Feature-specific: @-mention detection & UI - // ============================================ - /** Get all server names for @-mention validation. */ - getServerNames() { - return this.manager.getServers().map((s) => s.name); - } - /** Get enabled server names for @-mention validation. */ - getEnabledServerNames() { - return this.manager.getServers().filter((s) => s.enabled).map((s) => s.name); - } - /** Get servers with context-saving enabled (for @-mention autocomplete). */ - getContextSavingServers() { - return this.manager.getServers().filter((s) => s.enabled && s.contextSaving); - } - /** Check if a server name is valid for @-mention. */ - isValidMcpMention(name) { - return this.manager.getServers().some((s) => s.name === name && s.enabled && s.contextSaving); - } - /** - * Extract MCP mentions from text. - * Only matches against enabled servers with context-saving mode. - */ - extractMentions(text) { - const validNames = new Set( - this.manager.getServers().filter((s) => s.enabled && s.contextSaving).map((s) => s.name) - ); - return extractMcpMentions(text, validNames); - } - /** Check if any context-saving servers are enabled. */ - hasContextSavingServers() { - return this.manager.getServers().some((s) => s.enabled && s.contextSaving); - } - /** - * Transform MCP mentions in text by appending " MCP" after each valid @mention. - * This is applied to API requests only, not shown in UI. - */ - transformMentions(text) { - const validNames = new Set( - this.manager.getServers().filter((s) => s.enabled && s.contextSaving).map((s) => s.name) - ); - return transformMcpMentions(text, validNames); - } - // ============================================ - // Access to underlying manager (for core layer) - // ============================================ - /** Get the underlying server manager. */ - getManager() { - return this.manager; - } -}; - -// src/features/settings/ClaudianSettings.ts -var fs9 = __toESM(require("fs")); -var import_obsidian26 = require("obsidian"); - -// src/features/settings/keyboardNavigation.ts -var NAV_ACTIONS = ["scrollUp", "scrollDown", "focusInput"]; -var buildNavMappingText = (settings) => { - return [ - `map ${settings.scrollUpKey} scrollUp`, - `map ${settings.scrollDownKey} scrollDown`, - `map ${settings.focusInputKey} focusInput` - ].join("\n"); -}; -var parseNavMappings = (value) => { - const parsed = {}; - const usedKeys = /* @__PURE__ */ new Map(); - const lines = value.split("\n"); - for (const rawLine of lines) { - const line = rawLine.trim(); - if (!line) continue; - const parts = line.split(/\s+/); - if (parts.length !== 3 || parts[0] !== "map") { - return { error: 'Each line must follow "map "' }; - } - const key = parts[1]; - const action = parts[2]; - if (!NAV_ACTIONS.includes(action)) { - return { error: `Unknown action: ${parts[2]}` }; - } - if (key.length !== 1) { - return { error: `Key must be a single character for ${action}` }; - } - const normalizedKey = key.toLowerCase(); - if (usedKeys.has(normalizedKey)) { - return { error: "Navigation keys must be unique" }; - } - if (parsed[action]) { - return { error: `Duplicate mapping for ${action}` }; - } - usedKeys.set(normalizedKey, action); - parsed[action] = key; - } - const missing = NAV_ACTIONS.filter((action) => !parsed[action]); - if (missing.length > 0) { - return { error: `Missing mapping for ${missing.join(", ")}` }; - } - return { settings: parsed }; -}; - // src/features/settings/ClaudianSettings.ts function formatHotkey(hotkey) { const isMac = navigator.platform.includes("Mac"); @@ -38600,10 +65512,10 @@ function openHotkeySettings(app) { setting.open(); setting.openTabById("hotkeys"); setTimeout(() => { - var _a, _b, _c; + var _a3, _b, _c; const tab = setting.activeTab; if (tab) { - const searchEl = (_b = tab.searchInputEl) != null ? _b : (_a = tab.searchComponent) == null ? void 0 : _a.inputEl; + const searchEl = (_b = tab.searchInputEl) != null ? _b : (_a3 = tab.searchComponent) == null ? void 0 : _a3.inputEl; if (searchEl) { searchEl.value = "Claudian"; (_c = tab.updateHotkeyVisibility) == null ? void 0 : _c.call(tab); @@ -38612,32 +65524,59 @@ function openHotkeySettings(app) { }, 100); } function getHotkeyForCommand(app, commandId) { - var _a, _b; + var _a3, _b; const hotkeyManager = app.hotkeyManager; if (!hotkeyManager) return null; - const customHotkeys = (_a = hotkeyManager.customKeys) == null ? void 0 : _a[commandId]; + const customHotkeys = (_a3 = hotkeyManager.customKeys) == null ? void 0 : _a3[commandId]; const defaultHotkeys = (_b = hotkeyManager.defaultKeys) == null ? void 0 : _b[commandId]; const hotkeys = (customHotkeys == null ? void 0 : customHotkeys.length) > 0 ? customHotkeys : defaultHotkeys; if (!hotkeys || hotkeys.length === 0) return null; return hotkeys.map(formatHotkey).join(", "); } -var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { +function addHotkeySettingRow(containerEl, app, commandId, translationPrefix) { + const hotkey = getHotkeyForCommand(app, commandId); + const item = containerEl.createDiv({ cls: "claudian-hotkey-item" }); + item.createSpan({ cls: "claudian-hotkey-name", text: t(`${translationPrefix}.name`) }); + if (hotkey) { + item.createSpan({ cls: "claudian-hotkey-badge", text: hotkey }); + } + item.addEventListener("click", () => openHotkeySettings(app)); +} +var ClaudianSettingTab = class extends import_obsidian29.PluginSettingTab { constructor(app, plugin) { super(app, plugin); + this.contextLimitsContainer = null; this.plugin = plugin; } display() { const { containerEl } = this; containerEl.empty(); containerEl.addClass("claudian-settings"); - new import_obsidian26.Setting(containerEl).setName("Customization").setHeading(); - new import_obsidian26.Setting(containerEl).setName("What should Claudian call you?").setDesc("Your name for personalized greetings (leave empty for generic greetings)").addText( - (text) => text.setPlaceholder("Enter your name").setValue(this.plugin.settings.userName).onChange(async (value) => { + setLocale(this.plugin.settings.locale); + new import_obsidian29.Setting(containerEl).setName(t("settings.language.name")).setDesc(t("settings.language.desc")).addDropdown((dropdown) => { + const locales = getAvailableLocales(); + for (const locale of locales) { + dropdown.addOption(locale, getLocaleDisplayName(locale)); + } + dropdown.setValue(this.plugin.settings.locale).onChange(async (value) => { + if (!setLocale(value)) { + dropdown.setValue(this.plugin.settings.locale); + return; + } + this.plugin.settings.locale = value; + await this.plugin.saveSettings(); + this.display(); + }); + }); + new import_obsidian29.Setting(containerEl).setName(t("settings.customization")).setHeading(); + new import_obsidian29.Setting(containerEl).setName(t("settings.userName.name")).setDesc(t("settings.userName.desc")).addText((text) => { + text.setPlaceholder(t("settings.userName.name")).setValue(this.plugin.settings.userName).onChange(async (value) => { this.plugin.settings.userName = value; await this.plugin.saveSettings(); - }) - ); - new import_obsidian26.Setting(containerEl).setName("Excluded tags").setDesc("Notes with these tags will not auto-load as context (one per line, without #)").addTextArea((text) => { + }); + text.inputEl.addEventListener("blur", () => this.restartServiceForPromptChange()); + }); + new import_obsidian29.Setting(containerEl).setName(t("settings.excludedTags.name")).setDesc(t("settings.excludedTags.desc")).addTextArea((text) => { text.setPlaceholder("system\nprivate\ndraft").setValue(this.plugin.settings.excludedTags.join("\n")).onChange(async (value) => { this.plugin.settings.excludedTags = value.split(/\r?\n/).map((s) => s.trim().replace(/^#/, "")).filter((s) => s.length > 0); await this.plugin.saveSettings(); @@ -38645,22 +65584,33 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { text.inputEl.rows = 4; text.inputEl.cols = 30; }); - new import_obsidian26.Setting(containerEl).setName("Media folder").setDesc("Folder containing attachments/images. When notes use ![[image.jpg]], Claude will look here. Leave empty for vault root.").addText((text) => { + new import_obsidian29.Setting(containerEl).setName(t("settings.mediaFolder.name")).setDesc(t("settings.mediaFolder.desc")).addText((text) => { text.setPlaceholder("attachments").setValue(this.plugin.settings.mediaFolder).onChange(async (value) => { this.plugin.settings.mediaFolder = value.trim(); await this.plugin.saveSettings(); }); text.inputEl.addClass("claudian-settings-media-input"); + text.inputEl.addEventListener("blur", () => this.restartServiceForPromptChange()); }); - new import_obsidian26.Setting(containerEl).setName("Custom system prompt").setDesc("Additional instructions appended to the default system prompt").addTextArea((text) => { - text.setPlaceholder("Add custom instructions here...").setValue(this.plugin.settings.systemPrompt).onChange(async (value) => { + new import_obsidian29.Setting(containerEl).setName(t("settings.systemPrompt.name")).setDesc(t("settings.systemPrompt.desc")).addTextArea((text) => { + text.setPlaceholder(t("settings.systemPrompt.name")).setValue(this.plugin.settings.systemPrompt).onChange(async (value) => { this.plugin.settings.systemPrompt = value; await this.plugin.saveSettings(); }); text.inputEl.rows = 6; text.inputEl.cols = 50; + text.inputEl.addEventListener("blur", () => this.restartServiceForPromptChange()); }); - new import_obsidian26.Setting(containerEl).setName("Auto-generate conversation titles").setDesc("Automatically generate conversation titles after the first exchange.").addToggle( + new import_obsidian29.Setting(containerEl).setName(t("settings.enableAutoScroll.name")).setDesc(t("settings.enableAutoScroll.desc")).addToggle( + (toggle) => { + var _a3; + return toggle.setValue((_a3 = this.plugin.settings.enableAutoScroll) != null ? _a3 : true).onChange(async (value) => { + this.plugin.settings.enableAutoScroll = value; + await this.plugin.saveSettings(); + }); + } + ); + new import_obsidian29.Setting(containerEl).setName(t("settings.autoTitle.name")).setDesc(t("settings.autoTitle.desc")).addToggle( (toggle) => toggle.setValue(this.plugin.settings.enableAutoTitleGeneration).onChange(async (value) => { this.plugin.settings.enableAutoTitleGeneration = value; await this.plugin.saveSettings(); @@ -38668,8 +65618,8 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { }) ); if (this.plugin.settings.enableAutoTitleGeneration) { - new import_obsidian26.Setting(containerEl).setName("Title generation model").setDesc("Model used for auto-generating conversation titles.").addDropdown((dropdown) => { - dropdown.addOption("", "Auto (Haiku)"); + new import_obsidian29.Setting(containerEl).setName(t("settings.titleModel.name")).setDesc(t("settings.titleModel.desc")).addDropdown((dropdown) => { + dropdown.addOption("", t("settings.titleModel.auto")); const envVars = parseEnvironmentVariables(this.plugin.settings.environmentVariables); const customModels = getModelsFromEnvironment(envVars); const models = customModels.length > 0 ? customModels : DEFAULT_CLAUDE_MODELS; @@ -38682,7 +65632,7 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { }); }); } - new import_obsidian26.Setting(containerEl).setName("Vim-style navigation mappings").setDesc('One mapping per line. Format: "map " (actions: scrollUp, scrollDown, focusInput).').addTextArea((text) => { + new import_obsidian29.Setting(containerEl).setName(t("settings.navMappings.name")).setDesc(t("settings.navMappings.desc")).addTextArea((text) => { let pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation); let saveTimeout = null; const commitValue = async (showError) => { @@ -38693,7 +65643,7 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { const result = parseNavMappings(pendingValue); if (!result.settings) { if (showError) { - new import_obsidian26.Notice(`Invalid navigation mappings: ${result.error}`); + new import_obsidian29.Notice(`${t("common.error")}: ${result.error}`); pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation); text.setValue(pendingValue); } @@ -38723,35 +65673,83 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { await commitValue(true); }); }); - new import_obsidian26.Setting(containerEl).setName("Hotkeys").setHeading(); - const inlineEditCommandId = "claudian:inline-edit"; - const inlineEditHotkey = getHotkeyForCommand(this.app, inlineEditCommandId); - new import_obsidian26.Setting(containerEl).setName("Inline edit hotkey").setDesc(inlineEditHotkey ? `Current: ${inlineEditHotkey}` : "No hotkey set. Click to configure.").addButton( - (button) => button.setButtonText(inlineEditHotkey ? "Change" : "Set hotkey").onClick(() => openHotkeySettings(this.app)) + new import_obsidian29.Setting(containerEl).setName(t("settings.tabBarPosition.name")).setDesc(t("settings.tabBarPosition.desc")).addDropdown((dropdown) => { + var _a3; + dropdown.addOption("input", t("settings.tabBarPosition.input")).addOption("header", t("settings.tabBarPosition.header")).setValue((_a3 = this.plugin.settings.tabBarPosition) != null ? _a3 : "input").onChange(async (value) => { + this.plugin.settings.tabBarPosition = value; + await this.plugin.saveSettings(); + for (const leaf of this.plugin.app.workspace.getLeavesOfType("claudian-view")) { + if (leaf.view instanceof ClaudianView) { + leaf.view.updateLayoutForPosition(); + } + } + }); + }); + new import_obsidian29.Setting(containerEl).setName(t("settings.openInMainTab.name")).setDesc(t("settings.openInMainTab.desc")).addToggle( + (toggle) => toggle.setValue(this.plugin.settings.openInMainTab).onChange(async (value) => { + this.plugin.settings.openInMainTab = value; + await this.plugin.saveSettings(); + }) ); - const openChatCommandId = "claudian:open-chat"; - const openChatHotkey = getHotkeyForCommand(this.app, openChatCommandId); - new import_obsidian26.Setting(containerEl).setName("Open chat hotkey").setDesc(openChatHotkey ? `Current: ${openChatHotkey}` : "No hotkey set. Click to configure.").addButton( - (button) => button.setButtonText(openChatHotkey ? "Change" : "Set hotkey").onClick(() => openHotkeySettings(this.app)) - ); - new import_obsidian26.Setting(containerEl).setName("Slash Commands").setHeading(); - const slashCommandsDesc = containerEl.createDiv({ cls: "claudian-slash-settings-desc" }); - slashCommandsDesc.createEl("p", { - text: "Create custom prompt templates triggered by /command. Use $ARGUMENTS for all arguments, $1/$2 for positional args, @file for file content, and !`bash` for command output.", - cls: "setting-item-description" + new import_obsidian29.Setting(containerEl).setName(t("settings.hotkeys")).setHeading(); + const hotkeyGrid = containerEl.createDiv({ cls: "claudian-hotkey-grid" }); + addHotkeySettingRow(hotkeyGrid, this.app, "claudian:inline-edit", "settings.inlineEditHotkey"); + addHotkeySettingRow(hotkeyGrid, this.app, "claudian:open-view", "settings.openChatHotkey"); + addHotkeySettingRow(hotkeyGrid, this.app, "claudian:new-session", "settings.newSessionHotkey"); + addHotkeySettingRow(hotkeyGrid, this.app, "claudian:new-tab", "settings.newTabHotkey"); + addHotkeySettingRow(hotkeyGrid, this.app, "claudian:close-current-tab", "settings.closeTabHotkey"); + new import_obsidian29.Setting(containerEl).setName(t("settings.slashCommands.name")).setHeading(); + const slashCommandsDesc = containerEl.createDiv({ cls: "claudian-sp-settings-desc" }); + const descP = slashCommandsDesc.createEl("p", { cls: "setting-item-description" }); + descP.appendText(t("settings.slashCommands.desc") + " "); + descP.createEl("a", { + text: "Learn more", + href: "https://code.claude.com/docs/en/skills" }); const slashCommandsContainer = containerEl.createDiv({ cls: "claudian-slash-commands-container" }); new SlashCommandSettings(slashCommandsContainer, this.plugin); - new import_obsidian26.Setting(containerEl).setName("MCP Servers").setHeading(); + new import_obsidian29.Setting(containerEl).setName(t("settings.hiddenSlashCommands.name")).setDesc(t("settings.hiddenSlashCommands.desc")).addTextArea((text) => { + text.setPlaceholder(t("settings.hiddenSlashCommands.placeholder")).setValue((this.plugin.settings.hiddenSlashCommands || []).join("\n")).onChange(async (value) => { + var _a3; + this.plugin.settings.hiddenSlashCommands = value.split(/\r?\n/).map((s) => s.trim().replace(/^\//, "")).filter((s) => s.length > 0); + await this.plugin.saveSettings(); + (_a3 = this.plugin.getView()) == null ? void 0 : _a3.updateHiddenSlashCommands(); + }); + text.inputEl.rows = 4; + text.inputEl.cols = 30; + }); + new import_obsidian29.Setting(containerEl).setName(t("settings.subagents.name")).setHeading(); + const agentsDesc = containerEl.createDiv({ cls: "claudian-sp-settings-desc" }); + agentsDesc.createEl("p", { + text: t("settings.subagents.desc"), + cls: "setting-item-description" + }); + const agentsContainer = containerEl.createDiv({ cls: "claudian-agents-container" }); + new AgentSettings(agentsContainer, this.plugin); + new import_obsidian29.Setting(containerEl).setName(t("settings.mcpServers.name")).setHeading(); const mcpDesc = containerEl.createDiv({ cls: "claudian-mcp-settings-desc" }); mcpDesc.createEl("p", { - text: "Configure Model Context Protocol servers to extend Claude's capabilities with external tools and data sources. Servers with context-saving mode require @mention to activate.", + text: t("settings.mcpServers.desc"), cls: "setting-item-description" }); const mcpContainer = containerEl.createDiv({ cls: "claudian-mcp-container" }); new McpSettingsManager(mcpContainer, this.plugin); - new import_obsidian26.Setting(containerEl).setName("Safety").setHeading(); - new import_obsidian26.Setting(containerEl).setName("Enable command blocklist").setDesc("Block potentially dangerous bash commands").addToggle( + new import_obsidian29.Setting(containerEl).setName(t("settings.plugins.name")).setHeading(); + const pluginsDesc = containerEl.createDiv({ cls: "claudian-plugin-settings-desc" }); + pluginsDesc.createEl("p", { + text: t("settings.plugins.desc"), + cls: "setting-item-description" + }); + const pluginsContainer = containerEl.createDiv({ cls: "claudian-plugins-container" }); + new PluginSettingsManager(pluginsContainer, this.plugin); + new import_obsidian29.Setting(containerEl).setName(t("settings.safety")).setHeading(); + new import_obsidian29.Setting(containerEl).setName(t("settings.loadUserSettings.name")).setDesc(t("settings.loadUserSettings.desc")).addToggle( + (toggle) => toggle.setValue(this.plugin.settings.loadUserClaudeSettings).onChange(async (value) => { + this.plugin.settings.loadUserClaudeSettings = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian29.Setting(containerEl).setName(t("settings.enableBlocklist.name")).setDesc(t("settings.enableBlocklist.desc")).addToggle( (toggle) => toggle.setValue(this.plugin.settings.enableBlocklist).onChange(async (value) => { this.plugin.settings.enableBlocklist = value; await this.plugin.saveSettings(); @@ -38760,7 +65758,7 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { const platformKey = getCurrentPlatformKey(); const isWindows2 = platformKey === "windows"; const platformLabel = isWindows2 ? "Windows" : "Unix"; - new import_obsidian26.Setting(containerEl).setName(`Blocked commands (${platformLabel})`).setDesc(`Patterns to block on ${platformLabel} (one per line). Supports regex.`).addTextArea((text) => { + new import_obsidian29.Setting(containerEl).setName(t("settings.blockedCommands.name", { platform: platformLabel })).setDesc(t("settings.blockedCommands.desc", { platform: platformLabel })).addTextArea((text) => { const placeholder = isWindows2 ? "del /s /q\nrd /s /q\nRemove-Item -Recurse -Force" : "rm -rf\nchmod 777\nmkfs"; text.setPlaceholder(placeholder).setValue(this.plugin.settings.blockedCommands[platformKey].join("\n")).onChange(async (value) => { this.plugin.settings.blockedCommands[platformKey] = value.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0); @@ -38770,7 +65768,7 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { text.inputEl.cols = 40; }); if (isWindows2) { - new import_obsidian26.Setting(containerEl).setName("Blocked commands (Unix/Git Bash)").setDesc("Unix patterns also blocked on Windows because Git Bash can invoke them.").addTextArea((text) => { + new import_obsidian29.Setting(containerEl).setName(t("settings.blockedCommands.unixName")).setDesc(t("settings.blockedCommands.unixDesc")).addTextArea((text) => { text.setPlaceholder("rm -rf\nchmod 777\nmkfs").setValue(this.plugin.settings.blockedCommands.unix.join("\n")).onChange(async (value) => { this.plugin.settings.blockedCommands.unix = value.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0); await this.plugin.saveSettings(); @@ -38779,7 +65777,7 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { text.inputEl.cols = 40; }); } - new import_obsidian26.Setting(containerEl).setName("Allowed export paths").setDesc("Paths outside the vault where files can be exported (one per line). Supports ~ for home directory.").addTextArea((text) => { + new import_obsidian29.Setting(containerEl).setName(t("settings.exportPaths.name")).setDesc(t("settings.exportPaths.desc")).addTextArea((text) => { const placeholder = process.platform === "win32" ? "~/Desktop\n~/Downloads\n%TEMP%" : "~/Desktop\n~/Downloads\n/tmp"; text.setPlaceholder(placeholder).setValue(this.plugin.settings.allowedExportPaths.join("\n")).onChange(async (value) => { this.plugin.settings.allowedExportPaths = value.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0); @@ -38787,58 +65785,71 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { }); text.inputEl.rows = 4; text.inputEl.cols = 40; + text.inputEl.addEventListener("blur", () => this.restartServiceForPromptChange()); }); - const approvedDesc = containerEl.createDiv({ cls: "claudian-approved-desc" }); - approvedDesc.createEl("p", { - text: 'Actions that have been permanently approved (via "Always Allow"). These will not require approval in Safe mode.', - cls: "setting-item-description" - }); - const permissions = this.plugin.settings.permissions; - if (permissions.length === 0) { - const emptyEl = containerEl.createDiv({ cls: "claudian-approved-empty" }); - emptyEl.setText('No approved actions yet. When you click "Always Allow" in the approval dialog, actions will appear here.'); - } else { - const listEl = containerEl.createDiv({ cls: "claudian-approved-list" }); - for (const action of permissions) { - const itemEl = listEl.createDiv({ cls: "claudian-approved-item" }); - const infoEl = itemEl.createDiv({ cls: "claudian-approved-item-info" }); - const toolEl = infoEl.createSpan({ cls: "claudian-approved-item-tool" }); - toolEl.setText(action.toolName); - const patternEl = infoEl.createDiv({ cls: "claudian-approved-item-pattern" }); - patternEl.setText(action.pattern); - const dateEl = infoEl.createSpan({ cls: "claudian-approved-item-date" }); - dateEl.setText(new Date(action.approvedAt).toLocaleDateString()); - const removeBtn = itemEl.createEl("button", { - text: "Remove", - cls: "claudian-approved-remove-btn" - }); - removeBtn.addEventListener("click", async () => { - this.plugin.settings.permissions = this.plugin.settings.permissions.filter((a) => a !== action); - await this.plugin.saveSettings(); - this.display(); - }); - } - new import_obsidian26.Setting(containerEl).setName("Clear all approved actions").setDesc("Remove all permanently approved actions").addButton( - (button) => button.setButtonText("Clear all").setWarning().onClick(async () => { - this.plugin.settings.permissions = []; - await this.plugin.saveSettings(); - this.display(); - }) - ); - } - new import_obsidian26.Setting(containerEl).setName("Environment").setHeading(); - new import_obsidian26.Setting(containerEl).setName("Custom variables").setDesc("Environment variables for Claude SDK (KEY=VALUE format, one per line)").addTextArea((text) => { - text.setPlaceholder("ANTHROPIC_API_KEY=your-key\nANTHROPIC_BASE_URL=https://api.example.com\nANTHROPIC_MODEL=custom-model").setValue(this.plugin.settings.environmentVariables).onChange(async (value) => { - await this.plugin.applyEnvironmentVariables(value); - }); + new import_obsidian29.Setting(containerEl).setName(t("settings.environment")).setHeading(); + new import_obsidian29.Setting(containerEl).setName(t("settings.customVariables.name")).setDesc(t("settings.customVariables.desc")).addTextArea((text) => { + text.setPlaceholder("ANTHROPIC_API_KEY=your-key\nANTHROPIC_BASE_URL=https://api.example.com\nANTHROPIC_MODEL=custom-model").setValue(this.plugin.settings.environmentVariables); text.inputEl.rows = 6; text.inputEl.cols = 50; text.inputEl.addClass("claudian-settings-env-textarea"); + text.inputEl.addEventListener("blur", async () => { + await this.plugin.applyEnvironmentVariables(text.inputEl.value); + this.renderContextLimitsSection(); + }); }); + this.contextLimitsContainer = containerEl.createDiv({ cls: "claudian-context-limits-container" }); + this.renderContextLimitsSection(); const envSnippetsContainer = containerEl.createDiv({ cls: "claudian-env-snippets-container" }); - new EnvSnippetManager(envSnippetsContainer, this.plugin); - new import_obsidian26.Setting(containerEl).setName("Advanced").setHeading(); - const cliPathSetting = new import_obsidian26.Setting(containerEl).setName("Claude CLI path").setDesc("Custom path to Claude Code CLI. Leave empty for auto-detection. Use cli.js path on Windows for npm installations."); + new EnvSnippetManager(envSnippetsContainer, this.plugin, () => { + this.renderContextLimitsSection(); + }); + new import_obsidian29.Setting(containerEl).setName(t("settings.advanced")).setHeading(); + new import_obsidian29.Setting(containerEl).setName(t("settings.show1MModel.name")).setDesc(t("settings.show1MModel.desc")).addToggle( + (toggle) => { + var _a3; + return toggle.setValue((_a3 = this.plugin.settings.show1MModel) != null ? _a3 : false).onChange(async (value) => { + var _a4; + this.plugin.settings.show1MModel = value; + await this.plugin.saveSettings(); + const view = (_a4 = this.plugin.app.workspace.getLeavesOfType("claudian-view")[0]) == null ? void 0 : _a4.view; + view == null ? void 0 : view.refreshModelSelector(); + }); + } + ); + new import_obsidian29.Setting(containerEl).setName(t("settings.enableChrome.name")).setDesc(t("settings.enableChrome.desc")).addToggle( + (toggle) => { + var _a3; + return toggle.setValue((_a3 = this.plugin.settings.enableChrome) != null ? _a3 : false).onChange(async (value) => { + this.plugin.settings.enableChrome = value; + await this.plugin.saveSettings(); + }); + } + ); + const maxTabsSetting = new import_obsidian29.Setting(containerEl).setName(t("settings.maxTabs.name")).setDesc(t("settings.maxTabs.desc")); + const maxTabsWarningEl = containerEl.createDiv({ cls: "claudian-max-tabs-warning" }); + maxTabsWarningEl.style.color = "var(--text-warning)"; + maxTabsWarningEl.style.fontSize = "0.85em"; + maxTabsWarningEl.style.marginTop = "-0.5em"; + maxTabsWarningEl.style.marginBottom = "0.5em"; + maxTabsWarningEl.style.display = "none"; + maxTabsWarningEl.setText(t("settings.maxTabs.warning")); + const updateMaxTabsWarning = (value) => { + maxTabsWarningEl.style.display = value > 5 ? "block" : "none"; + }; + maxTabsSetting.addSlider((slider) => { + var _a3, _b; + slider.setLimits(3, 10, 1).setValue((_a3 = this.plugin.settings.maxTabs) != null ? _a3 : 3).setDynamicTooltip().onChange(async (value) => { + this.plugin.settings.maxTabs = value; + await this.plugin.saveSettings(); + updateMaxTabsWarning(value); + }); + updateMaxTabsWarning((_b = this.plugin.settings.maxTabs) != null ? _b : 3); + }); + const hostnameKey = getHostnameKey(); + const platformDesc = process.platform === "win32" ? t("settings.cliPath.descWindows") : t("settings.cliPath.descUnix"); + const cliPathDescription = `${t("settings.cliPath.desc")} ${platformDesc}`; + const cliPathSetting = new import_obsidian29.Setting(containerEl).setName(`${t("settings.cliPath.name")} (${hostnameKey})`).setDesc(cliPathDescription); const validationEl = containerEl.createDiv({ cls: "claudian-cli-path-validation" }); validationEl.style.color = "var(--text-error)"; validationEl.style.fontSize = "0.85em"; @@ -38849,35 +65860,45 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { const trimmed = value.trim(); if (!trimmed) return null; const expandedPath = expandHomePath(trimmed); - if (!fs9.existsSync(expandedPath)) { - return "Path does not exist"; + if (!fs7.existsSync(expandedPath)) { + return t("settings.cliPath.validation.notExist"); } - const stat = fs9.statSync(expandedPath); + const stat = fs7.statSync(expandedPath); if (!stat.isFile()) { - return "Path is a directory, not a file"; + return t("settings.cliPath.validation.isDirectory"); } return null; }; cliPathSetting.addText((text) => { + var _a3; const placeholder = process.platform === "win32" ? "D:\\nodejs\\node_global\\node_modules\\@anthropic-ai\\claude-code\\cli.js" : "/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js"; - text.setPlaceholder(placeholder).setValue(this.plugin.settings.claudeCliPath || "").onChange(async (value) => { - var _a; - const error2 = validatePath(value); - if (error2) { - validationEl.setText(error2); + const currentValue = ((_a3 = this.plugin.settings.claudeCliPathsByHost) == null ? void 0 : _a3[hostnameKey]) || ""; + text.setPlaceholder(placeholder).setValue(currentValue).onChange(async (value) => { + var _a4, _b; + const error48 = validatePath(value); + if (error48) { + validationEl.setText(error48); validationEl.style.display = "block"; text.inputEl.style.borderColor = "var(--text-error)"; } else { validationEl.style.display = "none"; text.inputEl.style.borderColor = ""; } - this.plugin.settings.claudeCliPath = value.trim(); + const trimmed = value.trim(); + if (!this.plugin.settings.claudeCliPathsByHost) { + this.plugin.settings.claudeCliPathsByHost = {}; + } + this.plugin.settings.claudeCliPathsByHost[hostnameKey] = trimmed; await this.plugin.saveSettings(); - (_a = this.plugin.agentService) == null ? void 0 : _a.cleanup(); + (_a4 = this.plugin.cliResolver) == null ? void 0 : _a4.reset(); + const view = this.plugin.getView(); + await ((_b = view == null ? void 0 : view.getTabManager()) == null ? void 0 : _b.broadcastToAllTabs( + (service) => Promise.resolve(service.cleanup()) + )); }); text.inputEl.addClass("claudian-settings-cli-path-input"); text.inputEl.style.width = "100%"; - const initialError = validatePath(this.plugin.settings.claudeCliPath || ""); + const initialError = validatePath(currentValue); if (initialError) { validationEl.setText(initialError); validationEl.style.display = "block"; @@ -38885,22 +65906,489 @@ var ClaudianSettingTab = class extends import_obsidian26.PluginSettingTab { } }); } + renderContextLimitsSection() { + var _a3; + const container = this.contextLimitsContainer; + if (!container) return; + container.empty(); + const envVars = parseEnvironmentVariables(this.plugin.settings.environmentVariables); + const uniqueModelIds = getCustomModelIds(envVars); + if (uniqueModelIds.size === 0) { + return; + } + const headerEl = container.createDiv({ cls: "claudian-context-limits-header" }); + headerEl.createSpan({ text: t("settings.customContextLimits.name"), cls: "claudian-context-limits-label" }); + const descEl = container.createDiv({ cls: "claudian-context-limits-desc" }); + descEl.setText(t("settings.customContextLimits.desc")); + const listEl = container.createDiv({ cls: "claudian-context-limits-list" }); + for (const modelId of uniqueModelIds) { + const currentValue = (_a3 = this.plugin.settings.customContextLimits) == null ? void 0 : _a3[modelId]; + const itemEl = listEl.createDiv({ cls: "claudian-context-limits-item" }); + const nameEl = itemEl.createDiv({ cls: "claudian-context-limits-model" }); + nameEl.setText(modelId); + const inputWrapper = itemEl.createDiv({ cls: "claudian-context-limits-input-wrapper" }); + const inputEl = inputWrapper.createEl("input", { + type: "text", + placeholder: "200k", + cls: "claudian-context-limits-input", + value: currentValue ? formatContextLimit(currentValue) : "" + }); + const validationEl = inputWrapper.createDiv({ cls: "claudian-context-limit-validation" }); + inputEl.addEventListener("input", async () => { + const trimmed = inputEl.value.trim(); + if (!this.plugin.settings.customContextLimits) { + this.plugin.settings.customContextLimits = {}; + } + if (!trimmed) { + delete this.plugin.settings.customContextLimits[modelId]; + validationEl.style.display = "none"; + inputEl.classList.remove("claudian-input-error"); + } else { + const parsed = parseContextLimit(trimmed); + if (parsed === null) { + validationEl.setText(t("settings.customContextLimits.invalid")); + validationEl.style.display = "block"; + inputEl.classList.add("claudian-input-error"); + return; + } + this.plugin.settings.customContextLimits[modelId] = parsed; + validationEl.style.display = "none"; + inputEl.classList.remove("claudian-input-error"); + } + await this.plugin.saveSettings(); + }); + } + } + async restartServiceForPromptChange() { + const view = this.plugin.getView(); + const tabManager = view == null ? void 0 : view.getTabManager(); + if (!tabManager) return; + try { + await tabManager.broadcastToAllTabs( + async (service) => { + await service.ensureReady({ force: true }); + } + ); + } catch (e2) { + } + } }; +// src/utils/claudeCli.ts +var fs8 = __toESM(require("fs")); +var ClaudeCliResolver = class { + constructor() { + this.resolvedPath = null; + this.lastHostnamePath = ""; + this.lastLegacyPath = ""; + this.lastEnvText = ""; + // Cache hostname since it doesn't change during a session + this.cachedHostname = getHostnameKey(); + } + /** + * Resolves CLI path with priority: hostname-specific -> legacy -> auto-detect. + * @param hostnamePaths Per-device CLI paths keyed by hostname (preferred) + * @param legacyPath Legacy claudeCliPath (for backwards compatibility) + * @param envText Environment variables text + */ + resolve(hostnamePaths, legacyPath, envText) { + var _a3; + const hostnameKey = this.cachedHostname; + const hostnamePath = ((_a3 = hostnamePaths == null ? void 0 : hostnamePaths[hostnameKey]) != null ? _a3 : "").trim(); + const normalizedLegacy = (legacyPath != null ? legacyPath : "").trim(); + const normalizedEnv = envText != null ? envText : ""; + if (this.resolvedPath && hostnamePath === this.lastHostnamePath && normalizedLegacy === this.lastLegacyPath && normalizedEnv === this.lastEnvText) { + return this.resolvedPath; + } + this.lastHostnamePath = hostnamePath; + this.lastLegacyPath = normalizedLegacy; + this.lastEnvText = normalizedEnv; + this.resolvedPath = resolveClaudeCliPath(hostnamePath, normalizedLegacy, normalizedEnv); + return this.resolvedPath; + } + reset() { + this.resolvedPath = null; + this.lastHostnamePath = ""; + this.lastLegacyPath = ""; + this.lastEnvText = ""; + } +}; +function resolveClaudeCliPath(hostnamePath, legacyPath, envText) { + const trimmedHostname = (hostnamePath != null ? hostnamePath : "").trim(); + if (trimmedHostname) { + try { + const expandedPath = expandHomePath(trimmedHostname); + if (fs8.existsSync(expandedPath)) { + const stat = fs8.statSync(expandedPath); + if (stat.isFile()) { + return expandedPath; + } + } + } catch (e2) { + } + } + const trimmedLegacy = (legacyPath != null ? legacyPath : "").trim(); + if (trimmedLegacy) { + try { + const expandedPath = expandHomePath(trimmedLegacy); + if (fs8.existsSync(expandedPath)) { + const stat = fs8.statSync(expandedPath); + if (stat.isFile()) { + return expandedPath; + } + } + } catch (e2) { + } + } + const customEnv = parseEnvironmentVariables(envText || ""); + return findClaudeCLIPath(customEnv.PATH); +} + +// src/utils/sdkSession.ts +var import_fs3 = require("fs"); +var fs9 = __toESM(require("fs/promises")); +var os5 = __toESM(require("os")); +var path9 = __toESM(require("path")); +function encodeVaultPathForSDK(vaultPath) { + const absolutePath = path9.resolve(vaultPath); + return absolutePath.replace(/[^a-zA-Z0-9]/g, "-"); +} +function getSDKProjectsPath() { + return path9.join(os5.homedir(), ".claude", "projects"); +} +function isValidSessionId(sessionId) { + if (!sessionId || sessionId.length === 0 || sessionId.length > 128) { + return false; + } + if (sessionId.includes("..") || sessionId.includes("/") || sessionId.includes("\\")) { + return false; + } + return /^[a-zA-Z0-9_-]+$/.test(sessionId); +} +function getSDKSessionPath(vaultPath, sessionId) { + if (!isValidSessionId(sessionId)) { + throw new Error(`Invalid session ID: ${sessionId}`); + } + const projectsPath = getSDKProjectsPath(); + const encodedVault = encodeVaultPathForSDK(vaultPath); + return path9.join(projectsPath, encodedVault, `${sessionId}.jsonl`); +} +function sdkSessionExists(vaultPath, sessionId) { + try { + const sessionPath = getSDKSessionPath(vaultPath, sessionId); + return (0, import_fs3.existsSync)(sessionPath); + } catch (e2) { + return false; + } +} +async function deleteSDKSession(vaultPath, sessionId) { + try { + const sessionPath = getSDKSessionPath(vaultPath, sessionId); + if (!(0, import_fs3.existsSync)(sessionPath)) return; + await fs9.unlink(sessionPath); + } catch (e2) { + } +} +async function readSDKSession(vaultPath, sessionId) { + try { + const sessionPath = getSDKSessionPath(vaultPath, sessionId); + if (!(0, import_fs3.existsSync)(sessionPath)) { + return { messages: [], skippedLines: 0 }; + } + const content = await fs9.readFile(sessionPath, "utf-8"); + const lines = content.split("\n").filter((line) => line.trim()); + const messages = []; + let skippedLines = 0; + for (const line of lines) { + try { + const msg = JSON.parse(line); + messages.push(msg); + } catch (e2) { + skippedLines++; + } + } + return { messages, skippedLines }; + } catch (error48) { + const errorMsg = error48 instanceof Error ? error48.message : String(error48); + return { messages: [], skippedLines: 0, error: errorMsg }; + } +} +function extractTextContent(content) { + if (!content) return ""; + if (typeof content === "string") return content; + return content.filter( + (block) => block.type === "text" && typeof block.text === "string" && block.text.trim() !== "(no content)" + ).map((block) => block.text).join("\n"); +} +function isRebuiltContextContent(textContent) { + if (!/^(User|Assistant):\s/.test(textContent)) return false; + return textContent.includes("\n\nUser:") || textContent.includes("\n\nAssistant:") || textContent.includes("\n\nA:"); +} +function extractDisplayContent(textContent) { + return extractContentBeforeXmlContext(textContent); +} +function extractImages(content) { + if (!content || typeof content === "string") return void 0; + const imageBlocks = content.filter( + (block) => { + var _a3; + return block.type === "image" && !!((_a3 = block.source) == null ? void 0 : _a3.data); + } + ); + if (imageBlocks.length === 0) return void 0; + return imageBlocks.map((block, index) => ({ + id: `sdk-img-${Date.now()}-${index}`, + name: `image-${index + 1}`, + mediaType: block.source.media_type, + data: block.source.data, + size: Math.ceil(block.source.data.length * 0.75), + // Approximate original size from base64 + source: "paste" + })); +} +function extractToolCalls(content, toolResults) { + var _a3; + if (!content || typeof content === "string") return void 0; + const toolUses = content.filter( + (block) => block.type === "tool_use" && !!block.id && !!block.name + ); + if (toolUses.length === 0) return void 0; + const results = toolResults != null ? toolResults : /* @__PURE__ */ new Map(); + if (!toolResults) { + for (const block of content) { + if (block.type === "tool_result" && block.tool_use_id) { + const resultContent = typeof block.content === "string" ? block.content : JSON.stringify(block.content); + results.set(block.tool_use_id, { + content: resultContent, + isError: (_a3 = block.is_error) != null ? _a3 : false + }); + } + } + } + return toolUses.map((block) => { + var _a4; + const result = results.get(block.id); + return { + id: block.id, + name: block.name, + input: (_a4 = block.input) != null ? _a4 : {}, + status: result ? result.isError ? "error" : "completed" : "completed", + result: result == null ? void 0 : result.content, + isExpanded: false + }; + }); +} +function mapContentBlocks(content) { + var _a3; + if (!content || typeof content === "string") return void 0; + const blocks = []; + for (const block of content) { + switch (block.type) { + case "text": { + const trimmed = (_a3 = block.text) == null ? void 0 : _a3.trim(); + if (trimmed && trimmed !== "(no content)") { + blocks.push({ type: "text", content: trimmed }); + } + break; + } + case "thinking": + if (block.thinking) { + blocks.push({ type: "thinking", content: block.thinking }); + } + break; + case "tool_use": + if (block.id) { + blocks.push({ type: "tool_use", toolId: block.id }); + } + break; + } + } + return blocks.length > 0 ? blocks : void 0; +} +function parseSDKMessageToChat(sdkMsg, toolResults) { + var _a3; + if (sdkMsg.type === "file-history-snapshot") return null; + if (sdkMsg.type === "system") { + if (sdkMsg.subtype === "compact_boundary") { + const timestamp2 = sdkMsg.timestamp ? new Date(sdkMsg.timestamp).getTime() : Date.now(); + return { + id: sdkMsg.uuid || `compact-${timestamp2}-${Math.random().toString(36).slice(2)}`, + role: "assistant", + content: "", + timestamp: timestamp2, + contentBlocks: [{ type: "compact_boundary" }] + }; + } + return null; + } + if (sdkMsg.type === "result") return null; + if (sdkMsg.type !== "user" && sdkMsg.type !== "assistant") return null; + const content = (_a3 = sdkMsg.message) == null ? void 0 : _a3.content; + const textContent = extractTextContent(content); + const images = sdkMsg.type === "user" ? extractImages(content) : void 0; + const hasToolUse = Array.isArray(content) && content.some((b3) => b3.type === "tool_use"); + const hasImages = images && images.length > 0; + if (!textContent && !hasToolUse && !hasImages && (!content || typeof content === "string")) return null; + const timestamp = sdkMsg.timestamp ? new Date(sdkMsg.timestamp).getTime() : Date.now(); + const isCompactCommand = sdkMsg.type === "user" && textContent.includes("/compact"); + let displayContent; + if (sdkMsg.type === "user") { + displayContent = isCompactCommand ? "/compact" : extractDisplayContent(textContent); + } + const isInterrupt = sdkMsg.type === "user" && (textContent === "[Request interrupted by user]" || textContent === "[Request interrupted by user for tool use]" || textContent.includes("") && textContent.includes("Compaction canceled")); + const isRebuiltContext = sdkMsg.type === "user" && isRebuiltContextContent(textContent); + return { + id: sdkMsg.uuid || `sdk-${timestamp}-${Math.random().toString(36).slice(2)}`, + role: sdkMsg.type, + content: textContent, + displayContent, + timestamp, + toolCalls: sdkMsg.type === "assistant" ? extractToolCalls(content, toolResults) : void 0, + contentBlocks: sdkMsg.type === "assistant" ? mapContentBlocks(content) : void 0, + images, + ...isInterrupt && { isInterrupt: true }, + ...isRebuiltContext && { isRebuiltContext: true } + }; +} +function collectToolResults(sdkMessages) { + var _a3, _b; + const results = /* @__PURE__ */ new Map(); + for (const sdkMsg of sdkMessages) { + const content = (_a3 = sdkMsg.message) == null ? void 0 : _a3.content; + if (!content || typeof content === "string") continue; + for (const block of content) { + if (block.type === "tool_result" && block.tool_use_id) { + const resultContent = typeof block.content === "string" ? block.content : JSON.stringify(block.content); + results.set(block.tool_use_id, { + content: resultContent, + isError: (_b = block.is_error) != null ? _b : false + }); + } + } + } + return results; +} +function collectStructuredPatchResults(sdkMessages) { + var _a3; + const results = /* @__PURE__ */ new Map(); + for (const sdkMsg of sdkMessages) { + if (sdkMsg.type !== "user" || !sdkMsg.toolUseResult) continue; + const content = (_a3 = sdkMsg.message) == null ? void 0 : _a3.content; + if (!content || typeof content === "string") continue; + for (const block of content) { + if (block.type === "tool_result" && block.tool_use_id) { + results.set(block.tool_use_id, sdkMsg.toolUseResult); + } + } + } + return results; +} +function isSystemInjectedMessage(sdkMsg) { + var _a3; + if (sdkMsg.type !== "user") return false; + if ("toolUseResult" in sdkMsg || "sourceToolUseID" in sdkMsg || !!sdkMsg.isMeta) { + return true; + } + const text = extractTextContent((_a3 = sdkMsg.message) == null ? void 0 : _a3.content); + if (!text) return false; + if (text.includes("/compact")) return false; + if (text.includes("") && text.includes("Compaction canceled")) return false; + if (text.startsWith("This session is being continued from a previous conversation")) return true; + if (text.includes("")) return true; + if (text.includes("") || text.includes("")) return true; + return false; +} +function mergeAssistantMessage(target, source) { + if (source.content) { + if (target.content) { + target.content = target.content + "\n\n" + source.content; + } else { + target.content = source.content; + } + } + if (source.toolCalls) { + target.toolCalls = [...target.toolCalls || [], ...source.toolCalls]; + } + if (source.contentBlocks) { + target.contentBlocks = [...target.contentBlocks || [], ...source.contentBlocks]; + } +} +async function loadSDKSessionMessages(vaultPath, sessionId) { + var _a3, _b; + const result = await readSDKSession(vaultPath, sessionId); + if (result.error) { + return { messages: [], skippedLines: result.skippedLines, error: result.error }; + } + const toolResults = collectToolResults(result.messages); + const toolUseResults = collectStructuredPatchResults(result.messages); + const chatMessages = []; + let pendingAssistant = null; + const seenUuids = /* @__PURE__ */ new Set(); + for (const sdkMsg of result.messages) { + if (sdkMsg.uuid) { + if (seenUuids.has(sdkMsg.uuid)) continue; + seenUuids.add(sdkMsg.uuid); + } + if (isSystemInjectedMessage(sdkMsg)) continue; + if (sdkMsg.type === "assistant" && ((_a3 = sdkMsg.message) == null ? void 0 : _a3.model) === "") continue; + const chatMsg = parseSDKMessageToChat(sdkMsg, toolResults); + if (!chatMsg) continue; + if (chatMsg.role === "assistant") { + const isCompactBoundary = (_b = chatMsg.contentBlocks) == null ? void 0 : _b.some((b3) => b3.type === "compact_boundary"); + if (isCompactBoundary) { + if (pendingAssistant) { + chatMessages.push(pendingAssistant); + } + chatMessages.push(chatMsg); + pendingAssistant = null; + } else if (pendingAssistant) { + mergeAssistantMessage(pendingAssistant, chatMsg); + } else { + pendingAssistant = chatMsg; + } + } else { + if (pendingAssistant) { + chatMessages.push(pendingAssistant); + pendingAssistant = null; + } + chatMessages.push(chatMsg); + } + } + if (pendingAssistant) { + chatMessages.push(pendingAssistant); + } + if (toolUseResults.size > 0) { + for (const msg of chatMessages) { + if (msg.role !== "assistant" || !msg.toolCalls) continue; + for (const toolCall of msg.toolCalls) { + const toolUseResult = toolUseResults.get(toolCall.id); + if (toolUseResult && !toolCall.diffData) { + toolCall.diffData = extractDiffData(toolUseResult, toolCall); + } + } + } + } + chatMessages.sort((a, b3) => a.timestamp - b3.timestamp); + return { messages: chatMessages, skippedLines: result.skippedLines }; +} + // src/main.ts -var ClaudianPlugin = class extends import_obsidian27.Plugin { +var ClaudianPlugin = class extends import_obsidian30.Plugin { constructor() { super(...arguments); this.conversations = []; - this.activeConversationId = null; this.runtimeEnvironmentVariables = ""; - this.hasNotifiedEnvChange = false; } async onload() { await this.loadSettings(); - this.mcpService = new McpService(this); - await this.mcpService.loadServers(); - this.agentService = new ClaudianService(this, this.mcpService.getManager()); + this.cliResolver = new ClaudeCliResolver(); + this.mcpManager = new McpServerManager(this.storage.mcp); + await this.mcpManager.loadServers(); + const vaultPath = this.app.vault.adapter.basePath; + this.pluginManager = new PluginManager(vaultPath, this.storage.ccSettings); + await this.pluginManager.loadPlugins(); + this.agentManager = new AgentManager(vaultPath, this.pluginManager); + await this.agentManager.loadAgents(); this.registerView( VIEW_TYPE_CLAUDIAN, (leaf) => new ClaudianView(leaf, this) @@ -38919,9 +66407,9 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { id: "inline-edit", name: "Inline edit", editorCallback: async (editor, view) => { - var _a; + var _a3; const selectedText = editor.getSelection(); - const notePath = ((_a = view.file) == null ? void 0 : _a.path) || "unknown"; + const notePath = ((_a3 = view.file) == null ? void 0 : _a3.path) || "unknown"; let editContext; if (selectedText.trim()) { editContext = { mode: "selection", selectedText }; @@ -38938,27 +66426,84 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { const modal = new InlineEditModal(this.app, this, editContext, notePath); const result = await modal.openAndWait(); if (result.decision === "accept" && result.editedText !== void 0) { - new import_obsidian27.Notice(editContext.mode === "cursor" ? "Inserted" : "Edit applied"); + new import_obsidian30.Notice(editContext.mode === "cursor" ? "Inserted" : "Edit applied"); } } }); + this.addCommand({ + id: "new-tab", + name: "New tab", + checkCallback: (checking) => { + const leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0]; + if (!leaf) return false; + const view = leaf.view; + const tabManager = view.getTabManager(); + if (!tabManager) return false; + if (!tabManager.canCreateTab()) return false; + if (!checking) { + tabManager.createTab(); + } + return true; + } + }); + this.addCommand({ + id: "new-session", + name: "New session (in current tab)", + checkCallback: (checking) => { + const leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0]; + if (!leaf) return false; + const view = leaf.view; + const tabManager = view.getTabManager(); + if (!tabManager) return false; + const activeTab = tabManager.getActiveTab(); + if (!activeTab) return false; + if (activeTab.state.isStreaming) return false; + if (!checking) { + tabManager.createNewConversation(); + } + return true; + } + }); + this.addCommand({ + id: "close-current-tab", + name: "Close current tab", + checkCallback: (checking) => { + const leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0]; + if (!leaf) return false; + const view = leaf.view; + const tabManager = view.getTabManager(); + if (!tabManager) return false; + if (!checking) { + const activeTabId = tabManager.getActiveTabId(); + if (activeTabId) { + tabManager.closeTab(activeTabId); + } + } + return true; + } + }); this.addSettingTab(new ClaudianSettingTab(this.app, this)); } - onunload() { - this.agentService.cleanup(); + async onunload() { + for (const view of this.getAllViews()) { + const tabManager = view.getTabManager(); + if (tabManager) { + const state = tabManager.getPersistedState(); + await this.storage.setTabManagerState(state); + } + } } - /** Opens the Claudian sidebar view, creating it if necessary. */ async activateView() { const { workspace } = this.app; let leaf = workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0]; if (!leaf) { - const rightLeaf = workspace.getRightLeaf(false); - if (rightLeaf) { - await rightLeaf.setViewState({ + const newLeaf = this.settings.openInMainTab ? workspace.getLeaf("tab") : workspace.getRightLeaf(false); + if (newLeaf) { + await newLeaf.setViewState({ type: VIEW_TYPE_CLAUDIAN, active: true }); - leaf = rightLeaf; + leaf = newLeaf; } } if (leaf) { @@ -38967,32 +66512,105 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { } /** Loads settings and conversations from persistent storage. */ async loadSettings() { + var _a3, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o; this.storage = new StorageService(this); - const { settings, state } = await this.storage.initialize(); - const slashCommands = await this.storage.commands.loadAll(); + const { claudian } = await this.storage.initialize(); + const slashCommands = await this.storage.loadAllSlashCommands(); this.settings = { ...DEFAULT_SETTINGS, - ...settings, - // State fields from data.json - lastEnvHash: state.lastEnvHash, - lastClaudeModel: state.lastClaudeModel, - lastCustomModel: state.lastCustomModel, + ...claudian, slashCommands }; - this.conversations = await this.storage.sessions.loadAllConversations(); - this.activeConversationId = state.activeConversationId; - if (this.activeConversationId && !this.conversations.find((c) => c.id === this.activeConversationId)) { - this.activeConversationId = null; + (_b = (_a3 = this.settings).claudeCliPathsByHost) != null ? _b : _a3.claudeCliPathsByHost = {}; + const hostname4 = getHostnameKey(); + let didMigrateCliPath = false; + if (!this.settings.claudeCliPathsByHost[hostname4]) { + const platformPaths = this.settings.claudeCliPaths; + const migratedPath = ((_c = platformPaths == null ? void 0 : platformPaths[getCliPlatformKey()]) == null ? void 0 : _c.trim()) || ((_d = this.settings.claudeCliPath) == null ? void 0 : _d.trim()); + if (migratedPath) { + this.settings.claudeCliPathsByHost[hostname4] = migratedPath; + this.settings.claudeCliPath = ""; + didMigrateCliPath = true; + } } + delete this.settings.claudeCliPaths; + const { conversations: legacyConversations, failedCount } = await this.storage.sessions.loadAllConversations(); + const legacyIds = new Set(legacyConversations.map((c3) => c3.id)); + for (const conversation of legacyConversations) { + const meta3 = await this.storage.sessions.loadMetadata(conversation.id); + if (!meta3) continue; + conversation.isNative = true; + conversation.title = (_e = meta3.title) != null ? _e : conversation.title; + conversation.titleGenerationStatus = (_f = meta3.titleGenerationStatus) != null ? _f : conversation.titleGenerationStatus; + conversation.createdAt = (_g = meta3.createdAt) != null ? _g : conversation.createdAt; + conversation.updatedAt = (_h = meta3.updatedAt) != null ? _h : conversation.updatedAt; + conversation.lastResponseAt = (_i = meta3.lastResponseAt) != null ? _i : conversation.lastResponseAt; + if (meta3.sessionId !== void 0) { + conversation.sessionId = meta3.sessionId; + } + conversation.currentNote = (_j = meta3.currentNote) != null ? _j : conversation.currentNote; + conversation.externalContextPaths = (_k = meta3.externalContextPaths) != null ? _k : conversation.externalContextPaths; + conversation.enabledMcpServers = (_l = meta3.enabledMcpServers) != null ? _l : conversation.enabledMcpServers; + conversation.usage = (_m = meta3.usage) != null ? _m : conversation.usage; + if (meta3.sdkSessionId !== void 0) { + conversation.sdkSessionId = meta3.sdkSessionId; + } else if (conversation.sdkSessionId === void 0 && conversation.sessionId) { + conversation.sdkSessionId = conversation.sessionId; + } + conversation.previousSdkSessionIds = (_n = meta3.previousSdkSessionIds) != null ? _n : conversation.previousSdkSessionIds; + conversation.legacyCutoffAt = (_o = meta3.legacyCutoffAt) != null ? _o : conversation.legacyCutoffAt; + } + const nativeMetadata = await this.storage.sessions.listNativeMetadata(); + const nativeConversations = nativeMetadata.filter((meta3) => !legacyIds.has(meta3.id)).map((meta3) => { + const resumeSessionId = meta3.sessionId !== void 0 ? meta3.sessionId : meta3.id; + const sdkSessionId = meta3.sdkSessionId !== void 0 ? meta3.sdkSessionId : resumeSessionId != null ? resumeSessionId : void 0; + return { + id: meta3.id, + title: meta3.title, + createdAt: meta3.createdAt, + updatedAt: meta3.updatedAt, + lastResponseAt: meta3.lastResponseAt, + sessionId: resumeSessionId, + sdkSessionId, + previousSdkSessionIds: meta3.previousSdkSessionIds, + messages: [], + // Messages are in SDK storage, loaded on demand + currentNote: meta3.currentNote, + externalContextPaths: meta3.externalContextPaths, + enabledMcpServers: meta3.enabledMcpServers, + usage: meta3.usage, + titleGenerationStatus: meta3.titleGenerationStatus, + legacyCutoffAt: meta3.legacyCutoffAt, + isNative: true, + subagentData: meta3.subagentData + // Preserve for applying to loaded messages + }; + }); + this.conversations = [...legacyConversations, ...nativeConversations].sort( + (a, b3) => { + var _a4, _b2; + return ((_a4 = b3.lastResponseAt) != null ? _a4 : b3.updatedAt) - ((_b2 = a.lastResponseAt) != null ? _b2 : a.updatedAt); + } + ); + if (failedCount > 0) { + new import_obsidian30.Notice(`Failed to load ${failedCount} conversation${failedCount > 1 ? "s" : ""}`); + } + setLocale(this.settings.locale); const backfilledConversations = this.backfillConversationResponseTimestamps(); this.runtimeEnvironmentVariables = this.settings.environmentVariables || ""; const { changed, invalidatedConversations } = this.reconcileModelWithEnvironment(this.runtimeEnvironmentVariables); - if (changed) { + if (changed || didMigrateCliPath) { await this.saveSettings(); } const conversationsToSave = /* @__PURE__ */ new Set([...backfilledConversations, ...invalidatedConversations]); for (const conv of conversationsToSave) { - await this.storage.sessions.saveConversation(conv); + if (conv.isNative) { + await this.storage.sessions.saveMetadata( + this.storage.sessions.toSessionMetadata(conv) + ); + } else { + await this.storage.sessions.saveConversation(conv); + } } } backfillConversationResponseTimestamps() { @@ -39000,8 +66618,8 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { for (const conv of this.conversations) { if (conv.lastResponseAt != null) continue; if (!conv.messages || conv.messages.length === 0) continue; - for (let i = conv.messages.length - 1; i >= 0; i--) { - const msg = conv.messages[i]; + for (let i2 = conv.messages.length - 1; i2 >= 0; i2--) { + const msg = conv.messages[i2]; if (msg.role === "assistant") { conv.lastResponseAt = msg.timestamp; updated.push(conv); @@ -39015,36 +66633,87 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { async saveSettings() { const { slashCommands: _, - lastEnvHash: __, - lastClaudeModel: ___, - lastCustomModel: ____, ...settingsToSave } = this.settings; - await this.storage.settings.save(settingsToSave); - await this.storage.saveState({ - activeConversationId: this.activeConversationId, - lastEnvHash: this.settings.lastEnvHash || "", - lastClaudeModel: this.settings.lastClaudeModel || "haiku", - lastCustomModel: this.settings.lastCustomModel || "" - }); + await this.storage.saveClaudianSettings(settingsToSave); } - /** Updates and persists environment variables, notifying if restart is needed. */ + /** Updates and persists environment variables, restarting processes to apply changes. */ async applyEnvironmentVariables(envText) { + var _a3, _b, _c; + const envChanged = envText !== this.runtimeEnvironmentVariables; this.settings.environmentVariables = envText; - await this.saveSettings(); - if (envText !== this.runtimeEnvironmentVariables) { - if (!this.hasNotifiedEnvChange) { - new import_obsidian27.Notice("Environment variables changed. Restart the plugin for changes to take effect."); - this.hasNotifiedEnvChange = true; - } - } else { - this.hasNotifiedEnvChange = false; + if (!envChanged) { + await this.saveSettings(); + return; } + this.runtimeEnvironmentVariables = envText; + const { changed, invalidatedConversations } = this.reconcileModelWithEnvironment(envText); + await this.saveSettings(); + if (invalidatedConversations.length > 0) { + for (const conv of invalidatedConversations) { + if (conv.isNative) { + await this.storage.sessions.saveMetadata( + this.storage.sessions.toSessionMetadata(conv) + ); + } else { + await this.storage.sessions.saveConversation(conv); + } + } + } + const view = this.getView(); + const tabManager = view == null ? void 0 : view.getTabManager(); + if (tabManager) { + for (const tab of tabManager.getAllTabs()) { + if (tab.state.isStreaming) { + (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.cancelStreaming(); + } + } + let failedTabs = 0; + if (changed) { + for (const tab of tabManager.getAllTabs()) { + if (!tab.service || !tab.serviceInitialized) { + continue; + } + try { + const externalContextPaths = (_c = (_b = tab.ui.externalContextSelector) == null ? void 0 : _b.getExternalContexts()) != null ? _c : []; + tab.service.resetSession(); + await tab.service.ensureReady({ externalContextPaths }); + } catch (e2) { + failedTabs++; + } + } + } else { + try { + await tabManager.broadcastToAllTabs( + async (service) => { + await service.ensureReady({ force: true }); + } + ); + } catch (e2) { + failedTabs++; + } + } + if (failedTabs > 0) { + new import_obsidian30.Notice(`Environment changes applied, but ${failedTabs} tab(s) failed to restart.`); + } + } + view == null ? void 0 : view.refreshModelSelector(); + const noticeText = changed ? "Environment variables applied. Sessions will be rebuilt on next message." : "Environment variables applied."; + new import_obsidian30.Notice(noticeText); } /** Returns the runtime environment variables (fixed at plugin load). */ getActiveEnvironmentVariables() { return this.runtimeEnvironmentVariables; } + getResolvedClaudeCliPath() { + return this.cliResolver.resolve( + this.settings.claudeCliPathsByHost, + // Per-device paths (preferred) + this.settings.claudeCliPath, + // Legacy path (fallback) + this.getActiveEnvironmentVariables() + ); + } getDefaultModelValues() { return DEFAULT_CLAUDE_MODELS.map((m) => m.value); } @@ -39078,13 +66747,11 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { * conversations that had their sessionId cleared (also requiring save). */ reconcileModelWithEnvironment(envText) { - var _a; const currentHash = this.computeEnvHash(envText); const savedHash = this.settings.lastEnvHash || ""; if (currentHash === savedHash) { return { changed: false, invalidatedConversations: [] }; } - (_a = this.agentService) == null ? void 0 : _a.resetSession(); const invalidatedConversations = []; for (const conv of this.conversations) { if (conv.sessionId) { @@ -39102,35 +66769,6 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { this.settings.lastEnvHash = currentHash; return { changed: true, invalidatedConversations }; } - /** Removes cached images associated with a conversation if not used elsewhere. */ - cleanupConversationImages(conversation) { - const cachePaths = /* @__PURE__ */ new Set(); - for (const message of conversation.messages || []) { - if (!message.images) continue; - for (const img of message.images) { - if (img.cachePath) { - cachePaths.add(img.cachePath); - } - } - } - if (cachePaths.size === 0) return; - const inUseElsewhere = /* @__PURE__ */ new Set(); - for (const conv of this.conversations) { - if (conv.id === conversation.id) continue; - for (const msg of conv.messages || []) { - if (!msg.images) continue; - for (const img of msg.images) { - if (img.cachePath && cachePaths.has(img.cachePath)) { - inUseElsewhere.add(img.cachePath); - } - } - } - } - const deletable = Array.from(cachePaths).filter((p) => !inUseElsewhere.has(p)); - if (deletable.length > 0) { - deleteCachedImages(this.app, deletable); - } - } generateConversationId() { return `conv-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`; } @@ -39145,89 +66783,249 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { } getConversationPreview(conv) { const firstUserMsg = conv.messages.find((m) => m.role === "user"); - if (!firstUserMsg) return "New conversation"; + if (!firstUserMsg) { + return conv.isNative ? "SDK session" : "New conversation"; + } return firstUserMsg.content.substring(0, 50) + (firstUserMsg.content.length > 50 ? "..." : ""); } - /** Creates a new conversation and sets it as active. */ - async createConversation() { + async loadSdkMessagesForConversation(conversation) { + var _a3; + if (!conversation.isNative || conversation.sdkMessagesLoaded) return; + const vaultPath = getVaultPath(this.app); + if (!vaultPath) return; + const allSessionIds = [ + ...conversation.previousSdkSessionIds || [], + (_a3 = conversation.sdkSessionId) != null ? _a3 : conversation.sessionId + ].filter((id) => !!id); + if (allSessionIds.length === 0) return; + const allSdkMessages = []; + let missingSessionCount = 0; + let errorCount = 0; + let successCount = 0; + for (const sessionId of allSessionIds) { + if (!sdkSessionExists(vaultPath, sessionId)) { + missingSessionCount++; + continue; + } + const result = await loadSDKSessionMessages(vaultPath, sessionId); + if (result.error) { + errorCount++; + continue; + } + successCount++; + allSdkMessages.push(...result.messages); + } + const allSessionsMissing = missingSessionCount === allSessionIds.length; + const hasLoadErrors = errorCount > 0 && successCount === 0 && !allSessionsMissing; + if (hasLoadErrors) { + return; + } + const filteredSdkMessages = allSdkMessages.filter((msg) => !msg.isRebuiltContext); + const afterCutoff = conversation.legacyCutoffAt != null ? filteredSdkMessages.filter((msg) => msg.timestamp > conversation.legacyCutoffAt) : filteredSdkMessages; + const merged = this.dedupeMessages([ + ...conversation.messages, + ...afterCutoff + ]).sort((a, b3) => a.timestamp - b3.timestamp); + if (conversation.subagentData) { + this.applySubagentData(merged, conversation.subagentData); + } + conversation.messages = merged; + conversation.sdkMessagesLoaded = true; + } + /** + * Applies cached subagentData to messages. + * Restores subagent info so Task tools can show tool count and status. + * Also updates contentBlocks to properly identify Task tools as subagents. + */ + applySubagentData(messages, subagentData) { + var _a3; + for (const msg of messages) { + if (msg.role !== "assistant") continue; + for (const [subagentId, subagent] of Object.entries(subagentData)) { + if (!msg.subagents) { + msg.subagents = []; + } + const hasSubagentBlock = (_a3 = msg.contentBlocks) == null ? void 0 : _a3.some( + (b3) => b3.type === "subagent" && b3.subagentId === subagentId || b3.type === "tool_use" && b3.toolId === subagentId + ); + if (!hasSubagentBlock) continue; + const existingIdx = msg.subagents.findIndex((s) => s.id === subagentId); + if (existingIdx === -1) { + msg.subagents.push(subagent); + } else { + msg.subagents[existingIdx] = subagent; + } + if (msg.contentBlocks) { + for (let i2 = 0; i2 < msg.contentBlocks.length; i2++) { + const block = msg.contentBlocks[i2]; + if (block.type === "tool_use" && block.toolId === subagentId) { + msg.contentBlocks[i2] = { + type: "subagent", + subagentId, + mode: subagent.mode + }; + } else if (block.type === "subagent" && block.subagentId === subagentId && !block.mode) { + block.mode = subagent.mode; + } + } + } + } + } + } + dedupeMessages(messages) { + const seen = /* @__PURE__ */ new Set(); + const result = []; + for (const message of messages) { + if (seen.has(message.id)) continue; + seen.add(message.id); + result.push(message); + } + return result; + } + /** + * Creates a new conversation and sets it as active. + * + * New conversations always use SDK-native storage. + * The session ID may be captured after the first SDK response. + */ + async createConversation(sessionId) { + const conversationId = sessionId != null ? sessionId : this.generateConversationId(); const conversation = { - id: this.generateConversationId(), + id: conversationId, title: this.generateDefaultTitle(), createdAt: Date.now(), updatedAt: Date.now(), - sessionId: null, - messages: [] + sessionId: sessionId != null ? sessionId : null, + sdkSessionId: sessionId != null ? sessionId : void 0, + messages: [], + isNative: true }; this.conversations.unshift(conversation); - this.activeConversationId = conversation.id; - this.agentService.resetSession(); - await this.storage.sessions.saveConversation(conversation); - await this.storage.updateState({ activeConversationId: this.activeConversationId }); + await this.storage.sessions.saveMetadata( + this.storage.sessions.toSessionMetadata(conversation) + ); return conversation; } - /** Switches to an existing conversation by ID. */ + /** + * Switches to an existing conversation by ID. + * + * For native sessions, loads messages from SDK storage if not already loaded. + */ async switchConversation(id) { - const conversation = this.conversations.find((c) => c.id === id); + const conversation = this.conversations.find((c3) => c3.id === id); if (!conversation) return null; - this.activeConversationId = id; - this.agentService.setSessionId(conversation.sessionId); - await this.storage.updateState({ activeConversationId: this.activeConversationId }); + await this.loadSdkMessagesForConversation(conversation); return conversation; } - /** Deletes a conversation and switches to another if necessary. */ + /** + * Deletes a conversation and resets any tabs using it. + * + * For native sessions, deletes the metadata file and SDK session file. + * For legacy sessions, deletes the JSONL file. + */ async deleteConversation(id) { - const index = this.conversations.findIndex((c) => c.id === id); + var _a3, _b, _c; + const index = this.conversations.findIndex((c3) => c3.id === id); if (index === -1) return; const conversation = this.conversations[index]; - this.cleanupConversationImages(conversation); this.conversations.splice(index, 1); - await this.storage.sessions.deleteConversation(id); - if (this.activeConversationId === id) { - if (this.conversations.length > 0) { - await this.switchConversation(this.conversations[0].id); - } else { - await this.createConversation(); + const vaultPath = getVaultPath(this.app); + const sdkSessionId = (_a3 = conversation.sdkSessionId) != null ? _a3 : conversation.sessionId; + if (vaultPath && sdkSessionId) { + await deleteSDKSession(vaultPath, sdkSessionId); + } + if (conversation.isNative) { + await this.storage.sessions.deleteMetadata(id); + } else { + await this.storage.sessions.deleteConversation(id); + } + for (const view of this.getAllViews()) { + const tabManager = view.getTabManager(); + if (!tabManager) continue; + for (const tab of tabManager.getAllTabs()) { + if (tab.conversationId === id) { + (_b = tab.controllers.inputController) == null ? void 0 : _b.cancelStreaming(); + await ((_c = tab.controllers.conversationController) == null ? void 0 : _c.createNew({ force: true })); + } } } } /** Renames a conversation. */ async renameConversation(id, title) { - const conversation = this.conversations.find((c) => c.id === id); + const conversation = this.conversations.find((c3) => c3.id === id); if (!conversation) return; conversation.title = title.trim() || this.generateDefaultTitle(); conversation.updatedAt = Date.now(); - await this.storage.sessions.saveConversation(conversation); + if (conversation.isNative) { + await this.storage.sessions.saveMetadata( + this.storage.sessions.toSessionMetadata(conversation) + ); + } else { + await this.storage.sessions.saveConversation(conversation); + } } - /** Updates conversation properties (messages, sessionId, etc.). */ + /** + * Updates conversation properties. + * + * For native sessions, saves metadata only (SDK handles messages including images). + * For legacy sessions, saves full JSONL. + * + * Image data is cleared from memory after save (SDK/JSONL has persisted it). + */ async updateConversation(id, updates) { - const conversation = this.conversations.find((c) => c.id === id); + const conversation = this.conversations.find((c3) => c3.id === id); if (!conversation) return; Object.assign(conversation, updates, { updatedAt: Date.now() }); - await this.storage.sessions.saveConversation(conversation); + if (conversation.isNative) { + await this.storage.sessions.saveMetadata( + this.storage.sessions.toSessionMetadata(conversation) + ); + } else { + await this.storage.sessions.saveConversation(conversation); + } + for (const msg of conversation.messages) { + if (msg.images) { + for (const img of msg.images) { + img.data = ""; + } + } + } } - /** Returns the current active conversation. */ - getActiveConversation() { - return this.conversations.find((c) => c.id === this.activeConversationId) || null; + /** + * Gets a conversation by ID from the in-memory cache. + * + * For native sessions, loads messages from SDK storage if not already loaded. + */ + async getConversationById(id) { + const conversation = this.conversations.find((c3) => c3.id === id) || null; + if (conversation) { + await this.loadSdkMessagesForConversation(conversation); + } + return conversation; } - /** Gets a conversation by ID from the in-memory cache. */ - getConversationById(id) { - return this.conversations.find((c) => c.id === id) || null; + /** + * Gets a conversation by ID without loading SDK messages. + * Use this for UI code that only needs metadata (title, etc.). + */ + getConversationSync(id) { + return this.conversations.find((c3) => c3.id === id) || null; } /** Finds an existing empty conversation (no messages). */ findEmptyConversation() { - return this.conversations.find((c) => c.messages.length === 0) || null; + return this.conversations.find((c3) => c3.messages.length === 0) || null; } /** Returns conversation metadata list for the history dropdown. */ getConversationList() { - return this.conversations.map((c) => ({ - id: c.id, - title: c.title, - createdAt: c.createdAt, - updatedAt: c.updatedAt, - lastResponseAt: c.lastResponseAt, - messageCount: c.messages.length, - preview: this.getConversationPreview(c), - titleGenerationStatus: c.titleGenerationStatus + return this.conversations.map((c3) => ({ + id: c3.id, + title: c3.title, + createdAt: c3.createdAt, + updatedAt: c3.updatedAt, + lastResponseAt: c3.lastResponseAt, + messageCount: c3.messages.length, + preview: this.getConversationPreview(c3), + titleGenerationStatus: c3.titleGenerationStatus, + isNative: c3.isNative })); } /** Returns the active Claudian view from workspace, if open. */ @@ -39238,4 +67036,43 @@ var ClaudianPlugin = class extends import_obsidian27.Plugin { } return null; } + /** Returns all open Claudian views in the workspace. */ + getAllViews() { + const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN); + return leaves.map((leaf) => leaf.view); + } + /** + * Checks if a conversation is open in any Claudian view. + * Returns the view and tab if found, null otherwise. + */ + findConversationAcrossViews(conversationId) { + for (const view of this.getAllViews()) { + const tabManager = view.getTabManager(); + if (!tabManager) continue; + const tabs = tabManager.getAllTabs(); + for (const tab of tabs) { + if (tab.conversationId === conversationId) { + return { view, tabId: tab.id }; + } + } + } + return null; + } + /** + * Gets SDK supported commands from any ready service. + * The command list is the same for all services, so we just need one ready. + * Used by inline edit and other contexts that don't have direct TabManager access. + */ + async getSdkCommands() { + for (const view of this.getAllViews()) { + const tabManager = view.getTabManager(); + if (tabManager) { + const commands = await tabManager.getSdkCommands(); + if (commands.length > 0) { + return commands; + } + } + } + return []; + } }; diff --git a/.obsidian/plugins/claudian/styles.css b/.obsidian/plugins/claudian/styles.css index cb75e16..687fb39 100644 --- a/.obsidian/plugins/claudian/styles.css +++ b/.obsidian/plugins/claudian/styles.css @@ -2,6 +2,19 @@ /* Built from src/style/ modules */ +/* ============================================ + base/variables.css + ============================================ */ +/* Brand & semantic color tokens */ +.claudian-container { + --claudian-brand: #D97757; + --claudian-brand-rgb: 217, 119, 87; + --claudian-error: #dc3545; + --claudian-error-rgb: 220, 53, 69; + --claudian-compact: #5bc0de; +} + + /* ============================================ base/container.css ============================================ */ @@ -17,7 +30,6 @@ /* ============================================ base/animations.css ============================================ */ -/* Thinking pulse animation */ @keyframes thinking-pulse { 0%, 100% { @@ -29,26 +41,23 @@ } } -/* Spinner rotation */ @keyframes spin { to { transform: rotate(360deg); } } -/* Context path icon glow */ -@keyframes context-path-glow { +@keyframes external-context-glow { 0%, 100% { - filter: drop-shadow(0 0 2px rgba(217, 119, 87, 0.4)); + filter: drop-shadow(0 0 2px rgba(var(--claudian-brand-rgb), 0.4)); } 50% { - filter: drop-shadow(0 0 6px rgba(217, 119, 87, 0.8)); + filter: drop-shadow(0 0 6px rgba(var(--claudian-brand-rgb), 0.8)); } } -/* MCP selector icon glow */ @keyframes mcp-glow { 0%, 100% { @@ -60,48 +69,44 @@ } } -/* Inline edit spinner */ -@keyframes claudian-inline-spin { - 0% { - transform: rotate(0deg); - } - - 100% { - transform: rotate(360deg); - } -} - -/* Instruction modal spinner */ -@keyframes claudian-instruction-spin { +@keyframes claudian-spin { to { transform: rotate(360deg); } } -/* MCP test spinner */ -@keyframes claudian-mcp-spin { - to { - transform: rotate(360deg); - } -} - - /* ============================================ components/header.css ============================================ */ -/* Header */ +/* Header - logo, title/tabs slot, and actions */ .claudian-header { display: flex; align-items: center; - justify-content: space-between; padding: 0 12px 12px 12px; } +/* Title slot: contains logo + title (or tabs in header mode) */ +.claudian-title-slot { + display: flex; + align-items: center; + gap: 8px; + flex: 1; + min-width: 0; /* Allow flex item to shrink below content size */ +} + +/* Legacy class for backwards compatibility */ .claudian-title { display: flex; align-items: center; gap: 8px; + flex-shrink: 0; +} + +.claudian-title-text { + margin: 0; + font-size: 14px; + font-weight: 600; } .claudian-logo { @@ -109,20 +114,24 @@ align-items: center; } -.claudian-header h4 { - margin: 0; - font-size: 14px; - font-weight: 600; -} - -/* Header actions (right side) */ +/* Header actions (right side - always stays right via margin-left: auto) */ .claudian-header-actions { display: flex; align-items: center; gap: 4px; + flex-shrink: 0; + margin-left: auto; +} + +.claudian-header-actions-slot { + /* No margin-left: auto here; it's set by the base .claudian-header-actions */ +} + +.claudian-header .claudian-tab-bar-container { + display: flex; + gap: 4px; } -/* Header icon buttons (history, new, etc.) */ .claudian-header-btn { display: flex; align-items: center; @@ -144,28 +153,102 @@ height: 16px; } +.claudian-new-tab-btn svg { + width: 16.8px; + height: 16.8px; +} + +/* ============================================ + components/tabs.css + ============================================ */ +.claudian-tab-bar-container { + display: flex; + align-items: center; + gap: 4px; +} + +.claudian-tab-badges { + display: flex; + align-items: center; + gap: 4px; +} + +.claudian-tab-badge { + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border-radius: 4px; + border: 2px solid var(--background-modifier-border); + font-size: 12px; + font-weight: 500; + cursor: pointer; + color: var(--text-muted); + background: var(--background-primary); + transition: border-color 0.15s ease, color 0.15s ease, background 0.15s ease; +} + +.claudian-tab-badge:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +.claudian-tab-badge-active { + border-color: var(--interactive-accent); + color: var(--text-normal); +} + +.claudian-tab-badge-streaming { + border-color: var(--claudian-brand, #da7756); +} + +.claudian-tab-badge-attention { + border-color: var(--text-error); +} + +.claudian-tab-badge-idle { + border-color: var(--background-modifier-border); +} + +.claudian-tab-content-container { + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; + overflow: hidden; +} + +.claudian-tab-content { + position: relative; /* For scroll-to-bottom button positioning */ + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; + overflow: hidden; +} + /* ============================================ components/history.css ============================================ */ -/* History dropdown container */ .claudian-history-container { position: relative; } -/* History dropdown menu */ +/* History dropup menu (opens upward since it's at bottom of view) */ .claudian-history-menu { display: none; position: absolute; - top: 100%; + bottom: 100%; right: 0; - margin-top: 4px; + margin-bottom: 4px; background: var(--background-secondary); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid var(--background-modifier-border); border-radius: 6px; - box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25); + box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.25); z-index: 1000; max-height: 400px; overflow: hidden; @@ -176,6 +259,15 @@ display: block; } +/* Header mode: dropdown instead of dropup */ +.claudian-container--header-mode .claudian-history-menu { + bottom: auto; + top: 100%; + margin-bottom: 0; + margin-top: 4px; + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25); +} + .claudian-history-header { padding: 8px 12px; font-size: 12px; @@ -198,7 +290,6 @@ font-size: 13px; } -/* History item */ .claudian-history-item { display: flex; align-items: center; @@ -303,7 +394,6 @@ color: var(--color-red); } -/* Rename input */ .claudian-rename-input { width: 100%; padding: 2px 4px; @@ -334,7 +424,16 @@ /* ============================================ components/messages.css ============================================ */ -/* Messages area */ +/* Messages wrapper (for scroll-to-bottom button positioning) */ +.claudian-messages-wrapper { + position: relative; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; +} + .claudian-messages { flex: 1; overflow-y: auto; @@ -369,7 +468,6 @@ letter-spacing: -0.01em; } -/* Individual messages */ .claudian-message { padding: 10px 14px; border-radius: 8px; @@ -378,8 +476,8 @@ } .claudian-message-user { + position: relative; background: rgba(0, 0, 0, 0.3); - color: var(--text-on-accent); align-self: flex-end; border-bottom-right-radius: 4px; } @@ -390,11 +488,6 @@ color: inherit; } -.claudian-message-user ::-moz-selection { - background: rgba(255, 255, 255, 0.35); - color: inherit; -} - .claudian-message-assistant { background: transparent; align-self: stretch; @@ -404,14 +497,12 @@ text-align: left; } -/* Message content */ .claudian-message-content { line-height: 1.5; user-select: text; -webkit-user-select: text; } -/* Interrupted message */ .claudian-interrupted { color: #d45d5d; } @@ -420,11 +511,50 @@ color: var(--text-muted); } -/* Text blocks within message content */ .claudian-text-block { + position: relative; margin: 0; } +.claudian-text-copy-btn { + position: absolute; + bottom: 0; + right: 0; + padding: 4px 8px; + font-size: 11px; + font-family: var(--font-monospace); + background: var(--background-primary); + border: none; + color: var(--text-muted); + cursor: pointer; + opacity: 0; + transition: opacity 0.15s ease, color 0.15s ease, background 0.15s ease; + border-radius: 3px; + z-index: 2; + display: flex; + align-items: center; + gap: 4px; +} + +.claudian-text-copy-btn svg { + width: 14px; + height: 14px; +} + +.claudian-text-block:hover .claudian-text-copy-btn { + opacity: 1; +} + +.claudian-text-copy-btn:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +/* Copied state - only affects color, visibility still controlled by hover */ +.claudian-text-copy-btn.copied { + color: var(--text-accent); +} + .claudian-text-block+.claudian-tool-call { margin-top: 8px; } @@ -447,7 +577,6 @@ padding-left: 20px; } -/* Scrollbar styling */ .claudian-messages::-webkit-scrollbar { width: 6px; } @@ -465,6 +594,92 @@ background: var(--background-modifier-border-hover); } +/* Response duration footer - styled as another line of content */ +.claudian-response-footer { + margin-top: 8px; +} + +.claudian-baked-duration { + color: var(--text-muted); + font-size: 12px; + font-weight: 500; + font-style: italic; +} + +/* Compact boundary indicator */ +.claudian-compact-boundary { + display: flex; + align-items: center; + gap: 10px; + margin: 12px 0; +} + +.claudian-compact-boundary::before, +.claudian-compact-boundary::after { + content: ''; + flex: 1; + height: 1px; + background: var(--background-modifier-border); +} + +.claudian-compact-boundary-label { + color: var(--text-muted); + font-size: 11px; + white-space: nowrap; +} + + +/* ============================================ + components/scroll-to-bottom.css + ============================================ */ +/* Scroll-to-bottom button */ +.claudian-scroll-to-bottom { + position: absolute; + bottom: 12px; + left: 50%; + transform: translateX(-50%); + width: fit-content; + height: 24px; + padding: 0 12px; + display: flex; + align-items: center; + justify-content: center; + gap: 6px; + background: var(--background-secondary) !important; + border: 0.5px solid var(--background-modifier-border) !important; + border-radius: 6px; + cursor: pointer; + color: var(--text-muted); + font-size: 12px; + box-shadow: none; + opacity: 0; + pointer-events: none; + transition: opacity 0.2s ease, background 0.15s ease, color 0.15s ease; + z-index: 10; +} + +.claudian-scroll-to-bottom.visible { + opacity: 1; + pointer-events: auto; +} + +.claudian-scroll-to-bottom:hover { + background: var(--background-secondary-alt) !important; + color: var(--text-normal); + border-color: var(--background-modifier-border-hover) !important; + opacity: 1; +} + +.claudian-scroll-to-bottom:focus-visible { + outline: 2px solid var(--interactive-accent); + outline-offset: 2px; +} + +.claudian-scroll-to-bottom:active { + transform: translateX(-50%) scale(0.95); +} + + /* ============================================ components/code.css @@ -478,8 +693,7 @@ /* Code blocks in chat messages */ .claudian-code-wrapper pre, .claudian-message-content pre { - background: var(--background-secondary); - border: 1px solid var(--background-modifier-border); + background: rgba(0, 0, 0, 0.2); padding: 8px 12px; border-radius: 6px; overflow-x: auto; @@ -562,25 +776,27 @@ color: var(--text-normal); } - /* ============================================ components/thinking.css ============================================ */ -/* Thinking indicator */ .claudian-thinking { - color: #D97757; + color: var(--claudian-brand); font-style: italic; padding: 4px 0; text-align: left; animation: thinking-pulse 1.5s ease-in-out infinite; } +.claudian-thinking.claudian-thinking--compact { + color: var(--claudian-compact); +} + .claudian-thinking-hint { color: var(--text-muted); font-style: normal; + font-variant-numeric: tabular-nums; } -/* Thinking block (extended thinking) */ .claudian-thinking-block { margin: 8px 0; } @@ -601,20 +817,20 @@ margin-top: 8px; } -/* Thinking block header - transparent */ .claudian-thinking-header { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; + overflow: hidden; } .claudian-thinking-label { flex: 1; font-size: 13px; font-weight: 500; - color: #D97757; + color: var(--claudian-brand); } /* Thinking block content - tree-branch style */ @@ -637,7 +853,6 @@ margin-bottom: 0; } -/* Thinking content code blocks - inherits from wrapper, adjust spacing */ .claudian-thinking-content .claudian-code-wrapper { margin: 8px 0; } @@ -656,18 +871,17 @@ /* ============================================ components/toolcalls.css ============================================ */ -/* Tool call container - transparent, no border */ .claudian-tool-call { margin: 8px 0; } -/* Tool call header - transparent */ .claudian-tool-header { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; + overflow: hidden; } .claudian-tool-icon { @@ -683,16 +897,25 @@ } .claudian-tool-label { - flex: 1; font-family: var(--font-monospace); font-size: 13px; - font-weight: 500; + font-weight: 400; color: var(--text-normal); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.claudian-tool-current { + flex: 1; + font-family: var(--font-monospace); + font-size: 13px; + color: var(--text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + .claudian-tool-status { display: flex; align-items: center; @@ -719,34 +942,23 @@ .claudian-tool-status.status-blocked { color: var(--color-orange); } - -/* Spinner animation */ -.claudian-spinner { - width: 14px; - height: 14px; - border: 2px solid var(--background-modifier-border); - border-top-color: var(--text-accent); - border-radius: 50%; - animation: spin 0.8s linear infinite; -} - -/* Tool call content - tree-branch style */ +/* Tool call content - border-left style (like thinking block) */ .claudian-tool-content { - padding: 4px 0 4px 24px; + padding: 4px 0 4px 16px; + margin-left: 7px; + border-left: 2px solid var(--background-modifier-border); +} + +/* TodoWrite content - no border (renders todo panel directly) */ +.claudian-tool-content-todo { + border-left: none; + margin-left: 0; + padding-left: 0; } -/* Tree-branch result row */ .claudian-tool-result-row { display: flex; align-items: flex-start; - gap: 4px; -} - -.claudian-tool-branch { - font-family: monospace; - color: var(--text-faint); - flex-shrink: 0; - line-height: 1.4; } .claudian-tool-result-text { @@ -759,7 +971,6 @@ flex: 1; } -/* Result items - regular text lines */ .claudian-tool-result-item { display: block; margin-bottom: 2px; @@ -783,137 +994,195 @@ /* ============================================ - components/todo-panel.css + components/status-panel.css ============================================ */ -/* Todo Panel - persistent bottom panel for todos */ +/* Status Panel - persistent bottom panel for async subagents and todos */ -/* Main container - no border/background, flows seamlessly */ -.claudian-todo-panel { - padding: 0; +.claudian-status-panel-container { + flex-shrink: 0; + padding: 0 14px; } -/* Todos container */ -.claudian-todo-panel-todos { +.claudian-status-panel { + padding-top: 12px; +} + +/* Async Subagent Section */ + +.claudian-status-panel-subagents { + margin-bottom: 4px; +} + +.claudian-status-panel-done-row { + display: flex; + align-items: center; + gap: 8px; + padding: 2px 0; +} + +.claudian-status-panel-combined-row { + justify-content: flex-start; +} + +.claudian-status-panel-combined-row .claudian-status-panel-done-text { + flex: 1; +} + +.claudian-status-panel-icon.claudian-status-panel-done-icon { + color: var(--color-green); +} + +.claudian-status-panel-icon.claudian-status-panel-bot-icon { + color: var(--interactive-accent); +} + +.claudian-status-panel-done-text { + font-family: var(--font-monospace); + font-size: 13px; + color: var(--text-normal); +} + +.claudian-status-panel-running-row { + display: flex; + justify-content: flex-end; + padding: 2px 0; +} + +.claudian-status-panel-running-text { + font-family: var(--font-monospace); + font-size: 13px; + color: var(--color-cyan); +} + +/* Todo Section */ + +.claudian-status-panel-todos { margin-top: 4px; } -/* Header (collapsed view) - subtle hover only */ -.claudian-todo-panel-header { +.claudian-status-panel-header { display: flex; align-items: center; - gap: 6px; + gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; transition: background 0.15s ease; + overflow: hidden; } -.claudian-todo-panel-header:hover { +.claudian-status-panel-header:hover { background: var(--background-modifier-hover); } -.claudian-todo-panel-header:focus-visible { +.claudian-status-panel-header:focus-visible { outline: 2px solid var(--interactive-accent); outline-offset: 2px; } -/* List icon */ -.claudian-todo-panel-icon { +.claudian-status-panel-icon { display: flex; align-items: center; - color: var(--interactive-accent); + color: var(--text-accent); flex-shrink: 0; } -.claudian-todo-panel-icon svg { +.claudian-status-panel-icon svg { width: 16px; height: 16px; } -/* Label */ -.claudian-todo-panel-label { +.claudian-status-panel-label { font-family: var(--font-monospace); font-size: 13px; font-weight: 500; - color: var(--interactive-accent); + color: var(--text-normal); } -/* Current task preview (collapsed state) */ -.claudian-todo-panel-current { +.claudian-status-panel-current { + flex: 1; font-family: var(--font-monospace); font-size: 13px; color: var(--text-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - flex: 1; } -/* Content (expanded list) */ -.claudian-todo-panel-content { - padding: 4px 0 4px 18px; -} - -/* Individual todo item - reuses existing styles */ -.claudian-todo-panel-content .claudian-todo-item { - display: flex; - align-items: flex-start; - gap: 8px; - padding: 4px 0; -} - -.claudian-todo-panel-content .claudian-todo-item:first-child { - padding-top: 0; -} - -.claudian-todo-panel-content .claudian-todo-item:last-child { - padding-bottom: 0; -} - -.claudian-todo-panel-content .claudian-todo-status-icon { +.claudian-status-panel-status { display: flex; align-items: center; flex-shrink: 0; - width: 16px; - height: 16px; - margin-top: 1px; } -.claudian-todo-panel-content .claudian-todo-status-icon svg { - width: 16px; - height: 16px; +.claudian-status-panel-status svg { + width: 14px; + height: 14px; } -.claudian-todo-panel-content .claudian-todo-text { - font-family: var(--font-monospace); - font-size: 13px; - line-height: 1.4; - flex: 1; -} - -/* Status-specific styling */ -.claudian-todo-panel-content .claudian-todo-pending .claudian-todo-status-icon { - color: var(--text-muted); -} - -.claudian-todo-panel-content .claudian-todo-pending .claudian-todo-text { - color: var(--text-muted); -} - -.claudian-todo-panel-content .claudian-todo-in_progress .claudian-todo-status-icon { - color: var(--interactive-accent); -} - -.claudian-todo-panel-content .claudian-todo-in_progress .claudian-todo-text { - color: var(--text-normal); - font-weight: 500; -} - -.claudian-todo-panel-content .claudian-todo-completed .claudian-todo-status-icon { +.claudian-status-panel-status.status-completed { color: var(--color-green); } -.claudian-todo-panel-content .claudian-todo-completed .claudian-todo-text { +.claudian-status-panel-content { + padding: 2px 0; +} + +/* Individual todo item - shared by status panel and inline tool via .claudian-todo-list-container */ +.claudian-todo-list-container .claudian-todo-item { + display: flex; + align-items: flex-start; + padding: 1px 0; +} + +.claudian-todo-list-container .claudian-todo-status-icon { + display: flex; + align-items: center; + flex-shrink: 0; +} + +.claudian-todo-list-container .claudian-todo-status-icon svg { + width: 12px; + height: 12px; +} + +.claudian-todo-list-container .claudian-todo-text { + font-family: var(--font-monospace); + font-size: 12px; + line-height: 1.4; + flex: 1; + padding-left: 12px; +} + +.claudian-todo-list-container .claudian-todo-pending .claudian-todo-status-icon { + color: var(--text-normal); +} + +.claudian-todo-list-container .claudian-todo-pending .claudian-todo-status-icon svg { + transform: scale(2); +} + +.claudian-todo-list-container .claudian-todo-pending .claudian-todo-text { + color: var(--text-normal); +} + +.claudian-todo-list-container .claudian-todo-in_progress .claudian-todo-status-icon { + color: var(--interactive-accent); +} + +.claudian-todo-list-container .claudian-todo-in_progress .claudian-todo-status-icon svg { + transform: scale(2); +} + +.claudian-todo-list-container .claudian-todo-in_progress .claudian-todo-text { + color: var(--text-normal); +} + +.claudian-todo-list-container .claudian-todo-completed .claudian-todo-status-icon { + color: var(--color-green); +} + +.claudian-todo-list-container .claudian-todo-completed .claudian-todo-text { color: var(--text-muted); } @@ -921,7 +1190,6 @@ /* ============================================ components/subagent.css ============================================ */ -/* Subagent List (Task tool) - follows TodoList pattern */ .claudian-subagent-list { margin: 8px 0; } @@ -942,13 +1210,13 @@ margin-top: 8px; } -/* Subagent header */ .claudian-subagent-header { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; + overflow: hidden; } .claudian-subagent-icon { @@ -965,8 +1233,9 @@ .claudian-subagent-label { flex: 1; + font-family: var(--font-monospace); font-size: 13px; - font-weight: 500; + font-weight: 400; color: var(--text-normal); } @@ -999,49 +1268,48 @@ color: var(--color-red); } -/* Subagent content */ +/* Subagent content - border-left style (like thinking block) */ .claudian-subagent-content { - padding: 4px 0 4px 24px; + padding: 4px 0 4px 16px; + margin-left: 7px; + border-left: 2px solid var(--background-modifier-border); } -/* Tree branch indicator */ -.claudian-subagent-branch { - font-family: monospace; +.claudian-subagent-bullet { color: var(--text-faint); flex-shrink: 0; + font-size: 12px; line-height: 1.4; + margin-right: 4px; } -/* Individual tool item container */ .claudian-subagent-tool-item { display: flex; flex-direction: column; padding: 2px 0; } -/* Tool row (branch + label) */ .claudian-subagent-tool-row { display: flex; align-items: flex-start; - gap: 4px; } .claudian-subagent-tool-text { - font-size: 13px; + font-family: var(--font-monospace); + font-size: 12px; line-height: 1.4; flex: 1; - color: var(--text-normal); + color: var(--text-muted); } -/* Tool result area nested under tool (max 2 lines) */ .claudian-subagent-tool-result { display: flex; - align-items: flex-start; - gap: 4px; - padding: 2px 0 0 20px; + align-items: baseline; + padding: 2px 0 0 8px; } .claudian-subagent-result-text { + font-family: var(--font-monospace); font-size: 12px; color: var(--text-muted); line-height: 1.4; @@ -1051,23 +1319,19 @@ max-height: 2.8em; } -/* DONE indicator */ .claudian-subagent-done { display: flex; align-items: flex-start; - gap: 4px; padding: 2px 0; } .claudian-subagent-done-text { + font-family: var(--font-monospace); font-size: 12px; color: var(--text-faint); font-weight: 500; } -/* Async Subagent (Task tool with run_in_background=true) */ - -/* Status text display (e.g., "pending", "running agent_123", etc.) */ .claudian-subagent-status-text { font-size: 11px; font-family: var(--font-monospace); @@ -1076,742 +1340,35 @@ padding-left: 8px; } -/* Async-specific status styling */ -.claudian-subagent-list.async.pending .claudian-subagent-icon { - color: var(--text-muted); +.claudian-subagent-list.async .claudian-subagent-icon { + color: var(--interactive-accent); } .claudian-subagent-list.async.pending .claudian-subagent-status-text { color: var(--text-muted); } -.claudian-subagent-list.async.running .claudian-subagent-icon { - color: var(--interactive-accent); -} - .claudian-subagent-list.async.running .claudian-subagent-status-text { color: var(--text-accent); } -.claudian-subagent-list.async.awaiting .claudian-subagent-icon { - color: var(--color-yellow); -} - .claudian-subagent-list.async.awaiting .claudian-subagent-status-text { color: var(--color-yellow); } -.claudian-subagent-list.async.completed .claudian-subagent-icon { - color: var(--color-green); -} - .claudian-subagent-list.async.completed .claudian-subagent-status-text { color: var(--color-green); } -.claudian-subagent-list.async.error .claudian-subagent-icon { - color: var(--color-red); -} - .claudian-subagent-list.async.error .claudian-subagent-status-text { color: var(--color-red); } -.claudian-subagent-list.async.orphaned .claudian-subagent-icon { - color: var(--color-orange); -} - .claudian-subagent-list.async.orphaned .claudian-subagent-status-text { color: var(--color-orange); } -/* ============================================ - components/ask-user-question.css - ============================================ */ -/** - * AskUserQuestion styles - minimal design. - */ - -/* ============================================ - * Question Panel (replaces input area) - * ============================================ */ - -.claudian-ask-panel { - padding: 12px 0; - outline: none; -} - -.claudian-ask-panel:focus { - outline: none; -} - -/* Tab navigation row */ -.claudian-ask-panel-tabs { - display: flex; - align-items: center; - flex-wrap: wrap; - gap: 8px; - margin-bottom: 12px; - font-size: 13px; -} - -.claudian-ask-panel-nav { - color: var(--text-muted); - cursor: pointer; - user-select: none; -} - -.claudian-ask-panel-nav:hover { - color: var(--text-normal); -} - -.claudian-ask-panel-tab { - display: inline-flex; - align-items: center; - gap: 4px; - padding: 0 !important; - margin: 0 !important; - border: none !important; - border-radius: 0 !important; - background: none !important; - background-color: transparent !important; - color: var(--text-muted); - cursor: pointer; - font-size: 13px; - font-family: var(--font-monospace); - /* Completely reset button appearance */ - appearance: none !important; - -webkit-appearance: none !important; - -moz-appearance: none !important; - box-shadow: none !important; - outline: none !important; - text-decoration: none !important; - text-shadow: none !important; -} - -.claudian-ask-panel-tab:hover { - color: var(--text-normal); - background: none !important; - box-shadow: none !important; - border: none !important; -} - -.claudian-ask-panel-tab:focus { - outline: none !important; - box-shadow: none !important; - border: none !important; -} - -.claudian-ask-panel-tab.active { - color: var(--interactive-accent); - background: none !important; - border: none !important; -} - -.claudian-ask-panel-tab-check { - font-family: monospace; -} - -/* Green dot for answered tabs */ -.claudian-ask-panel-tab.answered .claudian-ask-panel-tab-check { - color: var(--color-green); -} - - -/* Question content */ -.claudian-ask-panel-content { - display: flex; - flex-direction: column; - gap: 8px; -} - -.claudian-ask-panel-question { - font-size: 14px; - font-weight: 600; - color: var(--text-normal); - margin-bottom: 8px; -} - -/* Options list */ -.claudian-ask-panel-options { - display: flex; - flex-direction: column; - gap: 2px; - font-family: var(--font-monospace); - font-size: 13px; -} - -.claudian-ask-panel-option { - display: flex; - align-items: flex-start; - gap: 8px; - padding: 4px 0; - cursor: pointer; - color: var(--text-normal); -} - -.claudian-ask-panel-option:hover { - color: var(--interactive-accent); -} - -.claudian-ask-panel-option.focused { - color: var(--interactive-accent); -} - -.claudian-ask-panel-option.selected { - color: var(--interactive-accent); -} - -/* Caret indicator (> or space) */ -.claudian-ask-panel-caret { - width: 12px; - flex-shrink: 0; - color: var(--interactive-accent); - font-weight: bold; -} - -/* Number/checkbox indicator */ -.claudian-ask-panel-indicator { - flex-shrink: 0; - color: var(--text-muted); - white-space: nowrap; -} - -.claudian-ask-panel-option.focused .claudian-ask-panel-caret { - color: var(--interactive-accent); -} - -.claudian-ask-panel-option.focused .claudian-ask-panel-indicator { - color: var(--interactive-accent); -} - -/* Green checkmark for selected items */ -.claudian-ask-panel-option.selected .claudian-ask-panel-indicator { - color: var(--color-green); -} - -.claudian-ask-panel-option-text { - display: flex; - flex-direction: column; - gap: 0; -} - -.claudian-ask-panel-label-row { - display: flex; - align-items: center; - gap: 4px; -} - -.claudian-ask-panel-option-label { - font-weight: 500; -} - -/* Checkmark after label for single-select */ -.claudian-ask-panel-checkmark { - color: var(--color-green); - font-weight: bold; -} - -.claudian-ask-panel-option-desc { - color: var(--text-muted); - font-weight: normal; -} - -/* Other option */ -.claudian-ask-panel-other { - flex-wrap: wrap; -} - -.claudian-ask-panel-other-input { - flex: 1; - min-width: 150px; - padding: 2px 4px; - border: none; - border-bottom: 1px solid var(--background-modifier-border); - background: transparent; - color: var(--text-normal); - font-family: var(--font-monospace); - font-size: 13px; -} - -.claudian-ask-panel-other-input:focus { - outline: none; - border-bottom-color: var(--interactive-accent); -} - -.claudian-ask-panel-other-input::placeholder { - color: var(--text-faint); -} - -/* Keyboard hint */ -.claudian-ask-panel-hint { - margin-top: 12px; - font-size: 12px; - color: var(--text-muted); -} - -/* Submit review panel */ -.claudian-ask-panel-summary { - display: flex; - flex-direction: column; - gap: 8px; - margin-bottom: 16px; - font-family: var(--font-monospace); - font-size: 13px; -} - -.claudian-ask-panel-summary-item { - display: flex; - flex-direction: column; - gap: 2px; -} - -.claudian-ask-panel-summary-question { - color: var(--text-normal); -} - -.claudian-ask-panel-summary-answer { - color: var(--color-green); - padding-left: 8px; -} - -.claudian-ask-panel-summary-answer.unanswered { - color: var(--text-muted); - font-style: italic; -} - -.claudian-ask-panel-submit-prompt { - font-size: 13px; - color: var(--text-muted); - margin-bottom: 8px; -} - -/* ============================================ - * Tool Call Result Block - matches toolcalls.css style - * ============================================ */ - -.claudian-ask-question-block { - margin: 8px 0; -} - -.claudian-ask-question-block.claudian-ask-question-pending { - display: none; -} - -/* Header - transparent like other tool calls */ -.claudian-ask-question-header { - display: flex; - align-items: center; - gap: 8px; - padding: 4px 0; - cursor: pointer; -} - -.claudian-ask-question-icon { - display: flex; - align-items: center; - flex-shrink: 0; - color: var(--text-accent); -} - -.claudian-ask-question-icon svg { - width: 16px; - height: 16px; -} - -.claudian-ask-question-label { - flex: 1; - font-size: 13px; - font-weight: 500; - color: var(--text-normal); - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.claudian-ask-question-count { - font-size: 12px; - color: var(--text-muted); -} - -.claudian-ask-question-status { - display: flex; - align-items: center; - flex-shrink: 0; -} - -.claudian-ask-question-status svg { - width: 14px; - height: 14px; -} - -.claudian-ask-question-status.status-completed { - color: var(--color-green); -} - -.claudian-ask-question-status.status-error, -.claudian-ask-question-status.status-blocked { - color: var(--color-red); -} - -/* Content - indented to align under label */ -.claudian-ask-question-content { - padding: 4px 0 4px 24px; -} - -/* Q&A pairs */ -.claudian-ask-question-qa { - display: flex; - flex-direction: column; - gap: 4px; - padding: 6px 0; -} - -.claudian-ask-question-qa + .claudian-ask-question-qa { - border-top: 1px solid var(--background-modifier-border); - padding-top: 10px; -} - -.claudian-ask-question-q-header { - font-size: 11px; - font-weight: 600; - color: var(--text-muted); - text-transform: uppercase; - letter-spacing: 0.5px; -} - -.claudian-ask-question-answer { - font-size: 13px; - color: var(--text-normal); - padding-left: 8px; - border-left: 2px solid var(--interactive-accent); -} - -.claudian-ask-question-error { - font-size: 12px; - color: var(--color-red); - font-style: italic; -} - -/* Q&A list - tree symbol + aligned container */ -.claudian-ask-question-list { - display: flex; - flex-direction: row; - align-items: flex-start; - gap: 8px; -} - -.claudian-ask-question-tree { - flex-shrink: 0; - font-size: 13px; - color: var(--text-muted); -} - -.claudian-ask-question-aligned { - flex: 1; - display: flex; - flex-direction: column; - gap: 8px; -} - -.claudian-ask-question-item { - display: flex; - flex-direction: column; - gap: 2px; -} - -.claudian-ask-question-q { - font-size: 13px; - color: var(--text-muted); - /* Hanging indent: wrapped lines align with text after "Q: " */ - padding-left: 1.5em; - text-indent: -1.5em; -} - -.claudian-ask-question-a { - font-size: 13px; - color: var(--color-green); - /* Hanging indent: wrapped lines align with text after "A: " */ - padding-left: 1.5em; - text-indent: -1.5em; -} - - -/* ============================================ - components/plan-approval.css - ============================================ */ -/** - * PlanApproval panel styles. - * Panel shows approval options (plan content is displayed in chat). - */ - -/* ============================================ - * Plan Approval Panel (replaces input area) - * ============================================ */ - -.claudian-plan-approval-panel { - /* Match input wrapper padding structure */ - padding: 10px; /* Same as .claudian-input */ - min-height: 60px; /* Same as .claudian-input min-height */ - outline: none; - display: flex; - flex-direction: column; - justify-content: center; -} - -.claudian-plan-approval-panel:focus { - outline: none; -} - -/* Header: "Would you like to proceed?" */ -.claudian-plan-approval-header { - font-size: 13px; - color: var(--text-muted); - margin-bottom: 6px; -} - -/* Options list - tighter spacing */ -.claudian-plan-approval-options { - display: flex; - flex-direction: column; - gap: 0; - font-family: var(--font-monospace); - font-size: 13px; -} - -.claudian-plan-approval-option { - display: flex; - align-items: center; - gap: 6px; - padding: 2px 0; - cursor: pointer; - color: var(--text-normal); - line-height: 1.4; -} - -.claudian-plan-approval-option:hover { - color: var(--interactive-accent); -} - -.claudian-plan-approval-option.focused { - color: var(--interactive-accent); -} - -/* Caret - narrower */ -.claudian-plan-approval-caret { - width: 10px; - flex-shrink: 0; - color: var(--interactive-accent); - font-weight: bold; -} - -.claudian-plan-approval-number { - flex-shrink: 0; - color: var(--text-muted); - white-space: nowrap; -} - -.claudian-plan-approval-option.focused .claudian-plan-approval-caret, -.claudian-plan-approval-option.focused .claudian-plan-approval-number { - color: var(--interactive-accent); -} - -.claudian-plan-approval-option-label { - font-weight: 500; -} - -/* Placeholder text for revise option (muted) */ -.claudian-plan-approval-placeholder { - color: var(--text-muted); - font-style: italic; -} - -/* Inline revise input - must blend perfectly with option text */ -.claudian-plan-approval-revise-inline { - flex: 1; - border: none !important; - background: transparent !important; - box-shadow: none !important; - color: var(--text-normal); - font-family: inherit; - font-size: inherit; - font-weight: 500; - outline: none; - padding: 0 !important; - margin: 0 !important; - line-height: inherit; - letter-spacing: inherit; - text-indent: 0; - min-width: 0; - height: auto; -} - -.claudian-plan-approval-revise-inline::placeholder { - color: var(--text-muted); - font-style: italic; - font-weight: 400; -} - -/* ============================================ - * Plan Message (distinct styling in chat) - * ============================================ */ - -.claudian-message-plan { - background: rgba(0, 0, 0, 0.15); - border-radius: 6px; - /* Match plan banner horizontal margin (0 12px 8px 12px) */ - margin: 8px 12px; - padding: 10px 16px; - /* Override assistant message width/max-width to respect margins */ - width: auto; - max-width: none; - /* Match plan banner font styling */ - font-size: 13px; - line-height: 1.5; -} - -/* ============================================ - * Approval Indicator (user's choice display) - * ============================================ */ - -.claudian-approval-indicator { - display: flex; - align-items: center; - gap: 4px; - margin: 8px 12px; - font-size: 13px; -} - -.claudian-approval-indicator-icon { - flex-shrink: 0; - display: flex; - align-items: center; -} - -.claudian-approval-indicator-icon svg { - width: 14px; - height: 14px; -} - -/* Text always muted */ -.claudian-approval-indicator-text { - color: var(--text-muted); - margin-left: 2px; -} - -/* Green check for approve (icon only) */ -.claudian-approval-indicator-approve .claudian-approval-indicator-icon { - color: var(--color-green); -} - -/* Red x for revise (icon only) */ -.claudian-approval-indicator-revise .claudian-approval-indicator-icon { - color: var(--color-red); -} - - -/* ============================================ - components/plan-banner.css - ============================================ */ -/** - * PlanBanner styles. - * Collapsible banner below header showing approved plan. - */ - -.claudian-plan-banner { - margin: 0 12px 8px 12px; - border-radius: 6px; - background: rgba(0, 168, 157, 0.08); - border: 1px solid rgba(0, 168, 157, 0.2); - overflow: hidden; -} - -.claudian-plan-banner.expanded { - background: rgba(0, 168, 157, 0.05); -} - -/* Header - clickable disclosure */ -.claudian-plan-banner-header { - display: flex; - align-items: center; - gap: 8px; - padding: 8px 12px; - cursor: pointer; - user-select: none; - transition: background 0.15s ease; -} - -.claudian-plan-banner-header:hover { - background: rgba(0, 168, 157, 0.1); -} - -.claudian-plan-banner-chevron { - font-size: 10px; - color: #00A89D; - transition: transform 0.15s ease; -} - -.claudian-plan-banner.expanded .claudian-plan-banner-chevron { - transform: rotate(0deg); -} - -.claudian-plan-banner-title { - font-size: 12px; - font-weight: 500; - color: #00A89D; -} - -/* Content area */ -.claudian-plan-banner-content { - padding: 0 12px 12px 12px; - max-height: 250px; - overflow-y: auto; - font-size: 13px; - line-height: 1.5; - border-top: 1px solid rgba(0, 168, 157, 0.15); -} - -.claudian-plan-banner-content h1, -.claudian-plan-banner-content h2, -.claudian-plan-banner-content h3 { - margin-top: 0.8em; - margin-bottom: 0.4em; - font-size: 14px; -} - -.claudian-plan-banner-content h1:first-child, -.claudian-plan-banner-content h2:first-child, -.claudian-plan-banner-content h3:first-child { - margin-top: 0.5em; -} - -.claudian-plan-banner-content p { - margin: 0.5em 0; -} - -.claudian-plan-banner-content ul, -.claudian-plan-banner-content ol { - margin: 0.5em 0; - padding-left: 1.5em; -} - -.claudian-plan-banner-content code { - font-size: 12px; - padding: 2px 4px; - background: var(--background-primary); - border-radius: 3px; -} - -.claudian-plan-banner-content pre { - padding: 8px; - background: var(--background-primary); - border-radius: 4px; - overflow-x: auto; - font-size: 12px; -} - - /* ============================================ components/input.css ============================================ */ @@ -1821,36 +1378,72 @@ padding: 12px 0 0 0; } -/* Input wrapper (border container) */ +/* Input wrapper (border container) - flex column so textarea expands when no chips */ +/* Height calculation: context row (36px) + textarea min (60px) + toolbar (38px) + border (2px) = 136px */ .claudian-input-wrapper { position: relative; + display: flex; + flex-direction: column; + min-height: 140px; border: 1px solid var(--background-modifier-border); border-radius: 6px; background: var(--background-primary); } +/* Context row (file chip left, selection indicator right) - inside input wrapper at top */ +/* Collapsed by default; expanded via .has-content class; textarea fills remaining space */ +.claudian-context-row { + display: none; + align-items: flex-start; + justify-content: space-between; + flex-shrink: 0; + padding: 6px 10px 0 10px; + gap: 8px; +} + +/* Show context row when it has visible content */ +.claudian-context-row.has-content { + display: flex; +} + +/* Nav row (tab badges left, header icons right) - above input wrapper */ +.claudian-input-nav-row { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 0 8px 0; + min-height: 0; +} + +/* Header mode: hide nav row above input (content moved to header) */ +.claudian-container--header-mode .claudian-input-nav-row { + display: none; +} + /* Selection indicator (shown when text is selected in editor) */ +/* Match file chip height (24px): chip has 16px remove button + 6px padding + 2px border */ +/* Indicator: 12px text + 10px padding (5+5) + 2px border = 24px */ .claudian-selection-indicator { - position: absolute; - top: 4px; - right: 8px; color: #7abaff; - font-size: 11px; + font-size: 12px; + line-height: 1; opacity: 0.9; pointer-events: none; white-space: nowrap; - z-index: 1; - background: var(--background-primary); - padding: 2px 6px; + padding: 5px 6px; + border: 1px solid transparent; border-radius: 4px; + margin-left: auto; + flex-shrink: 0; } .claudian-input { width: 100%; + flex: 1 1 0; min-height: 60px; - max-height: 200px; + /* max-height dynamically set by JS: max(150px, 55% of view height) */ resize: none; - padding: 10px; + padding: 8px 10px 10px 10px; border: none !important; border-radius: 6px; background: transparent !important; @@ -1859,6 +1452,7 @@ font-size: 14px; line-height: 1.4; box-shadow: none !important; + overflow-y: auto; } .claudian-input:hover, @@ -1878,6 +1472,7 @@ display: flex; align-items: center; justify-content: flex-start; + flex-shrink: 0; padding: 4px 6px 6px 6px; } @@ -1886,8 +1481,6 @@ display: none; flex-wrap: wrap; gap: 6px; - padding: 4px 0; - margin-bottom: 8px; } .claudian-file-chip { @@ -1899,6 +1492,7 @@ border: 1px solid var(--background-modifier-border); border-radius: 12px; font-size: 12px; + line-height: 1; max-width: 200px; cursor: pointer; } @@ -2023,13 +1617,13 @@ } .claudian-meter-fill { - stroke: #D97757; + stroke: var(--claudian-brand); transition: stroke-dashoffset 0.3s ease, stroke 0.3s ease; } .claudian-context-meter-percent { font-size: 11px; - color: #D97757; + color: var(--claudian-brand); min-width: 24px; text-align: right; transition: color 0.3s ease; @@ -2062,6 +1656,11 @@ cursor: pointer; color: var(--text-muted); font-size: 12px; + transition: color 0.2s ease; +} + +.claudian-model-btn.ready { + color: var(--claudian-brand); } .claudian-model-label { @@ -2119,8 +1718,8 @@ } .claudian-model-option.selected { - background: rgba(217, 119, 87, 0.15); - color: #D97757; + background: rgba(var(--claudian-brand-rgb), 0.15); + color: var(--claudian-brand); font-weight: 500; } @@ -2152,7 +1751,7 @@ .claudian-thinking-current { padding: 3px 8px; font-size: 11px; - color: #D97757; + color: var(--claudian-brand); font-weight: 500; cursor: pointer; border-radius: 3px; @@ -2200,8 +1799,8 @@ } .claudian-thinking-gear.selected { - background: rgba(217, 119, 87, 0.15); - color: #D97757; + background: rgba(var(--claudian-brand-rgb), 0.15); + color: var(--claudian-brand); font-weight: 500; } @@ -2253,58 +1852,27 @@ } .claudian-toggle-switch.active { - background: rgba(217, 119, 87, 0.3); + background: rgba(var(--claudian-brand-rgb), 0.3); } .claudian-toggle-switch.active::after { transform: translateX(14px); - background: #D97757; -} - -/* Plan mode state */ -.claudian-permission-toggle.plan-mode { - cursor: pointer; -} - -.claudian-permission-toggle.plan-mode .claudian-permission-label { - display: flex; - align-items: center; - gap: 4px; - color: #00A89D; - font-weight: 500; - min-width: auto; -} - -.claudian-permission-toggle.plan-mode .claudian-toggle-switch { - display: none; -} - -.claudian-plan-mode-icon { - display: flex; - align-items: center; - font-size: 10px; - letter-spacing: 2px; - transform: scaleX(1.3); - margin-right: 2px; -} - -.claudian-permission-toggle.plan-mode:hover .claudian-permission-label { - opacity: 0.8; + background: var(--claudian-brand); } /* ============================================ - toolbar/context-path.css + toolbar/external-context.css ============================================ */ -/* Context Path Selector */ -.claudian-context-path-selector { +/* External Context Selector */ +.claudian-external-context-selector { position: relative; display: flex; align-items: center; margin-left: 8px; } -.claudian-context-path-icon-wrapper { +.claudian-external-context-icon-wrapper { position: relative; display: flex; align-items: center; @@ -2312,7 +1880,7 @@ cursor: pointer; } -.claudian-context-path-icon { +.claudian-external-context-icon { display: flex; align-items: center; justify-content: center; @@ -2324,39 +1892,39 @@ transition: all 0.2s ease; } -.claudian-context-path-icon-wrapper:hover .claudian-context-path-icon { +.claudian-external-context-icon-wrapper:hover .claudian-external-context-icon { background: var(--background-modifier-hover); opacity: 0.8; } -.claudian-context-path-icon.active { - color: #D97757; +.claudian-external-context-icon.active { + color: var(--claudian-brand); opacity: 1; - animation: context-path-glow 2s ease-in-out infinite; + animation: external-context-glow 2s ease-in-out infinite; } -.claudian-context-path-icon svg { +.claudian-external-context-icon svg { width: 16px; height: 16px; } -.claudian-context-path-badge { +.claudian-external-context-badge { position: absolute; top: 0; right: 0; font-size: 9px; font-weight: 600; - color: #D97757; + color: var(--claudian-brand); opacity: 0; transition: opacity 0.15s ease; pointer-events: none; } -.claudian-context-path-badge.visible { +.claudian-external-context-badge.visible { opacity: 1; } -.claudian-context-path-dropdown { +.claudian-external-context-dropdown { position: absolute; left: 50%; transform: translateX(-50%); @@ -2374,12 +1942,12 @@ z-index: 100; } -.claudian-context-path-selector:hover .claudian-context-path-dropdown { +.claudian-external-context-selector:hover .claudian-external-context-dropdown { opacity: 1; visibility: visible; } -.claudian-context-path-header { +.claudian-external-context-header { padding: 10px 12px; font-size: 12px; font-weight: 600; @@ -2387,12 +1955,12 @@ border-bottom: 1px solid var(--background-modifier-border); } -.claudian-context-path-list { +.claudian-external-context-list { max-height: 200px; overflow-y: auto; } -.claudian-context-path-empty { +.claudian-external-context-empty { padding: 16px 12px; text-align: center; color: var(--text-muted); @@ -2400,7 +1968,7 @@ font-style: italic; } -.claudian-context-path-item { +.claudian-external-context-item { display: flex; align-items: center; padding: 8px 12px; @@ -2408,11 +1976,11 @@ border-bottom: 1px solid var(--background-modifier-border-focus); } -.claudian-context-path-item:last-child { +.claudian-external-context-item:last-child { border-bottom: none; } -.claudian-context-path-text { +.claudian-external-context-text { flex: 1; font-size: 12px; font-family: var(--font-monospace); @@ -2422,7 +1990,39 @@ white-space: nowrap; } -.claudian-context-path-remove { +.claudian-external-context-lock { + display: flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: 4px; + cursor: pointer; + color: var(--text-muted); + opacity: 0.4; + transition: all 0.15s ease; +} + +.claudian-external-context-lock:hover { + background: var(--background-modifier-hover); + opacity: 0.8; +} + +.claudian-external-context-lock.locked { + color: var(--claudian-brand); + opacity: 0.9; +} + +.claudian-external-context-lock.locked:hover { + opacity: 1; +} + +.claudian-external-context-lock svg { + width: 12px; + height: 12px; +} + +.claudian-external-context-remove { display: flex; align-items: center; justify-content: center; @@ -2435,13 +2035,13 @@ transition: all 0.15s ease; } -.claudian-context-path-remove:hover { - background: rgba(220, 53, 69, 0.15); - color: #dc3545; +.claudian-external-context-remove:hover { + background: rgba(var(--claudian-error-rgb), 0.15); + color: var(--claudian-error); opacity: 1; } -.claudian-context-path-remove svg { +.claudian-external-context-remove svg { width: 14px; height: 14px; } @@ -2484,7 +2084,7 @@ } .claudian-mcp-selector-icon.active { - color: #D97757; + color: var(--claudian-brand); opacity: 1; animation: mcp-glow 2s ease-in-out infinite; } @@ -2500,7 +2100,7 @@ right: 0; font-size: 9px; font-weight: 600; - color: #D97757; + color: var(--claudian-brand); opacity: 0; transition: opacity 0.15s ease; pointer-events: none; @@ -2579,7 +2179,7 @@ } .claudian-mcp-selector-item.enabled { - background: rgba(217, 119, 87, 0.1); + background: rgba(var(--claudian-brand-rgb), 0.1); } .claudian-mcp-selector-check { @@ -2590,12 +2190,12 @@ height: 16px; border: 1px solid var(--background-modifier-border); border-radius: 3px; - color: #D97757; + color: var(--claudian-brand); } .claudian-mcp-selector-item.enabled .claudian-mcp-selector-check { - background: rgba(217, 119, 87, 0.2); - border-color: #D97757; + background: rgba(var(--claudian-brand-rgb), 0.2); + border-color: var(--claudian-brand); } .claudian-mcp-selector-check svg { @@ -2625,8 +2225,8 @@ font-weight: 600; padding: 1px 4px; border-radius: 3px; - background: rgba(217, 119, 87, 0.2); - color: #D97757; + background: rgba(var(--claudian-brand-rgb), 0.2); + color: var(--claudian-brand); flex-shrink: 0; margin-left: auto; } @@ -2748,16 +2348,29 @@ /* Context file items in @-mention dropdown */ .claudian-mention-item.context-file .claudian-mention-icon { - color: #D97757; + color: var(--claudian-brand); +} + +.claudian-mention-item.context-file .claudian-mention-text { + flex-direction: row; + overflow: hidden; + white-space: nowrap; +} + +.claudian-mention-item.context-file .claudian-mention-name-context { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; } /* Context folder filter items in @-mention dropdown */ .claudian-mention-item.context-folder .claudian-mention-icon { - color: #D97757; + color: var(--claudian-brand); } .claudian-mention-name-folder { - color: #D97757; + color: var(--claudian-brand); font-weight: 600; } @@ -2765,6 +2378,70 @@ color: var(--text-normal); } +/* Agent folder items in @-mention dropdown */ +.claudian-mention-item.agent-folder .claudian-mention-icon { + color: var(--link-color); +} + +.claudian-mention-name-agent-folder { + color: var(--link-color); + font-weight: 600; +} + +/* Agent items in @-mention dropdown (inside @Agents/) */ +.claudian-mention-item.agent .claudian-mention-icon { + color: var(--link-color); +} + +.claudian-mention-item.agent .claudian-mention-text { + flex-direction: row; + align-items: baseline; + gap: 6px; + overflow: hidden; + white-space: nowrap; +} + +.claudian-mention-item.agent .claudian-mention-name-agent { + color: var(--text-normal); + font-size: 13px; + flex-shrink: 0; +} + +.claudian-mention-item.agent .claudian-mention-agent-desc { + font-size: 11px; + color: var(--text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + min-width: 0; +} + + +/* ============================================ + features/file-link.css + ============================================ */ +/* Clickable file links that open files in Obsidian */ +.claudian-file-link { + color: var(--text-accent); + text-decoration: none; + cursor: pointer; + border-radius: 3px; + transition: color 0.15s ease; +} + +.claudian-file-link:hover { + color: var(--text-accent-hover); + text-decoration: underline; +} + +/* File link inside inline code */ +code .claudian-file-link { + color: var(--text-accent); +} + +code .claudian-file-link:hover { + color: var(--text-accent-hover); +} /* ============================================ @@ -2836,23 +2513,44 @@ /* Remove button */ .claudian-image-remove { - display: flex; - align-items: center; - justify-content: center; - width: 18px; - height: 18px; + position: relative; + width: 20px; + height: 20px; border-radius: 50%; cursor: pointer; - color: var(--text-muted); - font-size: 16px; - line-height: 1; - transition: background 0.15s ease, color 0.15s ease; + transition: background 0.15s ease; flex-shrink: 0; + font-size: 0; /* Hide text character */ +} + +.claudian-image-remove::before, +.claudian-image-remove::after { + content: ''; + position: absolute; + top: 50%; + left: 50%; + width: 10px; + height: 2px; + background: var(--text-muted); + border-radius: 1px; + transition: background 0.15s ease; +} + +.claudian-image-remove::before { + transform: translate(-50%, -50%) rotate(45deg); +} + +.claudian-image-remove::after { + transform: translate(-50%, -50%) rotate(-45deg); } .claudian-image-remove:hover { background: var(--background-modifier-error); - color: var(--text-on-accent); +} + +.claudian-image-remove:hover::before, +.claudian-image-remove:hover::after { + background: var(--text-on-accent); } /* Drop overlay - inside input wrapper */ @@ -2862,8 +2560,8 @@ left: 0; right: 0; bottom: 0; - background: rgba(217, 119, 87, 0.08); - border: 2px dashed #D97757; + background: rgba(var(--claudian-brand-rgb), 0.08); + border: 2px dashed var(--claudian-brand); border-radius: 6px; display: none; align-items: center; @@ -2881,7 +2579,7 @@ flex-direction: column; align-items: center; gap: 4px; - color: #D97757; + color: var(--claudian-brand); } .claudian-drop-content svg { @@ -2930,6 +2628,51 @@ } +/* ============================================ + features/image-embed.css + ============================================ */ +/* Image embed styles - displays ![[image.png]] wikilinks as actual images */ + +.claudian-embedded-image { + display: inline-block; + max-width: 100%; + margin: 0.5em 0; + vertical-align: middle; +} + +.claudian-embedded-image img { + max-width: 100%; + height: auto; + border-radius: var(--radius-s); + cursor: pointer; + transition: opacity 0.2s ease; +} + +.claudian-embedded-image img:hover { + opacity: 0.9; +} + +/* When image is inline with text */ +.claudian-text-block p .claudian-embedded-image { + margin: 0.25em 0; +} + +/* Block-level image (standalone on its own line) */ +.claudian-text-block p > .claudian-embedded-image:only-child { + display: block; + margin: 0.75em 0; +} + +/* Fallback when image file not found */ +.claudian-embedded-image-fallback { + color: var(--text-muted); + font-style: italic; + background: var(--background-modifier-hover); + padding: 0.1em 0.4em; + border-radius: var(--radius-s); +} + + /* ============================================ features/image-modal.css ============================================ */ @@ -3061,10 +2804,10 @@ height: 14px; margin-top: -7px; border: 2px solid var(--background-modifier-border); - border-top-color: #D97757; + border-top-color: var(--claudian-brand); border-radius: 50%; box-sizing: border-box; - animation: claudian-inline-spin 0.8s linear infinite; + animation: claudian-spin 0.8s linear infinite; } /* Agent reply - shown when agent asks clarifying question */ @@ -3139,13 +2882,7 @@ .claudian-write-edit-block { margin: 4px 0; background: transparent; - scrollbar-width: none; - -ms-overflow-style: none; -} - -.claudian-write-edit-block::-webkit-scrollbar { - width: 0; - height: 0; + overflow: hidden; } .claudian-text-block+.claudian-write-edit-block { @@ -3159,11 +2896,12 @@ .claudian-write-edit-header { display: flex; align-items: center; - gap: 6px; + gap: 8px; padding: 4px 0; cursor: pointer; user-select: none; background: transparent; + overflow: hidden; } .claudian-write-edit-icon { @@ -3180,8 +2918,9 @@ .claudian-write-edit-label { flex: 1; + min-width: 0; font-size: 13px; - font-weight: 500; + font-weight: 400; color: var(--text-normal); overflow: hidden; text-overflow: ellipsis; @@ -3219,11 +2958,6 @@ height: 16px; } -.claudian-write-edit-status.status-running .claudian-spinner { - width: 14px; - height: 14px; -} - .claudian-write-edit-status.status-completed { color: var(--color-green); } @@ -3236,13 +2970,7 @@ .claudian-write-edit-content { padding: 0; background: transparent; - scrollbar-width: none; - -ms-overflow-style: none; -} - -.claudian-write-edit-content::-webkit-scrollbar { - width: 0; - height: 0; + overflow: hidden; } .claudian-write-edit-diff-row { @@ -3258,13 +2986,6 @@ max-height: 300px; overflow-y: auto; overflow-x: auto; - scrollbar-width: none; - -ms-overflow-style: none; -} - -.claudian-write-edit-diff::-webkit-scrollbar { - width: 0; - height: 0; } .claudian-write-edit-loading, @@ -3395,8 +3116,8 @@ } .claudian-slash-name { - font-size: 13px; - font-weight: 600; + font-size: 12px; + font-weight: 500; color: var(--text-normal); font-family: var(--font-monospace); } @@ -3405,13 +3126,15 @@ font-size: 12px; color: var(--text-muted); margin-left: 8px; - font-style: italic; } .claudian-slash-desc { - font-size: 12px; + font-size: 11px; color: var(--text-muted); margin-top: 2px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .claudian-slash-empty { @@ -3459,7 +3182,7 @@ } .claudian-approval-icon { - color: #D97757; + color: var(--claudian-brand); } .claudian-approval-tool-name { @@ -3514,7 +3237,7 @@ } .claudian-always-btn { - background: #D97757; + background: var(--claudian-brand); color: white; border: none; } @@ -3523,6 +3246,29 @@ background: #c56a4a; } +.claudian-approval-reason { + color: var(--text-muted); + font-size: 13px; + margin-bottom: 8px; +} + +.claudian-approval-blocked-path { + font-family: var(--font-monospace); + font-size: 12px; + color: var(--text-muted); + padding: 4px 8px; + background: var(--background-primary-alt); + border-radius: 4px; + margin-bottom: 8px; + word-break: break-all; +} + +.claudian-approval-agent { + color: var(--text-muted); + font-size: 13px; + margin-bottom: 8px; +} + /* ============================================ modals/instruction.css @@ -3676,7 +3422,7 @@ border: 2px solid var(--background-modifier-border); border-top-color: var(--interactive-accent); border-radius: 50%; - animation: claudian-instruction-spin 0.8s linear infinite; + animation: claudian-spin 0.8s linear infinite; } /* Instruction modal content sections */ @@ -3780,7 +3526,7 @@ .claudian-mcp-test-spinner { width: 20px; height: 20px; - animation: claudian-mcp-spin 1s linear infinite; + animation: claudian-spin 1s linear infinite; } .claudian-mcp-test-spinner svg { @@ -3913,6 +3659,10 @@ font-size: 12px; color: var(--text-muted); margin-top: 4px; + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; } .claudian-mcp-test-no-tools { @@ -3960,8 +3710,9 @@ } /* Custom section descriptions - align with items */ -.claudian-slash-settings-desc, +.claudian-sp-settings-desc, .claudian-mcp-settings-desc, +.claudian-plugin-settings-desc, .claudian-approved-desc { padding: 0 12px; } @@ -3996,96 +3747,271 @@ color: var(--text-error); } +/* Hotkey grid - 3 columns */ +.claudian-hotkey-grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 4px 12px; + padding: 4px 0; +} + +.claudian-hotkey-item { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 12px; + cursor: pointer; + border-radius: 6px; +} + +.claudian-hotkey-item:hover { + background: var(--background-modifier-hover); +} + +.claudian-hotkey-name { + flex: 1; + color: var(--text-normal); + font-size: var(--font-ui-small); +} + +.claudian-hotkey-badge { + color: var(--text-muted); + font-size: var(--font-ui-smaller); + background: var(--background-modifier-hover); + padding: 2px 6px; + border-radius: 4px; + font-family: var(--font-monospace); +} + /* Media folder input width */ .claudian-settings-media-input { width: 200px; } +/* ── Shared settings panel layout (used by slash-settings + agent-settings) ── */ -/* ============================================ - settings/approved-actions.css - ============================================ */ -/* Settings - Approved Actions List */ -.claudian-approved-desc { +.claudian-sp-header { + display: flex; + justify-content: space-between; + align-items: center; margin-bottom: 12px; + padding: 0 12px; } -.claudian-approved-empty { - padding: 16px; +.claudian-sp-label { + font-size: var(--font-ui-small); + color: var(--text-muted); + font-weight: var(--font-medium); +} + +.claudian-sp-header-actions { + display: flex; + gap: 4px; +} + +.claudian-sp-empty-state { + padding: 20px; text-align: center; color: var(--text-muted); background: var(--background-secondary); border-radius: 6px; - font-size: 13px; - margin-bottom: 16px; + margin-top: 8px; } -.claudian-approved-list { - margin-bottom: 16px; -} - -.claudian-approved-item { +.claudian-sp-list { display: flex; - align-items: center; + flex-direction: column; + gap: 8px; + margin-top: 8px; +} + +.claudian-sp-item { + display: flex; + align-items: flex-start; justify-content: space-between; padding: 12px; background: var(--background-secondary); border-radius: 6px; - margin-bottom: 8px; } -.claudian-approved-item-info { +.claudian-sp-item:hover { + background: var(--background-modifier-hover); +} + +.claudian-sp-info { flex: 1; min-width: 0; } -.claudian-approved-item-tool { - display: inline-block; - padding: 2px 8px; - background: rgba(217, 119, 87, 0.15); - color: #D97757; - border-radius: 4px; - font-size: 12px; - font-weight: 500; - margin-right: 8px; +.claudian-sp-item-header { + display: flex; + align-items: baseline; + gap: 8px; } -.claudian-approved-item-pattern { +.claudian-sp-item-name { + font-weight: 600; font-family: var(--font-monospace); - font-size: 12px; color: var(--text-normal); - margin-top: 4px; - word-break: break-all; - overflow: hidden; - text-overflow: ellipsis; } -.claudian-approved-item-date { - font-size: 11px; +.claudian-sp-item-desc { + font-size: 13px; color: var(--text-muted); - margin-left: 8px; + margin-top: 2px; } -.claudian-approved-remove-btn { - padding: 4px 12px; - font-size: 12px; - background: var(--background-modifier-error); - color: var(--text-on-accent); - border: none; - border-radius: 4px; - cursor: pointer; +.claudian-sp-item-actions { + display: flex; + gap: 4px; + margin-left: 16px; flex-shrink: 0; - margin-left: 12px; } -.claudian-approved-remove-btn:hover { - opacity: 0.9; +.claudian-sp-advanced-section { + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + padding: 0 12px; + margin: 8px 0; +} + +.claudian-sp-advanced-summary { + cursor: pointer; + padding: 8px 0; + font-size: var(--font-ui-small); + color: var(--text-muted); + font-weight: var(--font-medium); +} + +.claudian-sp-advanced-section[open] .claudian-sp-advanced-summary { + margin-bottom: 4px; +} + +.claudian-sp-modal .modal-content { + max-width: 600px; + width: auto; +} + +.claudian-sp-content-area { + width: 100%; + font-family: var(--font-monospace); + font-size: 13px; + padding: 8px; + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + background: var(--background-primary); + color: var(--text-normal); + resize: vertical; + margin-top: 8px; +} + +.claudian-sp-content-area:focus { + outline: none; + border-color: var(--interactive-accent); +} + +.claudian-sp-modal-buttons { + display: flex; + gap: 8px; + margin-top: 16px; + justify-content: flex-end; } /* ============================================ settings/env-snippets.css ============================================ */ +/* Context Limits Styles */ +.claudian-context-limits-container { + margin-top: 16px; +} + +.claudian-context-limits-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 8px; + margin-top: 16px; + padding: 0 12px; +} + +.claudian-context-limits-label { + font-size: var(--font-ui-small); + color: var(--text-muted); + font-weight: var(--font-medium); +} + +.claudian-context-limits-desc { + font-size: var(--font-ui-smaller); + color: var(--text-muted); + padding: 0 12px; + margin-bottom: 8px; +} + +.claudian-context-limits-list { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 8px; +} + +.claudian-context-limits-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px; + background: var(--background-secondary); + border-radius: 6px; + transition: background-color 0.2s; +} + +.claudian-context-limits-item:hover { + background: var(--background-modifier-hover); +} + +.claudian-context-limits-model { + font-family: var(--font-monospace); + font-size: var(--font-ui-small); + color: var(--text-normal); + flex: 1; + min-width: 0; + word-break: break-all; +} + +.claudian-context-limits-input-wrapper { + display: flex; + flex-direction: column; + align-items: flex-end; + margin-left: 16px; + flex-shrink: 0; +} + +.claudian-context-limits-input { + width: 80px; + padding: 4px 8px; + font-size: var(--font-ui-small); + border: 1px solid var(--background-modifier-border); + border-radius: 4px; + background: var(--background-primary); + color: var(--text-normal); +} + +.claudian-context-limits-input:focus { + border-color: var(--interactive-accent); + outline: none; +} + +.claudian-context-limits-input.claudian-input-error { + border-color: var(--text-error); +} + +.claudian-context-limit-validation { + display: none; + font-size: var(--font-ui-smaller); + color: var(--text-error); + margin-top: 4px; +} + /* Environment Snippets Styles */ .claudian-env-snippets-container { margin-top: 16px; @@ -4315,109 +4241,40 @@ opacity: 0.9; } +/* Context limits section in snippet modal */ +.claudian-snippet-context-limits { + margin-top: 1em; +} + +.claudian-snippet-context-limits .setting-item-description { + margin-bottom: 0.5em; +} + +.claudian-snippet-limit-row { + display: flex; + align-items: center; + gap: 0.5em; + margin-bottom: 0.25em; +} + +.claudian-snippet-limit-model { + font-family: var(--font-monospace); + font-size: var(--font-ui-small); +} + +.claudian-snippet-limit-spacer { + flex: 1; +} + +.claudian-snippet-limit-input { + width: 80px; +} + /* ============================================ settings/slash-settings.css ============================================ */ -/* Slash Command Settings */ -.claudian-slash-settings-desc { - margin-bottom: 12px; -} - -.claudian-slash-header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 12px; - padding: 0 12px; -} - -.claudian-slash-label { - font-size: var(--font-ui-small); - color: var(--text-muted); - font-weight: var(--font-medium); -} - -.claudian-slash-header-actions { - display: flex; - gap: 4px; -} - -.claudian-add-slash-btn { - padding: 4px 12px; - font-size: 12px; - background: var(--interactive-accent); - color: var(--text-on-accent); - border: none; - border-radius: 4px; - cursor: pointer; -} - -.claudian-add-slash-btn:hover { - opacity: 0.9; -} - -.claudian-export-btn, -.claudian-import-btn { - padding: 4px 12px; - font-size: 12px; - background: var(--background-modifier-border); - color: var(--text-normal); - border: none; - border-radius: 4px; - cursor: pointer; -} - -.claudian-export-btn:hover, -.claudian-import-btn:hover { - background: var(--background-modifier-border-hover); -} - -.claudian-slash-empty-state { - padding: 20px; - text-align: center; - color: var(--text-muted); - background: var(--background-secondary); - border-radius: 6px; - margin-top: 8px; -} - -.claudian-slash-list { - display: flex; - flex-direction: column; - gap: 8px; - margin-top: 8px; -} - -.claudian-slash-item-settings { - display: flex; - align-items: flex-start; - justify-content: space-between; - padding: 12px; - background: var(--background-secondary); - border-radius: 6px; -} - -.claudian-slash-item-settings:hover { - background: var(--background-modifier-hover); -} - -.claudian-slash-info { - flex: 1; - min-width: 0; -} - -.claudian-slash-item-header { - display: flex; - align-items: baseline; - gap: 8px; -} - -.claudian-slash-item-name { - font-weight: 600; - font-family: var(--font-monospace); - color: var(--text-normal); -} +/* Slash Command Settings — unique rules only (shared layout in base.css .claudian-sp-*) */ .claudian-slash-item-hint { font-size: 12px; @@ -4425,86 +4282,13 @@ font-style: italic; } -.claudian-slash-item-desc { - font-size: 13px; - color: var(--text-muted); - margin-top: 2px; -} - -.claudian-slash-item-preview { - font-size: 12px; - color: var(--text-faint); - font-family: var(--font-monospace); - margin-top: 4px; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.claudian-slash-item-actions { - display: flex; - gap: 4px; - margin-left: 16px; - flex-shrink: 0; -} - -.claudian-edit-slash-btn { - padding: 4px 12px; - font-size: 12px; +.claudian-slash-item-badge { + font-size: 10px; + padding: 2px 6px; background: var(--background-modifier-border); - color: var(--text-normal); - border: none; border-radius: 4px; - cursor: pointer; -} - -.claudian-edit-slash-btn:hover { - background: var(--background-modifier-border-hover); -} - -.claudian-delete-slash-btn { - padding: 4px 12px; - font-size: 12px; - background: var(--background-modifier-error); - color: var(--text-on-accent); - border: none; - border-radius: 4px; - cursor: pointer; -} - -.claudian-delete-slash-btn:hover { - opacity: 0.9; -} - -/* Slash Command Modal */ -.claudian-slash-modal .modal-content { - max-width: 600px; - width: auto; -} - -.claudian-slash-content-area { - width: 100%; - font-family: var(--font-monospace); - font-size: 13px; - padding: 8px; - border: 1px solid var(--background-modifier-border); - border-radius: 4px; - background: var(--background-primary); - color: var(--text-normal); - resize: vertical; - margin-top: 8px; -} - -.claudian-slash-content-area:focus { - outline: none; - border-color: var(--interactive-accent); -} - -.claudian-slash-modal-buttons { - display: flex; - gap: 8px; - margin-top: 16px; - justify-content: flex-end; + color: var(--text-muted); + text-transform: uppercase; } @@ -4724,100 +4508,223 @@ } +/* ============================================ + settings/plugin-settings.css + ============================================ */ +/* Plugin Settings */ +.claudian-plugin-settings-desc { + margin-bottom: 12px; +} + +.claudian-plugins-container { + margin-top: 8px; +} + +.claudian-plugin-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 12px; + padding: 0 12px; +} + +.claudian-plugin-label { + font-size: var(--font-ui-small); + color: var(--text-muted); + font-weight: var(--font-medium); +} + +.claudian-plugin-empty { + padding: 16px; + text-align: center; + color: var(--text-muted); + font-size: 13px; + background: var(--background-secondary); + border-radius: 6px; +} + +.claudian-plugin-list { + display: flex; + flex-direction: column; + gap: 8px; +} + +.claudian-plugin-section-header { + font-size: 11px; + color: var(--text-muted); + text-transform: uppercase; + padding: 8px 12px 4px; + font-weight: 600; +} + +.claudian-plugin-item { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 10px 12px; + background: var(--background-secondary); + border-radius: 6px; + transition: background 0.15s ease; +} + +.claudian-plugin-item:hover { + background: var(--background-modifier-hover); +} + +.claudian-plugin-item-disabled { + opacity: 0.6; +} + +.claudian-plugin-item-error { + opacity: 0.8; +} + +.claudian-plugin-status { + width: 8px; + height: 8px; + border-radius: 50%; + margin-top: 6px; + flex-shrink: 0; +} + +.claudian-plugin-status-enabled { + background: var(--color-green); +} + +.claudian-plugin-status-disabled { + background: var(--text-muted); +} + +.claudian-plugin-status-error { + background: var(--text-error); +} + +.claudian-plugin-info { + flex: 1; + min-width: 0; +} + +.claudian-plugin-name-row { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.claudian-plugin-name { + font-weight: 600; +} + +.claudian-plugin-version-badge { + font-size: 10px; + padding: 2px 6px; + background: var(--background-modifier-border); + border-radius: 4px; + color: var(--text-muted); +} + +.claudian-plugin-error-badge { + font-size: 10px; + padding: 2px 6px; + background: var(--text-error); + color: var(--text-on-accent); + border-radius: 4px; + text-transform: uppercase; +} + +.claudian-plugin-preview { + font-size: 12px; + color: var(--text-muted); + margin-top: 4px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.claudian-plugin-preview-error { + color: var(--text-error); +} + +.claudian-plugin-actions { + display: flex; + gap: 4px; + flex-shrink: 0; +} + +.claudian-plugin-action-btn { + display: flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: none; + background: transparent; + border-radius: 4px; + cursor: pointer; + color: var(--text-muted); + transition: background 0.15s ease, color 0.15s ease; +} + +.claudian-plugin-action-btn:hover { + background: var(--background-modifier-hover); + color: var(--text-normal); +} + +.claudian-plugin-action-btn svg { + width: 14px; + height: 14px; +} + + +/* ============================================ + settings/agent-settings.css + ============================================ */ +/* Agent Settings — all structural rules live in base.css .claudian-sp-* */ +/* This file is kept as a placeholder for future agent-specific overrides. */ + + /* ============================================ accessibility.css ============================================ */ /* Accessibility - Focus Visible Styles */ -/* Collapsible headers - keyboard focus indicators */ +/* outline + offset + border-radius */ .claudian-tool-header:focus-visible, .claudian-thinking-header:focus-visible, -.claudian-subagent-header:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; - border-radius: 4px; -} - -/* Header buttons focus indicators */ -.claudian-header-btn:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; - border-radius: 4px; -} - -/* Action buttons in history dropdown */ -.claudian-action-btn:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; -} - -/* History items focus indicator */ -.claudian-history-item-content:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: -2px; - border-radius: 4px; -} - -/* Approval modal buttons */ -.claudian-approval-btn:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; -} - -/* Toggle switch focus indicator */ -.claudian-toggle-switch:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; -} - -/* Model selector button */ -.claudian-model-btn:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; - border-radius: 4px; -} - -/* Thinking budget selector */ +.claudian-subagent-header:focus-visible, +.claudian-header-btn:focus-visible, +.claudian-model-btn:focus-visible, .claudian-thinking-current:focus-visible { outline: 2px solid var(--interactive-accent); outline-offset: 2px; border-radius: 4px; } -/* File chips focus indicator */ -.claudian-file-chip:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; -} - -/* Image chips focus indicator */ -.claudian-image-chip:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; -} - -/* Remove buttons focus indicator */ +/* outline + offset only */ +.claudian-action-btn:focus-visible, +.claudian-approval-btn:focus-visible, +.claudian-toggle-switch:focus-visible, +.claudian-file-chip:focus-visible, +.claudian-image-chip:focus-visible, .claudian-file-chip-remove:focus-visible, .claudian-image-remove:focus-visible, -.claudian-image-modal-close:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; -} - -/* Settings buttons */ +.claudian-image-modal-close:focus-visible, .claudian-approved-remove-btn:focus-visible, .claudian-save-env-btn:focus-visible, .claudian-restore-snippet-btn:focus-visible, .claudian-edit-snippet-btn:focus-visible, .claudian-delete-snippet-btn:focus-visible, .claudian-cancel-btn:focus-visible, -.claudian-save-btn:focus-visible { - outline: 2px solid var(--interactive-accent); - outline-offset: 2px; -} - -/* Code language label (copy button) */ +.claudian-save-btn:focus-visible, .claudian-code-lang-label:focus-visible { outline: 2px solid var(--interactive-accent); outline-offset: 2px; } + +/* outline + negative offset + border-radius */ +.claudian-history-item-content:focus-visible { + outline: 2px solid var(--interactive-accent); + outline-offset: -2px; + border-radius: 4px; +} diff --git a/.obsidian/plugins/note-buddy/main.js b/.obsidian/plugins/note-buddy/main.js index ba70431..9b01d92 100644 --- a/.obsidian/plugins/note-buddy/main.js +++ b/.obsidian/plugins/note-buddy/main.js @@ -239,6 +239,16 @@ var OpenCodeClient = class _OpenCodeClient { this.providersCacheTime = 0; this.cachedDefaults = null; } + /** + * Fetches available AI providers and models from the OpenCode server. + * + * Results are cached for 5 minutes to reduce API calls. The cache can be bypassed + * by setting forceRefresh to true or by calling clearModelsCache() first. + * + * @param forceRefresh - If true, bypasses cache and fetches fresh data from server + * @returns Array of providers with their available models + * @throws Error if the server is unreachable, returns invalid JSON, or responds with non-200 status + */ async getCapabilities(forceRefresh = false) { const now = Date.now(); if (!forceRefresh && this.cachedProviders && now - this.providersCacheTime < MODELS_CACHE_TTL) { @@ -294,12 +304,360 @@ var ChatView = class extends import_obsidian2.ItemView { super(leaf); this.plugin = plugin; this.messages = []; + this.isUserNearBottom = true; + this.hasInitialScroll = false; + this.previousScrollTop = 0; + this.previousWasNearBottom = true; + this.isInitialized = false; + this.handleMessagesScroll = () => { + const threshold = 32; + const distanceToBottom = this.messagesContainer.scrollHeight - this.messagesContainer.scrollTop - this.messagesContainer.clientHeight; + this.isUserNearBottom = distanceToBottom <= threshold; + this.previousScrollTop = this.messagesContainer.scrollTop; + this.previousWasNearBottom = this.isUserNearBottom; + if (this.isUserNearBottom) { + this.hideNewMessageIndicator(); + } + }; this.client = new OpenCodeClient( plugin.settings.serviceUrl, plugin.settings.defaultModelId, plugin.onModelUnavailable?.bind(plugin) ); } + /** + * Show loading indicator + */ + showLoading() { + if (this.loadingIndicator) return; + this.loadingIndicator = this.messagesContainer.createDiv({ cls: "nb-loading-indicator" }); + const dotsContainer = this.loadingIndicator.createDiv({ cls: "nb-loading-dots" }); + dotsContainer.createDiv({ cls: "nb-loading-dot" }); + dotsContainer.createDiv({ cls: "nb-loading-dot" }); + dotsContainer.createDiv({ cls: "nb-loading-dot" }); + this.maybeAutoScroll(); + } + /** + * Hide loading indicator + */ + hideLoading() { + if (this.loadingIndicator) { + this.loadingIndicator.remove(); + this.loadingIndicator = void 0; + } + } + /** + * Scroll to bottom of messages + */ + scrollToBottom() { + this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight; + this.hideNewMessageIndicator(); + } + showNewMessageIndicator() { + if (!this.newMessageIndicator) return; + this.newMessageIndicator.style.display = "flex"; + } + hideNewMessageIndicator() { + if (!this.newMessageIndicator) return; + this.newMessageIndicator.style.display = "none"; + } + maybeAutoScroll() { + if (!this.messagesContainer) return; + if (!this.hasInitialScroll) { + this.scrollToBottom(); + this.hasInitialScroll = true; + return; + } + if (this.isUserNearBottom) { + this.scrollToBottom(); + } else { + this.showNewMessageIndicator(); + } + } + /** + * Render error message with retry button + */ + renderErrorMessage(errorText, retryMessage) { + const errorContainer = this.messagesContainer.createDiv({ cls: "nb-error-container" }); + errorContainer.createDiv({ cls: "nb-error-message", text: errorText }); + if (retryMessage) { + const retryButton = errorContainer.createEl("button", { + cls: "nb-retry-button", + text: "Retry" + }); + retryButton.onclick = () => { + const errorIndex = this.messages.findIndex((m) => m.kind === "error" && m.text === errorText); + if (errorIndex !== -1) { + this.messages.splice(errorIndex, 1); + } + this.retrySendMessage(retryMessage); + }; + } + } + /** + * Send message with timeout + */ + async sendWithTimeout(promise, timeoutMs) { + return Promise.race([ + promise, + new Promise( + (_, reject) => setTimeout(() => reject(new Error("Request timed out after 30 seconds")), timeoutMs) + ) + ]); + } + /** + * Retry sending a message + */ + async retrySendMessage(message) { + this.renderMessages(); + this.showLoading(); + try { + if (!this.plugin.sessionState) { + this.plugin.sessionState = await this.sendWithTimeout( + this.client.createSession(), + 3e4 + ); + } + const sendData = { + parts: [{ type: "text", text: message }] + }; + if (this.plugin.settings.defaultModelId) { + const parts = this.plugin.settings.defaultModelId.split("/"); + if (parts.length === 2) { + sendData.model = { + providerID: parts[0], + modelID: parts[1] + }; + } + } + let response; + try { + response = await this.sendWithTimeout( + this.client.sendMessageToSession(this.plugin.sessionState.sessionID, sendData), + 3e4 + ); + } catch (sendError) { + const err = sendError; + if (err.message.includes("Session not found")) { + this.plugin.sessionState = await this.sendWithTimeout( + this.client.createSession(), + 3e4 + ); + response = await this.sendWithTimeout( + this.client.sendMessageToSession(this.plugin.sessionState.sessionID, sendData), + 3e4 + ); + } else { + throw sendError; + } + } + this.hideLoading(); + for (const part of response.parts) { + this.messages.push({ kind: "assistantPart", part }); + } + this.renderMessages(); + await this.saveChatState(); + } catch (error) { + this.hideLoading(); + this.messages.push({ + kind: "error", + text: `Failed to send message: ${error.message}`, + retryMessage: message + }); + this.renderMessages(); + await this.saveChatState(); + } + } + /** + * Clear chat history with confirmation + */ + async clearChat() { + const confirmed = confirm("Are you sure you want to clear the chat history? This cannot be undone."); + if (!confirmed) return; + this.messages = []; + this.plugin.sessionState = void 0; + await this.saveChatState(); + this.renderMessages(); + try { + this.plugin.sessionState = await this.sendWithTimeout( + this.client.createSession(), + 3e4 + ); + await this.saveChatState(); + } catch (error) { + console.error("[NoteBuddy] Failed to create new session after clearing chat:", error); + } + } + /** + * Render markdown text to HTML elements + * Supports: code blocks, inline code, bold, italic, lists + */ + renderMarkdown(text, container) { + const lines = text.split("\n"); + let inCodeBlock = false; + let codeBlockContent = []; + let listItems = []; + let inList = false; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (line.trim().startsWith("```")) { + if (inCodeBlock) { + const pre = container.createEl("pre"); + const code = pre.createEl("code"); + code.textContent = codeBlockContent.join("\n"); + codeBlockContent = []; + inCodeBlock = false; + } else { + inCodeBlock = true; + } + continue; + } + if (inCodeBlock) { + codeBlockContent.push(line); + continue; + } + const listMatch = line.match(/^(\s*)([-*]|\d+\.)\s+(.+)$/); + if (listMatch) { + if (!inList) { + inList = true; + listItems = []; + } + listItems.push(listMatch[3]); + continue; + } else if (inList) { + const ul = container.createEl("ul"); + listItems.forEach((item) => { + const li = ul.createEl("li"); + this.renderInlineMarkdown(item, li); + }); + listItems = []; + inList = false; + } + if (line.trim()) { + const p = container.createEl("span"); + this.renderInlineMarkdown(line, p); + if (i < lines.length - 1) { + container.createEl("br"); + } + } + } + if (inList) { + const ul = container.createEl("ul"); + listItems.forEach((item) => { + const li = ul.createEl("li"); + this.renderInlineMarkdown(item, li); + }); + } + } + /** + * Render inline markdown (bold, italic, inline code) + */ + renderInlineMarkdown(text, container) { + const codeRegex = /`([^`]+)`/g; + let lastIndex = 0; + let match; + const parts = []; + while ((match = codeRegex.exec(text)) !== null) { + if (match.index > lastIndex) { + parts.push({ type: "text", content: text.substring(lastIndex, match.index) }); + } + parts.push({ type: "code", content: match[1] }); + lastIndex = match.index + match[0].length; + } + if (lastIndex < text.length) { + parts.push({ type: "text", content: text.substring(lastIndex) }); + } + parts.forEach((part) => { + if (part.type === "code") { + container.createEl("code", { text: part.content }); + } else { + this.renderTextWithFormatting(part.content, container); + } + }); + } + /** + * Render a message bubble with appropriate styling + */ + renderMessageBubble(kind, content, container) { + const messageEl = container.createDiv({ + cls: `nb-message nb-message-${kind}` + }); + this.renderMarkdown(content, messageEl); + return messageEl; + } + /** + * Render text with bold and italic formatting + */ + renderTextWithFormatting(text, container) { + const boldRegex = /\*\*([^*]+)\*\*/g; + const italicRegex = /\*([^*]+)\*/g; + let result = text; + const elements = []; + let match; + while ((match = boldRegex.exec(text)) !== null) { + elements.push({ start: match.index, end: match.index + match[0].length, type: "bold" }); + } + while ((match = italicRegex.exec(text)) !== null) { + const currentMatch = match; + const isBold = elements.some((e) => e.start <= currentMatch.index && currentMatch.index < e.end); + if (!isBold) { + elements.push({ + start: currentMatch.index, + end: currentMatch.index + currentMatch[0].length, + type: "italic" + }); + } + } + elements.sort((a, b) => a.start - b.start); + let lastIndex = 0; + elements.forEach((el) => { + if (el.start > lastIndex) { + container.appendText(text.substring(lastIndex, el.start)); + } + const content = text.substring(el.start, el.end); + if (el.type === "bold") { + const cleaned = content.replace(/\*\*/g, ""); + container.createEl("strong", { text: cleaned }); + } else { + const cleaned = content.replace(/\*/g, ""); + container.createEl("em", { text: cleaned }); + } + lastIndex = el.end; + }); + if (lastIndex < text.length) { + container.appendText(text.substring(lastIndex)); + } + } + /** + * Save chat state to plugin data + */ + async saveChatState() { + try { + const chatState = { + messages: this.messages, + sessionState: this.plugin.sessionState + }; + await this.plugin.saveData({ ...this.plugin.settings, chatState }); + } catch (error) { + console.error("[NoteBuddy] Failed to save chat state:", error); + } + } + /** + * Load chat state from plugin data + */ + async loadChatState() { + try { + const data = await this.plugin.loadData(); + if (data?.chatState) { + this.messages = data.chatState.messages || []; + if (data.chatState.sessionState) { + this.plugin.sessionState = data.chatState.sessionState; + } + } + } catch (error) { + console.error("[NoteBuddy] Failed to load chat state:", error); + } + } getViewType() { return VIEW_TYPE_CHAT; } @@ -307,80 +665,63 @@ var ChatView = class extends import_obsidian2.ItemView { return "NoteBuddy Chat"; } async onOpen() { + if (!this.isInitialized) { + await this.loadChatState(); + this.isInitialized = true; + } const container = this.containerEl.children[1]; container.empty(); + container.addClass("note-buddy-chat-view"); const chatContainer = container.createDiv({ cls: "nb-chat-container" }); - chatContainer.style.cssText = ` - display: flex; - flex-direction: column; - height: 100%; - gap: 1rem; - `; + const toolbar = chatContainer.createDiv({ cls: "nb-toolbar" }); + toolbar.createDiv({ cls: "nb-toolbar-title", text: "NoteBuddy Chat" }); + const toolbarActions = toolbar.createDiv({ cls: "nb-toolbar-actions" }); + const clearButton = toolbarActions.createEl("button", { + cls: "nb-toolbar-button", + attr: { "aria-label": "Clear chat", title: "Clear chat" } + }); + (0, import_obsidian2.setIcon)(clearButton, "trash-2"); + clearButton.onclick = () => this.clearChat(); const messagesContainer = chatContainer.createDiv({ cls: "nb-messages-container" }); this.messagesContainer = messagesContainer; - messagesContainer.style.cssText = ` - flex: 1; - overflow-y: auto; - display: flex; - flex-direction: column; - gap: 0.5rem; - padding: 1rem; - `; + this.messagesContainer.addEventListener("scroll", this.handleMessagesScroll); + this.previousScrollTop = 0; + this.previousWasNearBottom = true; + const newMessageIndicator = chatContainer.createDiv({ cls: "nb-new-message-indicator" }); + const indicatorButton = newMessageIndicator.createEl("button", { + cls: "nb-new-message-button", + text: "\u65B0\u6D88\u606F", + attr: { "aria-label": "New messages" } + }); + indicatorButton.onclick = () => { + this.scrollToBottom(); + }; + this.newMessageIndicator = newMessageIndicator; + this.hideNewMessageIndicator(); this.renderMessages(); - const welcomeMessage = messagesContainer.createDiv({ cls: "nb-message nb-message-system" }); - welcomeMessage.createSpan({ text: "Welcome to NoteBuddy! Chat with your notes here." }); - welcomeMessage.style.cssText = ` - padding: 0.75rem; - background-color: var(--background-secondary); - border-radius: 0.5rem; - font-size: 0.9rem; - color: var(--text-muted); - `; const inputContainer = chatContainer.createDiv({ cls: "nb-input-container" }); - inputContainer.style.cssText = ` - display: flex; - gap: 0.5rem; - padding: 1rem; - border-top: 1px solid var(--background-modifier-border); - `; const textarea = inputContainer.createEl("textarea", { cls: "nb-chat-input", attr: { placeholder: "Type your message..." } }); - textarea.style.cssText = ` - flex: 1; - min-height: 60px; - max-height: 150px; - padding: 0.5rem; - border: 1px solid var(--background-modifier-border); - border-radius: 0.375rem; - background-color: var(--background-primary); - color: var(--text-normal); - resize: vertical; - font-family: inherit; - `; const sendButton = inputContainer.createEl("button", { cls: "nb-send-button", - text: "Send" + attr: { "aria-label": "Send message", title: "Send message" } }); - sendButton.style.cssText = ` - padding: 0.5rem 1rem; - background-color: var(--interactive-accent); - color: var(--text-on-accent); - border: none; - border-radius: 0.375rem; - cursor: pointer; - font-weight: 500; - `; + (0, import_obsidian2.setIcon)(sendButton, "send"); const sendMessage = async () => { const message = textarea.value.trim(); if (!message) return; this.messages.push({ kind: "userText", text: message }); this.renderMessages(); textarea.value = ""; + this.showLoading(); try { if (!this.plugin.sessionState) { - this.plugin.sessionState = await this.client.createSession(); + this.plugin.sessionState = await this.sendWithTimeout( + this.client.createSession(), + 3e4 + ); } const sendData = { parts: [{ type: "text", text: message }] @@ -396,24 +737,41 @@ var ChatView = class extends import_obsidian2.ItemView { } let response; try { - response = await this.client.sendMessageToSession(this.plugin.sessionState.sessionID, sendData); + response = await this.sendWithTimeout( + this.client.sendMessageToSession(this.plugin.sessionState.sessionID, sendData), + 3e4 + ); } catch (sendError) { const err = sendError; if (err.message.includes("Session not found")) { - this.plugin.sessionState = await this.client.createSession(); - response = await this.client.sendMessageToSession(this.plugin.sessionState.sessionID, sendData); + this.plugin.sessionState = await this.sendWithTimeout( + this.client.createSession(), + 3e4 + ); + response = await this.sendWithTimeout( + this.client.sendMessageToSession(this.plugin.sessionState.sessionID, sendData), + 3e4 + ); } else { throw sendError; } } + this.hideLoading(); for (const part of response.parts) { this.messages.push({ kind: "assistantPart", part }); } this.renderMessages(); - this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight; + await this.saveChatState(); } catch (error) { + this.hideLoading(); console.error("[NoteBuddy] Send failed:", error); - new import_obsidian2.Notice(`Failed to send message: ${error.message}`); + this.messages.push({ + kind: "error", + text: `Failed to send message: ${error.message}`, + retryMessage: message + }); + this.renderMessages(); + await this.saveChatState(); } }; sendButton.onclick = sendMessage; @@ -428,49 +786,38 @@ var ChatView = class extends import_obsidian2.ItemView { console.log("[NoteBuddy] Chat view closed"); } renderMessages() { + const shouldRestoreScroll = !this.isUserNearBottom; + const previousScrollTop = this.previousScrollTop; this.messagesContainer.empty(); if (this.messages.length === 0) { - const welcomeMessage = this.messagesContainer.createDiv({ cls: "nb-message nb-message-system" }); - welcomeMessage.createSpan({ text: "Welcome to NoteBuddy! Chat with your notes here." }); - welcomeMessage.style.cssText = ` - padding: 0.75rem; - background-color: var(--background-secondary); - border-radius: 0.5rem; - font-size: 0.9rem; - color: var(--text-muted); - `; + const emptyState = this.messagesContainer.createDiv({ cls: "nb-empty-state" }); + emptyState.createDiv({ cls: "nb-empty-title", text: "Welcome to NoteBuddy" }); + emptyState.createDiv({ + cls: "nb-empty-subtitle", + text: "Ask your notes a question or start a new conversation." + }); + this.hideNewMessageIndicator(); + this.hasInitialScroll = true; return; } for (const item of this.messages) { if (item.kind === "userText") { - const messageEl2 = this.messagesContainer.createDiv({ cls: "nb-message nb-message-user" }); - messageEl2.createSpan({ text: item.text }); - messageEl2.style.cssText = ` - padding: 0.75rem; - background-color: var(--background-modifier-accent); - border-radius: 0.5rem; - font-size: 0.9rem; - align-self: flex-end; - max-width: 70%; - `; + this.renderMessageBubble("user", item.text, this.messagesContainer); + continue; + } + if (item.kind === "error") { + this.renderErrorMessage(item.text, item.retryMessage); continue; } const part = item.part; const messageEl = this.messagesContainer.createDiv({ cls: "nb-message nb-message-assistant" }); - messageEl.style.cssText = ` - padding: 0.75rem; - background-color: var(--background-secondary); - border-radius: 0.5rem; - font-size: 0.9rem; - align-self: flex-start; - max-width: 70%; - `; switch (part.type) { case "text": - messageEl.createSpan({ text: part.text }); + this.renderMarkdown(part.text, messageEl); break; case "reasoning": - messageEl.createSpan({ text: part.text }); + messageEl.createEl("div", { text: "Reasoning:", cls: "nb-part-label" }); + this.renderMarkdown(part.text, messageEl); break; case "tool": messageEl.createEl("strong", { text: `Tool: ${part.tool}` }); @@ -514,6 +861,12 @@ var ChatView = class extends import_obsidian2.ItemView { break; } } + if (shouldRestoreScroll) { + this.messagesContainer.scrollTop = previousScrollTop; + this.showNewMessageIndicator(); + } else { + this.maybeAutoScroll(); + } } }; @@ -536,44 +889,81 @@ var NoteBuddySettingTab = class extends import_obsidian3.PluginSettingTab { } catch { } } - new import_obsidian3.Setting(containerEl).setName("Service URL").setDesc("The URL of the OpenCode service (must include protocol, hostname, and port)").addText( + const connectionGroup = containerEl.createDiv({ cls: "nb-settings-group" }); + connectionGroup.createEl("h3", { text: "Connection Settings", cls: "nb-settings-group-title" }); + new import_obsidian3.Setting(connectionGroup).setName("Service URL").setDesc("The URL of the OpenCode service (must include protocol, hostname, and port)").addText( (text) => text.setPlaceholder("http://127.0.0.1:4096").setValue(this.plugin.settings.serviceUrl).onChange(async (value) => { + const previousServiceUrl = this.plugin.settings.serviceUrl; + const validationEl = text.inputEl.parentElement?.querySelector(".nb-settings-validation-error, .nb-settings-validation-success"); + if (validationEl) { + validationEl.remove(); + } if (!value.startsWith("http://") && !value.startsWith("https://")) { - new import_obsidian3.Notice("Service URL must start with http:// or https://"); + const errorEl = text.inputEl.parentElement?.createDiv({ cls: "nb-settings-validation-error" }); + if (errorEl) errorEl.textContent = "Service URL must start with http:// or https://"; return; } try { const url = new URL(value); if (!url.hostname || url.hostname === "") { - new import_obsidian3.Notice("Service URL must include a valid hostname"); + const errorEl = text.inputEl.parentElement?.createDiv({ cls: "nb-settings-validation-error" }); + if (errorEl) errorEl.textContent = "Service URL must include a valid hostname"; return; } if (!url.port || url.port === "") { - new import_obsidian3.Notice("Service URL must include a port number"); + const errorEl = text.inputEl.parentElement?.createDiv({ cls: "nb-settings-validation-error" }); + if (errorEl) errorEl.textContent = "Service URL must include a port number"; return; } + const successEl = text.inputEl.parentElement?.createDiv({ cls: "nb-settings-validation-success" }); + if (successEl) successEl.textContent = "\u2713 Valid URL format"; } catch (e) { - new import_obsidian3.Notice("Service URL must be a valid URL format"); + const errorEl = text.inputEl.parentElement?.createDiv({ cls: "nb-settings-validation-error" }); + if (errorEl) errorEl.textContent = "Service URL must be a valid URL format"; + return; + } + if (this.plugin.sessionState && previousServiceUrl !== value) { + if (this.lastServiceUrlWarning !== value) { + new import_obsidian3.Notice("Active chat detected. Clear the current conversation before switching the Service URL."); + this.lastServiceUrlWarning = value; + } + text.setValue(previousServiceUrl); return; } this.plugin.settings.serviceUrl = value; await this.plugin.saveSettings(); }) ); - new import_obsidian3.Setting(containerEl).setName("Test Connection").setDesc("Test the connection to the service").addButton( - (button) => button.setButtonText("Test").setCta().onClick(async () => { + new import_obsidian3.Setting(connectionGroup).setName("Test Connection").setDesc("Test the connection to the service").addButton( + (button) => button.setIcon("plug").setButtonText("Test").setCta().onClick(async () => { + button.setButtonText("Testing..."); + button.setDisabled(true); const client = new OpenCodeClient(this.plugin.settings.serviceUrl, this.plugin.settings.defaultModelId); const result = await client.healthCheck(); + button.setButtonText("Test"); + button.setDisabled(false); if (result.status === "connected") { - new import_obsidian3.Notice("Connection successful!"); + new import_obsidian3.Notice("\u2713 Connection successful!"); } else { - new import_obsidian3.Notice(`Connection failed: ${result.lastError}`); + new import_obsidian3.Notice(`\u2717 Connection failed: ${result.lastError}`); } }) ); - this.displayModelSelection(containerEl); - this.displayRefreshButton(containerEl); + const modelGroup = containerEl.createDiv({ cls: "nb-settings-group" }); + modelGroup.createEl("h3", { text: "Model Selection", cls: "nb-settings-group-title" }); + this.displayModelSelection(modelGroup); + this.displayRefreshButton(modelGroup); } + /** + * Loads available AI providers and models from the OpenCode server. + * + * Sets the loading state and updates the providers list. On error, sets providers + * to an empty array and logs the error. The loading state is always cleared in finally. + * + * @param client - Optional OpenCodeClient instance to use (creates new one if not provided) + * @param forceRefresh - If true, bypasses cache and fetches fresh data from server + * @throws Error if the server request fails (error is logged and re-thrown) + */ async loadProviders(client, forceRefresh) { if (this.isLoadingModels) { return; @@ -590,6 +980,15 @@ var NoteBuddySettingTab = class extends import_obsidian3.PluginSettingTab { this.isLoadingModels = false; } } + /** + * Displays the model selection dropdown in the settings UI. + * + * Builds a dropdown with options in "Provider Name - Model Name" format, including + * a "Use server default" option. The current selection is restored from settings, + * and changes are immediately persisted via plugin.saveSettings(). + * + * @param containerEl - The HTML element to add the dropdown setting to + */ displayModelSelection(containerEl) { const modelOptions = {}; modelOptions[""] = "Use server default"; @@ -616,7 +1015,7 @@ var NoteBuddySettingTab = class extends import_obsidian3.PluginSettingTab { } displayRefreshButton(container) { new import_obsidian3.Setting(container).setName("Refresh Models").setDesc("Reload the list of available models from the service").addButton( - (button) => button.setButtonText("Refresh").onClick(async () => { + (button) => button.setIcon("refresh-cw").setButtonText("Refresh").onClick(async () => { const client = new OpenCodeClient(this.plugin.settings.serviceUrl, this.plugin.settings.defaultModelId); client.clearModelsCache(); try { diff --git a/.obsidian/plugins/obsidian-excalidraw-plugin/data.json b/.obsidian/plugins/obsidian-excalidraw-plugin/data.json index 115d4e7..1e070b7 100644 --- a/.obsidian/plugins/obsidian-excalidraw-plugin/data.json +++ b/.obsidian/plugins/obsidian-excalidraw-plugin/data.json @@ -123,7 +123,7 @@ "mdBorderColor": "Black", "mdCSS": "", "scriptEngineSettings": {}, - "previousRelease": "2.20.0", + "previousRelease": "2.20.2", "showReleaseNotes": true, "compareManifestToPluginVersion": true, "showNewVersionNotification": true, diff --git a/.obsidian/plugins/obsidian-excalidraw-plugin/main.js b/.obsidian/plugins/obsidian-excalidraw-plugin/main.js index 006acc1..39bc18d 100644 --- a/.obsidian/plugins/obsidian-excalidraw-plugin/main.js +++ b/.obsidian/plugins/obsidian-excalidraw-plugin/main.js @@ -1,10 +1,10 @@ "use strict";var obsidian_module=require("obsidian"),view=require("@codemirror/view"),commands=require("@codemirror/commands"),lr=require("@lezer/lr"),language=require("@codemirror/language"),state=require("@codemirror/state");;const INITIAL_TIMESTAMP=Date.now();var LZString=function(){var r=String.fromCharCode,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",e={};function t(r,o){if(!e[r]){e[r]={};for(var n=0;n>>8,n[2*e+1]=s%256}return n},decompressFromUint8Array:function(o){if(null==o)return i.decompress(o);for(var n=new Array(o.length/2),e=0,t=n.length;e>=1}else{for(t=1,e=0;e>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e>=1;0==--l&&(l=Math.pow(2,h),h++),s[p]=f++,c=String(a)}if(""!==c){if(Object.prototype.hasOwnProperty.call(u,c)){if(c.charCodeAt(0)<256){for(e=0;e>=1}else{for(t=1,e=0;e>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e>=1;0==--l&&(l=Math.pow(2,h),h++)}for(t=2,e=0;e>=1;for(;;){if(m<<=1,v==o-1){d.push(n(m));break}v++}return d.join("")},decompress:function(r){return null==r?"":""==r?null:i._decompress(r.length,32768,function(o){return r.charCodeAt(o)})},_decompress:function(o,n,e){var t,i,s,u,a,p,c,l=[],f=4,h=4,d=3,m="",v=[],g={val:e(0),position:n,index:1};for(t=0;t<3;t+=1)l[t]=t;for(s=0,a=Math.pow(2,2),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 2:return""}for(l[3]=c,i=c,v.push(c);;){if(g.index>o)return"";for(s=0,a=Math.pow(2,d),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(c=s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 2:return v.join("")}if(0==f&&(f=Math.pow(2,d),d++),l[c])m=l[c];else{if(c!==h)return null;m=i+i.charAt(0)}v.push(m),l[h++]=i+m.charAt(0),i=m,0==--f&&(f=Math.pow(2,d),d++)}}};return i}();"function"==typeof define&&define.amd?define(function(){return LZString}):"undefined"!=typeof module&&null!=module?module.exports=LZString:"undefined"!=typeof angular&&null!=angular&&angular.module("LZString",[]).factory("LZString",function(){return LZString}); let REACT_PACKAGES = `!function(){var e,t;e=this,t=function(e){function M(e){return null!==e&&"object"==typeof e&&"function"==typeof(e=te&&e[te]||e["@@iterator"])?e:null}function t(e,t,n){this.props=e,this.context=t,this.refs=oe,this.updater=n||ne}function n(){}function r(e,t,n){this.props=e,this.context=t,this.refs=oe,this.updater=n||ne}function o(e,t,n){var r,o={},u=null,a=null;if(null!=t)for(r in void 0!==t.ref&&(a=t.ref),void 0!==t.key&&(u=""+t.key),t)ae.call(t,r)&&!ie.hasOwnProperty(r)&&(o[r]=t[r]);var i=arguments.length-2;if(1===i)o.children=n;else if(1>>1,o=e[r];if(!(0>>1;rt)||e&&!q());){var r,o=R.callback;"function"==typeof o?(R.callback=null,P=R.priorityLevel,r=o(R.expirationTime<=t),t=v(),"function"==typeof r?R.callback=r:R===i(C)&&l(C),y(t)):l(C),R=i(C)}var u,a=null!==R||(null!==(u=i(E))&&_(d,u.startTime-t),!1);return a}finally{R=null,P=n,$=!1}}function q(){return!(v()-de")?l.replace("",n.displayName):l}while(1<=u&&0<=i);break}}}finally{xo=!1,Error.prepareStackTrace=t}return(n=n?n.displayName||n.name:"")?Q(n):""}function $(e){switch(e.tag){case 5:return Q(e.type);case 16:return Q("Lazy");case 13:return Q("Suspense");case 19:return Q("SuspenseList");case 0:case 2:case 15:return e=j(e.type,!1);case 11:return e=j(e.type.render,!1);case 1:return e=j(e.type,!0);default:return""}}function q(e){if(null!=e){if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case co:return"Fragment";case so:return"Portal";case po:return"Profiler";case fo:return"StrictMode";case yo:return"Suspense";case vo:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case ho:return(e.displayName||"Context")+".Consumer";case mo:return(e._context.displayName||"Context")+".Provider";case go:var n=e.render;return e=(e=e.displayName)?e:""!==(e=n.displayName||n.name||"")?"ForwardRef("+e+")":"ForwardRef";case bo:return null!==(n=e.displayName||null)?n:q(e.type)||"Memo";case ko:n=e._payload,e=e._init;try{return q(e(n))}catch(e){}}}return null}function K(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=n.render).displayName||e.name||"",n.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return q(n);case 8:return n===fo?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof n)return n.displayName||n.name||null;if("string"==typeof n)return n}return null}function Y(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function X(e){var n=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===n||"radio"===n)}function G(e){var n,t,r=X(e)?"checked":"value",l=Object.getOwnPropertyDescriptor(e.constructor.prototype,r),a=""+e[r];if(!e.hasOwnProperty(r)&&void 0!==l&&"function"==typeof l.get&&"function"==typeof l.set)return n=l.get,t=l.set,Object.defineProperty(e,r,{configurable:!0,get:function(){return n.call(this)},set:function(e){a=""+e,t.call(this,e)}}),Object.defineProperty(e,r,{enumerable:l.enumerable}),{getValue:function(){return a},setValue:function(e){a=""+e},stopTracking:function(){e._valueTracker=null,delete e[r]}}}function Z(e){e._valueTracker||(e._valueTracker=G(e))}function J(e){var n,t,r;return!(!e||(n=e._valueTracker)&&(t=n.getValue(),r="",(e=r=e?X(e)?e.checked?"true":"false":e.value:r)===t||(n.setValue(e),0)))}function ee(n){if(void 0===(n=n||("undefined"!=typeof document?document:void 0)))return null;try{return n.activeElement||n.body}catch(e){return n.body}}function ne(e,n){var t=n.checked;return g({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=t?t:e._wrapperState.initialChecked})}function te(e,n){var t=null==n.defaultValue?"":n.defaultValue,r=null!=n.checked?n.checked:n.defaultChecked,t=Y(null!=n.value?n.value:t);e._wrapperState={initialChecked:r,initialValue:t,controlled:"checkbox"===n.type||"radio"===n.type?null!=n.checked:null!=n.value}}function re(e,n){null!=(n=n.checked)&&B(e,"checked",n,!1)}function le(e,n){re(e,n);var t=Y(n.value),r=n.type;if(null!=t)"number"===r?(0===t&&""===e.value||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");n.hasOwnProperty("value")?oe(e,n.type,t):n.hasOwnProperty("defaultValue")&&oe(e,n.type,Y(n.defaultValue)),null==n.checked&&null!=n.defaultChecked&&(e.defaultChecked=!!n.defaultChecked)}function ae(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(("submit"===r||"reset"===r)&&null==n.value)return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}""!==(t=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==t&&(e.name=t)}function oe(e,n,t){"number"===n&&ee(e.ownerDocument)===e||(null==t?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}function ue(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l>>=0)?32:31-(iu(e)/su|0)|0}function Re(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function De(e,n){var t=e.pendingLanes;if(0===t)return 0;var r,l=0,a=e.suspendedLanes,o=e.pingedLanes,u=268435455&t;if(0!==u?0!==(r=u&~a)?l=Re(r):0!==(o&=u)&&(l=Re(o)):0!==(u=t&~a)?l=Re(u):0!==o&&(l=Re(o)),0===l)return 0;if(0!==n&&n!==l&&0==(n&a)&&((o=n&-n)<=(a=l&-l)||16===a&&0!=(4194240&o)))return n;if(0!=(4&l)&&(l|=16&t),0!==(n=e.entangledLanes))for(e=e.entanglements,n&=l;0>=r,a-=r,Xi=1<<32-uu(n)+a|t<u?(i=o,o=null):i=o.sibling;var s=y(n,o,t[u],r);if(null===s){null===o&&(o=i);break}f&&o&&null===s.alternate&&d(n,o),e=h(s,e,u),null===a?l=s:a.sibling=s,a=s,o=i}if(u===t.length)p(n,o);else if(null===o)for(;uu?(i=o,o=null):i=o.sibling;var c=y(n,o,s.value,r);if(null===c){null===o&&(o=i);break}f&&o&&null===c.alternate&&d(n,o),e=h(c,e,u),null===a?l=c:a.sibling=c,a=c,o=i}if(s.done)p(n,o);else if(null===o)for(;!s.done;u++,s=t.next())null!==(s=g(n,s.value,r))&&(e=h(s,e,u),null===a?l=s:a.sibling=s,a=s);else{for(o=m(n,o);!s.done;u++,s=t.next())null!==(s=v(o,n,u,s.value,r))&&(f&&null!==s.alternate&&o.delete(null===s.key?u:s.key),e=h(s,e,u),null===a?l=s:a.sibling=s,a=s);f&&o.forEach(function(e){return d(n,e)})}return E&&vt(n,u),l}function w(e,n,t,r){if("object"==typeof(t="object"==typeof t&&null!==t&&t.type===co&&null===t.key?t.props.children:t)&&null!==t){switch(t.$$typeof){case io:e:{for(var l=t.key,a=n;null!==a;){if(a.key===l){if((l=t.type)===co){if(7===a.tag){p(e,a.sibling),(n=o(a,t.props.children)).return=e,e=n;break e}}else if(a.elementType===l||"object"==typeof l&&null!==l&&l.$$typeof===ko&&Mt(l)===a.type){p(e,a.sibling),(n=o(a,t.props)).ref=Lt(e,a,t),n.return=e,e=n;break e}p(e,a);break}d(e,a),a=a.sibling}e=t.type===co?((n=za(t.props.children,e.mode,r,t.key)).return=e,n):((r=Na(t.type,t.key,t.props,null,e.mode,r)).ref=Lt(e,n,t),r.return=e,r)}return u(e);case so:e:{for(a=t.key;null!==n;){if(n.key===a){if(4===n.tag&&n.stateNode.containerInfo===t.containerInfo&&n.stateNode.implementation===t.implementation){p(e,n.sibling),(n=o(n,t.children||[])).return=e,e=n;break e}p(e,n);break}d(e,n),n=n.sibling}(n=La(t,e.mode,r)).return=e,e=n}return u(e);case ko:return w(e,n,(a=t._init)(t._payload),r)}if(Eo(t))return b(e,n,t,r);if(H(t))return k(e,n,t,r);Tt(e,t)}return"string"==typeof t&&""!==t||"number"==typeof t?(t=""+t,(n=null!==n&&6===n.tag?(p(e,n.sibling),o(n,t)):(p(e,n),_a(t,e.mode,r))).return=e,u(e=n)):p(e,n)}return w}function Rt(){os=as=ls=null}function Dt(e,n){n=rs.current,s(rs),e._currentValue=n}function Ot(e,n,t){for(;null!==e;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,null!==r&&(r.childLanes|=n)):null!==r&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function It(e,n){(os=as=null)!==(e=(ls=e).dependencies)&&null!==e.firstContext&&(0!=(e.lanes&n)&&(_=!0),e.firstContext=null)}function Ut(e){var n=e._currentValue;if(os!==e)if(e={context:e,memoizedValue:n,next:null},null===as){if(null===ls)throw Error(S(308));as=e,ls.dependencies={lanes:0,firstContext:e}}else as=as.next=e;return n}function Vt(e){null===us?us=[e]:us.push(e)}function At(e,n,t,r){var l=n.interleaved;return null===l?(t.next=t,Vt(n)):(t.next=l.next,l.next=t),n.interleaved=t,Wt(e,r)}function Wt(e,n){e.lanes|=n;var t=e.alternate;for(null!==t&&(t.lanes|=n),e=(t=e).return;null!==e;)e.childLanes|=n,null!==(t=e.alternate)&&(t.childLanes|=n),e=(t=e).return;return 3===t.tag?t.stateNode:null}function Bt(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ht(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Qt(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function jt(e,n,t){var r,l=e.updateQueue;return null===l?null:(l=l.shared,(0!=(2&F)?(null===(r=l.pending)?n.next=n:(n.next=r.next,r.next=n),l.pending=n,is):(null===(r=l.interleaved)?(n.next=n,Vt(l)):(n.next=r.next,r.next=n),l.interleaved=n,Wt))(e,t))}function $t(e,n,t){var r;null!==(n=n.updateQueue)&&(n=n.shared,0!=(4194240&t))&&(r=n.lanes,r&=e.pendingLanes,He(e,n.lanes=t|=r))}function qt(e,n){var t=e.updateQueue,r=e.alternate;if(null!==r&&t===(r=r.updateQueue)){var l=null,a=null;if(null!==(t=t.firstBaseUpdate)){do{var o={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null}}while(null===a?l=a=o:a=a.next=o,null!==(t=t.next));null===a?l=a=n:a=a.next=n}else l=a=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,effects:r.effects},e.updateQueue=t}else null===(e=t.lastBaseUpdate)?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function Kt(e,n,t,r){var l,a,o=e.updateQueue,u=(ss=!1,o.firstBaseUpdate),i=o.lastBaseUpdate;if(null!==(f=o.shared.pending)&&(o.shared.pending=null,a=(l=f).next,(l.next=null)===i?u=a:i.next=a,i=l,null!==(c=e.alternate))&&(f=(c=c.updateQueue).lastBaseUpdate)!==i&&(null===f?c.firstBaseUpdate=a:f.next=a,c.lastBaseUpdate=l),null!==u){for(var s=o.baseState,i=0,c=a=l=null,f=u;;){var d=f.lane,p=f.eventTime;if((r&d)===d){null!==c&&(c=c.next={eventTime:p,lane:0,tag:f.tag,payload:f.payload,callback:f.callback,next:null});e:{var m=e,h=f,d=n,p=t;switch(h.tag){case 1:if("function"==typeof(m=h.payload)){s=m.call(p,s,d);break e}s=m;break e;case 3:m.flags=-65537&m.flags|128;case 0:if(null==(d="function"==typeof(m=h.payload)?m.call(p,s,d):m))break e;s=g({},s,d);break e;case 2:ss=!0}}null!==f.callback&&0!==f.lane&&(e.flags|=64,null===(d=o.effects)?o.effects=[f]:d.push(f))}else p={eventTime:p,lane:d,tag:f.tag,payload:f.payload,callback:f.callback,next:null},null===c?(a=c=p,l=s):c=c.next=p,i|=d;if(null===(f=f.next)){if(null===(f=o.shared.pending))break;f=(d=f).next,d.next=null,o.lastBaseUpdate=d,o.shared.pending=null}}if(null===c&&(l=s),o.baseState=l,o.firstBaseUpdate=a,o.lastBaseUpdate=c,null!==(n=o.shared.interleaved))for(o=n;i|=o.lane,(o=o.next)!==n;);else null===u&&(o.shared.lanes=0);Qs|=i,e.lanes=i,e.memoizedState=s}}function Yt(e,n,t){if(e=n.effects,(n.effects=null)!==e)for(n=0;n<\\/script>",e=e.removeChild(e.firstChild)):"string"==typeof r.is?e=o.createElement(t,{is:r.is}):(e=o.createElement(t),"select"===t&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,t),e[Li]=n,e[Ti]=r,Ls(e,n,!1,!1),n.stateNode=e;e:{switch(o=ye(t,r),t){case"dialog":c("cancel",e),c("close",e),a=r;break;case"iframe":case"object":case"embed":c("load",e),a=r;break;case"video":case"audio":for(a=0;aYs&&(n.flags|=128,wl(i,!(r=!0)),n.lanes=4194304)}else{if(!r)if(null!==(e=nr(o))){if(n.flags|=128,r=!0,null!==(t=e.updateQueue)&&(n.updateQueue=t,n.flags|=4),wl(i,!0),null===i.tail&&"hidden"===i.tailMode&&!o.alternate&&!E)return p(n),null}else 2*y()-i.renderingStartTime>Ys&&1073741824!==t&&(n.flags|=128,wl(i,!(r=!0)),n.lanes=4194304);i.isBackwards?(o.sibling=n.child,n.child=o):(null!==(t=i.last)?t.sibling=o:n.child=o,i.last=o)}if(null!==i.tail)return n=i.tail,i.rendering=n,i.tail=n.sibling,i.renderingStartTime=y(),n.sibling=null,t=C.current,f(C,r?1&t|2:1&t),n}return p(n),null;case 22:case 23:return O=Bs.current,s(Bs),r=null!==n.memoizedState,null!==e&&null!==e.memoizedState!==r&&(n.flags|=8192),r&&0!=(1&n.mode)?0!=(1073741824&O)&&(p(n),6&n.subtreeFlags)&&(n.flags|=8192):p(n),null;case 24:case 25:return null}throw Error(S(156,n.tag))}function xl(e,n,t){switch(wt(n),n.tag){case 1:return h(n.type)&&(s(b),s(v)),65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 3:return Zt(),s(b),s(v),tr(),0!=(65536&(e=n.flags))&&0==(128&e)?(n.flags=-65537&e|128,n):null;case 5:return er(n),null;case 13:if(s(C),null!==(e=n.memoizedState)&&null!==e.dehydrated){if(null===n.alternate)throw Error(S(340));Pt()}return 65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 19:return s(C),null;case 4:return Zt(),null;case 10:return Dt(n.type._context),null;case 22:case 23:return O=Bs.current,s(Bs),null;default:return null}}function El(n,t){var e=n.ref;if(null!==e)if("function"==typeof e)try{e(null)}catch(e){w(n,t,e)}else e.current=null}function Cl(n,t,e){try{e()}catch(e){w(n,t,e)}}function Nl(e,n){if(Ei=Su,Dn(e=Rn())){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:if((a=(t=(t=e.ownerDocument)&&t.defaultView||window).getSelection&&t.getSelection())&&0!==a.rangeCount){var t=a.anchorNode,r=a.anchorOffset,l=a.focusNode,a=a.focusOffset;try{t.nodeType,l.nodeType}catch(e){t=null;break e}var o,u=0,i=-1,s=-1,c=0,f=0,d=e,p=null;n:for(;;){for(;d!==t||0!==r&&3!==d.nodeType||(i=u+r),d!==l||0!==a&&3!==d.nodeType||(s=u+a),3===d.nodeType&&(u+=d.nodeValue.length),null!==(o=d.firstChild);)p=d,d=o;for(;;){if(d===e)break n;if(p===t&&++c===r&&(i=u),p===l&&++f===a&&(s=u),null!==(o=d.nextSibling))break;p=(d=p).parentNode}d=o}t=-1===i||-1===s?null:{start:i,end:s}}else t=null;t=t||{start:0,end:0}}else t=null;for(Su=!(Ci={focusedElem:e,selectionRange:t}),T=n;null!==T;)if(e=(n=T).child,0!=(1028&n.subtreeFlags)&&null!==e)e.return=n,T=e;else for(;null!==T;){n=T;try{var m,h,g,y,v=n.alternate;if(0!=(1024&n.flags))switch(n.tag){case 0:case 11:case 15:break;case 1:null!==v&&(m=v.memoizedProps,h=v.memoizedState,y=(g=n.stateNode).getSnapshotBeforeUpdate(n.elementType===n.type?m:Ar(n.type,m),h),g.__reactInternalSnapshotBeforeUpdate=y);break;case 3:var b=n.stateNode.containerInfo;1===b.nodeType?b.textContent="":9===b.nodeType&&b.documentElement&&b.removeChild(b.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(S(163))}}catch(e){w(n,n.return,e)}if(null!==(e=n.sibling)){e.return=n.return,T=e;break}T=n.return}return v=Os,Os=!1,v}function zl(e,n,t){var r=n.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var l,a=r=r.next;do{}while((a.tag&e)===e&&(l=a.destroy,(a.destroy=void 0)!==l)&&Cl(n,t,l),(a=a.next)!==r)}}function Pl(e,n){if(null!==(n=null!==(n=n.updateQueue)?n.lastEffect:null)){var t,r=n=n.next;do{}while((r.tag&e)===e&&(t=r.create,r.destroy=t()),(r=r.next)!==n)}}function _l(e){var n,t=e.ref;null!==t&&(n=e.stateNode,e.tag,e=n,"function"==typeof t?t(e):t.current=e)}function Ll(e){var n=e.alternate;null!==n&&(e.alternate=null,Ll(n)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(n=e.stateNode)&&(delete n[Li],delete n[Ti],delete n[Fi],delete n[Ri],delete n[Di]),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Tl(e){return 5===e.tag||3===e.tag||4===e.tag}function Ml(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||Tl(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e=(e.child.return=e).child}if(!(2&e.flags))return e.stateNode}}function Fl(e,n,t){var r=e.tag;if(5===r||6===r)e=e.stateNode,n?(8===t.nodeType?t.parentNode:t).insertBefore(e,n):(8===t.nodeType?(n=t.parentNode).insertBefore(e,t):(n=t).appendChild(e),null==(t=t._reactRootContainer)&&null===n.onclick&&(n.onclick=Jn));else if(4!==r&&null!==(e=e.child))for(Fl(e,n,t),e=e.sibling;null!==e;)Fl(e,n,t),e=e.sibling}function Rl(e,n,t){var r=e.tag;if(5===r||6===r)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(4!==r&&null!==(e=e.child))for(Rl(e,n,t),e=e.sibling;null!==e;)Rl(e,n,t),e=e.sibling}function Dl(e,n,t){for(t=t.child;null!==t;)Ol(e,n,t),t=t.sibling}function Ol(e,n,t){if(ou&&"function"==typeof ou.onCommitFiberUnmount)try{ou.onCommitFiberUnmount(au,t)}catch(e){}switch(t.tag){case 5:L||El(t,n);case 6:var r=M,l=Is;M=null,Dl(e,n,t),Is=l,null!==(M=r)&&(Is?(e=M,t=t.stateNode,(8===e.nodeType?e.parentNode:e).removeChild(t)):M.removeChild(t.stateNode));break;case 18:null!==M&&(Is?(e=M,t=t.stateNode,8===e.nodeType?tt(e.parentNode,t):1===e.nodeType&&tt(e,t),Je(e)):tt(M,t.stateNode));break;case 4:r=M,l=Is,M=t.stateNode.containerInfo,Is=!0,Dl(e,n,t),M=r,Is=l;break;case 0:case 11:case 14:case 15:if(!L&&null!==(r=t.updateQueue)&&null!==(r=r.lastEffect)){l=r=r.next;do{var a=(o=l).destroy,o=o.tag}while(void 0===a||0==(2&o)&&0==(4&o)||Cl(t,n,a),(l=l.next)!==r)}Dl(e,n,t);break;case 1:if(!L&&(El(t,n),"function"==typeof(r=t.stateNode).componentWillUnmount))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(e){w(t,n,e)}Dl(e,n,t);break;case 21:Dl(e,n,t);break;case 22:1&t.mode?(L=(r=L)||null!==t.memoizedState,Dl(e,n,t),L=r):Dl(e,n,t);break;default:Dl(e,n,t)}}function Il(t){var r,e=t.updateQueue;null!==e&&((t.updateQueue=null)===(r=t.stateNode)&&(r=t.stateNode=new Ds),e.forEach(function(e){var n=ka.bind(null,t,e);r.has(e)||(r.add(e),e.then(n,n))}))}function Ul(e,n,t){if(null!==(t=n.deletions))for(var r=0;r