diff --git a/.claude/settings.local.json b/.claude/settings.local.json index ba69db5..8042e06 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -5,7 +5,14 @@ "Bash(grep:*)", "Bash(sed:*)", "Bash(rg:*)", - "Bash(npx tsc:*)" + "Bash(npx tsc:*)", + "Bash(npm run watch:*)", + "Bash(npm run lint)", + "Bash(cat:*)", + "WebSearch", + "Bash(npm run lint:*)", + "Bash(mkdir:*)", + "Bash(npm install)" ], "deny": [] }, diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..c250752 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,116 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +This is a VS Code extension that provides a chat interface for Claude Code within VS Code. It creates a webview-based chat UI in the sidebar and allows users to interact with Claude without using the terminal. + +## Key Architecture + +### Extension Structure +- **Main Entry**: `src/extension.ts` - Extension activation and command registration +- **Chat Provider**: `ClaudeChatProvider` class manages webview lifecycle and message handling +- **Webview UI**: `src/ui.ts` generates HTML, `src/script.ts` handles client-side logic +- **MCP Server**: `claude-code-chat-permissions-mcp/` contains permission management server + +### Communication Pattern +- Extension host โ†” Webview: Message-based communication via `postMessage` +- MCP Server: Runs as separate Node.js process for tool permission management +- File references: Uses `@` syntax for context inclusion + +## Development Commands + +```bash +# Install dependencies +npm install + +# Compile TypeScript +npm run compile + +# Watch mode for development +npm run watch + +# Run linter +npm run lint + +# Test extension (opens new VS Code window) +# Press F5 in VS Code or run: +npm run test + +# Build for publishing +npm run vscode:prepublish +``` + +## MCP Server Development + +```bash +# Navigate to MCP directory +cd claude-code-chat-permissions-mcp + +# Install MCP dependencies +npm install + +# Compile MCP server +npx tsc mcp-permissions.ts + +# Server is invoked automatically by the extension +``` + +## Testing the Extension + +1. Open project in VS Code +2. Press F5 to launch Extension Development Host +3. Use Cmd/Ctrl+Shift+C to open Claude Code Chat +4. Test in sidebar by clicking the Claude icon in activity bar + +## Important Configuration + +### Extension Settings (package.json) +- `claude-code-chat.wslSupport`: Enable/disable WSL integration +- `claude-code-chat.thinkingLevel`: Set AI reasoning intensity (not_verbose, verbose, very_verbose) + +### Key Bindings +- **Open Chat**: Ctrl+Shift+C (Windows/Linux) or Cmd+Shift+C (Mac) + +## Code Conventions + +### TypeScript Guidelines +- Target: ES2022, Module: Node16 +- Strict type checking enabled +- Use VS Code API types from `@types/vscode` + +### Message Protocol +Messages between extension and webview follow this pattern: +```typescript +webview.postMessage({ command: 'commandName', data: {...} }) +``` + +### File Handling +- Always use VS Code URI for file paths +- Support WSL paths via `wslSupport` configuration +- Handle image data as base64 strings + +## Common Tasks + +### Adding New Commands +1. Register in `package.json` under `contributes.commands` +2. Add handler in `extension.ts` activate function +3. Update webview message handlers if needed + +### Modifying UI +1. Edit HTML generation in `src/ui.ts` +2. Update styles in `src/ui-styles.ts` +3. Add client-side logic in `src/script.ts` + +### Updating MCP Permissions +1. Modify `claude-code-chat-permissions-mcp/mcp-permissions.ts` +2. Recompile with `npx tsc` +3. Test permission changes through extension + +## Debugging Tips + +- Use VS Code's Extension Development Host for live debugging +- Check Output panel > "Claude Code Chat" for extension logs +- Webview console accessible via Developer Tools (Help > Toggle Developer Tools) +- MCP server logs visible in extension output channel \ No newline at end of file diff --git a/claude-code-chat-permissions-mcp/mcp-permissions.js b/claude-code-chat-permissions-mcp/mcp-permissions.js index 5591534..464c8e9 100644 --- a/claude-code-chat-permissions-mcp/mcp-permissions.js +++ b/claude-code-chat-permissions-mcp/mcp-permissions.js @@ -1,13954 +1,238 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -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 }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// node_modules/uri-js/dist/es5/uri.all.js -var require_uri_all = __commonJS({ - "node_modules/uri-js/dist/es5/uri.all.js"(exports2, module2) { - (function(global, factory) { - typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global.URI = global.URI || {}); - })(exports2, function(exports3) { - "use strict"; - function merge() { - for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { - sets[_key] = arguments[_key]; - } - if (sets.length > 1) { - sets[0] = sets[0].slice(0, -1); - var xl = sets.length - 1; - for (var x = 1; x < xl; ++x) { - sets[x] = sets[x].slice(1, -1); - } - sets[xl] = sets[xl].slice(1); - return sets.join(""); - } else { - return sets[0]; - } - } - function subexp(str) { - return "(?:" + str + ")"; - } - function typeOf(o) { - return o === void 0 ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); - } - function toUpperCase(str) { - return str.toUpperCase(); - } - function toArray(obj) { - return obj !== void 0 && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; - } - function assign(target, source) { - var obj = target; - if (source) { - for (var key in source) { - obj[key] = source[key]; - } - } - return obj; - } - function buildExps(isIRI2) { - var ALPHA$$ = "[A-Za-z]", CR$ = "[\\x0D]", DIGIT$$ = "[0-9]", DQUOTE$$ = "[\\x22]", HEXDIG$$2 = merge(DIGIT$$, "[A-Fa-f]"), LF$$ = "[\\x0A]", SP$$ = "[\\x20]", PCT_ENCODED$2 = subexp(subexp("%[EFef]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%" + HEXDIG$$2 + HEXDIG$$2)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI2 ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI2 ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$2 + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$2 + "|" + PCT_ENCODED$2) + "+"), IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + ZONEID$), IPVFUTURE$ = subexp("[vV]" + HEXDIG$$2 + "+\\." + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), REG_NAME$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$)) + "*"), HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")|" + REG_NAME$), PORT$ = subexp(DIGIT$$ + "*"), AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), PCHAR$ = subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\@]")) + "+"), PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), PATH_EMPTY$ = "(?!" + PCHAR$ + ")", PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; - return { - NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), - NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"), - NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"), - NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"), - NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"), - NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), - NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), - ESCAPE: new RegExp(merge("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"), - UNRESERVED: new RegExp(UNRESERVED$$2, "g"), - OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$2, RESERVED$$), "g"), - PCT_ENCODED: new RegExp(PCT_ENCODED$2, "g"), - IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), - IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") - //RFC 6874, with relaxed parsing rules - }; - } - var URI_PROTOCOL = buildExps(false); - var IRI_PROTOCOL = buildExps(true); - var slicedToArray = /* @__PURE__ */ function() { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = void 0; - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - return _arr; - } - return function(arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; - }(); - var toConsumableArray = function(arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; - return arr2; - } else { - return Array.from(arr); - } - }; - var maxInt = 2147483647; - var base = 36; - var tMin = 1; - var tMax = 26; - var skew = 38; - var damp = 700; - var initialBias = 72; - var initialN = 128; - var delimiter = "-"; - var regexPunycode = /^xn--/; - var regexNonASCII = /[^\0-\x7E]/; - var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; - var errors = { - "overflow": "Overflow: input needs wider integers to process", - "not-basic": "Illegal input >= 0x80 (not a basic code point)", - "invalid-input": "Invalid input" - }; - var baseMinusTMin = base - tMin; - var floor = Math.floor; - var stringFromCharCode = String.fromCharCode; - function error$1(type) { - throw new RangeError(errors[type]); - } - function map(array, fn) { - var result = []; - var length = array.length; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - function mapDomain(string, fn) { - var parts = string.split("@"); - var result = ""; - if (parts.length > 1) { - result = parts[0] + "@"; - string = parts[1]; - } - string = string.replace(regexSeparators, "."); - var labels = string.split("."); - var encoded = map(labels, fn).join("."); - return result + encoded; - } - function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - while (counter < length) { - var value = string.charCodeAt(counter++); - if (value >= 55296 && value <= 56319 && counter < length) { - var extra = string.charCodeAt(counter++); - if ((extra & 64512) == 56320) { - output.push(((value & 1023) << 10) + (extra & 1023) + 65536); - } else { - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - var ucs2encode = function ucs2encode2(array) { - return String.fromCodePoint.apply(String, toConsumableArray(array)); - }; - var basicToDigit = function basicToDigit2(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - }; - var digitToBasic = function digitToBasic2(digit, flag) { - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - }; - var adapt = function adapt2(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for ( - ; - /* no initialization */ - delta > baseMinusTMin * tMax >> 1; - k += base - ) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - }; - var decode = function decode2(input) { - var output = []; - var inputLength = input.length; - var i = 0; - var n = initialN; - var bias = initialBias; - var basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - for (var j = 0; j < basic; ++j) { - if (input.charCodeAt(j) >= 128) { - error$1("not-basic"); - } - output.push(input.charCodeAt(j)); - } - for (var index = basic > 0 ? basic + 1 : 0; index < inputLength; ) { - var oldi = i; - for ( - var w = 1, k = base; - ; - /* no condition */ - k += base - ) { - if (index >= inputLength) { - error$1("invalid-input"); - } - var digit = basicToDigit(input.charCodeAt(index++)); - if (digit >= base || digit > floor((maxInt - i) / w)) { - error$1("overflow"); - } - i += digit * w; - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (digit < t) { - break; - } - var baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error$1("overflow"); - } - w *= baseMinusT; - } - var out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - if (floor(i / out) > maxInt - n) { - error$1("overflow"); - } - n += floor(i / out); - i %= out; - output.splice(i++, 0, n); - } - return String.fromCodePoint.apply(String, output); - }; - var encode = function encode2(input) { - var output = []; - input = ucs2decode(input); - var inputLength = input.length; - var n = initialN; - var delta = 0; - var bias = initialBias; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = void 0; - try { - for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _currentValue2 = _step.value; - if (_currentValue2 < 128) { - output.push(stringFromCharCode(_currentValue2)); - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - var basicLength = output.length; - var handledCPCount = basicLength; - if (basicLength) { - output.push(delimiter); - } - while (handledCPCount < inputLength) { - var m = maxInt; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = void 0; - try { - for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var currentValue = _step2.value; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - var handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error$1("overflow"); - } - delta += (m - n) * handledCPCountPlusOne; - n = m; - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = void 0; - try { - for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _currentValue = _step3.value; - if (_currentValue < n && ++delta > maxInt) { - error$1("overflow"); - } - if (_currentValue == n) { - var q = delta; - for ( - var k = base; - ; - /* no condition */ - k += base - ) { - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (q < t) { - break; - } - var qMinusT = q - t; - var baseMinusT = base - t; - output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); - q = floor(qMinusT / baseMinusT); - } - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - ++delta; - ++n; - } - return output.join(""); - }; - var toUnicode = function toUnicode2(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); - }; - var toASCII = function toASCII2(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) ? "xn--" + encode(string) : string; - }); - }; - var punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - "version": "2.1.0", - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - "ucs2": { - "decode": ucs2decode, - "encode": ucs2encode - }, - "decode": decode, - "encode": encode, - "toASCII": toASCII, - "toUnicode": toUnicode - }; - var SCHEMES = {}; - function pctEncChar(chr) { - var c = chr.charCodeAt(0); - var e = void 0; - if (c < 16) e = "%0" + c.toString(16).toUpperCase(); - else if (c < 128) e = "%" + c.toString(16).toUpperCase(); - else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); - else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); - return e; - } - function pctDecChars(str) { - var newStr = ""; - var i = 0; - var il = str.length; - while (i < il) { - var c = parseInt(str.substr(i + 1, 2), 16); - if (c < 128) { - newStr += String.fromCharCode(c); - i += 3; - } else if (c >= 194 && c < 224) { - if (il - i >= 6) { - var c2 = parseInt(str.substr(i + 4, 2), 16); - newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); - } else { - newStr += str.substr(i, 6); - } - i += 6; - } else if (c >= 224) { - if (il - i >= 9) { - var _c = parseInt(str.substr(i + 4, 2), 16); - var c3 = parseInt(str.substr(i + 7, 2), 16); - newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); - } else { - newStr += str.substr(i, 9); - } - i += 9; - } else { - newStr += str.substr(i, 3); - i += 3; - } - } - return newStr; - } - function _normalizeComponentEncoding(components, protocol) { - function decodeUnreserved2(str) { - var decStr = pctDecChars(str); - return !decStr.match(protocol.UNRESERVED) ? str : decStr; - } - if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_SCHEME, ""); - if (components.userinfo !== void 0) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.host !== void 0) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.path !== void 0) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.query !== void 0) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.fragment !== void 0) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - return components; - } - function _stripLeadingZeros(str) { - return str.replace(/^0*(.*)/, "$1") || "0"; - } - function _normalizeIPv4(host, protocol) { - var matches = host.match(protocol.IPV4ADDRESS) || []; - var _matches = slicedToArray(matches, 2), address = _matches[1]; - if (address) { - return address.split(".").map(_stripLeadingZeros).join("."); - } else { - return host; - } - } - function _normalizeIPv6(host, protocol) { - var matches = host.match(protocol.IPV6ADDRESS) || []; - var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2]; - if (address) { - var _address$toLowerCase$ = address.toLowerCase().split("::").reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last = _address$toLowerCase$2[0], first = _address$toLowerCase$2[1]; - var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; - var lastFields = last.split(":").map(_stripLeadingZeros); - var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); - var fieldCount = isLastFieldIPv4Address ? 7 : 8; - var lastFieldsStart = lastFields.length - fieldCount; - var fields = Array(fieldCount); - for (var x = 0; x < fieldCount; ++x) { - fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ""; - } - if (isLastFieldIPv4Address) { - fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); - } - var allZeroFields = fields.reduce(function(acc, field, index) { - if (!field || field === "0") { - var lastLongest = acc[acc.length - 1]; - if (lastLongest && lastLongest.index + lastLongest.length === index) { - lastLongest.length++; - } else { - acc.push({ index, length: 1 }); - } - } - return acc; - }, []); - var longestZeroFields = allZeroFields.sort(function(a, b) { - return b.length - a.length; - })[0]; - var newHost = void 0; - if (longestZeroFields && longestZeroFields.length > 1) { - var newFirst = fields.slice(0, longestZeroFields.index); - var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); - newHost = newFirst.join(":") + "::" + newLast.join(":"); - } else { - newHost = fields.join(":"); - } - if (zone) { - newHost += "%" + zone; - } - return newHost; - } else { - return host; - } - } - var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; - var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === void 0; - function parse(uriString) { - var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var components = {}; - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; - var matches = uriString.match(URI_PARSE); - if (matches) { - if (NO_MATCH_IS_UNDEFINED) { - components.scheme = matches[1]; - components.userinfo = matches[3]; - components.host = matches[4]; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = matches[7]; - components.fragment = matches[8]; - if (isNaN(components.port)) { - components.port = matches[5]; - } - } else { - components.scheme = matches[1] || void 0; - components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : void 0; - components.host = uriString.indexOf("//") !== -1 ? matches[4] : void 0; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = uriString.indexOf("?") !== -1 ? matches[7] : void 0; - components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : void 0; - if (isNaN(components.port)) { - components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : void 0; - } - } - if (components.host) { - components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); - } - if (components.scheme === void 0 && components.userinfo === void 0 && components.host === void 0 && components.port === void 0 && !components.path && components.query === void 0) { - components.reference = "same-document"; - } else if (components.scheme === void 0) { - components.reference = "relative"; - } else if (components.fragment === void 0) { - components.reference = "absolute"; - } else { - components.reference = "uri"; - } - if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { - components.error = components.error || "URI is not a " + options.reference + " reference."; - } - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { - try { - components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; - } - } - _normalizeComponentEncoding(components, URI_PROTOCOL); - } else { - _normalizeComponentEncoding(components, protocol); - } - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(components, options); - } - } else { - components.error = components.error || "URI can not be parsed."; - } - return components; - } - function _recomposeAuthority(components, options) { - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - if (components.userinfo !== void 0) { - uriTokens.push(components.userinfo); - uriTokens.push("@"); - } - if (components.host !== void 0) { - uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_, $1, $2) { - return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; - })); - } - if (typeof components.port === "number" || typeof components.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(components.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - var RDS1 = /^\.\.?\//; - var RDS2 = /^\/\.(\/|$)/; - var RDS3 = /^\/\.\.(\/|$)/; - var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; - function removeDotSegments(input) { - var 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 { - var im = input.match(RDS5); - if (im) { - var s = im[0]; - input = input.slice(s.length); - output.push(s); - } else { - throw new Error("Unexpected dot segment condition"); - } - } - } - return output.join(""); - } - function serialize(components) { - var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); - if (components.host) { - if (protocol.IPV6ADDRESS.test(components.host)) { - } else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { - try { - components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - } - } - _normalizeComponentEncoding(components, protocol); - if (options.reference !== "suffix" && components.scheme) { - uriTokens.push(components.scheme); - uriTokens.push(":"); - } - var authority = _recomposeAuthority(components, options); - 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) { - var s = components.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if (authority === void 0) { - s = s.replace(/^\/\//, "/%2F"); - } - uriTokens.push(s); - } - if (components.query !== void 0) { - uriTokens.push("?"); - uriTokens.push(components.query); - } - if (components.fragment !== void 0) { - uriTokens.push("#"); - uriTokens.push(components.fragment); - } - return uriTokens.join(""); - } - function resolveComponents(base2, relative) { - var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; - var skipNormalization = arguments[3]; - var target = {}; - if (!skipNormalization) { - base2 = parse(serialize(base2, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base2.path; - if (relative.query !== void 0) { - target.query = relative.query; - } else { - target.query = base2.query; - } - } else { - if (relative.path.charAt(0) === "/") { - target.path = removeDotSegments(relative.path); - } else { - if ((base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0) && !base2.path) { - target.path = "/" + relative.path; - } else if (!base2.path) { - target.path = relative.path; - } else { - target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base2.userinfo; - target.host = base2.host; - target.port = base2.port; - } - target.scheme = base2.scheme; - } - target.fragment = relative.fragment; - return target; - } - function resolve(baseURI, relativeURI, options) { - var schemelessOptions = assign({ scheme: "null" }, options); - return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); - } - function normalize(uri, options) { - if (typeof uri === "string") { - uri = serialize(parse(uri, options), options); - } else if (typeOf(uri) === "object") { - uri = parse(serialize(uri, options), options); - } - return uri; - } - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = serialize(parse(uriA, options), options); - } else if (typeOf(uriA) === "object") { - uriA = serialize(uriA, options); - } - if (typeof uriB === "string") { - uriB = serialize(parse(uriB, options), options); - } else if (typeOf(uriB) === "object") { - uriB = serialize(uriB, options); - } - return uriA === uriB; - } - function escapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); - } - function unescapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); - } - var handler = { - scheme: "http", - domainHost: true, - parse: function parse2(components, options) { - if (!components.host) { - components.error = components.error || "HTTP URIs must have a host."; - } - return components; - }, - serialize: function serialize2(components, options) { - var 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; - } - }; - var handler$1 = { - scheme: "https", - domainHost: handler.domainHost, - parse: handler.parse, - serialize: handler.serialize - }; - function isSecure(wsComponents) { - return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; - } - var handler$2 = { - scheme: "ws", - domainHost: true, - parse: function parse2(components, options) { - var wsComponents = components; - wsComponents.secure = isSecure(wsComponents); - wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : ""); - wsComponents.path = void 0; - wsComponents.query = void 0; - return wsComponents; - }, - serialize: function serialize2(wsComponents, options) { - 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) { - var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path2 = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1]; - wsComponents.path = path2 && path2 !== "/" ? path2 : void 0; - wsComponents.query = query; - wsComponents.resourceName = void 0; - } - wsComponents.fragment = void 0; - return wsComponents; - } - }; - var handler$3 = { - scheme: "wss", - domainHost: handler$2.domainHost, - parse: handler$2.parse, - serialize: handler$2.serialize - }; - var O = {}; - var isIRI = true; - var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; - var HEXDIG$$ = "[0-9A-Fa-f]"; - var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); - var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; - var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; - var VCHAR$$ = merge(QTEXT$$, '[\\"\\\\]'); - var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; - var UNRESERVED = new RegExp(UNRESERVED$$, "g"); - var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); - var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); - var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); - var NOT_HFVALUE = NOT_HFNAME; - function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(UNRESERVED) ? str : decStr; - } - var handler$4 = { - scheme: "mailto", - parse: function parse$$1(components, options) { - var mailtoComponents = components; - var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; - mailtoComponents.path = void 0; - if (mailtoComponents.query) { - var unknownHeaders = false; - var headers = {}; - var hfields = mailtoComponents.query.split("&"); - for (var x = 0, xl = hfields.length; x < xl; ++x) { - var hfield = hfields[x].split("="); - switch (hfield[0]) { - case "to": - var toAddrs = hfield[1].split(","); - for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { - to.push(toAddrs[_x]); - } - break; - case "subject": - mailtoComponents.subject = unescapeComponent(hfield[1], options); - break; - case "body": - mailtoComponents.body = unescapeComponent(hfield[1], options); - break; - default: - unknownHeaders = true; - headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); - break; - } - } - if (unknownHeaders) mailtoComponents.headers = headers; - } - mailtoComponents.query = void 0; - for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { - var addr = to[_x2].split("@"); - addr[0] = unescapeComponent(addr[0]); - if (!options.unicodeSupport) { - try { - addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); - } catch (e) { - mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; - } - } else { - addr[1] = unescapeComponent(addr[1], options).toLowerCase(); - } - to[_x2] = addr.join("@"); - } - return mailtoComponents; - }, - serialize: function serialize$$1(mailtoComponents, options) { - var components = mailtoComponents; - var to = toArray(mailtoComponents.to); - if (to) { - for (var x = 0, xl = to.length; x < xl; ++x) { - var toAddr = String(to[x]); - var atIdx = toAddr.lastIndexOf("@"); - var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); - var domain = toAddr.slice(atIdx + 1); - try { - domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); - } catch (e) { - components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - to[x] = localPart + "@" + domain; - } - components.path = to.join(","); - } - var headers = mailtoComponents.headers = mailtoComponents.headers || {}; - if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; - if (mailtoComponents.body) headers["body"] = mailtoComponents.body; - var fields = []; - for (var name in headers) { - if (headers[name] !== O[name]) { - fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); - } - } - if (fields.length) { - components.query = fields.join("&"); - } - return components; - } - }; - var URN_PARSE = /^([^\:]+)\:(.*)/; - var handler$5 = { - scheme: "urn", - parse: function parse$$1(components, options) { - var matches = components.path && components.path.match(URN_PARSE); - var urnComponents = components; - if (matches) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = matches[1].toLowerCase(); - var nss = matches[2]; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - urnComponents.nid = nid; - urnComponents.nss = nss; - urnComponents.path = void 0; - if (schemeHandler) { - urnComponents = schemeHandler.parse(urnComponents, options); - } - } else { - urnComponents.error = urnComponents.error || "URN can not be parsed."; - } - return urnComponents; - }, - serialize: function serialize$$1(urnComponents, options) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = urnComponents.nid; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - if (schemeHandler) { - urnComponents = schemeHandler.serialize(urnComponents, options); - } - var uriComponents = urnComponents; - var nss = urnComponents.nss; - uriComponents.path = (nid || options.nid) + ":" + nss; - return uriComponents; - } - }; - var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; - var handler$6 = { - scheme: "urn:uuid", - parse: function parse2(urnComponents, options) { - var uuidComponents = urnComponents; - uuidComponents.uuid = uuidComponents.nss; - uuidComponents.nss = void 0; - if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { - uuidComponents.error = uuidComponents.error || "UUID is not valid."; - } - return uuidComponents; - }, - serialize: function serialize2(uuidComponents, options) { - var urnComponents = uuidComponents; - urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); - return urnComponents; - } - }; - SCHEMES[handler.scheme] = handler; - SCHEMES[handler$1.scheme] = handler$1; - SCHEMES[handler$2.scheme] = handler$2; - SCHEMES[handler$3.scheme] = handler$3; - SCHEMES[handler$4.scheme] = handler$4; - SCHEMES[handler$5.scheme] = handler$5; - SCHEMES[handler$6.scheme] = handler$6; - exports3.SCHEMES = SCHEMES; - exports3.pctEncChar = pctEncChar; - exports3.pctDecChars = pctDecChars; - exports3.parse = parse; - exports3.removeDotSegments = removeDotSegments; - exports3.serialize = serialize; - exports3.resolveComponents = resolveComponents; - exports3.resolve = resolve; - exports3.normalize = normalize; - exports3.equal = equal; - exports3.escapeComponent = escapeComponent; - exports3.unescapeComponent = unescapeComponent; - Object.defineProperty(exports3, "__esModule", { value: true }); - }); - } -}); - -// node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/fast-deep-equal/index.js"(exports2, module2) { - "use strict"; - 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; - }; - } -}); - -// node_modules/ajv/lib/compile/ucs2length.js -var require_ucs2length = __commonJS({ - "node_modules/ajv/lib/compile/ucs2length.js"(exports2, module2) { - "use strict"; - module2.exports = function ucs2length(str) { - var length = 0, len = str.length, pos = 0, 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; - }; - } -}); - -// node_modules/ajv/lib/compile/util.js -var require_util = __commonJS({ - "node_modules/ajv/lib/compile/util.js"(exports2, module2) { - "use strict"; - module2.exports = { - copy, - checkDataType, - checkDataTypes, - coerceToTypes, - toHash, - getProperty, - escapeQuotes, - equal: require_fast_deep_equal(), - ucs2length: require_ucs2length(), - varOccurences, - varReplace, - schemaHasRules, - schemaHasRulesExcept, - schemaUnknownRules, - toQuotedString, - getPathExpr, - getPath, - getData, - unescapeFragment, - unescapeJsonPointer, - escapeFragment, - escapeJsonPointer - }; - function copy(o, to) { - to = to || {}; - for (var key in o) to[key] = o[key]; - return to; - } - function checkDataType(dataType, data, strictNumbers, negate) { - var EQUAL = negate ? " !== " : " === ", AND = negate ? " || " : " && ", OK2 = negate ? "!" : "", NOT = negate ? "" : "!"; - switch (dataType) { - case "null": - return data + EQUAL + "null"; - case "array": - return OK2 + "Array.isArray(" + data + ")"; - case "object": - return "(" + OK2 + data + AND + "typeof " + data + EQUAL + '"object"' + AND + NOT + "Array.isArray(" + data + "))"; - case "integer": - return "(typeof " + data + EQUAL + '"number"' + AND + NOT + "(" + data + " % 1)" + AND + data + EQUAL + data + (strictNumbers ? AND + OK2 + "isFinite(" + data + ")" : "") + ")"; - case "number": - return "(typeof " + data + EQUAL + '"' + dataType + '"' + (strictNumbers ? AND + OK2 + "isFinite(" + data + ")" : "") + ")"; - default: - return "typeof " + data + EQUAL + '"' + dataType + '"'; - } - } - function checkDataTypes(dataTypes, data, strictNumbers) { - switch (dataTypes.length) { - case 1: - return checkDataType(dataTypes[0], data, strictNumbers, true); - default: - var code = ""; - var types = toHash(dataTypes); - if (types.array && types.object) { - code = types.null ? "(" : "(!" + data + " || "; - code += "typeof " + data + ' !== "object")'; - delete types.null; - delete types.array; - delete types.object; - } - if (types.number) delete types.integer; - for (var t in types) - code += (code ? " && " : "") + checkDataType(t, data, strictNumbers, true); - return code; - } - } - var COERCE_TO_TYPES = toHash(["string", "number", "integer", "boolean", "null"]); - function coerceToTypes(optionCoerceTypes, dataTypes) { - if (Array.isArray(dataTypes)) { - var types = []; - for (var i = 0; i < dataTypes.length; i++) { - var t = dataTypes[i]; - if (COERCE_TO_TYPES[t]) types[types.length] = t; - else if (optionCoerceTypes === "array" && t === "array") types[types.length] = t; - } - if (types.length) return types; - } else if (COERCE_TO_TYPES[dataTypes]) { - return [dataTypes]; - } else if (optionCoerceTypes === "array" && dataTypes === "array") { - return ["array"]; - } - } - function toHash(arr) { - var hash = {}; - for (var i = 0; i < arr.length; i++) hash[arr[i]] = true; - return hash; - } - var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var SINGLE_QUOTE = /'|\\/g; - function getProperty(key) { - return typeof key == "number" ? "[" + key + "]" : IDENTIFIER.test(key) ? "." + key : "['" + escapeQuotes(key) + "']"; - } - function escapeQuotes(str) { - return str.replace(SINGLE_QUOTE, "\\$&").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\f/g, "\\f").replace(/\t/g, "\\t"); - } - function varOccurences(str, dataVar) { - dataVar += "[^0-9]"; - var matches = str.match(new RegExp(dataVar, "g")); - return matches ? matches.length : 0; - } - function varReplace(str, dataVar, expr) { - dataVar += "([^0-9])"; - expr = expr.replace(/\$/g, "$$$$"); - return str.replace(new RegExp(dataVar, "g"), expr + "$1"); - } - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") return !schema; - for (var key in schema) if (rules[key]) return true; - } - function schemaHasRulesExcept(schema, rules, exceptKeyword) { - if (typeof schema == "boolean") return !schema && exceptKeyword != "not"; - for (var key in schema) if (key != exceptKeyword && rules[key]) return true; - } - function schemaUnknownRules(schema, rules) { - if (typeof schema == "boolean") return; - for (var key in schema) if (!rules[key]) return key; - } - function toQuotedString(str) { - return "'" + escapeQuotes(str) + "'"; - } - function getPathExpr(currentPath, expr, jsonPointers, isNumber) { - var path2 = jsonPointers ? "'/' + " + expr + (isNumber ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'"; - return joinPaths(currentPath, path2); - } - function getPath(currentPath, prop, jsonPointers) { - var path2 = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop)); - return joinPaths(currentPath, path2); - } - var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, lvl, paths) { - var up, jsonPointer, data, matches; - if ($data === "") return "rootData"; - if ($data[0] == "/") { - if (!JSON_POINTER.test($data)) throw new Error("Invalid JSON-pointer: " + $data); - jsonPointer = $data; - data = "rootData"; - } else { - matches = $data.match(RELATIVE_JSON_POINTER); - if (!matches) throw new Error("Invalid JSON-pointer: " + $data); - up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer == "#") { - if (up >= lvl) throw new Error("Cannot access property/index " + up + " levels up, current level is " + lvl); - return paths[lvl - up]; - } - if (up > lvl) throw new Error("Cannot access data " + up + " levels up, current level is " + lvl); - data = "data" + (lvl - up || ""); - if (!jsonPointer) return data; - } - var expr = data; - var segments = jsonPointer.split("/"); - for (var i = 0; i < segments.length; i++) { - var segment = segments[i]; - if (segment) { - data += getProperty(unescapeJsonPointer(segment)); - expr += " && " + data; - } - } - return expr; - } - function joinPaths(a, b) { - if (a == '""') return b; - return (a + " + " + b).replace(/([^\\])' \+ '/g, "$1"); - } - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - function escapeJsonPointer(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - } -}); - -// node_modules/ajv/lib/compile/schema_obj.js -var require_schema_obj = __commonJS({ - "node_modules/ajv/lib/compile/schema_obj.js"(exports2, module2) { - "use strict"; - var util2 = require_util(); - module2.exports = SchemaObject; - function SchemaObject(obj) { - util2.copy(obj, this); - } - } -}); - -// node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = __commonJS({ - "node_modules/json-schema-traverse/index.js"(exports2, 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 - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - 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"); - } - } -}); - -// node_modules/ajv/lib/compile/resolve.js -var require_resolve = __commonJS({ - "node_modules/ajv/lib/compile/resolve.js"(exports2, module2) { - "use strict"; - var URI = require_uri_all(); - var equal = require_fast_deep_equal(); - var util2 = require_util(); - var SchemaObject = require_schema_obj(); - var traverse = require_json_schema_traverse(); - module2.exports = resolve; - resolve.normalizeId = normalizeId; - resolve.fullPath = getFullPath; - resolve.url = resolveUrl; - resolve.ids = resolveIds; - resolve.inlineRef = inlineRef; - resolve.schema = resolveSchema; - function resolve(compile, root, ref) { - var refVal = this._refs[ref]; - if (typeof refVal == "string") { - if (this._refs[refVal]) refVal = this._refs[refVal]; - else return resolve.call(this, compile, root, refVal); - } - refVal = refVal || this._schemas[ref]; - if (refVal instanceof SchemaObject) { - return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal); - } - var res = resolveSchema.call(this, root, ref); - var schema, v, baseId; - if (res) { - schema = res.schema; - root = res.root; - baseId = res.baseId; - } - if (schema instanceof SchemaObject) { - v = schema.validate || compile.call(this, schema.schema, root, void 0, baseId); - } else if (schema !== void 0) { - v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, void 0, baseId); - } - return v; - } - function resolveSchema(root, ref) { - var p = URI.parse(ref), refPath = _getFullPath(p), baseId = getFullPath(this._getId(root.schema)); - if (Object.keys(root.schema).length === 0 || refPath !== baseId) { - var id = normalizeId(refPath); - var refVal = this._refs[id]; - if (typeof refVal == "string") { - return resolveRecursive.call(this, root, refVal, p); - } else if (refVal instanceof SchemaObject) { - if (!refVal.validate) this._compile(refVal); - root = refVal; - } else { - refVal = this._schemas[id]; - if (refVal instanceof SchemaObject) { - if (!refVal.validate) this._compile(refVal); - if (id == normalizeId(ref)) - return { schema: refVal, root, baseId }; - root = refVal; - } else { - return; - } - } - if (!root.schema) return; - baseId = getFullPath(this._getId(root.schema)); - } - return getJsonPointer.call(this, p, baseId, root.schema, root); - } - function resolveRecursive(root, ref, parsedRef) { - var res = resolveSchema.call(this, root, ref); - if (res) { - var schema = res.schema; - var baseId = res.baseId; - root = res.root; - var id = this._getId(schema); - if (id) baseId = resolveUrl(baseId, id); - return getJsonPointer.call(this, parsedRef, baseId, schema, root); - } - } - var PREVENT_SCOPE_CHANGE = util2.toHash(["properties", "patternProperties", "enum", "dependencies", "definitions"]); - function getJsonPointer(parsedRef, baseId, schema, root) { - parsedRef.fragment = parsedRef.fragment || ""; - if (parsedRef.fragment.slice(0, 1) != "/") return; - var parts = parsedRef.fragment.split("/"); - for (var i = 1; i < parts.length; i++) { - var part = parts[i]; - if (part) { - part = util2.unescapeFragment(part); - schema = schema[part]; - if (schema === void 0) break; - var id; - if (!PREVENT_SCOPE_CHANGE[part]) { - id = this._getId(schema); - if (id) baseId = resolveUrl(baseId, id); - if (schema.$ref) { - var $ref = resolveUrl(baseId, schema.$ref); - var res = resolveSchema.call(this, root, $ref); - if (res) { - schema = res.schema; - root = res.root; - baseId = res.baseId; - } - } - } - } - } - if (schema !== void 0 && schema !== root.schema) - return { schema, root, baseId }; - } - var SIMPLE_INLINED = util2.toHash([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum" - ]); - function inlineRef(schema, limit) { - if (limit === false) return false; - if (limit === void 0 || limit === true) return checkNoRef(schema); - else if (limit) return countKeys(schema) <= limit; - } - function checkNoRef(schema) { - var item; - if (Array.isArray(schema)) { - for (var i = 0; i < schema.length; i++) { - item = schema[i]; - if (typeof item == "object" && !checkNoRef(item)) return false; - } - } else { - for (var key in schema) { - if (key == "$ref") return false; - item = schema[key]; - if (typeof item == "object" && !checkNoRef(item)) return false; - } - } - return true; - } - function countKeys(schema) { - var count = 0, item; - if (Array.isArray(schema)) { - for (var i = 0; i < schema.length; i++) { - item = schema[i]; - if (typeof item == "object") count += countKeys(item); - if (count == Infinity) return Infinity; - } - } else { - for (var key in schema) { - if (key == "$ref") return Infinity; - if (SIMPLE_INLINED[key]) { - count++; - } else { - item = schema[key]; - if (typeof item == "object") count += countKeys(item) + 1; - if (count == Infinity) return Infinity; - } - } - } - return count; - } - function getFullPath(id, normalize) { - if (normalize !== false) id = normalizeId(id); - var p = URI.parse(id); - return _getFullPath(p); - } - function _getFullPath(p) { - return URI.serialize(p).split("#")[0] + "#"; - } - var TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - function resolveUrl(baseId, id) { - id = normalizeId(id); - return URI.resolve(baseId, id); - } - function resolveIds(schema) { - var schemaId = normalizeId(this._getId(schema)); - var baseIds = { "": schemaId }; - var fullPaths = { "": getFullPath(schemaId, false) }; - var localRefs = {}; - var self = this; - traverse(schema, { allKeys: true }, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (jsonPtr === "") return; - var id = self._getId(sch); - var baseId = baseIds[parentJsonPtr]; - var fullPath = fullPaths[parentJsonPtr] + "/" + parentKeyword; - if (keyIndex !== void 0) - fullPath += "/" + (typeof keyIndex == "number" ? keyIndex : util2.escapeFragment(keyIndex)); - if (typeof id == "string") { - id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); - var refVal = self._refs[id]; - if (typeof refVal == "string") refVal = self._refs[refVal]; - if (refVal && refVal.schema) { - if (!equal(sch, refVal.schema)) - throw new Error('id "' + id + '" resolves to more than one schema'); - } else if (id != normalizeId(fullPath)) { - if (id[0] == "#") { - if (localRefs[id] && !equal(sch, localRefs[id])) - throw new Error('id "' + id + '" resolves to more than one schema'); - localRefs[id] = sch; - } else { - self._refs[id] = fullPath; - } - } - } - baseIds[jsonPtr] = baseId; - fullPaths[jsonPtr] = fullPath; - }); - return localRefs; - } - } -}); - -// node_modules/ajv/lib/compile/error_classes.js -var require_error_classes = __commonJS({ - "node_modules/ajv/lib/compile/error_classes.js"(exports2, module2) { - "use strict"; - var resolve = require_resolve(); - module2.exports = { - Validation: errorSubclass(ValidationError), - MissingRef: errorSubclass(MissingRefError) - }; - function ValidationError(errors) { - this.message = "validation failed"; - this.errors = errors; - this.ajv = this.validation = true; - } - MissingRefError.message = function(baseId, ref) { - return "can't resolve reference " + ref + " from id " + baseId; - }; - function MissingRefError(baseId, ref, message) { - this.message = message || MissingRefError.message(baseId, ref); - this.missingRef = resolve.url(baseId, ref); - this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); - } - function errorSubclass(Subclass) { - Subclass.prototype = Object.create(Error.prototype); - Subclass.prototype.constructor = Subclass; - return Subclass; - } - } -}); - -// node_modules/fast-json-stable-stringify/index.js -var require_fast_json_stable_stringify = __commonJS({ - "node_modules/fast-json-stable-stringify/index.js"(exports2, module2) { - "use strict"; - module2.exports = function(data, opts) { - if (!opts) opts = {}; - if (typeof opts === "function") opts = { cmp: opts }; - var cycles = typeof opts.cycles === "boolean" ? opts.cycles : false; - var cmp = opts.cmp && /* @__PURE__ */ function(f) { - return function(node) { - return function(a, b) { - var aobj = { key: a, value: node[a] }; - var bobj = { key: b, value: node[b] }; - return f(aobj, bobj); - }; - }; - }(opts.cmp); - var seen = []; - return function stringify(node) { - if (node && node.toJSON && typeof node.toJSON === "function") { - node = node.toJSON(); - } - if (node === void 0) return; - if (typeof node == "number") return isFinite(node) ? "" + node : "null"; - if (typeof node !== "object") return JSON.stringify(node); - var i, out; - if (Array.isArray(node)) { - out = "["; - for (i = 0; i < node.length; i++) { - if (i) out += ","; - out += stringify(node[i]) || "null"; - } - return out + "]"; - } - if (node === null) return "null"; - if (seen.indexOf(node) !== -1) { - if (cycles) return JSON.stringify("__cycle__"); - throw new TypeError("Converting circular structure to JSON"); - } - var seenIndex = seen.push(node) - 1; - var keys = Object.keys(node).sort(cmp && cmp(node)); - out = ""; - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = stringify(node[key]); - if (!value) continue; - if (out) out += ","; - out += JSON.stringify(key) + ":" + value; - } - seen.splice(seenIndex, 1); - return "{" + out + "}"; - }(data); - }; - } -}); - -// node_modules/ajv/lib/dotjs/validate.js -var require_validate = __commonJS({ - "node_modules/ajv/lib/dotjs/validate.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_validate(it, $keyword, $ruleType) { - var out = ""; - var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, "$ref"), $id = it.self._getId(it.schema); - if (it.opts.strictKeywords) { - var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); - if ($unknownKwd) { - var $keywordsMsg = "unknown keyword: " + $unknownKwd; - if (it.opts.strictKeywords === "log") it.logger.warn($keywordsMsg); - else throw new Error($keywordsMsg); - } - } - if (it.isTop) { - out += " var validate = "; - if ($async) { - it.async = true; - out += "async "; - } - out += "function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; "; - if ($id && (it.opts.sourceCode || it.opts.processCode)) { - out += " " + ("/*# sourceURL=" + $id + " */") + " "; - } - } - if (typeof it.schema == "boolean" || !($refKeywords || it.schema.$ref)) { - var $keyword = "false schema"; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - if (it.schema === false) { - if (it.isTop) { - $breakOnError = true; - } else { - out += " var " + $valid + " = false; "; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "false schema") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} "; - if (it.opts.messages !== false) { - out += " , message: 'boolean schema is false' "; - } - if (it.opts.verbose) { - out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - } else { - if (it.isTop) { - if ($async) { - out += " return data; "; - } else { - out += " validate.errors = null; return true; "; - } - } else { - out += " var " + $valid + " = true; "; - } - } - if (it.isTop) { - out += " }; return validate; "; - } - return out; - } - if (it.isTop) { - var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = "data"; - it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); - it.baseId = it.baseId || it.rootId; - delete it.isTop; - it.dataPathArr = [""]; - if (it.schema.default !== void 0 && it.opts.useDefaults && it.opts.strictDefaults) { - var $defaultMsg = "default is ignored in the schema root"; - if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg); - else throw new Error($defaultMsg); - } - out += " var vErrors = null; "; - out += " var errors = 0; "; - out += " if (rootData === undefined) rootData = data; "; - } else { - var $lvl = it.level, $dataLvl = it.dataLevel, $data = "data" + ($dataLvl || ""); - if ($id) it.baseId = it.resolve.url(it.baseId, $id); - if ($async && !it.async) throw new Error("async schema in sync schema"); - out += " var errs_" + $lvl + " = errors;"; - } - var $valid = "valid" + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = "", $closingBraces2 = ""; - var $errorKeyword; - var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema); - if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { - if ($typeIsArray) { - if ($typeSchema.indexOf("null") == -1) $typeSchema = $typeSchema.concat("null"); - } else if ($typeSchema != "null") { - $typeSchema = [$typeSchema, "null"]; - $typeIsArray = true; - } - } - if ($typeIsArray && $typeSchema.length == 1) { - $typeSchema = $typeSchema[0]; - $typeIsArray = false; - } - if (it.schema.$ref && $refKeywords) { - if (it.opts.extendRefs == "fail") { - throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); - } else if (it.opts.extendRefs !== true) { - $refKeywords = false; - it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); - } - } - if (it.schema.$comment && it.opts.$comment) { - out += " " + it.RULES.all.$comment.code(it, "$comment"); - } - if ($typeSchema) { - if (it.opts.coerceTypes) { - var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); - } - var $rulesGroup = it.RULES.types[$typeSchema]; - if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) { - var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type"; - var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type", $method = $typeIsArray ? "checkDataTypes" : "checkDataType"; - out += " if (" + it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) + ") { "; - if ($coerceToTypes) { - var $dataType = "dataType" + $lvl, $coerced = "coerced" + $lvl; - out += " var " + $dataType + " = typeof " + $data + "; var " + $coerced + " = undefined; "; - if (it.opts.coerceTypes == "array") { - out += " if (" + $dataType + " == 'object' && Array.isArray(" + $data + ") && " + $data + ".length == 1) { " + $data + " = " + $data + "[0]; " + $dataType + " = typeof " + $data + "; if (" + it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers) + ") " + $coerced + " = " + $data + "; } "; - } - out += " if (" + $coerced + " !== undefined) ; "; - var arr1 = $coerceToTypes; - if (arr1) { - var $type, $i = -1, l1 = arr1.length - 1; - while ($i < l1) { - $type = arr1[$i += 1]; - if ($type == "string") { - out += " else if (" + $dataType + " == 'number' || " + $dataType + " == 'boolean') " + $coerced + " = '' + " + $data + "; else if (" + $data + " === null) " + $coerced + " = ''; "; - } else if ($type == "number" || $type == "integer") { - out += " else if (" + $dataType + " == 'boolean' || " + $data + " === null || (" + $dataType + " == 'string' && " + $data + " && " + $data + " == +" + $data + " "; - if ($type == "integer") { - out += " && !(" + $data + " % 1)"; - } - out += ")) " + $coerced + " = +" + $data + "; "; - } else if ($type == "boolean") { - out += " else if (" + $data + " === 'false' || " + $data + " === 0 || " + $data + " === null) " + $coerced + " = false; else if (" + $data + " === 'true' || " + $data + " === 1) " + $coerced + " = true; "; - } else if ($type == "null") { - out += " else if (" + $data + " === '' || " + $data + " === 0 || " + $data + " === false) " + $coerced + " = null; "; - } else if (it.opts.coerceTypes == "array" && $type == "array") { - out += " else if (" + $dataType + " == 'string' || " + $dataType + " == 'number' || " + $dataType + " == 'boolean' || " + $data + " == null) " + $coerced + " = [" + $data + "]; "; - } - } - } - out += " else { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '"; - if ($typeIsArray) { - out += "" + $typeSchema.join(","); - } else { - out += "" + $typeSchema; - } - out += "' } "; - if (it.opts.messages !== false) { - out += " , message: 'should be "; - if ($typeIsArray) { - out += "" + $typeSchema.join(","); - } else { - out += "" + $typeSchema; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } if (" + $coerced + " !== undefined) { "; - var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty"; - out += " " + $data + " = " + $coerced + "; "; - if (!$dataLvl) { - out += "if (" + $parentData + " !== undefined)"; - } - out += " " + $parentData + "[" + $parentDataProperty + "] = " + $coerced + "; } "; - } else { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '"; - if ($typeIsArray) { - out += "" + $typeSchema.join(","); - } else { - out += "" + $typeSchema; - } - out += "' } "; - if (it.opts.messages !== false) { - out += " , message: 'should be "; - if ($typeIsArray) { - out += "" + $typeSchema.join(","); - } else { - out += "" + $typeSchema; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - } - out += " } "; - } - } - if (it.schema.$ref && !$refKeywords) { - out += " " + it.RULES.all.$ref.code(it, "$ref") + " "; - if ($breakOnError) { - out += " } if (errors === "; - if ($top) { - out += "0"; - } else { - out += "errs_" + $lvl; - } - out += ") { "; - $closingBraces2 += "}"; - } - } else { - var arr2 = it.RULES; - if (arr2) { - var $rulesGroup, i2 = -1, l2 = arr2.length - 1; - while (i2 < l2) { - $rulesGroup = arr2[i2 += 1]; - if ($shouldUseGroup($rulesGroup)) { - if ($rulesGroup.type) { - out += " if (" + it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) + ") { "; - } - if (it.opts.useDefaults) { - if ($rulesGroup.type == "object" && it.schema.properties) { - var $schema = it.schema.properties, $schemaKeys = Object.keys($schema); - var arr3 = $schemaKeys; - if (arr3) { - var $propertyKey, i3 = -1, l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $sch = $schema[$propertyKey]; - if ($sch.default !== void 0) { - var $passData = $data + it.util.getProperty($propertyKey); - if (it.compositeRule) { - if (it.opts.strictDefaults) { - var $defaultMsg = "default is ignored for: " + $passData; - if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg); - else throw new Error($defaultMsg); - } - } else { - out += " if (" + $passData + " === undefined "; - if (it.opts.useDefaults == "empty") { - out += " || " + $passData + " === null || " + $passData + " === '' "; - } - out += " ) " + $passData + " = "; - if (it.opts.useDefaults == "shared") { - out += " " + it.useDefault($sch.default) + " "; - } else { - out += " " + JSON.stringify($sch.default) + " "; - } - out += "; "; - } - } - } - } - } else if ($rulesGroup.type == "array" && Array.isArray(it.schema.items)) { - var arr4 = it.schema.items; - if (arr4) { - var $sch, $i = -1, l4 = arr4.length - 1; - while ($i < l4) { - $sch = arr4[$i += 1]; - if ($sch.default !== void 0) { - var $passData = $data + "[" + $i + "]"; - if (it.compositeRule) { - if (it.opts.strictDefaults) { - var $defaultMsg = "default is ignored for: " + $passData; - if (it.opts.strictDefaults === "log") it.logger.warn($defaultMsg); - else throw new Error($defaultMsg); - } - } else { - out += " if (" + $passData + " === undefined "; - if (it.opts.useDefaults == "empty") { - out += " || " + $passData + " === null || " + $passData + " === '' "; - } - out += " ) " + $passData + " = "; - if (it.opts.useDefaults == "shared") { - out += " " + it.useDefault($sch.default) + " "; - } else { - out += " " + JSON.stringify($sch.default) + " "; - } - out += "; "; - } - } - } - } - } - } - var arr5 = $rulesGroup.rules; - if (arr5) { - var $rule, i5 = -1, l5 = arr5.length - 1; - while (i5 < l5) { - $rule = arr5[i5 += 1]; - if ($shouldUseRule($rule)) { - var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); - if ($code) { - out += " " + $code + " "; - if ($breakOnError) { - $closingBraces1 += "}"; - } - } - } - } - } - if ($breakOnError) { - out += " " + $closingBraces1 + " "; - $closingBraces1 = ""; - } - if ($rulesGroup.type) { - out += " } "; - if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { - out += " else { "; - var $schemaPath = it.schemaPath + ".type", $errSchemaPath = it.errSchemaPath + "/type"; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { type: '"; - if ($typeIsArray) { - out += "" + $typeSchema.join(","); - } else { - out += "" + $typeSchema; - } - out += "' } "; - if (it.opts.messages !== false) { - out += " , message: 'should be "; - if ($typeIsArray) { - out += "" + $typeSchema.join(","); - } else { - out += "" + $typeSchema; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } "; - } - } - if ($breakOnError) { - out += " if (errors === "; - if ($top) { - out += "0"; - } else { - out += "errs_" + $lvl; - } - out += ") { "; - $closingBraces2 += "}"; - } - } - } - } - } - if ($breakOnError) { - out += " " + $closingBraces2 + " "; - } - if ($top) { - if ($async) { - out += " if (errors === 0) return data; "; - out += " else throw new ValidationError(vErrors); "; - } else { - out += " validate.errors = vErrors; "; - out += " return errors === 0; "; - } - out += " }; return validate;"; - } else { - out += " var " + $valid + " = errors === errs_" + $lvl + ";"; - } - function $shouldUseGroup($rulesGroup2) { - var rules = $rulesGroup2.rules; - for (var i = 0; i < rules.length; i++) - if ($shouldUseRule(rules[i])) return true; - } - function $shouldUseRule($rule2) { - return it.schema[$rule2.keyword] !== void 0 || $rule2.implements && $ruleImplementsSomeKeyword($rule2); - } - function $ruleImplementsSomeKeyword($rule2) { - var impl = $rule2.implements; - for (var i = 0; i < impl.length; i++) - if (it.schema[impl[i]] !== void 0) return true; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/compile/index.js -var require_compile = __commonJS({ - "node_modules/ajv/lib/compile/index.js"(exports2, module2) { - "use strict"; - var resolve = require_resolve(); - var util2 = require_util(); - var errorClasses = require_error_classes(); - var stableStringify = require_fast_json_stable_stringify(); - var validateGenerator = require_validate(); - var ucs2length = util2.ucs2length; - var equal = require_fast_deep_equal(); - var ValidationError = errorClasses.Validation; - module2.exports = compile; - function compile(schema, root, localRefs, baseId) { - var self = this, opts = this._opts, refVal = [void 0], refs = {}, patterns = [], patternsHash = {}, defaults = [], defaultsHash = {}, customRules = []; - root = root || { schema, refVal, refs }; - var c = checkCompiling.call(this, schema, root, baseId); - var compilation = this._compilations[c.index]; - if (c.compiling) return compilation.callValidate = callValidate; - var formats = this._formats; - var RULES = this.RULES; - try { - var v = localCompile(schema, root, localRefs, baseId); - compilation.validate = v; - var cv = compilation.callValidate; - if (cv) { - cv.schema = v.schema; - cv.errors = null; - cv.refs = v.refs; - cv.refVal = v.refVal; - cv.root = v.root; - cv.$async = v.$async; - if (opts.sourceCode) cv.source = v.source; - } - return v; - } finally { - endCompiling.call(this, schema, root, baseId); - } - function callValidate() { - var validate = compilation.validate; - var result = validate.apply(this, arguments); - callValidate.errors = validate.errors; - return result; - } - function localCompile(_schema, _root, localRefs2, baseId2) { - var isRoot = !_root || _root && _root.schema == _schema; - if (_root.schema != root.schema) - return compile.call(self, _schema, _root, localRefs2, baseId2); - var $async = _schema.$async === true; - var sourceCode = validateGenerator({ - isTop: true, - schema: _schema, - isRoot, - baseId: baseId2, - root: _root, - schemaPath: "", - errSchemaPath: "#", - errorPath: '""', - MissingRefError: errorClasses.MissingRef, - RULES, - validate: validateGenerator, - util: util2, - resolve, - resolveRef, - usePattern, - useDefault, - useCustomRule, - opts, - formats, - logger: self.logger, - self - }); - sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode; - if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); - var validate; - try { - var makeValidate = new Function( - "self", - "RULES", - "formats", - "root", - "refVal", - "defaults", - "customRules", - "equal", - "ucs2length", - "ValidationError", - sourceCode - ); - validate = makeValidate( - self, - RULES, - formats, - root, - refVal, - defaults, - customRules, - equal, - ucs2length, - ValidationError - ); - refVal[0] = validate; - } catch (e) { - self.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } - validate.schema = _schema; - validate.errors = null; - validate.refs = refs; - validate.refVal = refVal; - validate.root = isRoot ? validate : _root; - if ($async) validate.$async = true; - if (opts.sourceCode === true) { - validate.source = { - code: sourceCode, - patterns, - defaults - }; - } - return validate; - } - function resolveRef(baseId2, ref, isRoot) { - ref = resolve.url(baseId2, ref); - var refIndex = refs[ref]; - var _refVal, refCode; - if (refIndex !== void 0) { - _refVal = refVal[refIndex]; - refCode = "refVal[" + refIndex + "]"; - return resolvedRef(_refVal, refCode); - } - if (!isRoot && root.refs) { - var rootRefId = root.refs[ref]; - if (rootRefId !== void 0) { - _refVal = root.refVal[rootRefId]; - refCode = addLocalRef(ref, _refVal); - return resolvedRef(_refVal, refCode); - } - } - refCode = addLocalRef(ref); - var v2 = resolve.call(self, localCompile, root, ref); - if (v2 === void 0) { - var localSchema = localRefs && localRefs[ref]; - if (localSchema) { - v2 = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId2); - } - } - if (v2 === void 0) { - removeLocalRef(ref); - } else { - replaceLocalRef(ref, v2); - return resolvedRef(v2, refCode); - } - } - function addLocalRef(ref, v2) { - var refId = refVal.length; - refVal[refId] = v2; - refs[ref] = refId; - return "refVal" + refId; - } - function removeLocalRef(ref) { - delete refs[ref]; - } - function replaceLocalRef(ref, v2) { - var refId = refs[ref]; - refVal[refId] = v2; - } - function resolvedRef(refVal2, code) { - return typeof refVal2 == "object" || typeof refVal2 == "boolean" ? { code, schema: refVal2, inline: true } : { code, $async: refVal2 && !!refVal2.$async }; - } - function usePattern(regexStr) { - var index = patternsHash[regexStr]; - if (index === void 0) { - index = patternsHash[regexStr] = patterns.length; - patterns[index] = regexStr; - } - return "pattern" + index; - } - function useDefault(value) { - switch (typeof value) { - case "boolean": - case "number": - return "" + value; - case "string": - return util2.toQuotedString(value); - case "object": - if (value === null) return "null"; - var valueStr = stableStringify(value); - var index = defaultsHash[valueStr]; - if (index === void 0) { - index = defaultsHash[valueStr] = defaults.length; - defaults[index] = value; - } - return "default" + index; - } - } - function useCustomRule(rule, schema2, parentSchema, it) { - if (self._opts.validateSchema !== false) { - var deps = rule.definition.dependencies; - if (deps && !deps.every(function(keyword) { - return Object.prototype.hasOwnProperty.call(parentSchema, keyword); - })) - throw new Error("parent schema must have all required keywords: " + deps.join(",")); - var validateSchema = rule.definition.validateSchema; - if (validateSchema) { - var valid = validateSchema(schema2); - if (!valid) { - var message = "keyword schema is invalid: " + self.errorsText(validateSchema.errors); - if (self._opts.validateSchema == "log") self.logger.error(message); - else throw new Error(message); - } - } - } - var compile2 = rule.definition.compile, inline = rule.definition.inline, macro = rule.definition.macro; - var validate; - if (compile2) { - validate = compile2.call(self, schema2, parentSchema, it); - } else if (macro) { - validate = macro.call(self, schema2, parentSchema, it); - if (opts.validateSchema !== false) self.validateSchema(validate, true); - } else if (inline) { - validate = inline.call(self, it, rule.keyword, schema2, parentSchema); - } else { - validate = rule.definition.validate; - if (!validate) return; - } - if (validate === void 0) - throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); - var index = customRules.length; - customRules[index] = validate; - return { - code: "customRule" + index, - validate - }; - } - } - function checkCompiling(schema, root, baseId) { - var index = compIndex.call(this, schema, root, baseId); - if (index >= 0) return { index, compiling: true }; - index = this._compilations.length; - this._compilations[index] = { - schema, - root, - baseId - }; - return { index, compiling: false }; - } - function endCompiling(schema, root, baseId) { - var i = compIndex.call(this, schema, root, baseId); - if (i >= 0) this._compilations.splice(i, 1); - } - function compIndex(schema, root, baseId) { - for (var i = 0; i < this._compilations.length; i++) { - var c = this._compilations[i]; - if (c.schema == schema && c.root == root && c.baseId == baseId) return i; - } - return -1; - } - function patternCode(i, patterns) { - return "var pattern" + i + " = new RegExp(" + util2.toQuotedString(patterns[i]) + ");"; - } - function defaultCode(i) { - return "var default" + i + " = defaults[" + i + "];"; - } - function refValCode(i, refVal) { - return refVal[i] === void 0 ? "" : "var refVal" + i + " = refVal[" + i + "];"; - } - function customRuleCode(i) { - return "var customRule" + i + " = customRules[" + i + "];"; - } - function vars(arr, statement) { - if (!arr.length) return ""; - var code = ""; - for (var i = 0; i < arr.length; i++) - code += statement(i, arr); - return code; - } - } -}); - -// node_modules/ajv/lib/cache.js -var require_cache = __commonJS({ - "node_modules/ajv/lib/cache.js"(exports2, module2) { - "use strict"; - var Cache = module2.exports = function Cache2() { - this._cache = {}; - }; - Cache.prototype.put = function Cache_put(key, value) { - this._cache[key] = value; - }; - Cache.prototype.get = function Cache_get(key) { - return this._cache[key]; - }; - Cache.prototype.del = function Cache_del(key) { - delete this._cache[key]; - }; - Cache.prototype.clear = function Cache_clear() { - this._cache = {}; - }; - } -}); - -// node_modules/ajv/lib/compile/formats.js -var require_formats = __commonJS({ - "node_modules/ajv/lib/compile/formats.js"(exports2, module2) { - "use strict"; - var util2 = require_util(); - 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]; - var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; - var 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; - 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; - var URIREF = /^(?:[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; - var URITEMPLATE = /^(?:(?:[^\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; - var URL2 = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; - var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; - var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; - var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; - var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; - module2.exports = formats; - function formats(mode) { - mode = mode == "full" ? "full" : "fast"; - return util2.copy(formats[mode]); - } - formats.fast = { - // date: http://tools.ietf.org/html/rfc3339#section-5.6 - date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, - // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 - time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, - "date-time": /^\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, - // 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, - "uri-template": URITEMPLATE, - url: URL2, - // 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 'willful 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, - hostname: HOSTNAME, - // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses - ipv6: /^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i, - regex, - // uuid: http://tools.ietf.org/html/rfc4122 - uuid: UUID, - // JSON-pointer: https://tools.ietf.org/html/rfc6901 - // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A - "json-pointer": JSON_POINTER, - "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT, - // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 - "relative-json-pointer": RELATIVE_JSON_POINTER - }; - formats.full = { - date, - time, - "date-time": date_time, - uri, - "uri-reference": URIREF, - "uri-template": URITEMPLATE, - url: URL2, - 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: HOSTNAME, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - ipv6: /^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i, - regex, - uuid: UUID, - "json-pointer": JSON_POINTER, - "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT, - "relative-json-pointer": RELATIVE_JSON_POINTER - }; - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - function date(str) { - var matches = str.match(DATE); - if (!matches) return false; - var year = +matches[1]; - var month = +matches[2]; - var day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function time(str, full) { - var matches = str.match(TIME); - if (!matches) return false; - var hour = matches[1]; - var minute = matches[2]; - var second = matches[3]; - var timeZone = matches[5]; - return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone); - } - var DATE_TIME_SEPARATOR = /t|\s/i; - function date_time(str) { - var dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); - } - var NOT_URI_FRAGMENT = /\/|:/; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - var Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } - } -}); - -// node_modules/ajv/lib/dotjs/ref.js -var require_ref = __commonJS({ - "node_modules/ajv/lib/dotjs/ref.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_ref(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $async, $refCode; - if ($schema == "#" || $schema == "#/") { - if (it.isRoot) { - $async = it.async; - $refCode = "validate"; - } else { - $async = it.root.schema.$async === true; - $refCode = "root.refVal[0]"; - } - } else { - var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); - if ($refVal === void 0) { - var $message = it.MissingRefError.message(it.baseId, $schema); - if (it.opts.missingRefs == "fail") { - it.logger.error($message); - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '$ref' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { ref: '" + it.util.escapeQuotes($schema) + "' } "; - if (it.opts.messages !== false) { - out += " , message: 'can\\'t resolve reference " + it.util.escapeQuotes($schema) + "' "; - } - if (it.opts.verbose) { - out += " , schema: " + it.util.toQuotedString($schema) + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - if ($breakOnError) { - out += " if (false) { "; - } - } else if (it.opts.missingRefs == "ignore") { - it.logger.warn($message); - if ($breakOnError) { - out += " if (true) { "; - } - } else { - throw new it.MissingRefError(it.baseId, $schema, $message); - } - } else if ($refVal.inline) { - var $it = it.util.copy(it); - $it.level++; - var $nextValid = "valid" + $it.level; - $it.schema = $refVal.schema; - $it.schemaPath = ""; - $it.errSchemaPath = $schema; - var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); - out += " " + $code + " "; - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - } - } else { - $async = $refVal.$async === true || it.async && $refVal.$async !== false; - $refCode = $refVal.code; - } - } - if ($refCode) { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.opts.passContext) { - out += " " + $refCode + ".call(this, "; - } else { - out += " " + $refCode + "( "; - } - out += " " + $data + ", (dataPath || '')"; - if (it.errorPath != '""') { - out += " + " + it.errorPath; - } - var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty"; - out += " , " + $parentData + " , " + $parentDataProperty + ", rootData) "; - var __callValidate = out; - out = $$outStack.pop(); - if ($async) { - if (!it.async) throw new Error("async schema referenced by sync schema"); - if ($breakOnError) { - out += " var " + $valid + "; "; - } - out += " try { await " + __callValidate + "; "; - if ($breakOnError) { - out += " " + $valid + " = true; "; - } - out += " } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; "; - if ($breakOnError) { - out += " " + $valid + " = false; "; - } - out += " } "; - if ($breakOnError) { - out += " if (" + $valid + ") { "; - } - } else { - out += " if (!" + __callValidate + ") { if (vErrors === null) vErrors = " + $refCode + ".errors; else vErrors = vErrors.concat(" + $refCode + ".errors); errors = vErrors.length; } "; - if ($breakOnError) { - out += " else { "; - } - } - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/allOf.js -var require_allOf = __commonJS({ - "node_modules/ajv/lib/dotjs/allOf.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_allOf(it, $keyword, $ruleType) { - var out = " "; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - var $currentBaseId = $it.baseId, $allSchemasEmpty = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) { - $allSchemasEmpty = false; - $it.schema = $sch; - $it.schemaPath = $schemaPath + "[" + $i + "]"; - $it.errSchemaPath = $errSchemaPath + "/" + $i; - out += " " + it.validate($it) + " "; - $it.baseId = $currentBaseId; - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - $closingBraces += "}"; - } - } - } - } - if ($breakOnError) { - if ($allSchemasEmpty) { - out += " if (true) { "; - } else { - out += " " + $closingBraces.slice(0, -1) + " "; - } - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/anyOf.js -var require_anyOf = __commonJS({ - "node_modules/ajv/lib/dotjs/anyOf.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_anyOf(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - var $noEmptySchema = $schema.every(function($sch2) { - return it.opts.strictKeywords ? typeof $sch2 == "object" && Object.keys($sch2).length > 0 || $sch2 === false : it.util.schemaHasRules($sch2, it.RULES.all); - }); - if ($noEmptySchema) { - var $currentBaseId = $it.baseId; - out += " var " + $errs + " = errors; var " + $valid + " = false; "; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - $it.schema = $sch; - $it.schemaPath = $schemaPath + "[" + $i + "]"; - $it.errSchemaPath = $errSchemaPath + "/" + $i; - out += " " + it.validate($it) + " "; - $it.baseId = $currentBaseId; - out += " " + $valid + " = " + $valid + " || " + $nextValid + "; if (!" + $valid + ") { "; - $closingBraces += "}"; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += " " + $closingBraces + " if (!" + $valid + ") { var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'anyOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} "; - if (it.opts.messages !== false) { - out += " , message: 'should match some schema in anyOf' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError(vErrors); "; - } else { - out += " validate.errors = vErrors; return false; "; - } - } - out += " } else { errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } "; - if (it.opts.allErrors) { - out += " } "; - } - } else { - if ($breakOnError) { - out += " if (true) { "; - } - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/comment.js -var require_comment = __commonJS({ - "node_modules/ajv/lib/dotjs/comment.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_comment(it, $keyword, $ruleType) { - var out = " "; - var $schema = it.schema[$keyword]; - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $comment = it.util.toQuotedString($schema); - if (it.opts.$comment === true) { - out += " console.log(" + $comment + ");"; - } else if (typeof it.opts.$comment == "function") { - out += " self._opts.$comment(" + $comment + ", " + it.util.toQuotedString($errSchemaPath) + ", validate.root.schema);"; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/const.js -var require_const = __commonJS({ - "node_modules/ajv/lib/dotjs/const.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_const(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - if (!$isData) { - out += " var schema" + $lvl + " = validate.schema" + $schemaPath + ";"; - } - out += "var " + $valid + " = equal(" + $data + ", schema" + $lvl + "); if (!" + $valid + ") { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'const' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValue: schema" + $lvl + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should be equal to constant' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " }"; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/contains.js -var require_contains = __commonJS({ - "node_modules/ajv/lib/dotjs/contains.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_contains(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all); - out += "var " + $errs + " = errors;var " + $valid + ";"; - if ($nonEmptySchema) { - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += " var " + $nextValid + " = false; for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { "; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + "[" + $idx + "]"; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - out += " if (" + $nextValid + ") break; } "; - it.compositeRule = $it.compositeRule = $wasComposite; - out += " " + $closingBraces + " if (!" + $nextValid + ") {"; - } else { - out += " if (" + $data + ".length == 0) {"; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'contains' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} "; - if (it.opts.messages !== false) { - out += " , message: 'should contain a valid item' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } else { "; - if ($nonEmptySchema) { - out += " errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } "; - } - if (it.opts.allErrors) { - out += " } "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/dependencies.js -var require_dependencies = __commonJS({ - "node_modules/ajv/lib/dotjs/dependencies.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_dependencies(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties; - for ($property in $schema) { - if ($property == "__proto__") continue; - var $sch = $schema[$property]; - var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; - $deps[$property] = $sch; - } - out += "var " + $errs + " = errors;"; - var $currentErrorPath = it.errorPath; - out += "var missing" + $lvl + ";"; - for (var $property in $propertyDeps) { - $deps = $propertyDeps[$property]; - if ($deps.length) { - out += " if ( " + $data + it.util.getProperty($property) + " !== undefined "; - if ($ownProperties) { - out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') "; - } - if ($breakOnError) { - out += " && ( "; - var arr1 = $deps; - if (arr1) { - var $propertyKey, $i = -1, l1 = arr1.length - 1; - while ($i < l1) { - $propertyKey = arr1[$i += 1]; - if ($i) { - out += " || "; - } - var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; - out += " ( ( " + $useData + " === undefined "; - if ($ownProperties) { - out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') "; - } - out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) "; - } - } - out += ")) { "; - var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '"; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } "; - if (it.opts.messages !== false) { - out += " , message: 'should have "; - if ($deps.length == 1) { - out += "property " + it.util.escapeQuotes($deps[0]); - } else { - out += "properties " + it.util.escapeQuotes($deps.join(", ")); - } - out += " when property " + it.util.escapeQuotes($property) + " is present' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - } else { - out += " ) { "; - var arr2 = $deps; - if (arr2) { - var $propertyKey, i2 = -1, l2 = arr2.length - 1; - while (i2 < l2) { - $propertyKey = arr2[i2 += 1]; - var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - out += " if ( " + $useData + " === undefined "; - if ($ownProperties) { - out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') "; - } - out += ") { var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } "; - if (it.opts.messages !== false) { - out += " , message: 'should have "; - if ($deps.length == 1) { - out += "property " + it.util.escapeQuotes($deps[0]); - } else { - out += "properties " + it.util.escapeQuotes($deps.join(", ")); - } - out += " when property " + it.util.escapeQuotes($property) + " is present' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "; - } - } - } - out += " } "; - if ($breakOnError) { - $closingBraces += "}"; - out += " else { "; - } - } - } - it.errorPath = $currentErrorPath; - var $currentBaseId = $it.baseId; - for (var $property in $schemaDeps) { - var $sch = $schemaDeps[$property]; - if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) { - out += " " + $nextValid + " = true; if ( " + $data + it.util.getProperty($property) + " !== undefined "; - if ($ownProperties) { - out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($property) + "') "; - } - out += ") { "; - $it.schema = $sch; - $it.schemaPath = $schemaPath + it.util.getProperty($property); - $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($property); - out += " " + it.validate($it) + " "; - $it.baseId = $currentBaseId; - out += " } "; - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - $closingBraces += "}"; - } - } - } - if ($breakOnError) { - out += " " + $closingBraces + " if (" + $errs + " == errors) {"; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/enum.js -var require_enum = __commonJS({ - "node_modules/ajv/lib/dotjs/enum.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_enum(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - var $i = "i" + $lvl, $vSchema = "schema" + $lvl; - if (!$isData) { - out += " var " + $vSchema + " = validate.schema" + $schemaPath + ";"; - } - out += "var " + $valid + ";"; - if ($isData) { - out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {"; - } - out += "" + $valid + " = false;for (var " + $i + "=0; " + $i + "<" + $vSchema + ".length; " + $i + "++) if (equal(" + $data + ", " + $vSchema + "[" + $i + "])) { " + $valid + " = true; break; }"; - if ($isData) { - out += " } "; - } - out += " if (!" + $valid + ") { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'enum' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { allowedValues: schema" + $lvl + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should be equal to one of the allowed values' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " }"; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/format.js -var require_format = __commonJS({ - "node_modules/ajv/lib/dotjs/format.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_format(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - if (it.opts.format === false) { - if ($breakOnError) { - out += " if (true) { "; - } - return out; - } - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats); - if ($isData) { - var $format = "format" + $lvl, $isObject = "isObject" + $lvl, $formatType = "formatType" + $lvl; - out += " var " + $format + " = formats[" + $schemaValue + "]; var " + $isObject + " = typeof " + $format + " == 'object' && !(" + $format + " instanceof RegExp) && " + $format + ".validate; var " + $formatType + " = " + $isObject + " && " + $format + ".type || 'string'; if (" + $isObject + ") { "; - if (it.async) { - out += " var async" + $lvl + " = " + $format + ".async; "; - } - out += " " + $format + " = " + $format + ".validate; } if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || "; - } - out += " ("; - if ($unknownFormats != "ignore") { - out += " (" + $schemaValue + " && !" + $format + " "; - if ($allowUnknown) { - out += " && self._opts.unknownFormats.indexOf(" + $schemaValue + ") == -1 "; - } - out += ") || "; - } - out += " (" + $format + " && " + $formatType + " == '" + $ruleType + "' && !(typeof " + $format + " == 'function' ? "; - if (it.async) { - out += " (async" + $lvl + " ? await " + $format + "(" + $data + ") : " + $format + "(" + $data + ")) "; - } else { - out += " " + $format + "(" + $data + ") "; - } - out += " : " + $format + ".test(" + $data + "))))) {"; - } else { - var $format = it.formats[$schema]; - if (!$format) { - if ($unknownFormats == "ignore") { - it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); - if ($breakOnError) { - out += " if (true) { "; - } - return out; - } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { - if ($breakOnError) { - out += " if (true) { "; - } - return out; - } else { - throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); - } - } - var $isObject = typeof $format == "object" && !($format instanceof RegExp) && $format.validate; - var $formatType = $isObject && $format.type || "string"; - if ($isObject) { - var $async = $format.async === true; - $format = $format.validate; - } - if ($formatType != $ruleType) { - if ($breakOnError) { - out += " if (true) { "; - } - return out; - } - if ($async) { - if (!it.async) throw new Error("async format in sync schema"); - var $formatRef = "formats" + it.util.getProperty($schema) + ".validate"; - out += " if (!(await " + $formatRef + "(" + $data + "))) { "; - } else { - out += " if (! "; - var $formatRef = "formats" + it.util.getProperty($schema); - if ($isObject) $formatRef += ".validate"; - if (typeof $format == "function") { - out += " " + $formatRef + "(" + $data + ") "; - } else { - out += " " + $formatRef + ".test(" + $data + ") "; - } - out += ") { "; - } - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'format' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { format: "; - if ($isData) { - out += "" + $schemaValue; - } else { - out += "" + it.util.toQuotedString($schema); - } - out += " } "; - if (it.opts.messages !== false) { - out += ` , message: 'should match format "`; - if ($isData) { - out += "' + " + $schemaValue + " + '"; - } else { - out += "" + it.util.escapeQuotes($schema); - } - out += `"' `; - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + it.util.toQuotedString($schema); - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } "; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/if.js -var require_if = __commonJS({ - "node_modules/ajv/lib/dotjs/if.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_if(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - $it.level++; - var $nextValid = "valid" + $it.level; - var $thenSch = it.schema["then"], $elseSch = it.schema["else"], $thenPresent = $thenSch !== void 0 && (it.opts.strictKeywords ? typeof $thenSch == "object" && Object.keys($thenSch).length > 0 || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = $elseSch !== void 0 && (it.opts.strictKeywords ? typeof $elseSch == "object" && Object.keys($elseSch).length > 0 || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId; - if ($thenPresent || $elsePresent) { - var $ifClause; - $it.createErrors = false; - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += " var " + $errs + " = errors; var " + $valid + " = true; "; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - out += " " + it.validate($it) + " "; - $it.baseId = $currentBaseId; - $it.createErrors = true; - out += " errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } "; - it.compositeRule = $it.compositeRule = $wasComposite; - if ($thenPresent) { - out += " if (" + $nextValid + ") { "; - $it.schema = it.schema["then"]; - $it.schemaPath = it.schemaPath + ".then"; - $it.errSchemaPath = it.errSchemaPath + "/then"; - out += " " + it.validate($it) + " "; - $it.baseId = $currentBaseId; - out += " " + $valid + " = " + $nextValid + "; "; - if ($thenPresent && $elsePresent) { - $ifClause = "ifClause" + $lvl; - out += " var " + $ifClause + " = 'then'; "; - } else { - $ifClause = "'then'"; - } - out += " } "; - if ($elsePresent) { - out += " else { "; - } - } else { - out += " if (!" + $nextValid + ") { "; - } - if ($elsePresent) { - $it.schema = it.schema["else"]; - $it.schemaPath = it.schemaPath + ".else"; - $it.errSchemaPath = it.errSchemaPath + "/else"; - out += " " + it.validate($it) + " "; - $it.baseId = $currentBaseId; - out += " " + $valid + " = " + $nextValid + "; "; - if ($thenPresent && $elsePresent) { - $ifClause = "ifClause" + $lvl; - out += " var " + $ifClause + " = 'else'; "; - } else { - $ifClause = "'else'"; - } - out += " } "; - } - out += " if (!" + $valid + ") { var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'if' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { failingKeyword: " + $ifClause + " } "; - if (it.opts.messages !== false) { - out += ` , message: 'should match "' + ` + $ifClause + ` + '" schema' `; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError(vErrors); "; - } else { - out += " validate.errors = vErrors; return false; "; - } - } - out += " } "; - if ($breakOnError) { - out += " else { "; - } - } else { - if ($breakOnError) { - out += " if (true) { "; - } - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/items.js -var require_items = __commonJS({ - "node_modules/ajv/lib/dotjs/items.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_items(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it.baseId; - out += "var " + $errs + " = errors;var " + $valid + ";"; - if (Array.isArray($schema)) { - var $additionalItems = it.schema.additionalItems; - if ($additionalItems === false) { - out += " " + $valid + " = " + $data + ".length <= " + $schema.length + "; "; - var $currErrSchemaPath = $errSchemaPath; - $errSchemaPath = it.errSchemaPath + "/additionalItems"; - out += " if (!" + $valid + ") { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'additionalItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schema.length + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should NOT have more than " + $schema.length + " items' "; - } - if (it.opts.verbose) { - out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } "; - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - $closingBraces += "}"; - out += " else { "; - } - } - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) { - out += " " + $nextValid + " = true; if (" + $data + ".length > " + $i + ") { "; - var $passData = $data + "[" + $i + "]"; - $it.schema = $sch; - $it.schemaPath = $schemaPath + "[" + $i + "]"; - $it.errSchemaPath = $errSchemaPath + "/" + $i; - $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); - $it.dataPathArr[$dataNxt] = $i; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - out += " } "; - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - $closingBraces += "}"; - } - } - } - } - if (typeof $additionalItems == "object" && (it.opts.strictKeywords ? typeof $additionalItems == "object" && Object.keys($additionalItems).length > 0 || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) { - $it.schema = $additionalItems; - $it.schemaPath = it.schemaPath + ".additionalItems"; - $it.errSchemaPath = it.errSchemaPath + "/additionalItems"; - out += " " + $nextValid + " = true; if (" + $data + ".length > " + $schema.length + ") { for (var " + $idx + " = " + $schema.length + "; " + $idx + " < " + $data + ".length; " + $idx + "++) { "; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + "[" + $idx + "]"; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - if ($breakOnError) { - out += " if (!" + $nextValid + ") break; "; - } - out += " } } "; - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - $closingBraces += "}"; - } - } - } else if (it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += " for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { "; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + "[" + $idx + "]"; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - if ($breakOnError) { - out += " if (!" + $nextValid + ") break; "; - } - out += " }"; - } - if ($breakOnError) { - out += " " + $closingBraces + " if (" + $errs + " == errors) {"; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/_limit.js -var require_limit = __commonJS({ - "node_modules/ajv/lib/dotjs/_limit.js"(exports2, module2) { - "use strict"; - module2.exports = function generate__limit(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = "data" + ($dataLvl || ""); - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - var $isMax = $keyword == "maximum", $exclusiveKeyword = $isMax ? "exclusiveMaximum" : "exclusiveMinimum", $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? "<" : ">", $notOp = $isMax ? ">" : "<", $errorKeyword = void 0; - if (!($isData || typeof $schema == "number" || $schema === void 0)) { - throw new Error($keyword + " must be number"); - } - if (!($isDataExcl || $schemaExcl === void 0 || typeof $schemaExcl == "number" || typeof $schemaExcl == "boolean")) { - throw new Error($exclusiveKeyword + " must be number or boolean"); - } - if ($isDataExcl) { - var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = "exclusive" + $lvl, $exclType = "exclType" + $lvl, $exclIsNumber = "exclIsNumber" + $lvl, $opExpr = "op" + $lvl, $opStr = "' + " + $opExpr + " + '"; - out += " var schemaExcl" + $lvl + " = " + $schemaValueExcl + "; "; - $schemaValueExcl = "schemaExcl" + $lvl; - out += " var " + $exclusive + "; var " + $exclType + " = typeof " + $schemaValueExcl + "; if (" + $exclType + " != 'boolean' && " + $exclType + " != 'undefined' && " + $exclType + " != 'number') { "; - var $errorKeyword = $exclusiveKeyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "_exclusiveLimit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} "; - if (it.opts.messages !== false) { - out += " , message: '" + $exclusiveKeyword + " should be boolean' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } else if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || "; - } - out += " " + $exclType + " == 'number' ? ( (" + $exclusive + " = " + $schemaValue + " === undefined || " + $schemaValueExcl + " " + $op + "= " + $schemaValue + ") ? " + $data + " " + $notOp + "= " + $schemaValueExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) : ( (" + $exclusive + " = " + $schemaValueExcl + " === true) ? " + $data + " " + $notOp + "= " + $schemaValue + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { var op" + $lvl + " = " + $exclusive + " ? '" + $op + "' : '" + $op + "='; "; - if ($schema === void 0) { - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword; - $schemaValue = $schemaValueExcl; - $isData = $isDataExcl; - } - } else { - var $exclIsNumber = typeof $schemaExcl == "number", $opStr = $op; - if ($exclIsNumber && $isData) { - var $opExpr = "'" + $opStr + "'"; - out += " if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || "; - } - out += " ( " + $schemaValue + " === undefined || " + $schemaExcl + " " + $op + "= " + $schemaValue + " ? " + $data + " " + $notOp + "= " + $schemaExcl + " : " + $data + " " + $notOp + " " + $schemaValue + " ) || " + $data + " !== " + $data + ") { "; - } else { - if ($exclIsNumber && $schema === void 0) { - $exclusive = true; - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword; - $schemaValue = $schemaExcl; - $notOp += "="; - } else { - if ($exclIsNumber) $schemaValue = Math[$isMax ? "min" : "max"]($schemaExcl, $schema); - if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { - $exclusive = true; - $errorKeyword = $exclusiveKeyword; - $errSchemaPath = it.errSchemaPath + "/" + $exclusiveKeyword; - $notOp += "="; - } else { - $exclusive = false; - $opStr += "="; - } - } - var $opExpr = "'" + $opStr + "'"; - out += " if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || "; - } - out += " " + $data + " " + $notOp + " " + $schemaValue + " || " + $data + " !== " + $data + ") { "; - } - } - $errorKeyword = $errorKeyword || $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "_limit") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { comparison: " + $opExpr + ", limit: " + $schemaValue + ", exclusive: " + $exclusive + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should be " + $opStr + " "; - if ($isData) { - out += "' + " + $schemaValue; - } else { - out += "" + $schemaValue + "'"; - } - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + $schema; - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } "; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/_limitItems.js -var require_limitItems = __commonJS({ - "node_modules/ajv/lib/dotjs/_limitItems.js"(exports2, module2) { - "use strict"; - module2.exports = function generate__limitItems(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = "data" + ($dataLvl || ""); - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == "number")) { - throw new Error($keyword + " must be number"); - } - var $op = $keyword == "maxItems" ? ">" : "<"; - out += "if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || "; - } - out += " " + $data + ".length " + $op + " " + $schemaValue + ") { "; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "_limitItems") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should NOT have "; - if ($keyword == "maxItems") { - out += "more"; - } else { - out += "fewer"; - } - out += " than "; - if ($isData) { - out += "' + " + $schemaValue + " + '"; - } else { - out += "" + $schema; - } - out += " items' "; - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + $schema; - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += "} "; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/_limitLength.js -var require_limitLength = __commonJS({ - "node_modules/ajv/lib/dotjs/_limitLength.js"(exports2, module2) { - "use strict"; - module2.exports = function generate__limitLength(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = "data" + ($dataLvl || ""); - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == "number")) { - throw new Error($keyword + " must be number"); - } - var $op = $keyword == "maxLength" ? ">" : "<"; - out += "if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || "; - } - if (it.opts.unicode === false) { - out += " " + $data + ".length "; - } else { - out += " ucs2length(" + $data + ") "; - } - out += " " + $op + " " + $schemaValue + ") { "; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "_limitLength") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should NOT be "; - if ($keyword == "maxLength") { - out += "longer"; - } else { - out += "shorter"; - } - out += " than "; - if ($isData) { - out += "' + " + $schemaValue + " + '"; - } else { - out += "" + $schema; - } - out += " characters' "; - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + $schema; - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += "} "; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/_limitProperties.js -var require_limitProperties = __commonJS({ - "node_modules/ajv/lib/dotjs/_limitProperties.js"(exports2, module2) { - "use strict"; - module2.exports = function generate__limitProperties(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = "data" + ($dataLvl || ""); - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == "number")) { - throw new Error($keyword + " must be number"); - } - var $op = $keyword == "maxProperties" ? ">" : "<"; - out += "if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || "; - } - out += " Object.keys(" + $data + ").length " + $op + " " + $schemaValue + ") { "; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "_limitProperties") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should NOT have "; - if ($keyword == "maxProperties") { - out += "more"; - } else { - out += "fewer"; - } - out += " than "; - if ($isData) { - out += "' + " + $schemaValue + " + '"; - } else { - out += "" + $schema; - } - out += " properties' "; - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + $schema; - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += "} "; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/multipleOf.js -var require_multipleOf = __commonJS({ - "node_modules/ajv/lib/dotjs/multipleOf.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_multipleOf(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - if (!($isData || typeof $schema == "number")) { - throw new Error($keyword + " must be number"); - } - out += "var division" + $lvl + ";if ("; - if ($isData) { - out += " " + $schemaValue + " !== undefined && ( typeof " + $schemaValue + " != 'number' || "; - } - out += " (division" + $lvl + " = " + $data + " / " + $schemaValue + ", "; - if (it.opts.multipleOfPrecision) { - out += " Math.abs(Math.round(division" + $lvl + ") - division" + $lvl + ") > 1e-" + it.opts.multipleOfPrecision + " "; - } else { - out += " division" + $lvl + " !== parseInt(division" + $lvl + ") "; - } - out += " ) "; - if ($isData) { - out += " ) "; - } - out += " ) { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'multipleOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { multipleOf: " + $schemaValue + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should be multiple of "; - if ($isData) { - out += "' + " + $schemaValue; - } else { - out += "" + $schemaValue + "'"; - } - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + $schema; - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += "} "; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/not.js -var require_not = __commonJS({ - "node_modules/ajv/lib/dotjs/not.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_not(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - $it.level++; - var $nextValid = "valid" + $it.level; - if (it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += " var " + $errs + " = errors; "; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.createErrors = false; - var $allErrorsOption; - if ($it.opts.allErrors) { - $allErrorsOption = $it.opts.allErrors; - $it.opts.allErrors = false; - } - out += " " + it.validate($it) + " "; - $it.createErrors = true; - if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; - it.compositeRule = $it.compositeRule = $wasComposite; - out += " if (" + $nextValid + ") { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} "; - if (it.opts.messages !== false) { - out += " , message: 'should NOT be valid' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } else { errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } "; - if (it.opts.allErrors) { - out += " } "; - } - } else { - out += " var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: {} "; - if (it.opts.messages !== false) { - out += " , message: 'should NOT be valid' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - if ($breakOnError) { - out += " if (false) { "; - } - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/oneOf.js -var require_oneOf = __commonJS({ - "node_modules/ajv/lib/dotjs/oneOf.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_oneOf(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - var $currentBaseId = $it.baseId, $prevValid = "prevValid" + $lvl, $passingSchemas = "passingSchemas" + $lvl; - out += "var " + $errs + " = errors , " + $prevValid + " = false , " + $valid + " = false , " + $passingSchemas + " = null; "; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) { - $it.schema = $sch; - $it.schemaPath = $schemaPath + "[" + $i + "]"; - $it.errSchemaPath = $errSchemaPath + "/" + $i; - out += " " + it.validate($it) + " "; - $it.baseId = $currentBaseId; - } else { - out += " var " + $nextValid + " = true; "; - } - if ($i) { - out += " if (" + $nextValid + " && " + $prevValid + ") { " + $valid + " = false; " + $passingSchemas + " = [" + $passingSchemas + ", " + $i + "]; } else { "; - $closingBraces += "}"; - } - out += " if (" + $nextValid + ") { " + $valid + " = " + $prevValid + " = true; " + $passingSchemas + " = " + $i + "; }"; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += "" + $closingBraces + "if (!" + $valid + ") { var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'oneOf' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { passingSchemas: " + $passingSchemas + " } "; - if (it.opts.messages !== false) { - out += " , message: 'should match exactly one schema in oneOf' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError(vErrors); "; - } else { - out += " validate.errors = vErrors; return false; "; - } - } - out += "} else { errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; }"; - if (it.opts.allErrors) { - out += " } "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/pattern.js -var require_pattern = __commonJS({ - "node_modules/ajv/lib/dotjs/pattern.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_pattern(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - var $regexp = $isData ? "(new RegExp(" + $schemaValue + "))" : it.usePattern($schema); - out += "if ( "; - if ($isData) { - out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || "; - } - out += " !" + $regexp + ".test(" + $data + ") ) { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'pattern' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { pattern: "; - if ($isData) { - out += "" + $schemaValue; - } else { - out += "" + it.util.toQuotedString($schema); - } - out += " } "; - if (it.opts.messages !== false) { - out += ` , message: 'should match pattern "`; - if ($isData) { - out += "' + " + $schemaValue + " + '"; - } else { - out += "" + it.util.escapeQuotes($schema); - } - out += `"' `; - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + it.util.toQuotedString($schema); - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += "} "; - if ($breakOnError) { - out += " else { "; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/properties.js -var require_properties = __commonJS({ - "node_modules/ajv/lib/dotjs/properties.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_properties(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - var $key = "key" + $lvl, $idx = "idx" + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl; - var $schemaKeys = Object.keys($schema || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == "object" && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; - var $required = it.schema.required; - if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { - var $requiredHash = it.util.toHash($required); - } - function notProto(p) { - return p !== "__proto__"; - } - out += "var " + $errs + " = errors;var " + $nextValid + " = true;"; - if ($ownProperties) { - out += " var " + $dataProperties + " = undefined;"; - } - if ($checkAdditional) { - if ($ownProperties) { - out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; "; - } else { - out += " for (var " + $key + " in " + $data + ") { "; - } - if ($someProperties) { - out += " var isAdditional" + $lvl + " = !(false "; - if ($schemaKeys.length) { - if ($schemaKeys.length > 8) { - out += " || validate.schema" + $schemaPath + ".hasOwnProperty(" + $key + ") "; - } else { - var arr1 = $schemaKeys; - if (arr1) { - var $propertyKey, i1 = -1, l1 = arr1.length - 1; - while (i1 < l1) { - $propertyKey = arr1[i1 += 1]; - out += " || " + $key + " == " + it.util.toQuotedString($propertyKey) + " "; - } - } - } - } - if ($pPropertyKeys.length) { - var arr2 = $pPropertyKeys; - if (arr2) { - var $pProperty, $i = -1, l2 = arr2.length - 1; - while ($i < l2) { - $pProperty = arr2[$i += 1]; - out += " || " + it.usePattern($pProperty) + ".test(" + $key + ") "; - } - } - } - out += " ); if (isAdditional" + $lvl + ") { "; - } - if ($removeAdditional == "all") { - out += " delete " + $data + "[" + $key + "]; "; - } else { - var $currentErrorPath = it.errorPath; - var $additionalProperty = "' + " + $key + " + '"; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - } - if ($noAdditional) { - if ($removeAdditional) { - out += " delete " + $data + "[" + $key + "]; "; - } else { - out += " " + $nextValid + " = false; "; - var $currErrSchemaPath = $errSchemaPath; - $errSchemaPath = it.errSchemaPath + "/additionalProperties"; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'additionalProperties' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { additionalProperty: '" + $additionalProperty + "' } "; - if (it.opts.messages !== false) { - out += " , message: '"; - if (it.opts._errorDataPathProperty) { - out += "is an invalid additional property"; - } else { - out += "should NOT have additional properties"; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: false , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - out += " break; "; - } - } - } else if ($additionalIsSchema) { - if ($removeAdditional == "failing") { - out += " var " + $errs + " = errors; "; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.schema = $aProperties; - $it.schemaPath = it.schemaPath + ".additionalProperties"; - $it.errSchemaPath = it.errSchemaPath + "/additionalProperties"; - $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + "[" + $key + "]"; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - out += " if (!" + $nextValid + ") { errors = " + $errs + "; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete " + $data + "[" + $key + "]; } "; - it.compositeRule = $it.compositeRule = $wasComposite; - } else { - $it.schema = $aProperties; - $it.schemaPath = it.schemaPath + ".additionalProperties"; - $it.errSchemaPath = it.errSchemaPath + "/additionalProperties"; - $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + "[" + $key + "]"; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - if ($breakOnError) { - out += " if (!" + $nextValid + ") break; "; - } - } - } - it.errorPath = $currentErrorPath; - } - if ($someProperties) { - out += " } "; - } - out += " } "; - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - $closingBraces += "}"; - } - } - var $useDefaults = it.opts.useDefaults && !it.compositeRule; - if ($schemaKeys.length) { - var arr3 = $schemaKeys; - if (arr3) { - var $propertyKey, i3 = -1, l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $sch = $schema[$propertyKey]; - if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) { - var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== void 0; - $it.schema = $sch; - $it.schemaPath = $schemaPath + $prop; - $it.errSchemaPath = $errSchemaPath + "/" + it.util.escapeFragment($propertyKey); - $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); - $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - $code = it.util.varReplace($code, $nextData, $passData); - var $useData = $passData; - } else { - var $useData = $nextData; - out += " var " + $nextData + " = " + $passData + "; "; - } - if ($hasDefault) { - out += " " + $code + " "; - } else { - if ($requiredHash && $requiredHash[$propertyKey]) { - out += " if ( " + $useData + " === undefined "; - if ($ownProperties) { - out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') "; - } - out += ") { " + $nextValid + " = false; "; - var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey); - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - $errSchemaPath = it.errSchemaPath + "/required"; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } "; - if (it.opts.messages !== false) { - out += " , message: '"; - if (it.opts._errorDataPathProperty) { - out += "is a required property"; - } else { - out += "should have required property \\'" + $missingProperty + "\\'"; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - $errSchemaPath = $currErrSchemaPath; - it.errorPath = $currentErrorPath; - out += " } else { "; - } else { - if ($breakOnError) { - out += " if ( " + $useData + " === undefined "; - if ($ownProperties) { - out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') "; - } - out += ") { " + $nextValid + " = true; } else { "; - } else { - out += " if (" + $useData + " !== undefined "; - if ($ownProperties) { - out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') "; - } - out += " ) { "; - } - } - out += " " + $code + " } "; - } - } - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - $closingBraces += "}"; - } - } - } - } - if ($pPropertyKeys.length) { - var arr4 = $pPropertyKeys; - if (arr4) { - var $pProperty, i4 = -1, l4 = arr4.length - 1; - while (i4 < l4) { - $pProperty = arr4[i4 += 1]; - var $sch = $pProperties[$pProperty]; - if (it.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it.util.schemaHasRules($sch, it.RULES.all)) { - $it.schema = $sch; - $it.schemaPath = it.schemaPath + ".patternProperties" + it.util.getProperty($pProperty); - $it.errSchemaPath = it.errSchemaPath + "/patternProperties/" + it.util.escapeFragment($pProperty); - if ($ownProperties) { - out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; "; - } else { - out += " for (var " + $key + " in " + $data + ") { "; - } - out += " if (" + it.usePattern($pProperty) + ".test(" + $key + ")) { "; - $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + "[" + $key + "]"; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - if ($breakOnError) { - out += " if (!" + $nextValid + ") break; "; - } - out += " } "; - if ($breakOnError) { - out += " else " + $nextValid + " = true; "; - } - out += " } "; - if ($breakOnError) { - out += " if (" + $nextValid + ") { "; - $closingBraces += "}"; - } - } - } - } - } - if ($breakOnError) { - out += " " + $closingBraces + " if (" + $errs + " == errors) {"; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/propertyNames.js -var require_propertyNames = __commonJS({ - "node_modules/ajv/lib/dotjs/propertyNames.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_propertyNames(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $errs = "errs__" + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - out += "var " + $errs + " = errors;"; - if (it.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it.util.schemaHasRules($schema, it.RULES.all)) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - var $key = "key" + $lvl, $idx = "idx" + $lvl, $i = "i" + $lvl, $invalidName = "' + " + $key + " + '", $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; - if ($ownProperties) { - out += " var " + $dataProperties + " = undefined; "; - } - if ($ownProperties) { - out += " " + $dataProperties + " = " + $dataProperties + " || Object.keys(" + $data + "); for (var " + $idx + "=0; " + $idx + "<" + $dataProperties + ".length; " + $idx + "++) { var " + $key + " = " + $dataProperties + "[" + $idx + "]; "; - } else { - out += " for (var " + $key + " in " + $data + ") { "; - } - out += " var startErrs" + $lvl + " = errors; "; - var $passData = $key; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += " " + it.util.varReplace($code, $nextData, $passData) + " "; - } else { - out += " var " + $nextData + " = " + $passData + "; " + $code + " "; - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += " if (!" + $nextValid + ") { for (var " + $i + "=startErrs" + $lvl + "; " + $i + " 0 || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) { - $required[$required.length] = $property; - } - } - } - } else { - var $required = $schema; - } - } - if ($isData || $required.length) { - var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties; - if ($breakOnError) { - out += " var missing" + $lvl + "; "; - if ($loopRequired) { - if (!$isData) { - out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; "; - } - var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '"; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - out += " var " + $valid + " = true; "; - if ($isData) { - out += " if (schema" + $lvl + " === undefined) " + $valid + " = true; else if (!Array.isArray(schema" + $lvl + ")) " + $valid + " = false; else {"; - } - out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { " + $valid + " = " + $data + "[" + $vSchema + "[" + $i + "]] !== undefined "; - if ($ownProperties) { - out += " && Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) "; - } - out += "; if (!" + $valid + ") break; } "; - if ($isData) { - out += " } "; - } - out += " if (!" + $valid + ") { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } "; - if (it.opts.messages !== false) { - out += " , message: '"; - if (it.opts._errorDataPathProperty) { - out += "is a required property"; - } else { - out += "should have required property \\'" + $missingProperty + "\\'"; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } else { "; - } else { - out += " if ( "; - var arr2 = $required; - if (arr2) { - var $propertyKey, $i = -1, l2 = arr2.length - 1; - while ($i < l2) { - $propertyKey = arr2[$i += 1]; - if ($i) { - out += " || "; - } - var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; - out += " ( ( " + $useData + " === undefined "; - if ($ownProperties) { - out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') "; - } - out += ") && (missing" + $lvl + " = " + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ") ) "; - } - } - out += ") { "; - var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '"; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } "; - if (it.opts.messages !== false) { - out += " , message: '"; - if (it.opts._errorDataPathProperty) { - out += "is a required property"; - } else { - out += "should have required property \\'" + $missingProperty + "\\'"; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } else { "; - } - } else { - if ($loopRequired) { - if (!$isData) { - out += " var " + $vSchema + " = validate.schema" + $schemaPath + "; "; - } - var $i = "i" + $lvl, $propertyPath = "schema" + $lvl + "[" + $i + "]", $missingProperty = "' + " + $propertyPath + " + '"; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - if ($isData) { - out += " if (" + $vSchema + " && !Array.isArray(" + $vSchema + ")) { var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } "; - if (it.opts.messages !== false) { - out += " , message: '"; - if (it.opts._errorDataPathProperty) { - out += "is a required property"; - } else { - out += "should have required property \\'" + $missingProperty + "\\'"; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (" + $vSchema + " !== undefined) { "; - } - out += " for (var " + $i + " = 0; " + $i + " < " + $vSchema + ".length; " + $i + "++) { if (" + $data + "[" + $vSchema + "[" + $i + "]] === undefined "; - if ($ownProperties) { - out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", " + $vSchema + "[" + $i + "]) "; - } - out += ") { var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } "; - if (it.opts.messages !== false) { - out += " , message: '"; - if (it.opts._errorDataPathProperty) { - out += "is a required property"; - } else { - out += "should have required property \\'" + $missingProperty + "\\'"; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } "; - if ($isData) { - out += " } "; - } - } else { - var arr3 = $required; - if (arr3) { - var $propertyKey, i3 = -1, l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - out += " if ( " + $useData + " === undefined "; - if ($ownProperties) { - out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it.util.escapeQuotes($propertyKey) + "') "; - } - out += ") { var err = "; - if (it.createErrors !== false) { - out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } "; - if (it.opts.messages !== false) { - out += " , message: '"; - if (it.opts._errorDataPathProperty) { - out += "is a required property"; - } else { - out += "should have required property \\'" + $missingProperty + "\\'"; - } - out += "' "; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "; - } - } - } - } - it.errorPath = $currentErrorPath; - } else if ($breakOnError) { - out += " if (true) {"; - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/uniqueItems.js -var require_uniqueItems = __commonJS({ - "node_modules/ajv/lib/dotjs/uniqueItems.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_uniqueItems(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - if (($schema || $isData) && it.opts.uniqueItems !== false) { - if ($isData) { - out += " var " + $valid + "; if (" + $schemaValue + " === false || " + $schemaValue + " === undefined) " + $valid + " = true; else if (typeof " + $schemaValue + " != 'boolean') " + $valid + " = false; else { "; - } - out += " var i = " + $data + ".length , " + $valid + " = true , j; if (i > 1) { "; - var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType); - if (!$itemType || $itemType == "object" || $itemType == "array" || $typeIsArray && ($itemType.indexOf("object") >= 0 || $itemType.indexOf("array") >= 0)) { - out += " outer: for (;i--;) { for (j = i; j--;) { if (equal(" + $data + "[i], " + $data + "[j])) { " + $valid + " = false; break outer; } } } "; - } else { - out += " var itemIndices = {}, item; for (;i--;) { var item = " + $data + "[i]; "; - var $method = "checkDataType" + ($typeIsArray ? "s" : ""); - out += " if (" + it.util[$method]($itemType, "item", it.opts.strictNumbers, true) + ") continue; "; - if ($typeIsArray) { - out += ` if (typeof item == 'string') item = '"' + item; `; - } - out += " if (typeof itemIndices[item] == 'number') { " + $valid + " = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "; - } - out += " } "; - if ($isData) { - out += " } "; - } - out += " if (!" + $valid + ") { "; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: 'uniqueItems' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { i: i, j: j } "; - if (it.opts.messages !== false) { - out += " , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "; - } - if (it.opts.verbose) { - out += " , schema: "; - if ($isData) { - out += "validate.schema" + $schemaPath; - } else { - out += "" + $schema; - } - out += " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - out += " } "; - if ($breakOnError) { - out += " else { "; - } - } else { - if ($breakOnError) { - out += " if (true) { "; - } - } - return out; - }; - } -}); - -// node_modules/ajv/lib/dotjs/index.js -var require_dotjs = __commonJS({ - "node_modules/ajv/lib/dotjs/index.js"(exports2, module2) { - "use strict"; - module2.exports = { - "$ref": require_ref(), - allOf: require_allOf(), - anyOf: require_anyOf(), - "$comment": require_comment(), - const: require_const(), - contains: require_contains(), - dependencies: require_dependencies(), - "enum": require_enum(), - format: require_format(), - "if": require_if(), - items: require_items(), - maximum: require_limit(), - minimum: require_limit(), - maxItems: require_limitItems(), - minItems: require_limitItems(), - maxLength: require_limitLength(), - minLength: require_limitLength(), - maxProperties: require_limitProperties(), - minProperties: require_limitProperties(), - multipleOf: require_multipleOf(), - not: require_not(), - oneOf: require_oneOf(), - pattern: require_pattern(), - properties: require_properties(), - propertyNames: require_propertyNames(), - required: require_required(), - uniqueItems: require_uniqueItems(), - validate: require_validate() - }; - } -}); - -// node_modules/ajv/lib/compile/rules.js -var require_rules = __commonJS({ - "node_modules/ajv/lib/compile/rules.js"(exports2, module2) { - "use strict"; - var ruleModules = require_dotjs(); - var toHash = require_util().toHash; - module2.exports = function rules() { - var RULES = [ - { - type: "number", - rules: [ - { "maximum": ["exclusiveMaximum"] }, - { "minimum": ["exclusiveMinimum"] }, - "multipleOf", - "format" - ] - }, - { - type: "string", - rules: ["maxLength", "minLength", "pattern", "format"] - }, - { - type: "array", - rules: ["maxItems", "minItems", "items", "contains", "uniqueItems"] - }, - { - type: "object", - rules: [ - "maxProperties", - "minProperties", - "required", - "dependencies", - "propertyNames", - { "properties": ["additionalProperties", "patternProperties"] } - ] - }, - { rules: ["$ref", "const", "enum", "not", "anyOf", "oneOf", "allOf", "if"] } - ]; - var ALL = ["type", "$comment"]; - var KEYWORDS = [ - "$schema", - "$id", - "id", - "$data", - "$async", - "title", - "description", - "default", - "definitions", - "examples", - "readOnly", - "writeOnly", - "contentMediaType", - "contentEncoding", - "additionalItems", - "then", - "else" - ]; - var TYPES = ["number", "integer", "string", "array", "object", "boolean", "null"]; - RULES.all = toHash(ALL); - RULES.types = toHash(TYPES); - RULES.forEach(function(group) { - group.rules = group.rules.map(function(keyword) { - var implKeywords; - if (typeof keyword == "object") { - var key = Object.keys(keyword)[0]; - implKeywords = keyword[key]; - keyword = key; - implKeywords.forEach(function(k) { - ALL.push(k); - RULES.all[k] = true; - }); - } - ALL.push(keyword); - var rule = RULES.all[keyword] = { - keyword, - code: ruleModules[keyword], - implements: implKeywords - }; - return rule; - }); - RULES.all.$comment = { - keyword: "$comment", - code: ruleModules.$comment - }; - if (group.type) RULES.types[group.type] = group; - }); - RULES.keywords = toHash(ALL.concat(KEYWORDS)); - RULES.custom = {}; - return RULES; - }; - } -}); - -// node_modules/ajv/lib/data.js -var require_data = __commonJS({ - "node_modules/ajv/lib/data.js"(exports2, module2) { - "use strict"; - var KEYWORDS = [ - "multipleOf", - "maximum", - "exclusiveMaximum", - "minimum", - "exclusiveMinimum", - "maxLength", - "minLength", - "pattern", - "additionalItems", - "maxItems", - "minItems", - "uniqueItems", - "maxProperties", - "minProperties", - "required", - "additionalProperties", - "enum", - "format", - "const" - ]; - module2.exports = function(metaSchema, keywordsJsonPointers) { - for (var i = 0; i < keywordsJsonPointers.length; i++) { - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - var segments = keywordsJsonPointers[i].split("/"); - var keywords = metaSchema; - var j; - for (j = 1; j < segments.length; j++) - keywords = keywords[segments[j]]; - for (j = 0; j < KEYWORDS.length; j++) { - var key = KEYWORDS[j]; - var schema = keywords[key]; - if (schema) { - keywords[key] = { - anyOf: [ - schema, - { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" } - ] - }; - } - } - } - return metaSchema; - }; - } -}); - -// node_modules/ajv/lib/compile/async.js -var require_async = __commonJS({ - "node_modules/ajv/lib/compile/async.js"(exports2, module2) { - "use strict"; - var MissingRefError = require_error_classes().MissingRef; - module2.exports = compileAsync; - function compileAsync(schema, meta, callback) { - var self = this; - if (typeof this._opts.loadSchema != "function") - throw new Error("options.loadSchema should be a function"); - if (typeof meta == "function") { - callback = meta; - meta = void 0; - } - var p = loadMetaSchemaOf(schema).then(function() { - var schemaObj = self._addSchema(schema, void 0, meta); - return schemaObj.validate || _compileAsync(schemaObj); - }); - if (callback) { - p.then( - function(v) { - callback(null, v); - }, - callback - ); - } - return p; - function loadMetaSchemaOf(sch) { - var $schema = sch.$schema; - return $schema && !self.getSchema($schema) ? compileAsync.call(self, { $ref: $schema }, true) : Promise.resolve(); - } - function _compileAsync(schemaObj) { - try { - return self._compile(schemaObj); - } catch (e) { - if (e instanceof MissingRefError) return loadMissingSchema(e); - throw e; - } - function loadMissingSchema(e) { - var ref = e.missingSchema; - if (added(ref)) throw new Error("Schema " + ref + " is loaded but " + e.missingRef + " cannot be resolved"); - var schemaPromise = self._loadingSchemas[ref]; - if (!schemaPromise) { - schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); - schemaPromise.then(removePromise, removePromise); - } - return schemaPromise.then(function(sch) { - if (!added(ref)) { - return loadMetaSchemaOf(sch).then(function() { - if (!added(ref)) self.addSchema(sch, ref, void 0, meta); - }); - } - }).then(function() { - return _compileAsync(schemaObj); - }); - function removePromise() { - delete self._loadingSchemas[ref]; - } - function added(ref2) { - return self._refs[ref2] || self._schemas[ref2]; - } - } - } - } - } -}); - -// node_modules/ajv/lib/dotjs/custom.js -var require_custom = __commonJS({ - "node_modules/ajv/lib/dotjs/custom.js"(exports2, module2) { - "use strict"; - module2.exports = function generate_custom(it, $keyword, $ruleType) { - var out = " "; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + "/" + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = "data" + ($dataLvl || ""); - var $valid = "valid" + $lvl; - var $errs = "errs__" + $lvl; - var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; - if ($isData) { - out += " var schema" + $lvl + " = " + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + "; "; - $schemaValue = "schema" + $lvl; - } else { - $schemaValue = $schema; - } - var $rule = this, $definition = "definition" + $lvl, $rDef = $rule.definition, $closingBraces = ""; - var $compile, $inline, $macro, $ruleValidate, $validateCode; - if ($isData && $rDef.$data) { - $validateCode = "keywordValidate" + $lvl; - var $validateSchema = $rDef.validateSchema; - out += " var " + $definition + " = RULES.custom['" + $keyword + "'].definition; var " + $validateCode + " = " + $definition + ".validate;"; - } else { - $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); - if (!$ruleValidate) return; - $schemaValue = "validate.schema" + $schemaPath; - $validateCode = $ruleValidate.code; - $compile = $rDef.compile; - $inline = $rDef.inline; - $macro = $rDef.macro; - } - var $ruleErrs = $validateCode + ".errors", $i = "i" + $lvl, $ruleErr = "ruleErr" + $lvl, $asyncKeyword = $rDef.async; - if ($asyncKeyword && !it.async) throw new Error("async keyword in sync schema"); - if (!($inline || $macro)) { - out += "" + $ruleErrs + " = null;"; - } - out += "var " + $errs + " = errors;var " + $valid + ";"; - if ($isData && $rDef.$data) { - $closingBraces += "}"; - out += " if (" + $schemaValue + " === undefined) { " + $valid + " = true; } else { "; - if ($validateSchema) { - $closingBraces += "}"; - out += " " + $valid + " = " + $definition + ".validateSchema(" + $schemaValue + "); if (" + $valid + ") { "; - } - } - if ($inline) { - if ($rDef.statements) { - out += " " + $ruleValidate.validate + " "; - } else { - out += " " + $valid + " = " + $ruleValidate.validate + "; "; - } - } else if ($macro) { - var $it = it.util.copy(it); - var $closingBraces = ""; - $it.level++; - var $nextValid = "valid" + $it.level; - $it.schema = $ruleValidate.validate; - $it.schemaPath = ""; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); - it.compositeRule = $it.compositeRule = $wasComposite; - out += " " + $code; - } else { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - out += " " + $validateCode + ".call( "; - if (it.opts.passContext) { - out += "this"; - } else { - out += "self"; - } - if ($compile || $rDef.schema === false) { - out += " , " + $data + " "; - } else { - out += " , " + $schemaValue + " , " + $data + " , validate.schema" + it.schemaPath + " "; - } - out += " , (dataPath || '')"; - if (it.errorPath != '""') { - out += " + " + it.errorPath; - } - var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : "parentDataProperty"; - out += " , " + $parentData + " , " + $parentDataProperty + " , rootData ) "; - var def_callRuleValidate = out; - out = $$outStack.pop(); - if ($rDef.errors === false) { - out += " " + $valid + " = "; - if ($asyncKeyword) { - out += "await "; - } - out += "" + def_callRuleValidate + "; "; - } else { - if ($asyncKeyword) { - $ruleErrs = "customErrors" + $lvl; - out += " var " + $ruleErrs + " = null; try { " + $valid + " = await " + def_callRuleValidate + "; } catch (e) { " + $valid + " = false; if (e instanceof ValidationError) " + $ruleErrs + " = e.errors; else throw e; } "; - } else { - out += " " + $ruleErrs + " = null; " + $valid + " = " + def_callRuleValidate + "; "; - } - } - } - if ($rDef.modifying) { - out += " if (" + $parentData + ") " + $data + " = " + $parentData + "[" + $parentDataProperty + "];"; - } - out += "" + $closingBraces; - if ($rDef.valid) { - if ($breakOnError) { - out += " if (true) { "; - } - } else { - out += " if ( "; - if ($rDef.valid === void 0) { - out += " !"; - if ($macro) { - out += "" + $nextValid; - } else { - out += "" + $valid; - } - } else { - out += " " + !$rDef.valid + " "; - } - out += ") { "; - $errorKeyword = $rule.keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ""; - if (it.createErrors !== false) { - out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it.errorPath + " , schemaPath: " + it.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } "; - if (it.opts.messages !== false) { - out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `; - } - if (it.opts.verbose) { - out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it.schemaPath + " , data: " + $data + " "; - } - out += " } "; - } else { - out += " {} "; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { - if (it.async) { - out += " throw new ValidationError([" + __err + "]); "; - } else { - out += " validate.errors = [" + __err + "]; return false; "; - } - } else { - out += " var err = " + __err + "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "; - } - var def_customError = out; - out = $$outStack.pop(); - if ($inline) { - if ($rDef.errors) { - if ($rDef.errors != "full") { - out += " for (var " + $i + "=" + $errs + "; " + $i + " BRAND, - DIRTY: () => DIRTY, - EMPTY_PATH: () => EMPTY_PATH, - INVALID: () => INVALID, - NEVER: () => NEVER, - OK: () => OK, - ParseStatus: () => ParseStatus, - Schema: () => ZodType, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBigInt: () => ZodBigInt, - ZodBoolean: () => ZodBoolean, - ZodBranded: () => ZodBranded, - ZodCatch: () => ZodCatch, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodEffects: () => ZodEffects, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNativeEnum: () => ZodNativeEnum, - ZodNever: () => ZodNever, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodParsedType: () => ZodParsedType, - ZodPipeline: () => ZodPipeline, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSchema: () => ZodType, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodSymbol: () => ZodSymbol, - ZodTransformer: () => ZodEffects, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - addIssueToContext: () => addIssueToContext, - any: () => anyType, - array: () => arrayType, - bigint: () => bigIntType, - boolean: () => booleanType, - coerce: () => coerce, - custom: () => custom, - date: () => dateType, - datetimeRegex: () => datetimeRegex, - defaultErrorMap: () => en_default, - discriminatedUnion: () => discriminatedUnionType, - effect: () => effectsType, - enum: () => enumType, - function: () => functionType, - getErrorMap: () => getErrorMap, - getParsedType: () => getParsedType, - instanceof: () => instanceOfType, - intersection: () => intersectionType, - isAborted: () => isAborted, - isAsync: () => isAsync, - isDirty: () => isDirty, - isValid: () => isValid, - late: () => late, - lazy: () => lazyType, - literal: () => literalType, - makeIssue: () => makeIssue, - map: () => mapType, - nan: () => nanType, - nativeEnum: () => nativeEnumType, - never: () => neverType, - null: () => nullType, - nullable: () => nullableType, - number: () => numberType, - object: () => objectType, - objectUtil: () => objectUtil, - oboolean: () => oboolean, - onumber: () => onumber, - optional: () => optionalType, - ostring: () => ostring, - pipeline: () => pipelineType, - preprocess: () => preprocessType, - promise: () => promiseType, - quotelessJson: () => quotelessJson, - record: () => recordType, - set: () => setType, - setErrorMap: () => setErrorMap, - strictObject: () => strictObjectType, - string: () => stringType, - symbol: () => symbolType, - transformer: () => effectsType, - tuple: () => tupleType, - undefined: () => undefinedType, - union: () => unionType, - unknown: () => unknownType, - util: () => util, - void: () => voidType -}); - -// node_modules/zod/v3/helpers/util.js -var util; -(function(util2) { - util2.assertEqual = (_) => { - }; - function assertIs(_arg) { - } - util2.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util2.assertNever = assertNever; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e) { - return obj[e]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - 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 joinValues(array, separator = " | ") { - return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); - } - util2.joinValues = joinValues; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -var ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" -]); -var getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -// node_modules/zod/v3/ZodError.js -var ZodIssueCode = util.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 quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -var ZodError = class _ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || function(issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -}; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - -// node_modules/zod/v3/locales/en.js -var errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } else { - util.assertNever(issue.validation); - } - } else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); - } - return { message }; -}; -var en_default = errorMap; - -// node_modules/zod/v3/errors.js -var overrideErrorMap = en_default; -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -// node_modules/zod/v3/helpers/parseUtil.js -var makeIssue = (params) => { - const { data, path: path2, errorMaps, issueData } = params; - const fullPath = [...path2, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; - } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; -}; -var EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData, - data: ctx.data, - 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 - // then global default map - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue); -} -var ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -}; -var INVALID = Object.freeze({ - status: "aborted" -}); -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; - -// 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?.message; -})(errorUtil || (errorUtil = {})); - -// node_modules/zod/v3/types.js -var ParseInputLazyPath = class { - constructor(parent, value, path2, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path2; - this._key = key; - } - 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 handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - } - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -var ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - 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: (data) => this["~validate"](data) - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform } - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(void 0).success; - } - isNullable() { - return this.safeParse(null).success; - } -}; -var cuidRegex = /^c[^\s-]{8,}$/i; -var cuid2Regex = /^[0-9a-z]+$/; -var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -var uuidRegex = /^[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 nanoidRegex = /^[a-z0-9_-]{21}$/i; -var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -var durationRegex = /^[-+]?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 emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -var emojiRegex; -var ipv4Regex = /^(?:(?: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 ipv4CidrRegex = /^(?:(?: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 ipv6Regex = /^(([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 ipv6CidrRegex = /^(([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 base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -var dateRegexSource = `((\\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 dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -var ZodString = class _ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message - }); - } - status.dirty(); - } - } else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "trim") { - input.data = input.data.trim(); - } else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "jwt") { - if (!isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check) { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); - } - toLowerCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); - } - toUpperCase() { - return new _ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - 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; -} -var ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -}; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message - }); - status.dirty(); - } - } else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -}; -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); -}; -var ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); -}; -var ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date" - }); - status.dirty(); - } - } else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; - } - _addCheck(check) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check] - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -}; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); -}; -var ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); -}; -var ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); -}; -var ZodNull = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); -}; -var ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); -}; -var ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -}; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); -}; -var ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; - } -}; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); -}; -var ZodVoid = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } -}; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); -}; -var ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).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)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape - }); - } else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element) - }); - } else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } else { - return schema; - } -} -var ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - 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, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * 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, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - 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, - catchall: index - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -}; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); -}; -var ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -}; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) - }); -}; -var getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } else if (type instanceof ZodLiteral) { - return [type.value]; - } else if (type instanceof ZodEnum) { - return type.options; - } else if (type instanceof ZodNativeEnum) { - return util.objectValues(type.enum); - } else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } else if (type instanceof ZodUndefined) { - return [void 0]; - } else if (type instanceof ZodNull) { - return [null]; - } else if (type instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } else { - return []; - } -}; -var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - 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) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); - } -}; -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -var ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } -}; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); -}; -var ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); - } -}; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); -}; -var ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) - }); - } -}; -var ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -}; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) - }); -}; -var ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); - } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -}; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); -}; -var ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error - } - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return OK(async function(...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } -}; -var ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -}; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) - }); -}; -var ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -}; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -var ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return _ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } -}; -ZodEnum.create = createZodEnum; -var ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -}; -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) - }); -}; -var ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); - } -}; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); -}; -var ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } - } - util.assertNever(effect); - } -}; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); -}; -var ZodOptional = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); -}; -var ZodNullable = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -}; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); -}; -var ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - removeDefault() { - return this._def.innerType; - } -}; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); -}; -var ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - } - } - removeCatch() { - return this._def.innerType; - } -}; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); -}; -var ZodNaN = class extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -}; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); -}; -var BRAND = Symbol("zod_brand"); -var ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -var ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } - } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); - } -}; -var ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -}; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); -}; -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} -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"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -var instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` -}) => custom((data) => data instanceof cls, params); -var stringType = ZodString.create; -var numberType = ZodNumber.create; -var nanType = ZodNaN.create; -var bigIntType = ZodBigInt.create; -var booleanType = ZodBoolean.create; -var dateType = ZodDate.create; -var symbolType = ZodSymbol.create; -var undefinedType = ZodUndefined.create; -var nullType = ZodNull.create; -var anyType = ZodAny.create; -var unknownType = ZodUnknown.create; -var neverType = ZodNever.create; -var voidType = ZodVoid.create; -var arrayType = ZodArray.create; -var objectType = ZodObject.create; -var strictObjectType = ZodObject.strictCreate; -var unionType = ZodUnion.create; -var discriminatedUnionType = ZodDiscriminatedUnion.create; -var intersectionType = ZodIntersection.create; -var tupleType = ZodTuple.create; -var recordType = ZodRecord.create; -var mapType = ZodMap.create; -var setType = ZodSet.create; -var functionType = ZodFunction.create; -var lazyType = ZodLazy.create; -var literalType = ZodLiteral.create; -var enumType = ZodEnum.create; -var nativeEnumType = ZodNativeEnum.create; -var promiseType = ZodPromise.create; -var effectsType = ZodEffects.create; -var optionalType = ZodOptional.create; -var nullableType = ZodNullable.create; -var preprocessType = ZodEffects.createWithPreprocess; -var pipelineType = ZodPipeline.create; -var ostring = () => stringType().optional(); -var onumber = () => numberType().optional(); -var oboolean = () => booleanType().optional(); -var coerce = { - string: (arg) => ZodString.create({ ...arg, coerce: true }), - number: (arg) => ZodNumber.create({ ...arg, coerce: true }), - boolean: (arg) => ZodBoolean.create({ - ...arg, - coerce: true - }), - bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), - date: (arg) => ZodDate.create({ ...arg, coerce: true }) -}; -var NEVER = INVALID; - -// node_modules/@modelcontextprotocol/sdk/dist/esm/types.js -var LATEST_PROTOCOL_VERSION = "2025-06-18"; -var SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-03-26", - "2024-11-05", - "2024-10-07" -]; -var JSONRPC_VERSION = "2.0"; -var ProgressTokenSchema = external_exports.union([external_exports.string(), external_exports.number().int()]); -var CursorSchema = external_exports.string(); -var RequestMetaSchema = external_exports.object({ - /** - * 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: external_exports.optional(ProgressTokenSchema) -}).passthrough(); -var BaseRequestParamsSchema = external_exports.object({ - _meta: external_exports.optional(RequestMetaSchema) -}).passthrough(); -var RequestSchema = external_exports.object({ - method: external_exports.string(), - params: external_exports.optional(BaseRequestParamsSchema) -}); -var BaseNotificationParamsSchema = external_exports.object({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var NotificationSchema = external_exports.object({ - method: external_exports.string(), - params: external_exports.optional(BaseNotificationParamsSchema) -}); -var ResultSchema = external_exports.object({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var RequestIdSchema = external_exports.union([external_exports.string(), external_exports.number().int()]); -var JSONRPCRequestSchema = external_exports.object({ - jsonrpc: external_exports.literal(JSONRPC_VERSION), - id: RequestIdSchema -}).merge(RequestSchema).strict(); -var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -var JSONRPCNotificationSchema = external_exports.object({ - jsonrpc: external_exports.literal(JSONRPC_VERSION) -}).merge(NotificationSchema).strict(); -var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -var JSONRPCResponseSchema = external_exports.object({ - jsonrpc: external_exports.literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -var isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -var ErrorCode; -(function(ErrorCode2) { - ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; - ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; - ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; - ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; - ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; - ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; - ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; -})(ErrorCode || (ErrorCode = {})); -var JSONRPCErrorSchema = external_exports.object({ - jsonrpc: external_exports.literal(JSONRPC_VERSION), - id: RequestIdSchema, - error: external_exports.object({ - /** - * The error type that occurred. - */ - code: external_exports.number().int(), - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: external_exports.string(), - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data: external_exports.optional(external_exports.unknown()) - }) -}).strict(); -var isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success; -var JSONRPCMessageSchema = external_exports.union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResponseSchema, - JSONRPCErrorSchema -]); -var EmptyResultSchema = ResultSchema.strict(); -var CancelledNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/cancelled"), - params: BaseNotificationParamsSchema.extend({ - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestIdSchema, - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: external_exports.string().optional() - }) -}); -var BaseMetadataSchema = external_exports.object({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: external_exports.string(), - /** - * 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: external_exports.optional(external_exports.string()) -}).passthrough(); -var ImplementationSchema = BaseMetadataSchema.extend({ - version: external_exports.string() -}); -var ClientCapabilitiesSchema = external_exports.object({ - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental: external_exports.optional(external_exports.object({}).passthrough()), - /** - * Present if the client supports sampling from an LLM. - */ - sampling: external_exports.optional(external_exports.object({}).passthrough()), - /** - * Present if the client supports eliciting user input. - */ - elicitation: external_exports.optional(external_exports.object({}).passthrough()), - /** - * Present if the client supports listing roots. - */ - roots: external_exports.optional(external_exports.object({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: external_exports.optional(external_exports.boolean()) - }).passthrough()) -}).passthrough(); -var InitializeRequestSchema = RequestSchema.extend({ - method: external_exports.literal("initialize"), - params: BaseRequestParamsSchema.extend({ - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: external_exports.string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema - }) -}); -var ServerCapabilitiesSchema = external_exports.object({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: external_exports.optional(external_exports.object({}).passthrough()), - /** - * Present if the server supports sending log messages to the client. - */ - logging: external_exports.optional(external_exports.object({}).passthrough()), - /** - * Present if the server supports sending completions to the client. - */ - completions: external_exports.optional(external_exports.object({}).passthrough()), - /** - * Present if the server offers any prompt templates. - */ - prompts: external_exports.optional(external_exports.object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: external_exports.optional(external_exports.boolean()) - }).passthrough()), - /** - * Present if the server offers any resources to read. - */ - resources: external_exports.optional(external_exports.object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: external_exports.optional(external_exports.boolean()), - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: external_exports.optional(external_exports.boolean()) - }).passthrough()), - /** - * Present if the server offers any tools to call. - */ - tools: external_exports.optional(external_exports.object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: external_exports.optional(external_exports.boolean()) - }).passthrough()) -}).passthrough(); -var InitializeResultSchema = ResultSchema.extend({ - /** - * 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: external_exports.string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - /** - * 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: external_exports.optional(external_exports.string()) -}); -var InitializedNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/initialized") -}); -var PingRequestSchema = RequestSchema.extend({ - method: external_exports.literal("ping") -}); -var ProgressSchema = external_exports.object({ - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - */ - progress: external_exports.number(), - /** - * Total number of items to process (or total progress required), if known. - */ - total: external_exports.optional(external_exports.number()), - /** - * An optional message describing the current progress. - */ - message: external_exports.optional(external_exports.string()) -}).passthrough(); -var ProgressNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/progress"), - params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({ - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressTokenSchema - }) -}); -var PaginatedRequestSchema = RequestSchema.extend({ - params: BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: external_exports.optional(CursorSchema) - }).optional() -}); -var PaginatedResultSchema = ResultSchema.extend({ - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor: external_exports.optional(CursorSchema) -}); -var ResourceContentsSchema = external_exports.object({ - /** - * The URI of this resource. - */ - uri: external_exports.string(), - /** - * The MIME type of this resource, if known. - */ - mimeType: external_exports.optional(external_exports.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var TextResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: external_exports.string() -}); -var BlobResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * A base64-encoded string representing the binary data of the item. - */ - blob: external_exports.string().base64() -}); -var ResourceSchema = BaseMetadataSchema.extend({ - /** - * The URI of this resource. - */ - uri: external_exports.string(), - /** - * 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: external_exports.optional(external_exports.string()), - /** - * The MIME type of this resource, if known. - */ - mimeType: external_exports.optional(external_exports.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}); -var ResourceTemplateSchema = BaseMetadataSchema.extend({ - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - */ - uriTemplate: external_exports.string(), - /** - * 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: external_exports.optional(external_exports.string()), - /** - * 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: external_exports.optional(external_exports.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}); -var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: external_exports.literal("resources/list") -}); -var ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: external_exports.array(ResourceSchema) -}); -var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: external_exports.literal("resources/templates/list") -}); -var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: external_exports.array(ResourceTemplateSchema) -}); -var ReadResourceRequestSchema = RequestSchema.extend({ - method: external_exports.literal("resources/read"), - params: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. - */ - uri: external_exports.string() - }) -}); -var ReadResourceResultSchema = ResultSchema.extend({ - contents: external_exports.array(external_exports.union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); -var ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/resources/list_changed") -}); -var SubscribeRequestSchema = RequestSchema.extend({ - method: external_exports.literal("resources/subscribe"), - params: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. - */ - uri: external_exports.string() - }) -}); -var UnsubscribeRequestSchema = RequestSchema.extend({ - method: external_exports.literal("resources/unsubscribe"), - params: BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to unsubscribe from. - */ - uri: external_exports.string() - }) -}); -var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/resources/updated"), - params: BaseNotificationParamsSchema.extend({ - /** - * 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: external_exports.string() - }) -}); -var PromptArgumentSchema = external_exports.object({ - /** - * The name of the argument. - */ - name: external_exports.string(), - /** - * A human-readable description of the argument. - */ - description: external_exports.optional(external_exports.string()), - /** - * Whether this argument must be provided. - */ - required: external_exports.optional(external_exports.boolean()) -}).passthrough(); -var PromptSchema = BaseMetadataSchema.extend({ - /** - * An optional description of what this prompt provides - */ - description: external_exports.optional(external_exports.string()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: external_exports.optional(external_exports.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: external_exports.optional(external_exports.object({}).passthrough()) -}); -var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: external_exports.literal("prompts/list") -}); -var ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: external_exports.array(PromptSchema) -}); -var GetPromptRequestSchema = RequestSchema.extend({ - method: external_exports.literal("prompts/get"), - params: BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: external_exports.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: external_exports.optional(external_exports.record(external_exports.string())) - }) -}); -var TextContentSchema = external_exports.object({ - type: external_exports.literal("text"), - /** - * The text content of the message. - */ - text: external_exports.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var ImageContentSchema = external_exports.object({ - type: external_exports.literal("image"), - /** - * The base64-encoded image data. - */ - data: external_exports.string().base64(), - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: external_exports.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var AudioContentSchema = external_exports.object({ - type: external_exports.literal("audio"), - /** - * The base64-encoded audio data. - */ - data: external_exports.string().base64(), - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: external_exports.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var EmbeddedResourceSchema = external_exports.object({ - type: external_exports.literal("resource"), - resource: external_exports.union([TextResourceContentsSchema, BlobResourceContentsSchema]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var ResourceLinkSchema = ResourceSchema.extend({ - type: external_exports.literal("resource_link") -}); -var ContentBlockSchema = external_exports.union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -var PromptMessageSchema = external_exports.object({ - role: external_exports.enum(["user", "assistant"]), - content: ContentBlockSchema -}).passthrough(); -var GetPromptResultSchema = ResultSchema.extend({ - /** - * An optional description for the prompt. - */ - description: external_exports.optional(external_exports.string()), - messages: external_exports.array(PromptMessageSchema) -}); -var PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/prompts/list_changed") -}); -var ToolAnnotationsSchema = external_exports.object({ - /** - * A human-readable title for the tool. - */ - title: external_exports.optional(external_exports.string()), - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint: external_exports.optional(external_exports.boolean()), - /** - * 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: external_exports.optional(external_exports.boolean()), - /** - * 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: external_exports.optional(external_exports.boolean()), - /** - * 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: external_exports.optional(external_exports.boolean()) -}).passthrough(); -var ToolSchema = BaseMetadataSchema.extend({ - /** - * A human-readable description of the tool. - */ - description: external_exports.optional(external_exports.string()), - /** - * A JSON Schema object defining the expected parameters for the tool. - */ - inputSchema: external_exports.object({ - type: external_exports.literal("object"), - properties: external_exports.optional(external_exports.object({}).passthrough()), - required: external_exports.optional(external_exports.array(external_exports.string())) - }).passthrough(), - /** - * An optional JSON Schema object defining the structure of the tool's output returned in - * the structuredContent field of a CallToolResult. - */ - outputSchema: external_exports.optional(external_exports.object({ - type: external_exports.literal("object"), - properties: external_exports.optional(external_exports.object({}).passthrough()), - required: external_exports.optional(external_exports.array(external_exports.string())) - }).passthrough()), - /** - * Optional additional tool information. - */ - annotations: external_exports.optional(ToolAnnotationsSchema), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}); -var ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: external_exports.literal("tools/list") -}); -var ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: external_exports.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: external_exports.array(ContentBlockSchema).default([]), - /** - * 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: external_exports.object({}).passthrough().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: external_exports.optional(external_exports.boolean()) -}); -var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ - toolResult: external_exports.unknown() -})); -var CallToolRequestSchema = RequestSchema.extend({ - method: external_exports.literal("tools/call"), - params: BaseRequestParamsSchema.extend({ - name: external_exports.string(), - arguments: external_exports.optional(external_exports.record(external_exports.unknown())) - }) -}); -var ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/tools/list_changed") -}); -var LoggingLevelSchema = external_exports.enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" -]); -var SetLevelRequestSchema = RequestSchema.extend({ - method: external_exports.literal("logging/setLevel"), - params: 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 LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/message"), - params: BaseNotificationParamsSchema.extend({ - /** - * The severity of this log message. - */ - level: LoggingLevelSchema, - /** - * An optional name of the logger issuing this message. - */ - logger: external_exports.optional(external_exports.string()), - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: external_exports.unknown() - }) -}); -var ModelHintSchema = external_exports.object({ - /** - * A hint for a model name. - */ - name: external_exports.string().optional() -}).passthrough(); -var ModelPreferencesSchema = external_exports.object({ - /** - * Optional hints to use for model selection. - */ - hints: external_exports.optional(external_exports.array(ModelHintSchema)), - /** - * How much to prioritize cost when selecting a model. - */ - costPriority: external_exports.optional(external_exports.number().min(0).max(1)), - /** - * How much to prioritize sampling speed (latency) when selecting a model. - */ - speedPriority: external_exports.optional(external_exports.number().min(0).max(1)), - /** - * How much to prioritize intelligence and capabilities when selecting a model. - */ - intelligencePriority: external_exports.optional(external_exports.number().min(0).max(1)) -}).passthrough(); -var SamplingMessageSchema = external_exports.object({ - role: external_exports.enum(["user", "assistant"]), - content: external_exports.union([TextContentSchema, ImageContentSchema, AudioContentSchema]) -}).passthrough(); -var CreateMessageRequestSchema = RequestSchema.extend({ - method: external_exports.literal("sampling/createMessage"), - params: BaseRequestParamsSchema.extend({ - messages: external_exports.array(SamplingMessageSchema), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: external_exports.optional(external_exports.string()), - /** - * 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. - */ - includeContext: external_exports.optional(external_exports.enum(["none", "thisServer", "allServers"])), - temperature: external_exports.optional(external_exports.number()), - /** - * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested. - */ - maxTokens: external_exports.number().int(), - stopSequences: external_exports.optional(external_exports.array(external_exports.string())), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: external_exports.optional(external_exports.object({}).passthrough()), - /** - * The server's preferences for which model to select. - */ - modelPreferences: external_exports.optional(ModelPreferencesSchema) - }) -}); -var CreateMessageResultSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: external_exports.string(), - /** - * The reason why sampling stopped. - */ - stopReason: external_exports.optional(external_exports.enum(["endTurn", "stopSequence", "maxTokens"]).or(external_exports.string())), - role: external_exports.enum(["user", "assistant"]), - content: external_exports.discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema - ]) -}); -var BooleanSchemaSchema = external_exports.object({ - type: external_exports.literal("boolean"), - title: external_exports.optional(external_exports.string()), - description: external_exports.optional(external_exports.string()), - default: external_exports.optional(external_exports.boolean()) -}).passthrough(); -var StringSchemaSchema = external_exports.object({ - type: external_exports.literal("string"), - title: external_exports.optional(external_exports.string()), - description: external_exports.optional(external_exports.string()), - minLength: external_exports.optional(external_exports.number()), - maxLength: external_exports.optional(external_exports.number()), - format: external_exports.optional(external_exports.enum(["email", "uri", "date", "date-time"])) -}).passthrough(); -var NumberSchemaSchema = external_exports.object({ - type: external_exports.enum(["number", "integer"]), - title: external_exports.optional(external_exports.string()), - description: external_exports.optional(external_exports.string()), - minimum: external_exports.optional(external_exports.number()), - maximum: external_exports.optional(external_exports.number()) -}).passthrough(); -var EnumSchemaSchema = external_exports.object({ - type: external_exports.literal("string"), - title: external_exports.optional(external_exports.string()), - description: external_exports.optional(external_exports.string()), - enum: external_exports.array(external_exports.string()), - enumNames: external_exports.optional(external_exports.array(external_exports.string())) -}).passthrough(); -var PrimitiveSchemaDefinitionSchema = external_exports.union([ - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema, - EnumSchemaSchema -]); -var ElicitRequestSchema = RequestSchema.extend({ - method: external_exports.literal("elicitation/create"), - params: BaseRequestParamsSchema.extend({ - /** - * The message to present to the user. - */ - message: external_exports.string(), - /** - * The schema for the requested user input. - */ - requestedSchema: external_exports.object({ - type: external_exports.literal("object"), - properties: external_exports.record(external_exports.string(), PrimitiveSchemaDefinitionSchema), - required: external_exports.optional(external_exports.array(external_exports.string())) - }).passthrough() - }) -}); -var ElicitResultSchema = ResultSchema.extend({ - /** - * The user's response action. - */ - action: external_exports.enum(["accept", "decline", "cancel"]), - /** - * The collected user input content (only present if action is "accept"). - */ - content: external_exports.optional(external_exports.record(external_exports.string(), external_exports.unknown())) -}); -var ResourceTemplateReferenceSchema = external_exports.object({ - type: external_exports.literal("ref/resource"), - /** - * The URI or URI template of the resource. - */ - uri: external_exports.string() -}).passthrough(); -var PromptReferenceSchema = external_exports.object({ - type: external_exports.literal("ref/prompt"), - /** - * The name of the prompt or prompt template - */ - name: external_exports.string() -}).passthrough(); -var CompleteRequestSchema = RequestSchema.extend({ - method: external_exports.literal("completion/complete"), - params: BaseRequestParamsSchema.extend({ - ref: external_exports.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: external_exports.object({ - /** - * The name of the argument - */ - name: external_exports.string(), - /** - * The value of the argument to use for completion matching. - */ - value: external_exports.string() - }).passthrough(), - context: external_exports.optional(external_exports.object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: external_exports.optional(external_exports.record(external_exports.string(), external_exports.string())) - })) - }) -}); -var CompleteResultSchema = ResultSchema.extend({ - completion: external_exports.object({ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: external_exports.array(external_exports.string()).max(100), - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: external_exports.optional(external_exports.number().int()), - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: external_exports.optional(external_exports.boolean()) - }).passthrough() -}); -var RootSchema = external_exports.object({ - /** - * The URI identifying the root. This *must* start with file:// for now. - */ - uri: external_exports.string().startsWith("file://"), - /** - * An optional name for the root. - */ - name: external_exports.optional(external_exports.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: external_exports.optional(external_exports.object({}).passthrough()) -}).passthrough(); -var ListRootsRequestSchema = RequestSchema.extend({ - method: external_exports.literal("roots/list") -}); -var ListRootsResultSchema = ResultSchema.extend({ - roots: external_exports.array(RootSchema) -}); -var RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: external_exports.literal("notifications/roots/list_changed") -}); -var ClientRequestSchema = external_exports.union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -var ClientNotificationSchema = external_exports.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -var ClientResultSchema = external_exports.union([ - EmptyResultSchema, - CreateMessageResultSchema, - ElicitResultSchema, - ListRootsResultSchema -]); -var ServerRequestSchema = external_exports.union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema -]); -var ServerNotificationSchema = external_exports.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema -]); -var ServerResultSchema = external_exports.union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema -]); -var McpError = class extends Error { - constructor(code, message, data) { - super(`MCP error ${code}: ${message}`); - this.code = code; - this.data = data; - this.name = "McpError"; - } -}; - -// 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.setNotificationHandler(CancelledNotificationSchema, (notification) => { - const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); - controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason); - }); - this.setNotificationHandler(ProgressNotificationSchema, (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler( - PingRequestSchema, - // Automatic pong by default. - (_request) => ({}) - ); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _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 new McpError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { maxTotalTimeout: info.maxTotalTimeout, totalElapsed }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * 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 _a, _b, _c; - this._transport = transport; - const _onclose = (_a = this.transport) === null || _a === void 0 ? void 0 : _a.onclose; - this._transport.onclose = () => { - _onclose === null || _onclose === void 0 ? void 0 : _onclose(); - this._onclose(); - }; - const _onerror = (_b = this.transport) === null || _b === void 0 ? void 0 : _b.onerror; - this._transport.onerror = (error) => { - _onerror === null || _onerror === void 0 ? void 0 : _onerror(error); - this._onerror(error); - }; - const _onmessage = (_c = this._transport) === null || _c === void 0 ? void 0 : _c.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra); - if (isJSONRPCResponse(message) || isJSONRPCError(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(); - } - _onclose() { - var _a; - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._transport = void 0; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - const error = new McpError(ErrorCode.ConnectionClosed, "Connection closed"); - for (const handler of responseHandlers.values()) { - handler(error); - } - } - _onerror(error) { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - } - _onnotification(notification) { - var _a; - const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== void 0 ? _a : this.fallbackNotificationHandler; - if (handler === void 0) { - return; - } - Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(request, extra) { - var _a, _b, _c, _d; - const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler; - if (handler === void 0) { - (_b = this._transport) === null || _b === void 0 ? void 0 : _b.send({ - jsonrpc: "2.0", - id: request.id, - error: { - code: ErrorCode.MethodNotFound, - message: "Method not found" - } - }).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`))); - return; - } - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const fullExtra = { - signal: abortController.signal, - sessionId: (_c = this._transport) === null || _c === void 0 ? void 0 : _c.sessionId, - _meta: (_d = request.params) === null || _d === void 0 ? void 0 : _d._meta, - sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }), - sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }), - authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo, - requestId: request.id, - requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo - }; - Promise.resolve().then(() => handler(request, fullExtra)).then((result) => { - var _a2; - if (abortController.signal.aborted) { - return; - } - return (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send({ - result, - jsonrpc: "2.0", - id: request.id - }); - }, (error) => { - var _a2, _b2; - if (abortController.signal.aborted) { - return; - } - return (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send({ - jsonrpc: "2.0", - id: request.id, - error: { - code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError, - message: (_b2 = error.message) !== null && _b2 !== void 0 ? _b2 : "Internal error" - } - }); - }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => { - this._requestHandlerAbortControllers.delete(request.id); - }); - } - _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 (error) { - responseHandler(error); - return; - } - } - handler(params); - } - _onresponse(response) { - const messageId = Number(response.id); - 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._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - if (isJSONRPCResponse(response)) { - handler(response); - } else { - const error = new McpError(response.error.code, response.error.message, response.error.data); - handler(error); - } - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - var _a; - await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close()); - } - /** - * Sends a request and wait for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request(request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e, _f; - if (!this._transport) { - reject(new Error("Not connected")); - return; - } - if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) { - this.assertCapabilityForMethod(request.method); - } - (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted(); - const messageId = this._requestMessageId++; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options === null || options === void 0 ? void 0 : options.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...((_c = request.params) === null || _c === void 0 ? void 0 : _c._meta) || {}, - progressToken: messageId - } - }; - } - const cancel = (reason) => { - var _a2; - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => this._onerror(new Error(`Failed to send cancellation: ${error}`))); - reject(reason); - }; - this._responseHandlers.set(messageId, (response) => { - var _a2; - if ((_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.aborted) { - return; - } - if (response instanceof Error) { - return reject(response); - } - try { - const result = resultSchema.parse(response.result); - resolve(result); - } catch (error) { - reject(error); - } - }); - (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener("abort", () => { - var _a2; - cancel((_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.reason); - }); - const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false); - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => { - this._cleanupTimeout(messageId); - reject(error); - }); - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - if (!this._transport) { - throw new Error("Not connected"); - } - this.assertNotificationCapability(notification.method); - const jsonrpcNotification = { - ...notification, - jsonrpc: "2.0" - }; - 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 = requestSchema.shape.method.value; - this.assertRequestHandlerCapability(method); - this._requestHandlers.set(method, (request, extra) => { - return Promise.resolve(handler(requestSchema.parse(request), 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) { - this._notificationHandlers.set(notificationSchema.shape.method.value, (notification) => Promise.resolve(handler(notificationSchema.parse(notification)))); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -}; -function mergeCapabilities(base, additional) { - return Object.entries(additional).reduce((acc, [key, value]) => { - if (value && typeof value === "object") { - acc[key] = acc[key] ? { ...acc[key], ...value } : value; - } else { - acc[key] = value; - } - return acc; - }, { ...base }); -} - -// node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js -var import_ajv = __toESM(require_ajv(), 1); -var Server = class extends Protocol { - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - var _a; - super(options); - this._serverInfo = _serverInfo; - this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; - this._instructions = options === null || options === void 0 ? void 0 : options.instructions; - this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request)); - this.setNotificationHandler(InitializedNotificationSchema, () => { - var _a2; - return (_a2 = this.oninitialized) === null || _a2 === void 0 ? void 0 : _a2.call(this); - }); - } - /** - * 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); - } - assertCapabilityForMethod(method) { - var _a, _b, _c; - switch (method) { - case "sampling/createMessage": - if (!((_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.sampling)) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - case "elicitation/create": - if (!((_b = this._clientCapabilities) === null || _b === void 0 ? void 0 : _b.elicitation)) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - case "roots/list": - if (!((_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.roots)) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - case "ping": - break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - case "notifications/cancelled": - break; - case "notifications/progress": - break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "sampling/createMessage": - if (!this._capabilities.sampling) { - throw new Error(`Server does not support sampling (required for ${method})`); - } - break; - case "logging/setLevel": - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case "ping": - case "initialize": - break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion() { - return this._clientVersion; - } - getCapabilities() { - return this._capabilities; - } - async ping() { - return this.request({ method: "ping" }, EmptyResultSchema); - } - async createMessage(params, options) { - return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); - } - async elicitInput(params, options) { - const result = await this.request({ method: "elicitation/create", params }, ElicitResultSchema, options); - if (result.action === "accept" && result.content) { - try { - const ajv = new import_ajv.default(); - const validate = ajv.compile(params.requestedSchema); - const isValid2 = validate(result.content); - if (!isValid2) { - throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${ajv.errorsText(validate.errors)}`); - } - } catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error}`); - } - } - return result; - } - async listRoots(params, options) { - return this.request({ method: "roots/list", params }, ListRootsResultSchema, options); - } - async sendLoggingMessage(params) { - return this.notification({ method: "notifications/message", params }); - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - async sendResourceListChanged() { - return this.notification({ - method: "notifications/resources/list_changed" - }); - } - async sendToolListChanged() { - return this.notification({ method: "notifications/tools/list_changed" }); - } - async sendPromptListChanged() { - return this.notification({ method: "notifications/prompts/list_changed" }); - } -}; - -// node_modules/zod-to-json-schema/dist/esm/Options.js -var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); -var defaultOptions = { - name: void 0, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - allowedAdditionalProperties: true, - rejectedAdditionalProperties: false, - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref", - openAiAnyTypeName: "OpenAiAnyType" -}; -var getDefaultOptions = (options) => typeof options === "string" ? { - ...defaultOptions, - name: options -} : { - ...defaultOptions, - ...options -}; - -// node_modules/zod-to-json-schema/dist/esm/Refs.js -var getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; - return { - ..._options, - flags: { hasReferencedOpenAiAnyType: false }, - currentPath, - propertyPath: void 0, - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - def._def, - { - def: def._def, - path: [..._options.basePath, _options.definitionPath, name], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: void 0 - } - ])) - }; -}; - -// node_modules/zod-to-json-schema/dist/esm/errorMessages.js -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) { - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage - }; - } -} -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); -} - -// node_modules/zod-to-json-schema/dist/esm/getRelativePath.js -var getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; - -// node_modules/zod-to-json-schema/dist/esm/parsers/any.js -function parseAnyDef(refs) { - if (refs.target !== "openAi") { - return {}; - } - const anyDefinitionPath = [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ]; - refs.flags.hasReferencedOpenAiAnyType = true; - return { - $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/array.js -function parseArrayDef(def, refs) { - const res = { - type: "array" - }; - if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { - res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - } - if (def.minLength) { - setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); - } - if (def.maxLength) { - setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); - } - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); - } - return res; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64" - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js -function parseBooleanDef() { - return { - type: "boolean" - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js -var parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -// node_modules/zod-to-json-schema/dist/esm/parsers/date.js -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) { - return { - anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) - }; - } - switch (strategy) { - case "string": - case "format:date-time": - return { - type: "string", - format: "date-time" - }; - case "format:date": - return { - type: "string", - format: "date" - }; - case "integer": - return integerDateParser(def, refs); - } -} -var integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time" - }; - if (refs.target === "openApi3") { - return res; - } - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors( - res, - "minimum", - check.value, - // This is in milliseconds - check.message, - refs - ); - break; - case "max": - setResponseValueAndErrors( - res, - "maximum", - check.value, - // This is in milliseconds - check.message, - refs - ); - break; - } - } - return res; -}; - -// node_modules/zod-to-json-schema/dist/esm/parsers/default.js -function parseDefaultDef(_def, refs) { - return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue() - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values) - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js -var isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") - return false; - return "allOf" in type; -}; -function parseIntersectionDef(def, refs) { - const allOf = [ - parseDef(def.left._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"] - }), - parseDef(def.right._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "1"] - }) - ].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; - const mergedAllOf = []; - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === void 0) { - unevaluatedProperties = void 0; - } - } else { - let nestedSchema = schema; - if ("additionalProperties" in schema && schema.additionalProperties === false) { - const { additionalProperties, ...rest } = schema; - nestedSchema = rest; - } else { - unevaluatedProperties = void 0; - } - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length ? { - allOf: mergedAllOf, - ...unevaluatedProperties - } : void 0; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js -function parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { - return { - type: Array.isArray(def.value) ? "array" : "object" - }; - } - if (refs.target === "openApi3") { - return { - type: parsedType === "bigint" ? "integer" : parsedType, - enum: [def.value] - }; - } - return { - type: parsedType === "bigint" ? "integer" : parsedType, - const: def.value - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/string.js -var emojiRegex2 = void 0; -var zodPatterns = { - /** - * `c` was changed to `[cC]` to replicate /i flag - */ - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - /** - * `a-z` was added to replicate /i flag - */ - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - /** - * Constructed a valid Unicode RegExp - * - * Lazily instantiate since this type of regex isn't supported - * in all envs (e.g. React Native). - * - * See: - * https://github.com/colinhacks/zod/issues/2433 - * Fix in Zod: - * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b - */ - emoji: () => { - if (emojiRegex2 === void 0) { - emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); - } - return emojiRegex2; - }, - /** - * Unused - */ - uuid: /^[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}$/, - /** - * Unused - */ - 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])$/, - ipv4Cidr: /^(?:(?: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])$/, - /** - * Unused - */ - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([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])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ -}; -function parseStringDef(def, refs) { - const res = { - type: "string" - }; - if (def.checks) { - for (const check of def.checks) { - switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check.message, refs); - break; - case "regex": - addPattern(res, check.regex, check.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check.message, refs); - break; - case "date": - addFormat(res, "date", check.message, refs); - break; - case "time": - addFormat(res, "time", check.message, refs); - break; - case "duration": - addFormat(res, "duration", check.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "includes": { - addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); - break; - } - case "ip": { - if (check.version !== "v6") { - addFormat(res, "ipv4", check.message, refs); - } - if (check.version !== "v4") { - addFormat(res, "ipv6", check.message, refs); - } - break; - } - case "base64url": - addPattern(res, zodPatterns.base64url, check.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check.message, refs); - break; - case "cidr": { - if (check.version !== "v6") { - addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); - } - if (check.version !== "v4") { - addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); - } - break; - } - case "emoji": - addPattern(res, zodPatterns.emoji(), check.message, refs); - break; - case "ulid": { - addPattern(res, zodPatterns.ulid, check.message, refs); - break; - } - case "base64": { - switch (refs.base64Strategy) { - case "format:binary": { - addFormat(res, "binary", check.message, refs); - break; - } - case "contentEncoding:base64": { - setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); - break; - } - case "pattern:zod": { - addPattern(res, zodPatterns.base64, check.message, refs); - break; - } - } - break; - } - case "nanoid": { - addPattern(res, zodPatterns.nanoid, check.message, refs); - } - case "toLowerCase": - case "toUpperCase": - case "trim": - break; - default: - /* @__PURE__ */ ((_) => { - })(check); - } - } - } - return res; -} -function escapeLiteralCheckValue(literal, refs) { - return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; -} -var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i = 0; i < source.length; i++) { - if (!ALPHA_NUMERIC.has(source[i])) { - result += "\\"; - } - result += source[i]; - } - return result; -} -function addFormat(schema, value, message, refs) { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) { - schema.anyOf = []; - } - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...schema.errorMessage && refs.errorMessages && { - errorMessage: { format: schema.errorMessage.format } - } - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.anyOf.push({ - format: value, - ...message && refs.errorMessages && { errorMessage: { format: message } } - }); - } else { - setResponseValueAndErrors(schema, "format", value, message, refs); - } -} -function addPattern(schema, regex, message, refs) { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) { - schema.allOf = []; - } - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...schema.errorMessage && refs.errorMessages && { - errorMessage: { pattern: schema.errorMessage.pattern } - } - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.allOf.push({ - pattern: stringifyRegExpWithFlags(regex, refs), - ...message && refs.errorMessages && { errorMessage: { pattern: message } } - }); - } else { - setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); - } -} -function stringifyRegExpWithFlags(regex, refs) { - if (!refs.applyRegexFlags || !regex.flags) { - return regex.source; - } - const flags = { - i: regex.flags.includes("i"), - m: regex.flags.includes("m"), - s: regex.flags.includes("s") - // `.` matches newlines - }; - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0; i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } else { - pattern += `${source[i]}${source[i].toUpperCase()}`; - } - continue; - } - } else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; - } - } - if (flags.m) { - if (source[i] === "^") { - pattern += `(^|(?<=[\r -]))`; - continue; - } else if (source[i] === "$") { - pattern += `($|(?=[\r -]))`; - continue; - } - } - if (flags.s && source[i] === ".") { - pattern += inCharGroup ? `${source[i]}\r -` : `[${source[i]}\r -]`; - continue; - } - pattern += source[i]; - if (source[i] === "\\") { - isEscaped = true; - } else if (inCharGroup && source[i] === "]") { - inCharGroup = false; - } else if (!inCharGroup && source[i] === "[") { - inCharGroup = true; - } - } - try { - new RegExp(pattern); - } catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/record.js -function parseRecordDef(def, refs) { - if (refs.target === "openAi") { - console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - } - if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", key] - }) ?? parseAnyDef(refs) - }), {}), - additionalProperties: refs.rejectedAdditionalProperties - }; - } - const schema = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? refs.allowedAdditionalProperties - }; - if (refs.target === "openApi3") { - return schema; - } - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { - const { type, ...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - ...schema, - propertyNames: { - enum: def.keyType._def.values - } - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { - const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } - return schema; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/map.js -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") { - return parseRecordDef(def, refs); - } - const keys = parseDef(def.keyType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "0"] - }) || parseAnyDef(refs); - const values = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "1"] - }) || parseAnyDef(refs); - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2 - } - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js -function parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], - enum: actualValues - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/never.js -function parseNeverDef(refs) { - return refs.target === "openAi" ? void 0 : { - not: parseAnyDef({ - ...refs, - currentPath: [...refs.currentPath, "not"] - }) - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/null.js -function parseNullDef(refs) { - return refs.target === "openApi3" ? { - enum: ["null"], - nullable: true - } : { - type: "null" - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/union.js -var primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null" -}; -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") - return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { - const types = options.reduce((types2, x) => { - const type = primitiveMappings[x._def.typeName]; - return type && !types2.includes(type) ? [...types2, type] : types2; - }, []); - return { - type: types.length > 1 ? types : types[0] - }; - } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case "string": - case "number": - case "boolean": - return [...acc, type]; - case "bigint": - return [...acc, "integer"]; - case "object": - if (x._def.value === null) - return [...acc, "null"]; - case "symbol": - case "undefined": - case "function": - default: - return acc; - } - }, []); - if (types.length === options.length) { - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []) - }; - } - } else if (options.every((x) => x._def.typeName === "ZodEnum")) { - return { - type: "string", - enum: options.reduce((acc, x) => [ - ...acc, - ...x._def.values.filter((x2) => !acc.includes(x2)) - ], []) - }; - } - return asAnyOf(def, refs); -} -var asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", `${i}`] - })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); - return anyOf.length ? { anyOf } : void 0; -}; - -// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js -function parseNullableDef(def, refs) { - if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") { - return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true - }; - } - return { - type: [ - primitiveMappings[def.innerType._def.typeName], - "null" - ] - }; - } - if (refs.target === "openApi3") { - const base2 = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath] - }); - if (base2 && "$ref" in base2) - return { allOf: [base2], nullable: true }; - return base2 && { ...base2, nullable: true }; - } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "0"] - }); - return base && { anyOf: [base, { type: "null" }] }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/number.js -function parseNumberDef(def, refs) { - const res = { - type: "number" - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check.message, refs); - break; - case "min": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check.inclusive) { - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - } - } else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - } - return res; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/object.js -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - properties: {} - }; - const required = []; - const shape = def.shape(); - for (const propName in shape) { - let propDef = shape[propName]; - if (propDef === void 0 || propDef._def === void 0) { - continue; - } - let propOptional = safeIsOptional(propDef); - if (propOptional && forceOptionalIntoNullable) { - if (propDef._def.typeName === "ZodOptional") { - propDef = propDef._def.innerType; - } - if (!propDef.isNullable()) { - propDef = propDef.nullable(); - } - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", propName], - propertyPath: [...refs.currentPath, "properties", propName] - }); - if (parsedDef === void 0) { - continue; - } - result.properties[propName] = parsedDef; - if (!propOptional) { - required.push(propName); - } - } - if (required.length) { - result.required = required; - } - const additionalProperties = decideAdditionalProperties(def, refs); - if (additionalProperties !== void 0) { - result.additionalProperties = additionalProperties; - } - return result; -} -function decideAdditionalProperties(def, refs) { - if (def.catchall._def.typeName !== "ZodNever") { - return parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }); - } - switch (def.unknownKeys) { - case "passthrough": - return refs.allowedAdditionalProperties; - case "strict": - return refs.rejectedAdditionalProperties; - case "strip": - return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; - } -} -function safeIsOptional(schema) { - try { - return schema.isOptional(); - } catch { - return true; - } -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js -var parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) { - return parseDef(def.innerType._def, refs); - } - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "1"] - }); - return innerSchema ? { - anyOf: [ - { - not: parseAnyDef(refs) - }, - innerSchema - ] - } : parseAnyDef(refs); -}; - -// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js -var parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") { - return parseDef(def.in._def, refs); - } else if (refs.pipeStrategy === "output") { - return parseDef(def.out._def, refs); - } - const a = parseDef(def.in._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"] - }); - const b = parseDef(def.out._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] - }); - return { - allOf: [a, b].filter((x) => x !== void 0) - }; -}; - -// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/set.js -function parseSetDef(def, refs) { - const items = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - const schema = { - type: "array", - uniqueItems: true, - items - }; - if (def.minSize) { - setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); - } - if (def.maxSize) { - setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - } - return schema; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js -function parseTupleDef(def, refs) { - if (def.rest) { - return { - type: "array", - minItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i}`] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"] - }) - }; - } else { - return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i}`] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) - }; - } -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js -function parseUndefinedDef(refs) { - return { - not: parseAnyDef(refs) - }; -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js -function parseUnknownDef(refs) { - return parseAnyDef(refs); -} - -// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js -var parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -// node_modules/zod-to-json-schema/dist/esm/selectParser.js -var selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: - return parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: - return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: - return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: - return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: - return parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: - return parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: - return parseUndefinedDef(refs); - case ZodFirstPartyTypeKind.ZodNull: - return parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: - return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: - return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: - return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: - return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: - return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: - return parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: - return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: - return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: - return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: - return parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: - return parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: - return () => def.getter()._def; - case ZodFirstPartyTypeKind.ZodPromise: - return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: - return parseNeverDef(refs); - case ZodFirstPartyTypeKind.ZodEffects: - return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind.ZodAny: - return parseAnyDef(refs); - case ZodFirstPartyTypeKind.ZodUnknown: - return parseUnknownDef(refs); - case ZodFirstPartyTypeKind.ZodDefault: - return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: - return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: - return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: - return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: - return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: - return void 0; - default: - return /* @__PURE__ */ ((_) => void 0)(typeName); - } -}; - -// node_modules/zod-to-json-schema/dist/esm/parseDef.js -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) { - return overrideResult; - } - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== void 0) { - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; - if (jsonSchema) { - addMeta(def, refs, jsonSchema); - } - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -var get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { $ref: item.path.join("/") }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": { - if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return parseAnyDef(refs); - } - return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; - } - } -}; -var addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; -}; - -// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js -var zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ - ...acc, - [name2]: parseDef(schema2._def, { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name2] - }, true) ?? parseAnyDef(refs) - }), {}) : void 0; - const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; - const main2 = parseDef(schema._def, name === void 0 ? refs : { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name] - }, false) ?? parseAnyDef(refs); - const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; - if (title !== void 0) { - main2.title = title; - } - if (refs.flags.hasReferencedOpenAiAnyType) { - if (!definitions) { - definitions = {}; - } - if (!definitions[refs.openAiAnyTypeName]) { - definitions[refs.openAiAnyTypeName] = { - // Skipping "object" as no properties can be defined and additionalProperties must be "false" - type: ["string", "number", "integer", "boolean", "array", "null"], - items: { - $ref: refs.$refStrategy === "relative" ? "1" : [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ].join("/") - } - }; - } - } - const combined = name === void 0 ? definitions ? { - ...main2, - [refs.definitionPath]: definitions - } : main2 : { - $ref: [ - ...refs.$refStrategy === "relative" ? [] : refs.basePath, - refs.definitionPath, - name - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main2 - } - }; - if (refs.target === "jsonSchema7") { - combined.$schema = "http://json-schema.org/draft-07/schema#"; - } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - } - if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { - console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - } - return combined; -}; - -// node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js -var McpZodTypeKind; -(function(McpZodTypeKind2) { - McpZodTypeKind2["Completable"] = "McpCompletable"; -})(McpZodTypeKind || (McpZodTypeKind = {})); -var Completable = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); - } - unwrap() { - return this._def.type; - } -}; -Completable.create = (type, params) => { - return new Completable({ - type, - typeName: McpZodTypeKind.Completable, - complete: params.complete, - ...processCreateParams2(params) - }); -}; -function processCreateParams2(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - var _a, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} - -// node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js -var McpServer = class { - constructor(serverInfo, options) { - this._registeredResources = {}; - this._registeredResourceTemplates = {}; - this._registeredTools = {}; - this._registeredPrompts = {}; - this._toolHandlersInitialized = false; - this._completionHandlerInitialized = false; - this._resourceHandlersInitialized = false; - this._promptHandlersInitialized = false; - this.server = new Server(serverInfo, options); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` 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) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - setToolRequestHandlers() { - if (this._toolHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(ListToolsRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(CallToolRequestSchema.shape.method.value); - this.server.registerCapabilities({ - tools: { - listChanged: true - } - }); - this.server.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema ? zodToJsonSchema(tool.inputSchema, { - strictUnions: true - }) : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations - }; - if (tool.outputSchema) { - toolDefinition.outputSchema = zodToJsonSchema(tool.outputSchema, { strictUnions: true }); - } - return toolDefinition; - }) - })); - this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { - const tool = this._registeredTools[request.params.name]; - if (!tool) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - } - if (!tool.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - } - let result; - if (tool.inputSchema) { - const parseResult = await tool.inputSchema.safeParseAsync(request.params.arguments); - if (!parseResult.success) { - throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${request.params.name}: ${parseResult.error.message}`); - } - const args = parseResult.data; - const cb = tool.callback; - try { - result = await Promise.resolve(cb(args, extra)); - } catch (error) { - result = { - content: [ - { - type: "text", - text: error instanceof Error ? error.message : String(error) - } - ], - isError: true - }; - } - } else { - const cb = tool.callback; - try { - result = await Promise.resolve(cb(extra)); - } catch (error) { - result = { - content: [ - { - type: "text", - text: error instanceof Error ? error.message : String(error) - } - ], - isError: true - }; - } - } - if (tool.outputSchema && !result.isError) { - if (!result.structuredContent) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} has an output schema but no structured content was provided`); - } - const parseResult = await tool.outputSchema.safeParseAsync(result.structuredContent); - if (!parseResult.success) { - throw new McpError(ErrorCode.InvalidParams, `Invalid structured content for tool ${request.params.name}: ${parseResult.error.message}`); - } - } - return result; - }); - this._toolHandlersInitialized = true; - } - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) { - return; - } - this.server.assertCanSetRequestHandler(CompleteRequestSchema.shape.method.value); - this.server.registerCapabilities({ - completions: {} - }); - this.server.setRequestHandler(CompleteRequestSchema, async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - return this.handleResourceCompletion(request, request.params.ref); - default: - throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - } - if (!prompt.argsSchema) { - return EMPTY_COMPLETION_RESULT; - } - const field = prompt.argsSchema.shape[request.params.argument.name]; - if (!(field instanceof Completable)) { - return EMPTY_COMPLETION_RESULT; - } - const def = field._def; - const suggestions = await def.complete(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) { - return EMPTY_COMPLETION_RESULT; - } - throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(ListResourcesRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(ListResourceTemplatesRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(ReadResourceRequestSchema.shape.method.value); - this.server.registerCapabilities({ - resources: { - listChanged: true - } - }); - this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) { - continue; - } - const result = await template.resourceTemplate.listCallback(extra); - for (const resource of result.resources) { - templateResources.push({ - ...template.metadata, - // the defined resource metadata should override the template metadata if present - ...resource - }); - } - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { - const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })); - return { resourceTemplates }; - }); - this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { - const uri = new URL(request.params.uri); - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); - } - return resource.readCallback(uri, extra); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) { - return template.readCallback(uri, variables, extra); - } - } - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); - }); - this.setCompletionRequestHandler(); - this._resourceHandlersInitialized = true; - } - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(ListPromptsRequestSchema.shape.method.value); - this.server.assertCanSetRequestHandler(GetPromptRequestSchema.shape.method.value); - this.server.registerCapabilities({ - prompts: { - listChanged: true - } - }); - this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ - prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0 - }; - }) - })); - this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - } - if (prompt.argsSchema) { - const parseResult = await prompt.argsSchema.safeParseAsync(request.params.arguments); - if (!parseResult.success) { - throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${parseResult.error.message}`); - } - const args = parseResult.data; - const cb = prompt.callback; - return await Promise.resolve(cb(args, extra)); - } else { - const cb = prompt.callback; - return await Promise.resolve(cb(extra)); - } - }); - this.setCompletionRequestHandler(); - this._promptHandlersInitialized = true; - } - resource(name, uriOrTemplate, ...rest) { - let metadata; - if (typeof rest[0] === "object") { - metadata = rest.shift(); - } - const readCallback = rest[0]; - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - registerResource(name, uriOrTemplate, config, readCallback) { - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (typeof updates.uri !== "undefined" && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) - this._registeredResources[updates.uri] = registeredResource; - } - if (typeof updates.name !== "undefined") - registeredResource.name = updates.name; - if (typeof updates.title !== "undefined") - registeredResource.title = updates.title; - if (typeof updates.metadata !== "undefined") - registeredResource.metadata = updates.metadata; - if (typeof updates.callback !== "undefined") - registeredResource.readCallback = updates.callback; - if (typeof updates.enabled !== "undefined") - registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (typeof updates.name !== "undefined" && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) - this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (typeof updates.title !== "undefined") - registeredResourceTemplate.title = updates.title; - if (typeof updates.template !== "undefined") - registeredResourceTemplate.resourceTemplate = updates.template; - if (typeof updates.metadata !== "undefined") - registeredResourceTemplate.metadata = updates.metadata; - if (typeof updates.callback !== "undefined") - registeredResourceTemplate.readCallback = updates.callback; - if (typeof updates.enabled !== "undefined") - registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback) { - const registeredPrompt = { - title, - description, - argsSchema: argsSchema === void 0 ? void 0 : external_exports.object(argsSchema), - callback, - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (typeof updates.name !== "undefined" && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) - this._registeredPrompts[updates.name] = registeredPrompt; - } - if (typeof updates.title !== "undefined") - registeredPrompt.title = updates.title; - if (typeof updates.description !== "undefined") - registeredPrompt.description = updates.description; - if (typeof updates.argsSchema !== "undefined") - registeredPrompt.argsSchema = external_exports.object(updates.argsSchema); - if (typeof updates.callback !== "undefined") - registeredPrompt.callback = updates.callback; - if (typeof updates.enabled !== "undefined") - registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, callback) { - const registeredTool = { - title, - description, - inputSchema: inputSchema === void 0 ? void 0 : external_exports.object(inputSchema), - outputSchema: outputSchema === void 0 ? void 0 : external_exports.object(outputSchema), - annotations, - callback, - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (typeof updates.name !== "undefined" && updates.name !== name) { - delete this._registeredTools[name]; - if (updates.name) - this._registeredTools[updates.name] = registeredTool; - } - if (typeof updates.title !== "undefined") - registeredTool.title = updates.title; - if (typeof updates.description !== "undefined") - registeredTool.description = updates.description; - if (typeof updates.paramsSchema !== "undefined") - registeredTool.inputSchema = external_exports.object(updates.paramsSchema); - if (typeof updates.callback !== "undefined") - registeredTool.callback = updates.callback; - if (typeof updates.annotations !== "undefined") - registeredTool.annotations = updates.annotations; - if (typeof updates.enabled !== "undefined") - registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - /** - * tool() implementation. Parses arguments passed to overrides defined above. - */ - tool(name, ...rest) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - let description; - let inputSchema; - let outputSchema; - let annotations; - if (typeof rest[0] === "string") { - description = rest.shift(); - } - if (rest.length > 1) { - const firstArg = rest[0]; - if (isZodRawShape(firstArg)) { - inputSchema = rest.shift(); - if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShape(rest[0])) { - annotations = rest.shift(); - } - } else if (typeof firstArg === "object" && firstArg !== null) { - annotations = rest.shift(); - } - } - const callback = rest[0]; - return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, callback); - } - /** - * Registers a tool with a config object and callback. - */ - registerTool(name, config, cb) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - const { title, description, inputSchema, outputSchema, annotations } = config; - return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, cb); - } - prompt(name, ...rest) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - let description; - if (typeof rest[0] === "string") { - description = rest.shift(); - } - let argsSchema; - if (rest.length > 1) { - argsSchema = rest.shift(); - } - const cb = rest[0]; - const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Registers a prompt with a config object and callback. - */ - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - const { title, description, argsSchema } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns True if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) { - this.server.sendResourceListChanged(); - } - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) { - this.server.sendToolListChanged(); - } - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) { - this.server.sendPromptListChanged(); - } - } -}; -var EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -function isZodRawShape(obj) { - if (typeof obj !== "object" || obj === null) - return false; - const isEmptyObject = Object.keys(obj).length === 0; - return isEmptyObject || Object.values(obj).some(isZodTypeLike); -} -function isZodTypeLike(value) { - return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function"; -} -function promptArgumentsFromSchema(schema) { - return Object.entries(schema.shape).map(([name, field]) => ({ - name, - description: field.description, - required: !field.isOptional() - })); -} -function createCompletionResult(suggestions) { - return { - completion: { - values: suggestions.slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } - }; -} -var EMPTY_COMPLETION_RESULT = { - completion: { - values: [], - hasMore: false - } -}; - -// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js -var import_node_process = __toESM(require("node:process"), 1); - -// 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/server/stdio.js -var StdioServerTransport = class { - constructor(_stdin = import_node_process.default.stdin, _stdout = import_node_process.default.stdout) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer(); - this._started = false; - this._ondata = (chunk) => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }; - this._onerror = (error) => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }; - } - /** - * Starts listening for messages on stdin. - */ - async start() { - if (this._started) { - throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); - } - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); - } - processReadBuffer() { - var _a, _b; - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); - } catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - } - async close() { - var _a; - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - const remainingDataListeners = this._stdin.listenerCount("data"); - if (remainingDataListeners === 0) { - this._stdin.pause(); - } - this._readBuffer.clear(); - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - } - send(message) { - return new Promise((resolve) => { - const json = serializeMessage(message); - if (this._stdout.write(json)) { - resolve(); - } else { - this._stdout.once("drain", resolve); - } - }); - } -}; - -// mcp-permissions.ts -var fs = __toESM(require("fs")); -var path = __toESM(require("path")); -var server = new McpServer({ - name: "Claude Code Permissions MCP Server", - version: "0.0.1" -}); +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __generator = (this && this.__generator) || function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js"); +var stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js"); +var zod_1 = require("zod"); +var fs = require("fs"); +var path = require("path"); +var server = new mcp_js_1.McpServer({ + name: "Claude Code Permissions MCP Server", + version: "0.0.1", +}); +// Get permissions directory from environment var PERMISSIONS_PATH = process.env.CLAUDE_PERMISSIONS_PATH; if (!PERMISSIONS_PATH) { - console.error("CLAUDE_PERMISSIONS_PATH environment variable not set"); - process.exit(1); + console.error("CLAUDE_PERMISSIONS_PATH environment variable not set"); + process.exit(1); } function getWorkspacePermissionsPath() { - if (!PERMISSIONS_PATH) return null; - return path.join(PERMISSIONS_PATH, "permissions.json"); + if (!PERMISSIONS_PATH) + return null; + return path.join(PERMISSIONS_PATH, 'permissions.json'); } function loadWorkspacePermissions() { - const permissionsPath = getWorkspacePermissionsPath(); - if (!permissionsPath || !fs.existsSync(permissionsPath)) { - return { alwaysAllow: {} }; - } - try { - const content = fs.readFileSync(permissionsPath, "utf8"); - return JSON.parse(content); - } catch (error) { - console.error(`Error loading workspace permissions: ${error}`); - return { alwaysAllow: {} }; - } + var permissionsPath = getWorkspacePermissionsPath(); + if (!permissionsPath || !fs.existsSync(permissionsPath)) { + return { alwaysAllow: {} }; + } + try { + var content = fs.readFileSync(permissionsPath, 'utf8'); + return JSON.parse(content); + } + catch (error) { + console.error("Error loading workspace permissions: ".concat(error)); + return { alwaysAllow: {} }; + } } function isAlwaysAllowed(toolName, input) { - const permissions = loadWorkspacePermissions(); - const toolPermission = permissions.alwaysAllow[toolName]; - if (!toolPermission) return false; - if (toolPermission === true) return true; - if (Array.isArray(toolPermission)) { - if (toolName === "Bash" && input.command) { - const command = input.command.trim(); - return toolPermission.some((allowedCmd) => { - if (allowedCmd.includes("*")) { - const baseCommand = allowedCmd.replace(" *", ""); - if (command === baseCommand) { - return true; - } - const pattern = allowedCmd.replace(/\*/g, ".*"); - return new RegExp(`^${pattern}$`).test(command); + var permissions = loadWorkspacePermissions(); + var toolPermission = permissions.alwaysAllow[toolName]; + if (!toolPermission) + return false; + // If it's true, always allow + if (toolPermission === true) + return true; + // If it's an array, check for specific commands (mainly for Bash) + if (Array.isArray(toolPermission)) { + if (toolName === 'Bash' && input.command) { + var command_1 = input.command.trim(); + return toolPermission.some(function (allowedCmd) { + // Support exact match or pattern matching + if (allowedCmd.includes('*')) { + // Handle patterns like "npm i *" to match both "npm i" and "npm i something" + var baseCommand = allowedCmd.replace(' *', ''); + if (command_1 === baseCommand) { + return true; // Exact match for base command + } + // Pattern match for command with arguments + var pattern = allowedCmd.replace(/\*/g, '.*'); + return new RegExp("^".concat(pattern, "$")).test(command_1); + } + return command_1.startsWith(allowedCmd); + }); } - return command.startsWith(allowedCmd); - }); } - } - return false; + return false; } function generateRequestId() { - return `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`; -} -async function requestPermission(tool_name, input) { - if (!PERMISSIONS_PATH) { - console.error("Permissions path not available"); - return { approved: false, reason: "Permissions path not configured" }; - } - if (isAlwaysAllowed(tool_name, input)) { - console.error(`Tool ${tool_name} is always allowed for this workspace`); - return { approved: true }; - } - const requestId = generateRequestId(); - const requestFile = path.join(PERMISSIONS_PATH, `${requestId}.request`); - const responseFile = path.join(PERMISSIONS_PATH, `${requestId}.response`); - const request = { - id: requestId, - tool: tool_name, - input, - timestamp: (/* @__PURE__ */ new Date()).toISOString() - }; - try { - fs.writeFileSync(requestFile, JSON.stringify(request, null, 2)); - return new Promise((resolve) => { - const timeout = setTimeout(() => { - watcher.close(); - if (fs.existsSync(requestFile)) { - fs.unlinkSync(requestFile); - } - console.error(`Permission request ${requestId} timed out`); - resolve({ approved: false, reason: "Permission request timed out" }); - }, 36e5); - const watcher = fs.watch(PERMISSIONS_PATH, (eventType, filename) => { - if (eventType === "rename" && filename === path.basename(responseFile)) { - if (fs.existsSync(responseFile)) { + return "req_".concat(Date.now(), "_").concat(Math.random().toString(36).substring(2, 9)); +} +function requestPermission(tool_name, input) { + return __awaiter(this, void 0, void 0, function () { + var requestId, requestFile, responseFile, request; + return __generator(this, function (_a) { + if (!PERMISSIONS_PATH) { + console.error("Permissions path not available"); + return [2 /*return*/, { approved: false, reason: "Permissions path not configured" }]; + } + // Check if this tool/command is always allowed for this workspace + if (isAlwaysAllowed(tool_name, input)) { + console.error("Tool ".concat(tool_name, " is always allowed for this workspace")); + return [2 /*return*/, { approved: true }]; + } + requestId = generateRequestId(); + requestFile = path.join(PERMISSIONS_PATH, "".concat(requestId, ".request")); + responseFile = path.join(PERMISSIONS_PATH, "".concat(requestId, ".response")); + request = { + id: requestId, + tool: tool_name, + input: input, + timestamp: new Date().toISOString() + }; try { - const responseContent = fs.readFileSync(responseFile, "utf8"); - const response = JSON.parse(responseContent); - fs.unlinkSync(responseFile); - clearTimeout(timeout); - watcher.close(); - resolve({ - approved: response.approved, - reason: response.approved ? void 0 : "User rejected the request" - }); - } catch (error) { - console.error(`Error reading response file: ${error}`); - } - } - } - }); - watcher.on("error", (error) => { - console.error(`File watcher error: ${error}`); - clearTimeout(timeout); - watcher.close(); - resolve({ approved: false, reason: "File watcher error" }); - }); - }); - } catch (error) { - console.error(`Error requesting permission: ${error}`); - return { approved: false, reason: `Error processing permission request: ${error}` }; - } -} -server.tool( - "approval_prompt", - "Request user permission to execute a tool via VS Code dialog", - { - tool_name: external_exports.string().describe("The name of the tool requesting permission"), - input: external_exports.object({}).passthrough().describe("The input for the tool"), - tool_use_id: external_exports.string().optional().describe("The unique tool use request ID") - }, - async ({ tool_name, input }) => { - console.error(`Requesting permission for tool: ${tool_name}`); - const permissionResult = await requestPermission(tool_name, input); - const behavior = permissionResult.approved ? "allow" : "deny"; - console.error(`Permission ${behavior}ed for tool: ${tool_name}`); - return { - content: [ - { - type: "text", - text: behavior === "allow" ? JSON.stringify({ - behavior, - updatedInput: input - }) : JSON.stringify({ - behavior, - message: permissionResult.reason || "Permission denied" - }) - } - ] - }; - } -); -async function main() { - const transport = new StdioServerTransport(); - await server.connect(transport); - console.error(`Permissions MCP Server running on stdio`); - console.error(`Using permissions directory: ${PERMISSIONS_PATH}`); -} -main().catch((error) => { - console.error("Fatal error in main():", error); - process.exit(1); + fs.writeFileSync(requestFile, JSON.stringify(request, null, 2)); + // Use fs.watch to wait for response file + return [2 /*return*/, new Promise(function (resolve) { + var timeout = setTimeout(function () { + watcher.close(); + // Clean up request file on timeout + if (fs.existsSync(requestFile)) { + fs.unlinkSync(requestFile); + } + console.error("Permission request ".concat(requestId, " timed out")); + resolve({ approved: false, reason: "Permission request timed out" }); + }, 3600000); // 1 hour timeout + var watcher = fs.watch(PERMISSIONS_PATH, function (eventType, filename) { + if (eventType === 'rename' && filename === path.basename(responseFile)) { + // Check if file exists (rename event can be for creation or deletion) + if (fs.existsSync(responseFile)) { + try { + var responseContent = fs.readFileSync(responseFile, 'utf8'); + var response = JSON.parse(responseContent); + // Clean up response file + fs.unlinkSync(responseFile); + // Clear timeout and close watcher + clearTimeout(timeout); + watcher.close(); + resolve({ + approved: response.approved, + reason: response.approved ? undefined : "User rejected the request" + }); + } + catch (error) { + console.error("Error reading response file: ".concat(error)); + // Continue watching in case of read error + } + } + } + }); + // Handle watcher errors + watcher.on('error', function (error) { + console.error("File watcher error: ".concat(error)); + clearTimeout(timeout); + watcher.close(); + resolve({ approved: false, reason: "File watcher error" }); + }); + })]; + } + catch (error) { + console.error("Error requesting permission: ".concat(error)); + return [2 /*return*/, { approved: false, reason: "Error processing permission request: ".concat(error) }]; + } + return [2 /*return*/]; + }); + }); +} +server.tool("approval_prompt", 'Request user permission to execute a tool via VS Code dialog', { + tool_name: zod_1.z.string().describe("The name of the tool requesting permission"), + input: zod_1.z.object({}).passthrough().describe("The input for the tool"), + tool_use_id: zod_1.z.string().optional().describe("The unique tool use request ID"), +}, function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) { + var permissionResult, behavior; + var tool_name = _b.tool_name, input = _b.input; + return __generator(this, function (_c) { + switch (_c.label) { + case 0: + console.error("Requesting permission for tool: ".concat(tool_name)); + return [4 /*yield*/, requestPermission(tool_name, input)]; + case 1: + permissionResult = _c.sent(); + behavior = permissionResult.approved ? "allow" : "deny"; + console.error("Permission ".concat(behavior, "ed for tool: ").concat(tool_name)); + return [2 /*return*/, { + content: [ + { + type: "text", + text: behavior === "allow" ? + JSON.stringify({ + behavior: behavior, + updatedInput: input, + }) + : + JSON.stringify({ + behavior: behavior, + message: permissionResult.reason || "Permission denied", + }), + }, + ], + }]; + } + }); +}); }); +function main() { + return __awaiter(this, void 0, void 0, function () { + var transport; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + transport = new stdio_js_1.StdioServerTransport(); + return [4 /*yield*/, server.connect(transport)]; + case 1: + _a.sent(); + console.error("Permissions MCP Server running on stdio"); + console.error("Using permissions directory: ".concat(PERMISSIONS_PATH)); + return [2 /*return*/]; + } + }); + }); +} +main().catch(function (error) { + console.error("Fatal error in main():", error); + process.exit(1); }); -/*! Bundled license information: - -uri-js/dist/es5/uri.all.js: - (** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *) -*/ diff --git a/package-lock.json b/package-lock.json index 82a87fc..1e3d15a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-code-chat", - "version": "1.0.0", + "version": "1.0.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-code-chat", - "version": "1.0.0", + "version": "1.0.6", "license": "SEE LICENSE IN LICENSE", "devDependencies": { "@types/mocha": "^10.0.10", diff --git a/src/extension.ts b/src/extension.ts index b27e2f5..2890058 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,10 +1,6 @@ import * as vscode from 'vscode'; -import * as cp from 'child_process'; -import * as util from 'util'; -import * as path from 'path'; -import getHtml from './ui'; - -const exec = util.promisify(cp.exec); +import { ClaudeChatProvider } from './providers/ClaudeChatProvider'; +import { ClaudeChatWebviewProvider } from './providers/ClaudeChatWebviewProvider'; export function activate(context: vscode.ExtensionContext) { console.log('Claude Code Chat extension is being activated!'); @@ -42,2366 +38,4 @@ export function activate(context: vscode.ExtensionContext) { console.log('Claude Code Chat extension activation completed successfully!'); } -export function deactivate() { } - -interface ConversationData { - sessionId: string; - startTime: string | undefined; - endTime: string; - messageCount: number; - totalCost: number; - totalTokens: { - input: number; - output: number; - }; - messages: Array<{ timestamp: string, messageType: string, data: any }>; - filename: string; -} - -class ClaudeChatWebviewProvider implements vscode.WebviewViewProvider { - constructor( - private readonly _extensionUri: vscode.Uri, - private readonly _context: vscode.ExtensionContext, - private readonly _chatProvider: ClaudeChatProvider - ) { } - - public resolveWebviewView( - webviewView: vscode.WebviewView, - _context: vscode.WebviewViewResolveContext, - _token: vscode.CancellationToken, - ) { - - webviewView.webview.options = { - enableScripts: true, - localResourceRoots: [this._extensionUri] - }; - - // Use the shared chat provider instance for the sidebar - this._chatProvider.showInWebview(webviewView.webview, webviewView); - - // Handle visibility changes to reinitialize when sidebar reopens - webviewView.onDidChangeVisibility(() => { - if (webviewView.visible) { - // Close main panel when sidebar becomes visible - if (this._chatProvider._panel) { - console.log('Closing main panel because sidebar became visible'); - this._chatProvider._panel.dispose(); - this._chatProvider._panel = undefined; - } - this._chatProvider.reinitializeWebview(); - } - }); - } -} - - -class ClaudeChatProvider { - public _panel: vscode.WebviewPanel | undefined; - private _webview: vscode.Webview | undefined; - private _webviewView: vscode.WebviewView | undefined; - private _disposables: vscode.Disposable[] = []; - private _messageHandlerDisposable: vscode.Disposable | undefined; - private _totalCost: number = 0; - private _totalTokensInput: number = 0; - private _totalTokensOutput: number = 0; - private _requestCount: number = 0; - private _currentSessionId: string | undefined; - private _backupRepoPath: string | undefined; - private _commits: Array<{ id: string, sha: string, message: string, timestamp: string }> = []; - private _conversationsPath: string | undefined; - private _permissionRequestsPath: string | undefined; - private _permissionWatcher: vscode.FileSystemWatcher | undefined; - private _pendingPermissionResolvers: Map void> | undefined; - private _currentConversation: Array<{ timestamp: string, messageType: string, data: any }> = []; - private _conversationStartTime: string | undefined; - private _conversationIndex: Array<{ - filename: string, - sessionId: string, - startTime: string, - endTime: string, - messageCount: number, - totalCost: number, - firstUserMessage: string, - lastUserMessage: string - }> = []; - private _currentClaudeProcess: cp.ChildProcess | undefined; - private _selectedModel: string = 'default'; // Default model - private _isProcessing: boolean | undefined; - private _draftMessage: string = ''; - - constructor( - private readonly _extensionUri: vscode.Uri, - private readonly _context: vscode.ExtensionContext - ) { - - // Initialize backup repository and conversations - this._initializeBackupRepo(); - this._initializeConversations(); - this._initializeMCPConfig(); - - // Load conversation index from workspace state - this._conversationIndex = this._context.workspaceState.get('claude.conversationIndex', []); - - // Load saved model preference - this._selectedModel = this._context.workspaceState.get('claude.selectedModel', 'default'); - - // Resume session from latest conversation - const latestConversation = this._getLatestConversation(); - this._currentSessionId = latestConversation?.sessionId; - } - - public show(column: vscode.ViewColumn | vscode.Uri = vscode.ViewColumn.Two) { - // Handle case where a URI is passed instead of ViewColumn - const actualColumn = column instanceof vscode.Uri ? vscode.ViewColumn.Two : column; - - // Close sidebar if it's open - this._closeSidebar(); - - if (this._panel) { - this._panel.reveal(actualColumn); - return; - } - - this._panel = vscode.window.createWebviewPanel( - 'claudeChat', - 'Claude Code Chat', - actualColumn, - { - enableScripts: true, - retainContextWhenHidden: true, - localResourceRoots: [this._extensionUri] - } - ); - - // Set icon for the webview tab using URI path - const iconPath = vscode.Uri.joinPath(this._extensionUri, 'icon.png'); - this._panel.iconPath = iconPath; - - this._panel.webview.html = this._getHtmlForWebview(); - - this._panel.onDidDispose(() => this.dispose(), null, this._disposables); - - this._setupWebviewMessageHandler(this._panel.webview); - this._initializePermissions(); - - // Resume session from latest conversation - const latestConversation = this._getLatestConversation(); - this._currentSessionId = latestConversation?.sessionId; - - // Load latest conversation history if available - if (latestConversation) { - this._loadConversationHistory(latestConversation.filename); - } - - // Send ready message immediately - setTimeout(() => { - // If no conversation to load, send ready immediately - if (!latestConversation) { - this._sendReadyMessage(); - } - }, 100); - } - - private _postMessage(message: any) { - if (this._panel && this._panel.webview) { - this._panel.webview.postMessage(message); - } else if (this._webview) { - this._webview.postMessage(message); - } - } - - private _sendReadyMessage() { - // Send current session info if available - /*if (this._currentSessionId) { - this._postMessage({ - type: 'sessionResumed', - data: { - sessionId: this._currentSessionId - } - }); - }*/ - - this._postMessage({ - type: 'ready', - data: this._isProcessing ? 'Claude is working...' : 'Ready to chat with Claude Code! Type your message below.' - }); - - // Send current model to webview - this._postMessage({ - type: 'modelSelected', - model: this._selectedModel - }); - - // Send platform information to webview - this._sendPlatformInfo(); - - // Send current settings to webview - this._sendCurrentSettings(); - - // Send saved draft message if any - if (this._draftMessage) { - this._postMessage({ - type: 'restoreInputText', - data: this._draftMessage - }); - } - } - - private _handleWebviewMessage(message: any) { - switch (message.type) { - case 'sendMessage': - this._sendMessageToClaude(message.text, message.planMode, message.thinkingMode); - return; - case 'newSession': - this._newSession(); - return; - case 'restoreCommit': - this._restoreToCommit(message.commitSha); - return; - case 'getConversationList': - this._sendConversationList(); - return; - case 'getWorkspaceFiles': - this._sendWorkspaceFiles(message.searchTerm); - return; - case 'selectImageFile': - this._selectImageFile(); - return; - case 'loadConversation': - this.loadConversation(message.filename); - return; - case 'stopRequest': - this._stopClaudeProcess(); - return; - case 'getSettings': - this._sendCurrentSettings(); - return; - case 'updateSettings': - this._updateSettings(message.settings); - return; - case 'getClipboardText': - this._getClipboardText(); - return; - case 'selectModel': - this._setSelectedModel(message.model); - return; - case 'openModelTerminal': - this._openModelTerminal(); - return; - case 'executeSlashCommand': - this._executeSlashCommand(message.command); - return; - case 'dismissWSLAlert': - this._dismissWSLAlert(); - return; - case 'openFile': - this._openFileInEditor(message.filePath); - return; - case 'createImageFile': - this._createImageFile(message.imageData, message.imageType); - return; - case 'permissionResponse': - this._handlePermissionResponse(message.id, message.approved, message.alwaysAllow); - return; - case 'getPermissions': - this._sendPermissions(); - return; - case 'removePermission': - this._removePermission(message.toolName, message.command); - return; - case 'addPermission': - this._addPermission(message.toolName, message.command); - return; - case 'loadMCPServers': - this._loadMCPServers(); - return; - case 'saveMCPServer': - this._saveMCPServer(message.name, message.config); - return; - case 'deleteMCPServer': - this._deleteMCPServer(message.name); - return; - case 'getCustomSnippets': - this._sendCustomSnippets(); - return; - case 'saveCustomSnippet': - this._saveCustomSnippet(message.snippet); - return; - case 'deleteCustomSnippet': - this._deleteCustomSnippet(message.snippetId); - return; - case 'enableYoloMode': - this._enableYoloMode(); - return; - case 'saveInputText': - this._saveInputText(message.text); - return; - } - } - - private _setupWebviewMessageHandler(webview: vscode.Webview) { - // Dispose of any existing message handler - if (this._messageHandlerDisposable) { - this._messageHandlerDisposable.dispose(); - } - - // Set up new message handler - this._messageHandlerDisposable = webview.onDidReceiveMessage( - message => this._handleWebviewMessage(message), - null, - this._disposables - ); - } - - private _closeSidebar() { - if (this._webviewView) { - // Switch VS Code to show Explorer view instead of chat sidebar - vscode.commands.executeCommand('workbench.view.explorer'); - } - } - - public showInWebview(webview: vscode.Webview, webviewView?: vscode.WebviewView) { - // Close main panel if it's open - if (this._panel) { - console.log('Closing main panel because sidebar is opening'); - this._panel.dispose(); - this._panel = undefined; - } - - this._webview = webview; - this._webviewView = webviewView; - this._webview.html = this._getHtmlForWebview(); - - this._setupWebviewMessageHandler(this._webview); - this._initializePermissions(); - - // Initialize the webview - this._initializeWebview(); - } - - private _initializeWebview() { - // Resume session from latest conversation - const latestConversation = this._getLatestConversation(); - this._currentSessionId = latestConversation?.sessionId; - - // Load latest conversation history if available - if (latestConversation) { - this._loadConversationHistory(latestConversation.filename); - } else { - // If no conversation to load, send ready immediately - setTimeout(() => { - this._sendReadyMessage(); - }, 100); - } - } - - public reinitializeWebview() { - // Only reinitialize if we have a webview (sidebar) - if (this._webview) { - this._initializePermissions(); - this._initializeWebview(); - // Set up message handler for the webview - this._setupWebviewMessageHandler(this._webview); - } - } - - private async _sendMessageToClaude(message: string, planMode?: boolean, thinkingMode?: boolean) { - const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; - const cwd = workspaceFolder ? workspaceFolder.uri.fsPath : process.cwd(); - - // Get thinking intensity setting - const configThink = vscode.workspace.getConfiguration('claudeCodeChat'); - const thinkingIntensity = configThink.get('thinking.intensity', 'think'); - - // Prepend mode instructions if enabled - let actualMessage = message; - if (planMode) { - actualMessage = 'PLAN FIRST FOR THIS MESSAGE ONLY: Plan first before making any changes. Show me in detail what you will change and wait for my explicit approval in a separate message before proceeding. Do not implement anything until I confirm. This planning requirement applies ONLY to this current message. \n\n' + message; - } - if (thinkingMode) { - let thinkingPrompt = ''; - const thinkingMesssage = ' THROUGH THIS STEP BY STEP: \n' - switch (thinkingIntensity) { - case 'think': - thinkingPrompt = 'THINK'; - break; - case 'think-hard': - thinkingPrompt = 'THINK HARD'; - break; - case 'think-harder': - thinkingPrompt = 'THINK HARDER'; - break; - case 'ultrathink': - thinkingPrompt = 'ULTRATHINK'; - break; - default: - thinkingPrompt = 'THINK'; - } - actualMessage = thinkingPrompt + thinkingMesssage + actualMessage; - } - - this._isProcessing = true; - - // Clear draft message since we're sending it - this._draftMessage = ''; - - // Show original user input in chat and save to conversation (without mode prefixes) - this._sendAndSaveMessage({ - type: 'userInput', - data: message - }); - - // Set processing state to true - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: true } - }); - - // Create backup commit before Claude makes changes - try { - await this._createBackupCommit(message); - } - catch (e) { - console.log("error", e); - } - - // Show loading indicator - this._postMessage({ - type: 'loading', - data: 'Claude is working...' - }); - - // Build command arguments with session management - const args = [ - '-p', - '--output-format', 'stream-json', '--verbose' - ]; - - // Get configuration - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - const yoloMode = config.get('permissions.yoloMode', false); - - if (yoloMode) { - // Yolo mode: skip all permissions regardless of MCP config - args.push('--dangerously-skip-permissions'); - } else { - // Add MCP configuration for permissions - const mcpConfigPath = this.getMCPConfigPath(); - if (mcpConfigPath) { - args.push('--mcp-config', this.convertToWSLPath(mcpConfigPath)); - args.push('--allowedTools', 'mcp__claude-code-chat-permissions__approval_prompt'); - args.push('--permission-prompt-tool', 'mcp__claude-code-chat-permissions__approval_prompt'); - } - } - - // Add model selection if not using default - if (this._selectedModel && this._selectedModel !== 'default') { - args.push('--model', this._selectedModel); - } - - // Add session resume if we have a current session - if (this._currentSessionId) { - args.push('--resume', this._currentSessionId); - console.log('Resuming session:', this._currentSessionId); - } else { - console.log('Starting new session'); - } - - console.log('Claude command args:', args); - const wslEnabled = config.get('wsl.enabled', false); - const wslDistro = config.get('wsl.distro', 'Ubuntu'); - const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); - const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); - - let claudeProcess: cp.ChildProcess; - - if (wslEnabled) { - // Use WSL with bash -ic for proper environment loading - console.log('Using WSL configuration:', { wslDistro, nodePath, claudePath }); - const wslCommand = `"${nodePath}" --no-warnings --enable-source-maps "${claudePath}" ${args.join(' ')}`; - - claudeProcess = cp.spawn('wsl', ['-d', wslDistro, 'bash', '-ic', wslCommand], { - cwd: cwd, - stdio: ['pipe', 'pipe', 'pipe'], - env: { - ...process.env, - FORCE_COLOR: '0', - NO_COLOR: '1' - } - }); - } else { - // Use native claude command - console.log('Using native Claude command'); - claudeProcess = cp.spawn('claude', args, { - shell: process.platform === 'win32', - cwd: cwd, - stdio: ['pipe', 'pipe', 'pipe'], - env: { - ...process.env, - FORCE_COLOR: '0', - NO_COLOR: '1' - } - }); - } - - // Store process reference for potential termination - this._currentClaudeProcess = claudeProcess; - - // Send the message to Claude's stdin (with mode prefixes if enabled) - if (claudeProcess.stdin) { - claudeProcess.stdin.write(actualMessage + '\n'); - claudeProcess.stdin.end(); - } - - let rawOutput = ''; - let errorOutput = ''; - - if (claudeProcess.stdout) { - claudeProcess.stdout.on('data', (data) => { - rawOutput += data.toString(); - - // Process JSON stream line by line - const lines = rawOutput.split('\n'); - rawOutput = lines.pop() || ''; // Keep incomplete line for next chunk - - for (const line of lines) { - if (line.trim()) { - try { - const jsonData = JSON.parse(line.trim()); - this._processJsonStreamData(jsonData); - } catch (error) { - console.log('Failed to parse JSON line:', line, error); - } - } - } - }); - } - - if (claudeProcess.stderr) { - claudeProcess.stderr.on('data', (data) => { - errorOutput += data.toString(); - }); - } - - claudeProcess.on('close', (code) => { - console.log('Claude process closed with code:', code); - console.log('Claude stderr output:', errorOutput); - - if (!this._currentClaudeProcess) { - return; - } - - // Clear process reference - this._currentClaudeProcess = undefined; - - // Clear loading indicator and set processing to false - this._postMessage({ - type: 'clearLoading' - }); - - // Reset processing state - this._isProcessing = false; - - // Clear processing state - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: false } - }); - - if (code !== 0 && errorOutput.trim()) { - // Error with output - this._sendAndSaveMessage({ - type: 'error', - data: errorOutput.trim() - }); - } - }); - - claudeProcess.on('error', (error) => { - console.log('Claude process error:', error.message); - - if (!this._currentClaudeProcess) { - return; - } - - // Clear process reference - this._currentClaudeProcess = undefined; - - this._postMessage({ - type: 'clearLoading' - }); - - this._isProcessing = false; - - // Clear processing state - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: false } - }); - - // Check if claude command is not installed - if (error.message.includes('ENOENT') || error.message.includes('command not found')) { - this._sendAndSaveMessage({ - type: 'error', - data: 'Install claude code first: https://www.anthropic.com/claude-code' - }); - } else { - this._sendAndSaveMessage({ - type: 'error', - data: `Error running Claude: ${error.message}` - }); - } - }); - } - - private _processJsonStreamData(jsonData: any) { - switch (jsonData.type) { - case 'system': - if (jsonData.subtype === 'init') { - // System initialization message - session ID will be captured from final result - console.log('System initialized'); - this._currentSessionId = jsonData.session_id; - //this._sendAndSaveMessage({ type: 'init', data: { sessionId: jsonData.session_id; } }) - - // Show session info in UI - this._sendAndSaveMessage({ - type: 'sessionInfo', - data: { - sessionId: jsonData.session_id, - tools: jsonData.tools || [], - mcpServers: jsonData.mcp_servers || [] - } - }); - } - break; - - case 'assistant': - if (jsonData.message && jsonData.message.content) { - // Track token usage in real-time if available - if (jsonData.message.usage) { - this._totalTokensInput += jsonData.message.usage.input_tokens || 0; - this._totalTokensOutput += jsonData.message.usage.output_tokens || 0; - - // Send real-time token update to webview - this._sendAndSaveMessage({ - type: 'updateTokens', - data: { - totalTokensInput: this._totalTokensInput, - totalTokensOutput: this._totalTokensOutput, - currentInputTokens: jsonData.message.usage.input_tokens || 0, - currentOutputTokens: jsonData.message.usage.output_tokens || 0, - cacheCreationTokens: jsonData.message.usage.cache_creation_input_tokens || 0, - cacheReadTokens: jsonData.message.usage.cache_read_input_tokens || 0 - } - }); - } - - // Process each content item in the assistant message - for (const content of jsonData.message.content) { - if (content.type === 'text' && content.text.trim()) { - // Show text content and save to conversation - this._sendAndSaveMessage({ - type: 'output', - data: content.text.trim() - }); - } else if (content.type === 'thinking' && content.thinking.trim()) { - // Show thinking content and save to conversation - this._sendAndSaveMessage({ - type: 'thinking', - data: content.thinking.trim() - }); - } else if (content.type === 'tool_use') { - // Show tool execution with better formatting - const toolInfo = `๐Ÿ”ง Executing: ${content.name}`; - let toolInput = ''; - - if (content.input) { - // Special formatting for TodoWrite to make it more readable - if (content.name === 'TodoWrite' && content.input.todos) { - toolInput = '\nTodo List Update:'; - for (const todo of content.input.todos) { - const status = todo.status === 'completed' ? 'โœ…' : - todo.status === 'in_progress' ? '๐Ÿ”„' : 'โณ'; - toolInput += `\n${status} ${todo.content} (priority: ${todo.priority})`; - } - } else { - // Send raw input to UI for formatting - toolInput = ''; - } - } - - // Show tool use and save to conversation - this._sendAndSaveMessage({ - type: 'toolUse', - data: { - toolInfo: toolInfo, - toolInput: toolInput, - rawInput: content.input, - toolName: content.name - } - }); - } - } - } - break; - - case 'user': - if (jsonData.message && jsonData.message.content) { - // Process tool results from user messages - for (const content of jsonData.message.content) { - if (content.type === 'tool_result') { - let resultContent = content.content || 'Tool executed successfully'; - - // Stringify if content is an object or array - if (typeof resultContent === 'object' && resultContent !== null) { - resultContent = JSON.stringify(resultContent, null, 2); - } - - const isError = content.is_error || false; - - // Find the last tool use to get the tool name - const lastToolUse = this._currentConversation[this._currentConversation.length - 1] - - const toolName = lastToolUse?.data?.toolName; - - // Don't send tool result for Read and Edit tools unless there's an error - if ((toolName === 'Read' || toolName === 'Edit' || toolName === 'TodoWrite' || toolName === 'MultiEdit') && !isError) { - // Still send to UI to hide loading state, but mark it as hidden - this._sendAndSaveMessage({ - type: 'toolResult', - data: { - content: resultContent, - isError: isError, - toolUseId: content.tool_use_id, - toolName: toolName, - hidden: true - } - }); - } else { - // Show tool result and save to conversation - this._sendAndSaveMessage({ - type: 'toolResult', - data: { - content: resultContent, - isError: isError, - toolUseId: content.tool_use_id, - toolName: toolName - } - }); - } - } - } - } - break; - - case 'result': - if (jsonData.subtype === 'success') { - // Check for login errors - if (jsonData.is_error && jsonData.result && jsonData.result.includes('Invalid API key')) { - this._handleLoginRequired(); - return; - } - - this._isProcessing = false; - - // Capture session ID from final result - if (jsonData.session_id) { - const isNewSession = !this._currentSessionId; - const sessionChanged = this._currentSessionId && this._currentSessionId !== jsonData.session_id; - - console.log('Session ID found in result:', { - sessionId: jsonData.session_id, - isNewSession, - sessionChanged, - currentSessionId: this._currentSessionId - }); - - this._currentSessionId = jsonData.session_id; - - // Show session info in UI - this._sendAndSaveMessage({ - type: 'sessionInfo', - data: { - sessionId: jsonData.session_id, - tools: jsonData.tools || [], - mcpServers: jsonData.mcp_servers || [] - } - }); - } - - // Clear processing state - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: false } - }); - - // Update cumulative tracking - this._requestCount++; - if (jsonData.total_cost_usd) { - this._totalCost += jsonData.total_cost_usd; - } - - console.log('Result received:', { - cost: jsonData.total_cost_usd, - duration: jsonData.duration_ms, - turns: jsonData.num_turns - }); - - // Send updated totals to webview - this._postMessage({ - type: 'updateTotals', - data: { - totalCost: this._totalCost, - totalTokensInput: this._totalTokensInput, - totalTokensOutput: this._totalTokensOutput, - requestCount: this._requestCount, - currentCost: jsonData.total_cost_usd, - currentDuration: jsonData.duration_ms, - currentTurns: jsonData.num_turns - } - }); - } - break; - } - } - - - private _newSession() { - - this._isProcessing = false - - // Update UI state - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: false } - }); - - // Try graceful termination first - if (this._currentClaudeProcess) { - const processToKill = this._currentClaudeProcess; - this._currentClaudeProcess = undefined; - processToKill.kill('SIGTERM'); - } - - // Clear current session - this._currentSessionId = undefined; - - // Clear commits and conversation - this._commits = []; - this._currentConversation = []; - this._conversationStartTime = undefined; - - // Reset counters - this._totalCost = 0; - this._totalTokensInput = 0; - this._totalTokensOutput = 0; - this._requestCount = 0; - - // Notify webview to clear all messages and reset session - this._postMessage({ - type: 'sessionCleared' - }); - } - - public newSessionOnConfigChange() { - // Reinitialize MCP config with new WSL paths - this._initializeMCPConfig(); - - // Start a new session due to configuration change - this._newSession(); - - // Show notification to user - vscode.window.showInformationMessage( - 'WSL configuration changed. Started a new Claude session.', - 'OK' - ); - - // Send message to webview about the config change - this._sendAndSaveMessage({ - type: 'configChanged', - data: 'โš™๏ธ WSL configuration changed. Started a new session.' - }); - } - - private _handleLoginRequired() { - - this._isProcessing = false; - - // Clear processing state - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: false } - }); - - // Show login required message - this._postMessage({ - type: 'loginRequired' - }); - - // Get configuration to check if WSL is enabled - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - const wslEnabled = config.get('wsl.enabled', false); - const wslDistro = config.get('wsl.distro', 'Ubuntu'); - const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); - const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); - - // Open terminal and run claude login - const terminal = vscode.window.createTerminal('Claude Login'); - if (wslEnabled) { - terminal.sendText(`wsl -d ${wslDistro} ${nodePath} --no-warnings --enable-source-maps ${claudePath}`); - } else { - terminal.sendText('claude'); - } - terminal.show(); - - // Show info message - vscode.window.showInformationMessage( - 'Please login to Claude in the terminal, then come back to this chat to continue.', - 'OK' - ); - - // Send message to UI about terminal - this._postMessage({ - type: 'terminalOpened', - data: `Please login to Claude in the terminal, then come back to this chat to continue.`, - }); - } - - private async _initializeBackupRepo(): Promise { - try { - const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; - if (!workspaceFolder) { return; } - - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) { - console.error('No workspace storage available'); - return; - } - console.log('Workspace storage path:', storagePath); - this._backupRepoPath = path.join(storagePath, 'backups', '.git'); - - // Create backup git directory if it doesn't exist - try { - await vscode.workspace.fs.stat(vscode.Uri.file(this._backupRepoPath)); - } catch { - await vscode.workspace.fs.createDirectory(vscode.Uri.file(this._backupRepoPath)); - - const workspacePath = workspaceFolder.uri.fsPath; - - // Initialize git repo with workspace as work-tree - await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" init`); - await exec(`git --git-dir="${this._backupRepoPath}" config user.name "Claude Code Chat"`); - await exec(`git --git-dir="${this._backupRepoPath}" config user.email "claude@anthropic.com"`); - - console.log(`Initialized backup repository at: ${this._backupRepoPath}`); - } - } catch (error: any) { - console.error('Failed to initialize backup repository:', error.message); - } - } - - private async _createBackupCommit(userMessage: string): Promise { - try { - const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; - if (!workspaceFolder || !this._backupRepoPath) { return; } - - const workspacePath = workspaceFolder.uri.fsPath; - const now = new Date(); - const timestamp = now.toISOString().replace(/[:.]/g, '-'); - const displayTimestamp = now.toISOString(); - const commitMessage = `Before: ${userMessage.substring(0, 50)}${userMessage.length > 50 ? '...' : ''}`; - - // Add all files using git-dir and work-tree (excludes .git automatically) - await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" add -A`); - - // Check if this is the first commit (no HEAD exists yet) - let isFirstCommit = false; - try { - await exec(`git --git-dir="${this._backupRepoPath}" rev-parse HEAD`); - } catch { - isFirstCommit = true; - } - - // Check if there are changes to commit - const { stdout: status } = await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" status --porcelain`); - - // Always create a checkpoint, even if no files changed - let actualMessage; - if (isFirstCommit) { - actualMessage = `Initial backup: ${userMessage.substring(0, 50)}${userMessage.length > 50 ? '...' : ''}`; - } else if (status.trim()) { - actualMessage = commitMessage; - } else { - actualMessage = `Checkpoint (no changes): ${userMessage.substring(0, 50)}${userMessage.length > 50 ? '...' : ''}`; - } - - // Create commit with --allow-empty to ensure checkpoint is always created - await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" commit --allow-empty -m "${actualMessage}"`); - const { stdout: sha } = await exec(`git --git-dir="${this._backupRepoPath}" rev-parse HEAD`); - - // Store commit info - const commitInfo = { - id: `commit-${timestamp}`, - sha: sha.trim(), - message: actualMessage, - timestamp: displayTimestamp - }; - - this._commits.push(commitInfo); - - // Show restore option in UI and save to conversation - this._sendAndSaveMessage({ - type: 'showRestoreOption', - data: commitInfo - }); - - console.log(`Created backup commit: ${commitInfo.sha.substring(0, 8)} - ${actualMessage}`); - } catch (error: any) { - console.error('Failed to create backup commit:', error.message); - } - } - - - private async _restoreToCommit(commitSha: string): Promise { - try { - const commit = this._commits.find(c => c.sha === commitSha); - if (!commit) { - this._postMessage({ - type: 'restoreError', - data: 'Commit not found' - }); - return; - } - - const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; - if (!workspaceFolder || !this._backupRepoPath) { - vscode.window.showErrorMessage('No workspace folder or backup repository available.'); - return; - } - - const workspacePath = workspaceFolder.uri.fsPath; - - this._postMessage({ - type: 'restoreProgress', - data: 'Restoring files from backup...' - }); - - // Restore files directly to workspace using git checkout - await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" checkout ${commitSha} -- .`); - - vscode.window.showInformationMessage(`Restored to commit: ${commit.message}`); - - this._sendAndSaveMessage({ - type: 'restoreSuccess', - data: { - message: `Successfully restored to: ${commit.message}`, - commitSha: commitSha - } - }); - - } catch (error: any) { - console.error('Failed to restore commit:', error.message); - vscode.window.showErrorMessage(`Failed to restore commit: ${error.message}`); - this._postMessage({ - type: 'restoreError', - data: `Failed to restore: ${error.message}` - }); - } - } - - private async _initializeConversations(): Promise { - try { - const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; - if (!workspaceFolder) { return; } - - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) { return; } - - this._conversationsPath = path.join(storagePath, 'conversations'); - - // Create conversations directory if it doesn't exist - try { - await vscode.workspace.fs.stat(vscode.Uri.file(this._conversationsPath)); - } catch { - await vscode.workspace.fs.createDirectory(vscode.Uri.file(this._conversationsPath)); - console.log(`Created conversations directory at: ${this._conversationsPath}`); - } - } catch (error: any) { - console.error('Failed to initialize conversations directory:', error.message); - } - } - - private async _initializeMCPConfig(): Promise { - try { - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) { return; } - - // Create MCP config directory - const mcpConfigDir = path.join(storagePath, 'mcp'); - try { - await vscode.workspace.fs.stat(vscode.Uri.file(mcpConfigDir)); - } catch { - await vscode.workspace.fs.createDirectory(vscode.Uri.file(mcpConfigDir)); - console.log(`Created MCP config directory at: ${mcpConfigDir}`); - } - - // Create or update mcp-servers.json with permissions server, preserving existing servers - const mcpConfigPath = path.join(mcpConfigDir, 'mcp-servers.json'); - const mcpPermissionsPath = this.convertToWSLPath(path.join(this._extensionUri.fsPath, 'mcp-permissions.js')); - const permissionRequestsPath = this.convertToWSLPath(path.join(storagePath, 'permission-requests')); - - // Load existing config or create new one - let mcpConfig: any = { mcpServers: {} }; - const mcpConfigUri = vscode.Uri.file(mcpConfigPath); - - try { - const existingContent = await vscode.workspace.fs.readFile(mcpConfigUri); - mcpConfig = JSON.parse(new TextDecoder().decode(existingContent)); - console.log('Loaded existing MCP config, preserving user servers'); - } catch { - console.log('No existing MCP config found, creating new one'); - } - - // Ensure mcpServers exists - if (!mcpConfig.mcpServers) { - mcpConfig.mcpServers = {}; - } - - // Add or update the permissions server entry - mcpConfig.mcpServers['claude-code-chat-permissions'] = { - command: 'node', - args: [mcpPermissionsPath], - env: { - CLAUDE_PERMISSIONS_PATH: permissionRequestsPath - } - }; - - const configContent = new TextEncoder().encode(JSON.stringify(mcpConfig, null, 2)); - await vscode.workspace.fs.writeFile(mcpConfigUri, configContent); - - console.log(`Updated MCP config at: ${mcpConfigPath}`); - } catch (error: any) { - console.error('Failed to initialize MCP config:', error.message); - } - } - - private async _initializePermissions(): Promise { - try { - - if (this._permissionWatcher) { - this._permissionWatcher.dispose(); - this._permissionWatcher = undefined; - } - - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) { return; } - - // Create permission requests directory - this._permissionRequestsPath = path.join(path.join(storagePath, 'permission-requests')); - try { - await vscode.workspace.fs.stat(vscode.Uri.file(this._permissionRequestsPath)); - } catch { - await vscode.workspace.fs.createDirectory(vscode.Uri.file(this._permissionRequestsPath)); - console.log(`Created permission requests directory at: ${this._permissionRequestsPath}`); - } - - console.log("DIRECTORY-----", this._permissionRequestsPath) - - // Set up file watcher for *.request files - this._permissionWatcher = vscode.workspace.createFileSystemWatcher( - new vscode.RelativePattern(this._permissionRequestsPath, '*.request') - ); - - this._permissionWatcher.onDidCreate(async (uri) => { - // Only handle file scheme URIs, ignore vscode-userdata scheme - if (uri.scheme === 'file') { - await this._handlePermissionRequest(uri); - } - }); - - this._disposables.push(this._permissionWatcher); - - } catch (error: any) { - console.error('Failed to initialize permissions:', error.message); - } - } - - private async _handlePermissionRequest(requestUri: vscode.Uri): Promise { - try { - // Read the request file - const content = await vscode.workspace.fs.readFile(requestUri); - const request = JSON.parse(new TextDecoder().decode(content)); - - // Show permission dialog - const approved = await this._showPermissionDialog(request); - - // Write response file - const responseFile = requestUri.fsPath.replace('.request', '.response'); - const response = { - id: request.id, - approved: approved, - timestamp: new Date().toISOString() - }; - - const responseContent = new TextEncoder().encode(JSON.stringify(response)); - await vscode.workspace.fs.writeFile(vscode.Uri.file(responseFile), responseContent); - - // Clean up request file - await vscode.workspace.fs.delete(requestUri); - - } catch (error: any) { - console.error('Failed to handle permission request:', error.message); - } - } - - private async _showPermissionDialog(request: any): Promise { - const toolName = request.tool || 'Unknown Tool'; - - // Generate pattern for Bash commands - let pattern = undefined; - if (toolName === 'Bash' && request.input?.command) { - pattern = this.getCommandPattern(request.input.command); - } - - // Send permission request to the UI - this._sendAndSaveMessage({ - type: 'permissionRequest', - data: { - id: request.id, - tool: toolName, - input: request.input, - pattern: pattern - } - }); - - // Wait for response from UI - return new Promise((resolve) => { - // Store the resolver so we can call it when we get the response - this._pendingPermissionResolvers = this._pendingPermissionResolvers || new Map(); - this._pendingPermissionResolvers.set(request.id, resolve); - }); - } - - private _handlePermissionResponse(id: string, approved: boolean, alwaysAllow?: boolean): void { - if (this._pendingPermissionResolvers && this._pendingPermissionResolvers.has(id)) { - const resolver = this._pendingPermissionResolvers.get(id); - if (resolver) { - resolver(approved); - this._pendingPermissionResolvers.delete(id); - - // Handle always allow setting - if (alwaysAllow && approved) { - void this._saveAlwaysAllowPermission(id); - } - } - } - } - - private async _saveAlwaysAllowPermission(requestId: string): Promise { - try { - // Read the original request to get tool name and input - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) return; - - const requestFileUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', `${requestId}.request`)); - - let requestContent: Uint8Array; - try { - requestContent = await vscode.workspace.fs.readFile(requestFileUri); - } catch { - return; // Request file doesn't exist - } - - const request = JSON.parse(new TextDecoder().decode(requestContent)); - - // Load existing workspace permissions - const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); - let permissions: any = { alwaysAllow: {} }; - - try { - const content = await vscode.workspace.fs.readFile(permissionsUri); - permissions = JSON.parse(new TextDecoder().decode(content)); - } catch { - // File doesn't exist yet, use default permissions - } - - // Add the new permission - const toolName = request.tool; - if (toolName === 'Bash' && request.input?.command) { - // For Bash, store the command pattern - if (!permissions.alwaysAllow[toolName]) { - permissions.alwaysAllow[toolName] = []; - } - if (Array.isArray(permissions.alwaysAllow[toolName])) { - const command = request.input.command.trim(); - const pattern = this.getCommandPattern(command); - if (!permissions.alwaysAllow[toolName].includes(pattern)) { - permissions.alwaysAllow[toolName].push(pattern); - } - } - } else { - // For other tools, allow all instances - permissions.alwaysAllow[toolName] = true; - } - - // Ensure permissions directory exists - const permissionsDir = vscode.Uri.file(path.dirname(permissionsUri.fsPath)); - try { - await vscode.workspace.fs.stat(permissionsDir); - } catch { - await vscode.workspace.fs.createDirectory(permissionsDir); - } - - // Save the permissions - const permissionsContent = new TextEncoder().encode(JSON.stringify(permissions, null, 2)); - await vscode.workspace.fs.writeFile(permissionsUri, permissionsContent); - - console.log(`Saved always-allow permission for ${toolName}`); - } catch (error) { - console.error('Error saving always-allow permission:', error); - } - } - - private getCommandPattern(command: string): string { - const parts = command.trim().split(/\s+/); - if (parts.length === 0) return command; - - const baseCmd = parts[0]; - const subCmd = parts.length > 1 ? parts[1] : ''; - - // Common patterns that should use wildcards - const patterns = [ - // Package managers - ['npm', 'install', 'npm install *'], - ['npm', 'i', 'npm i *'], - ['npm', 'add', 'npm add *'], - ['npm', 'remove', 'npm remove *'], - ['npm', 'uninstall', 'npm uninstall *'], - ['npm', 'update', 'npm update *'], - ['npm', 'run', 'npm run *'], - ['yarn', 'add', 'yarn add *'], - ['yarn', 'remove', 'yarn remove *'], - ['yarn', 'install', 'yarn install *'], - ['pnpm', 'install', 'pnpm install *'], - ['pnpm', 'add', 'pnpm add *'], - ['pnpm', 'remove', 'pnpm remove *'], - - // Git commands - ['git', 'add', 'git add *'], - ['git', 'commit', 'git commit *'], - ['git', 'push', 'git push *'], - ['git', 'pull', 'git pull *'], - ['git', 'checkout', 'git checkout *'], - ['git', 'branch', 'git branch *'], - ['git', 'merge', 'git merge *'], - ['git', 'clone', 'git clone *'], - ['git', 'reset', 'git reset *'], - ['git', 'rebase', 'git rebase *'], - ['git', 'tag', 'git tag *'], - - // Docker commands - ['docker', 'run', 'docker run *'], - ['docker', 'build', 'docker build *'], - ['docker', 'exec', 'docker exec *'], - ['docker', 'logs', 'docker logs *'], - ['docker', 'stop', 'docker stop *'], - ['docker', 'start', 'docker start *'], - ['docker', 'rm', 'docker rm *'], - ['docker', 'rmi', 'docker rmi *'], - ['docker', 'pull', 'docker pull *'], - ['docker', 'push', 'docker push *'], - - // Build tools - ['make', '', 'make *'], - ['cargo', 'build', 'cargo build *'], - ['cargo', 'run', 'cargo run *'], - ['cargo', 'test', 'cargo test *'], - ['cargo', 'install', 'cargo install *'], - ['mvn', 'compile', 'mvn compile *'], - ['mvn', 'test', 'mvn test *'], - ['mvn', 'package', 'mvn package *'], - ['gradle', 'build', 'gradle build *'], - ['gradle', 'test', 'gradle test *'], - - // System commands - ['curl', '', 'curl *'], - ['wget', '', 'wget *'], - ['ssh', '', 'ssh *'], - ['scp', '', 'scp *'], - ['rsync', '', 'rsync *'], - ['tar', '', 'tar *'], - ['zip', '', 'zip *'], - ['unzip', '', 'unzip *'], - - // Development tools - ['node', '', 'node *'], - ['python', '', 'python *'], - ['python3', '', 'python3 *'], - ['pip', 'install', 'pip install *'], - ['pip3', 'install', 'pip3 install *'], - ['composer', 'install', 'composer install *'], - ['composer', 'require', 'composer require *'], - ['bundle', 'install', 'bundle install *'], - ['gem', 'install', 'gem install *'], - ]; - - // Find matching pattern - for (const [cmd, sub, pattern] of patterns) { - if (baseCmd === cmd && (sub === '' || subCmd === sub)) { - return pattern; - } - } - - // Default: return exact command - return command; - } - - private async _sendPermissions(): Promise { - try { - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) { - this._postMessage({ - type: 'permissionsData', - data: { alwaysAllow: {} } - }); - return; - } - - const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); - let permissions: any = { alwaysAllow: {} }; - - try { - const content = await vscode.workspace.fs.readFile(permissionsUri); - permissions = JSON.parse(new TextDecoder().decode(content)); - } catch { - // File doesn't exist or can't be read, use default permissions - } - - this._postMessage({ - type: 'permissionsData', - data: permissions - }); - } catch (error) { - console.error('Error sending permissions:', error); - this._postMessage({ - type: 'permissionsData', - data: { alwaysAllow: {} } - }); - } - } - - private async _removePermission(toolName: string, command: string | null): Promise { - try { - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) return; - - const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); - let permissions: any = { alwaysAllow: {} }; - - try { - const content = await vscode.workspace.fs.readFile(permissionsUri); - permissions = JSON.parse(new TextDecoder().decode(content)); - } catch { - // File doesn't exist or can't be read, nothing to remove - return; - } - - // Remove the permission - if (command === null) { - // Remove entire tool permission - delete permissions.alwaysAllow[toolName]; - } else { - // Remove specific command from tool permissions - if (Array.isArray(permissions.alwaysAllow[toolName])) { - permissions.alwaysAllow[toolName] = permissions.alwaysAllow[toolName].filter( - (cmd: string) => cmd !== command - ); - // If no commands left, remove the tool entirely - if (permissions.alwaysAllow[toolName].length === 0) { - delete permissions.alwaysAllow[toolName]; - } - } - } - - // Save updated permissions - const permissionsContent = new TextEncoder().encode(JSON.stringify(permissions, null, 2)); - await vscode.workspace.fs.writeFile(permissionsUri, permissionsContent); - - // Send updated permissions to UI - this._sendPermissions(); - - console.log(`Removed permission for ${toolName}${command ? ` command: ${command}` : ''}`); - } catch (error) { - console.error('Error removing permission:', error); - } - } - - private async _addPermission(toolName: string, command: string | null): Promise { - try { - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) return; - - const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); - let permissions: any = { alwaysAllow: {} }; - - try { - const content = await vscode.workspace.fs.readFile(permissionsUri); - permissions = JSON.parse(new TextDecoder().decode(content)); - } catch { - // File doesn't exist, use default permissions - } - - // Add the new permission - if (command === null || command === '') { - // Allow all commands for this tool - permissions.alwaysAllow[toolName] = true; - } else { - // Add specific command pattern - if (!permissions.alwaysAllow[toolName]) { - permissions.alwaysAllow[toolName] = []; - } - - // Convert to array if it's currently set to true - if (permissions.alwaysAllow[toolName] === true) { - permissions.alwaysAllow[toolName] = []; - } - - if (Array.isArray(permissions.alwaysAllow[toolName])) { - // For Bash commands, convert to pattern using existing logic - let commandToAdd = command; - if (toolName === 'Bash') { - commandToAdd = this.getCommandPattern(command); - } - - // Add if not already present - if (!permissions.alwaysAllow[toolName].includes(commandToAdd)) { - permissions.alwaysAllow[toolName].push(commandToAdd); - } - } - } - - // Ensure permissions directory exists - const permissionsDir = vscode.Uri.file(path.dirname(permissionsUri.fsPath)); - try { - await vscode.workspace.fs.stat(permissionsDir); - } catch { - await vscode.workspace.fs.createDirectory(permissionsDir); - } - - // Save updated permissions - const permissionsContent = new TextEncoder().encode(JSON.stringify(permissions, null, 2)); - await vscode.workspace.fs.writeFile(permissionsUri, permissionsContent); - - // Send updated permissions to UI - this._sendPermissions(); - - console.log(`Added permission for ${toolName}${command ? ` command: ${command}` : ' (all commands)'}`); - } catch (error) { - console.error('Error adding permission:', error); - } - } - - private async _loadMCPServers(): Promise { - try { - const mcpConfigPath = this.getMCPConfigPath(); - if (!mcpConfigPath) { - this._postMessage({ type: 'mcpServers', data: {} }); - return; - } - - const mcpConfigUri = vscode.Uri.file(mcpConfigPath); - let mcpConfig: any = { mcpServers: {} }; - - try { - const content = await vscode.workspace.fs.readFile(mcpConfigUri); - mcpConfig = JSON.parse(new TextDecoder().decode(content)); - } catch (error) { - console.log('MCP config file not found or error reading:', error); - // File doesn't exist, return empty servers - } - - // Filter out internal servers before sending to UI - const filteredServers = Object.fromEntries( - Object.entries(mcpConfig.mcpServers || {}).filter(([name]) => name !== 'claude-code-chat-permissions') - ); - this._postMessage({ type: 'mcpServers', data: filteredServers }); - } catch (error) { - console.error('Error loading MCP servers:', error); - this._postMessage({ type: 'mcpServerError', data: { error: 'Failed to load MCP servers' } }); - } - } - - private async _saveMCPServer(name: string, config: any): Promise { - try { - const mcpConfigPath = this.getMCPConfigPath(); - if (!mcpConfigPath) { - this._postMessage({ type: 'mcpServerError', data: { error: 'Storage path not available' } }); - return; - } - - const mcpConfigUri = vscode.Uri.file(mcpConfigPath); - let mcpConfig: any = { mcpServers: {} }; - - // Load existing config - try { - const content = await vscode.workspace.fs.readFile(mcpConfigUri); - mcpConfig = JSON.parse(new TextDecoder().decode(content)); - } catch { - // File doesn't exist, use default structure - } - - // Ensure mcpServers exists - if (!mcpConfig.mcpServers) { - mcpConfig.mcpServers = {}; - } - - // Add/update the server - mcpConfig.mcpServers[name] = config; - - // Ensure directory exists - const mcpDir = vscode.Uri.file(path.dirname(mcpConfigPath)); - try { - await vscode.workspace.fs.stat(mcpDir); - } catch { - await vscode.workspace.fs.createDirectory(mcpDir); - } - - // Save the config - const configContent = new TextEncoder().encode(JSON.stringify(mcpConfig, null, 2)); - await vscode.workspace.fs.writeFile(mcpConfigUri, configContent); - - this._postMessage({ type: 'mcpServerSaved', data: { name } }); - console.log(`Saved MCP server: ${name}`); - } catch (error) { - console.error('Error saving MCP server:', error); - this._postMessage({ type: 'mcpServerError', data: { error: 'Failed to save MCP server' } }); - } - } - - private async _deleteMCPServer(name: string): Promise { - try { - const mcpConfigPath = this.getMCPConfigPath(); - if (!mcpConfigPath) { - this._postMessage({ type: 'mcpServerError', data: { error: 'Storage path not available' } }); - return; - } - - const mcpConfigUri = vscode.Uri.file(mcpConfigPath); - let mcpConfig: any = { mcpServers: {} }; - - // Load existing config - try { - const content = await vscode.workspace.fs.readFile(mcpConfigUri); - mcpConfig = JSON.parse(new TextDecoder().decode(content)); - } catch { - // File doesn't exist, nothing to delete - this._postMessage({ type: 'mcpServerError', data: { error: 'MCP config file not found' } }); - return; - } - - // Delete the server - if (mcpConfig.mcpServers && mcpConfig.mcpServers[name]) { - delete mcpConfig.mcpServers[name]; - - // Save the updated config - const configContent = new TextEncoder().encode(JSON.stringify(mcpConfig, null, 2)); - await vscode.workspace.fs.writeFile(mcpConfigUri, configContent); - - this._postMessage({ type: 'mcpServerDeleted', data: { name } }); - console.log(`Deleted MCP server: ${name}`); - } else { - this._postMessage({ type: 'mcpServerError', data: { error: `Server '${name}' not found` } }); - } - } catch (error) { - console.error('Error deleting MCP server:', error); - this._postMessage({ type: 'mcpServerError', data: { error: 'Failed to delete MCP server' } }); - } - } - - private async _sendCustomSnippets(): Promise { - try { - const customSnippets = this._context.globalState.get<{ [key: string]: any }>('customPromptSnippets', {}); - this._postMessage({ - type: 'customSnippetsData', - data: customSnippets - }); - } catch (error) { - console.error('Error loading custom snippets:', error); - this._postMessage({ - type: 'customSnippetsData', - data: {} - }); - } - } - - private async _saveCustomSnippet(snippet: any): Promise { - try { - const customSnippets = this._context.globalState.get<{ [key: string]: any }>('customPromptSnippets', {}); - customSnippets[snippet.id] = snippet; - - await this._context.globalState.update('customPromptSnippets', customSnippets); - - this._postMessage({ - type: 'customSnippetSaved', - data: { snippet } - }); - - console.log('Saved custom snippet:', snippet.name); - } catch (error) { - console.error('Error saving custom snippet:', error); - this._postMessage({ - type: 'error', - data: 'Failed to save custom snippet' - }); - } - } - - private async _deleteCustomSnippet(snippetId: string): Promise { - try { - const customSnippets = this._context.globalState.get<{ [key: string]: any }>('customPromptSnippets', {}); - - if (customSnippets[snippetId]) { - delete customSnippets[snippetId]; - await this._context.globalState.update('customPromptSnippets', customSnippets); - - this._postMessage({ - type: 'customSnippetDeleted', - data: { snippetId } - }); - - console.log('Deleted custom snippet:', snippetId); - } else { - this._postMessage({ - type: 'error', - data: 'Snippet not found' - }); - } - } catch (error) { - console.error('Error deleting custom snippet:', error); - this._postMessage({ - type: 'error', - data: 'Failed to delete custom snippet' - }); - } - } - - private convertToWSLPath(windowsPath: string): string { - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - const wslEnabled = config.get('wsl.enabled', false); - - if (wslEnabled && windowsPath.match(/^[a-zA-Z]:/)) { - // Convert C:\Users\... to /mnt/c/Users/... - return windowsPath.replace(/^([a-zA-Z]):/, '/mnt/$1').toLowerCase().replace(/\\/g, '/'); - } - - return windowsPath; - } - - public getMCPConfigPath(): string | undefined { - const storagePath = this._context.storageUri?.fsPath; - if (!storagePath) { return undefined; } - - const configPath = path.join(storagePath, 'mcp', 'mcp-servers.json'); - return path.join(configPath); - } - - private _sendAndSaveMessage(message: { type: string, data: any }): void { - - // Initialize conversation if this is the first message - if (this._currentConversation.length === 0) { - this._conversationStartTime = new Date().toISOString(); - } - - // Send to UI using the helper method - this._postMessage(message); - - // Save to conversation - this._currentConversation.push({ - timestamp: new Date().toISOString(), - messageType: message.type, - data: message.data - }); - - // Persist conversation - void this._saveCurrentConversation(); - } - - private async _saveCurrentConversation(): Promise { - if (!this._conversationsPath || this._currentConversation.length === 0) { return; } - if (!this._currentSessionId) { return; } - - try { - // Create filename from first user message and timestamp - const firstUserMessage = this._currentConversation.find(m => m.messageType === 'userInput'); - const firstMessage = firstUserMessage ? firstUserMessage.data : 'conversation'; - const startTime = this._conversationStartTime || new Date().toISOString(); - const sessionId = this._currentSessionId || 'unknown'; - - // Clean and truncate first message for filename - const cleanMessage = firstMessage - .replace(/[^a-zA-Z0-9\s]/g, '') // Remove special chars - .replace(/\s+/g, '-') // Replace spaces with dashes - .substring(0, 50) // Limit length - .toLowerCase(); - - const datePrefix = startTime.substring(0, 16).replace('T', '_').replace(/:/g, '-'); - const filename = `${datePrefix}_${cleanMessage}.json`; - - const conversationData: ConversationData = { - sessionId: sessionId, - startTime: this._conversationStartTime, - endTime: new Date().toISOString(), - messageCount: this._currentConversation.length, - totalCost: this._totalCost, - totalTokens: { - input: this._totalTokensInput, - output: this._totalTokensOutput - }, - messages: this._currentConversation, - filename - }; - - const filePath = path.join(this._conversationsPath, filename); - const content = new TextEncoder().encode(JSON.stringify(conversationData, null, 2)); - await vscode.workspace.fs.writeFile(vscode.Uri.file(filePath), content); - - // Update conversation index - this._updateConversationIndex(filename, conversationData); - - console.log(`Saved conversation: ${filename}`, this._conversationsPath); - } catch (error: any) { - console.error('Failed to save conversation:', error.message); - } - } - - - public async loadConversation(filename: string): Promise { - // Load the conversation history - await this._loadConversationHistory(filename); - } - - private _sendConversationList(): void { - this._postMessage({ - type: 'conversationList', - data: this._conversationIndex - }); - } - - private async _sendWorkspaceFiles(searchTerm?: string): Promise { - try { - // Always get all files and filter on the backend for better search results - const files = await vscode.workspace.findFiles( - '**/*', - '{**/node_modules/**,**/.git/**,**/dist/**,**/build/**,**/.next/**,**/.nuxt/**,**/target/**,**/bin/**,**/obj/**}', - 500 // Reasonable limit for filtering - ); - - let fileList = files.map(file => { - const relativePath = vscode.workspace.asRelativePath(file); - return { - name: file.path.split('/').pop() || '', - path: relativePath, - fsPath: file.fsPath - }; - }); - - // Filter results based on search term - if (searchTerm && searchTerm.trim()) { - const term = searchTerm.toLowerCase(); - fileList = fileList.filter(file => { - const fileName = file.name.toLowerCase(); - const filePath = file.path.toLowerCase(); - - // Check if term matches filename or any part of the path - return fileName.includes(term) || - filePath.includes(term) || - filePath.split('/').some(segment => segment.includes(term)); - }); - } - - // Sort and limit results - fileList = fileList - .sort((a, b) => a.name.localeCompare(b.name)) - .slice(0, 50); - - this._postMessage({ - type: 'workspaceFiles', - data: fileList - }); - } catch (error) { - console.error('Error getting workspace files:', error); - this._postMessage({ - type: 'workspaceFiles', - data: [] - }); - } - } - - private async _selectImageFile(): Promise { - try { - // Show VS Code's native file picker for images - const result = await vscode.window.showOpenDialog({ - canSelectFiles: true, - canSelectFolders: false, - canSelectMany: true, - title: 'Select image files', - filters: { - 'Images': ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'bmp'] - } - }); - - if (result && result.length > 0) { - // Send the selected file paths back to webview - result.forEach(uri => { - this._postMessage({ - type: 'imagePath', - path: uri.fsPath - }); - }); - } - - } catch (error) { - console.error('Error selecting image files:', error); - } - } - - private _stopClaudeProcess(): void { - console.log('Stop request received'); - - this._isProcessing = false - - // Update UI state - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: false } - }); - - if (this._currentClaudeProcess) { - console.log('Terminating Claude process...'); - - // Try graceful termination first - this._currentClaudeProcess.kill('SIGTERM'); - - // Force kill after 2 seconds if still running - setTimeout(() => { - if (this._currentClaudeProcess && !this._currentClaudeProcess.killed) { - console.log('Force killing Claude process...'); - this._currentClaudeProcess.kill('SIGKILL'); - } - }, 2000); - - // Clear process reference - this._currentClaudeProcess = undefined; - - this._postMessage({ - type: 'clearLoading' - }); - - // Send stop confirmation message directly to UI and save - this._sendAndSaveMessage({ - type: 'error', - data: 'โน๏ธ Claude code was stopped.' - }); - - console.log('Claude process termination initiated'); - } else { - console.log('No Claude process running to stop'); - } - } - - private _updateConversationIndex(filename: string, conversationData: ConversationData): void { - // Extract first and last user messages - const userMessages = conversationData.messages.filter((m: any) => m.messageType === 'userInput'); - const firstUserMessage = userMessages.length > 0 ? userMessages[0].data : 'No user message'; - const lastUserMessage = userMessages.length > 0 ? userMessages[userMessages.length - 1].data : firstUserMessage; - - // Create or update index entry - const indexEntry = { - filename: filename, - sessionId: conversationData.sessionId, - startTime: conversationData.startTime || '', - endTime: conversationData.endTime, - messageCount: conversationData.messageCount, - totalCost: conversationData.totalCost, - firstUserMessage: firstUserMessage.substring(0, 100), // Truncate for storage - lastUserMessage: lastUserMessage.substring(0, 100) - }; - - // Remove any existing entry for this session (in case of updates) - this._conversationIndex = this._conversationIndex.filter(entry => entry.filename !== conversationData.filename); - - // Add new entry at the beginning (most recent first) - this._conversationIndex.unshift(indexEntry); - - // Keep only last 50 conversations to avoid workspace state bloat - if (this._conversationIndex.length > 50) { - this._conversationIndex = this._conversationIndex.slice(0, 50); - } - - // Save to workspace state - this._context.workspaceState.update('claude.conversationIndex', this._conversationIndex); - } - - private _getLatestConversation(): any | undefined { - return this._conversationIndex.length > 0 ? this._conversationIndex[0] : undefined; - } - - private async _loadConversationHistory(filename: string): Promise { - console.log("_loadConversationHistory"); - if (!this._conversationsPath) { return; } - - try { - const filePath = path.join(this._conversationsPath, filename); - console.log("filePath", filePath); - - let conversationData: ConversationData; - try { - const fileUri = vscode.Uri.file(filePath); - const content = await vscode.workspace.fs.readFile(fileUri); - conversationData = JSON.parse(new TextDecoder().decode(content)); - } catch { - return; - } - - // Load conversation into current state - this._currentConversation = conversationData.messages || []; - this._conversationStartTime = conversationData.startTime; - this._totalCost = conversationData.totalCost || 0; - this._totalTokensInput = conversationData.totalTokens?.input || 0; - this._totalTokensOutput = conversationData.totalTokens?.output || 0; - - // Clear UI messages first, then send all messages to recreate the conversation - setTimeout(() => { - // Clear existing messages - this._postMessage({ - type: 'sessionCleared' - }); - - let requestStartTime: number - - // Small delay to ensure messages are cleared before loading new ones - setTimeout(() => { - const messages = this._currentConversation; - for (let i = 0; i < messages.length; i++) { - - const message = messages[i]; - - if(message.messageType === 'permissionRequest'){ - const isLast = i === messages.length - 1; - if(!isLast){ - continue; - } - } - - this._postMessage({ - type: message.messageType, - data: message.data - }); - if (message.messageType === 'userInput') { - try { - requestStartTime = new Date(message.timestamp).getTime() - } catch (e) { - console.log(e) - } - } - } - - // Send updated totals - this._postMessage({ - type: 'updateTotals', - data: { - totalCost: this._totalCost, - totalTokensInput: this._totalTokensInput, - totalTokensOutput: this._totalTokensOutput, - requestCount: this._requestCount - } - }); - - // Restore processing state if the conversation was saved while processing - if (this._isProcessing) { - this._postMessage({ - type: 'setProcessing', - data: { isProcessing: this._isProcessing, requestStartTime } - }); - } - // Send ready message after conversation is loaded - this._sendReadyMessage(); - }, 50); - }, 100); // Small delay to ensure webview is ready - - console.log(`Loaded conversation history: ${filename}`); - } catch (error: any) { - console.error('Failed to load conversation history:', error.message); - } - } - - private _getHtmlForWebview(): string { - return getHtml(vscode.env?.isTelemetryEnabled); - } - - private _sendCurrentSettings(): void { - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - const settings = { - 'thinking.intensity': config.get('thinking.intensity', 'think'), - 'wsl.enabled': config.get('wsl.enabled', false), - 'wsl.distro': config.get('wsl.distro', 'Ubuntu'), - 'wsl.nodePath': config.get('wsl.nodePath', '/usr/bin/node'), - 'wsl.claudePath': config.get('wsl.claudePath', '/usr/local/bin/claude'), - 'permissions.yoloMode': config.get('permissions.yoloMode', false) - }; - - this._postMessage({ - type: 'settingsData', - data: settings - }); - } - - private async _enableYoloMode(): Promise { - try { - // Update VS Code configuration to enable YOLO mode - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - - // Clear any global setting and set workspace setting - await config.update('permissions.yoloMode', true, vscode.ConfigurationTarget.Workspace); - - console.log('YOLO Mode enabled - all future permissions will be skipped'); - - // Send updated settings to UI - this._sendCurrentSettings(); - - } catch (error) { - console.error('Error enabling YOLO mode:', error); - } - } - - private _saveInputText(text: string): void { - this._draftMessage = text || ''; - } - - private async _updateSettings(settings: { [key: string]: any }): Promise { - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - - try { - for (const [key, value] of Object.entries(settings)) { - if (key === 'permissions.yoloMode') { - // YOLO mode is workspace-specific - await config.update(key, value, vscode.ConfigurationTarget.Workspace); - } else { - // Other settings are global (user-wide) - await config.update(key, value, vscode.ConfigurationTarget.Global); - } - } - - console.log('Settings updated:', settings); - } catch (error) { - console.error('Failed to update settings:', error); - vscode.window.showErrorMessage('Failed to update settings'); - } - } - - private async _getClipboardText(): Promise { - try { - const text = await vscode.env.clipboard.readText(); - this._postMessage({ - type: 'clipboardText', - data: text - }); - } catch (error) { - console.error('Failed to read clipboard:', error); - } - } - - private _setSelectedModel(model: string): void { - // Validate model name to prevent issues mentioned in the GitHub issue - const validModels = ['opus', 'sonnet', 'default']; - if (validModels.includes(model)) { - this._selectedModel = model; - console.log('Model selected:', model); - - // Store the model preference in workspace state - this._context.workspaceState.update('claude.selectedModel', model); - - // Show confirmation - vscode.window.showInformationMessage(`Claude model switched to: ${model.charAt(0).toUpperCase() + model.slice(1)}`); - } else { - console.error('Invalid model selected:', model); - vscode.window.showErrorMessage(`Invalid model: ${model}. Please select Opus, Sonnet, or Default.`); - } - } - - private _openModelTerminal(): void { - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - const wslEnabled = config.get('wsl.enabled', false); - const wslDistro = config.get('wsl.distro', 'Ubuntu'); - const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); - const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); - - // Build command arguments - const args = ['/model']; - - // Add session resume if we have a current session - if (this._currentSessionId) { - args.push('--resume', this._currentSessionId); - } - - // Create terminal with the claude /model command - const terminal = vscode.window.createTerminal('Claude Model Selection'); - if (wslEnabled) { - terminal.sendText(`wsl -d ${wslDistro} ${nodePath} --no-warnings --enable-source-maps ${claudePath} ${args.join(' ')}`); - } else { - terminal.sendText(`claude ${args.join(' ')}`); - } - terminal.show(); - - // Show info message - vscode.window.showInformationMessage( - 'Check the terminal to update your default model configuration. Come back to this chat here after making changes.', - 'OK' - ); - - // Send message to UI about terminal - this._postMessage({ - type: 'terminalOpened', - data: 'Check the terminal to update your default model configuration. Come back to this chat here after making changes.' - }); - } - - private _executeSlashCommand(command: string): void { - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - const wslEnabled = config.get('wsl.enabled', false); - const wslDistro = config.get('wsl.distro', 'Ubuntu'); - const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); - const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); - - // Build command arguments - const args = [`/${command}`]; - - // Add session resume if we have a current session - if (this._currentSessionId) { - args.push('--resume', this._currentSessionId); - } - - // Create terminal with the claude command - const terminal = vscode.window.createTerminal(`Claude /${command}`); - if (wslEnabled) { - terminal.sendText(`wsl -d ${wslDistro} ${nodePath} --no-warnings --enable-source-maps ${claudePath} ${args.join(' ')}`); - } else { - terminal.sendText(`claude ${args.join(' ')}`); - } - terminal.show(); - - // Show info message - vscode.window.showInformationMessage( - `Executing /${command} command in terminal. Check the terminal output and return when ready.`, - 'OK' - ); - - // Send message to UI about terminal - this._postMessage({ - type: 'terminalOpened', - data: `Executing /${command} command in terminal. Check the terminal output and return when ready.`, - }); - } - - private _sendPlatformInfo() { - const platform = process.platform; - const dismissed = this._context.globalState.get('wslAlertDismissed', false); - - // Get WSL configuration - const config = vscode.workspace.getConfiguration('claudeCodeChat'); - const wslEnabled = config.get('wsl.enabled', false); - - this._postMessage({ - type: 'platformInfo', - data: { - platform: platform, - isWindows: platform === 'win32', - wslAlertDismissed: dismissed, - wslEnabled: wslEnabled - } - }); - } - - private _dismissWSLAlert() { - this._context.globalState.update('wslAlertDismissed', true); - } - - private async _openFileInEditor(filePath: string) { - try { - const uri = vscode.Uri.file(filePath); - const document = await vscode.workspace.openTextDocument(uri); - await vscode.window.showTextDocument(document, vscode.ViewColumn.One); - } catch (error) { - vscode.window.showErrorMessage(`Failed to open file: ${filePath}`); - console.error('Error opening file:', error); - } - } - - private async _createImageFile(imageData: string, imageType: string) { - try { - const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; - if (!workspaceFolder) { return; } - - // Extract base64 data from data URL - const base64Data = imageData.split(',')[1]; - const buffer = Buffer.from(base64Data, 'base64'); - - // Get file extension from image type - const extension = imageType.split('/')[1] || 'png'; - - // Create unique filename with timestamp - const timestamp = Date.now(); - const imageFileName = `image_${timestamp}.${extension}`; - - // Create images folder in workspace .claude directory - const imagesDir = vscode.Uri.joinPath(workspaceFolder.uri, '.claude', 'claude-code-chat-images'); - await vscode.workspace.fs.createDirectory(imagesDir); - - // Create .gitignore to ignore all images - const gitignorePath = vscode.Uri.joinPath(imagesDir, '.gitignore'); - try { - await vscode.workspace.fs.stat(gitignorePath); - } catch { - // .gitignore doesn't exist, create it - const gitignoreContent = new TextEncoder().encode('*\n'); - await vscode.workspace.fs.writeFile(gitignorePath, gitignoreContent); - } - - // Create the image file - const imagePath = vscode.Uri.joinPath(imagesDir, imageFileName); - await vscode.workspace.fs.writeFile(imagePath, buffer); - - // Send the file path back to webview - this._postMessage({ - type: 'imagePath', - data: { - filePath: imagePath.fsPath - } - }); - - } catch (error) { - console.error('Error creating image file:', error); - vscode.window.showErrorMessage('Failed to create image file'); - } - } - - public dispose() { - if (this._panel) { - this._panel.dispose(); - this._panel = undefined; - } - - // Dispose message handler if it exists - if (this._messageHandlerDisposable) { - this._messageHandlerDisposable.dispose(); - this._messageHandlerDisposable = undefined; - } - - while (this._disposables.length) { - const disposable = this._disposables.pop(); - if (disposable) { - disposable.dispose(); - } - } - } -} \ No newline at end of file +export function deactivate() { } \ No newline at end of file diff --git a/src/providers/ClaudeChatProvider.ts b/src/providers/ClaudeChatProvider.ts new file mode 100644 index 0000000..3fee950 --- /dev/null +++ b/src/providers/ClaudeChatProvider.ts @@ -0,0 +1,1192 @@ +import * as vscode from 'vscode'; +import { WebviewMessage, PermissionRequest } from '../types'; +import { BackupService } from '../services/BackupService'; +import { ConversationService } from '../services/ConversationService'; +import { PermissionService } from '../services/PermissionService'; +import { SettingsService } from '../services/SettingsService'; +import { FileService } from '../services/FileService'; +import { ClaudeProcessService, JsonStreamData } from '../services/ClaudeProcessService'; +import getHtml from '../ui'; + +export class ClaudeChatProvider { + private _panel: vscode.WebviewPanel | undefined; + private _webview: vscode.Webview | undefined; + private _webviewView: vscode.WebviewView | undefined; + private _disposables: vscode.Disposable[] = []; + private _messageHandlerDisposable: vscode.Disposable | undefined; + private _totalCost: number = 0; + private _totalTokensInput: number = 0; + private _totalTokensOutput: number = 0; + private _requestCount: number = 0; + private _currentSessionId: string | undefined; + private _isProcessing: boolean = false; + private _draftMessage: string = ''; + + // Services + private _backupService: BackupService; + private _conversationService: ConversationService; + private _permissionService: PermissionService; + private _settingsService: SettingsService; + private _fileService: FileService; + private _claudeProcessService: ClaudeProcessService; + + constructor( + private readonly _extensionUri: vscode.Uri, + private readonly _context: vscode.ExtensionContext + ) { + // Initialize services + this._backupService = new BackupService(_context); + this._conversationService = new ConversationService(_context); + this._permissionService = new PermissionService(_context); + this._settingsService = new SettingsService(_context); + this._fileService = new FileService(); + this._claudeProcessService = new ClaudeProcessService(); + + // Initialize MCP config and permissions + this._permissionService.initializeMCPConfig(); + + // Set up permission request callback + this._permissionService.setPermissionRequestCallback((request) => { + this._handlePermissionRequest(request); + }); + + // Resume session from latest conversation + const latestConversation = this._conversationService.getLatestConversation(); + this._currentSessionId = latestConversation?.sessionId; + } + + public get panel(): vscode.WebviewPanel | undefined { + return this._panel; + } + + public show(column: vscode.ViewColumn | vscode.Uri = vscode.ViewColumn.Two) { + // Handle case where a URI is passed instead of ViewColumn + const actualColumn = column instanceof vscode.Uri ? vscode.ViewColumn.Two : column; + + // Close sidebar if it's open + this._closeSidebar(); + + if (this._panel) { + this._panel.reveal(actualColumn); + return; + } + + this._panel = vscode.window.createWebviewPanel( + 'claudeChat', + 'Claude Code Chat', + actualColumn, + { + enableScripts: true, + retainContextWhenHidden: true, + localResourceRoots: [this._extensionUri] + } + ); + + // Set icon for the webview tab using URI path + const iconPath = vscode.Uri.joinPath(this._extensionUri, 'icon.png'); + this._panel.iconPath = iconPath; + + this._panel.webview.html = this._getHtmlForWebview(); + + this._panel.onDidDispose(() => this.dispose(), null, this._disposables); + + this._setupWebviewMessageHandler(this._panel.webview); + + // Resume session from latest conversation + const latestConversation = this._conversationService.getLatestConversation(); + this._currentSessionId = latestConversation?.sessionId; + + // Load latest conversation history if available + if (latestConversation) { + this._loadConversationHistory(latestConversation.filename); + } + + // Send ready message immediately + setTimeout(() => { + // If no conversation to load, send ready immediately + if (!latestConversation) { + this._sendReadyMessage(); + } + }, 100); + } + + private _postMessage(message: any) { + if (this._panel && this._panel.webview) { + this._panel.webview.postMessage(message); + } else if (this._webview) { + this._webview.postMessage(message); + } + } + + private _sendReadyMessage() { + this._postMessage({ + type: 'ready', + data: this._isProcessing ? 'Claude is working...' : 'Ready to chat with Claude Code! Type your message below.' + }); + + // Send workspace info to webview + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + if (workspaceFolder) { + const workspaceName = workspaceFolder.name; + this._postMessage({ + type: 'workspaceInfo', + data: { name: workspaceName } + }); + } + + // Send current model to webview + this._postMessage({ + type: 'modelSelected', + model: this._settingsService.selectedModel + }); + + // Send platform information to webview + this._postMessage({ + type: 'platformInfo', + data: this._settingsService.getPlatformInfo() + }); + + // Send current settings to webview + this._postMessage({ + type: 'settingsData', + data: this._settingsService.getCurrentSettings() + }); + + // Send saved draft message if any + if (this._draftMessage) { + this._postMessage({ + type: 'restoreInputText', + data: this._draftMessage + }); + } + } + + private _handleWebviewMessage(message: WebviewMessage) { + switch (message.type) { + case 'sendMessage': + if (message.text) { + this._sendMessageToClaude(message.text, message.planMode, message.thinkingMode); + } + return; + case 'newSession': + this._newSession(); + return; + case 'restoreCommit': + if (message.data) { + this._restoreToCommit(message.data); + } + return; + case 'getConversationList': + this._sendConversationList(); + return; + case 'getWorkspaceFiles': + this._sendWorkspaceFiles(message.searchTerm); + return; + case 'selectImageFile': + this._selectImageFile(); + return; + case 'loadConversation': + if (message.filename) { + this.loadConversation(message.filename); + } + return; + case 'stopRequest': + this._stopClaudeProcess(); + return; + case 'getSettings': + this._sendCurrentSettings(); + return; + case 'updateSettings': + if (message.settings) { + this._updateSettings(message.settings); + } + return; + case 'getClipboardText': + this._getClipboardText(); + return; + case 'selectModel': + if (message.model) { + this._setSelectedModel(message.model); + } + return; + case 'openModelTerminal': + this._openModelTerminal(); + return; + case 'executeSlashCommand': + if (message.command) { + this._executeSlashCommand(message.command); + } + return; + case 'dismissWSLAlert': + this._dismissWSLAlert(); + return; + case 'openFile': + if (message.filePath) { + this._openFileInEditor(message.filePath); + } + return; + case 'createImageFile': + if (message.imageData && message.imageType) { + this._createImageFile(message.imageData, message.imageType); + } + return; + case 'permissionResponse': + if (message.id !== undefined && message.approved !== undefined) { + this._handlePermissionResponse(message.id, message.approved, message.alwaysAllow); + } + return; + case 'getPermissions': + this._sendPermissions(); + return; + case 'removePermission': + if (message.toolName) { + this._removePermission(message.toolName, message.command || null); + } + return; + case 'addPermission': + if (message.toolName) { + this._addPermission(message.toolName, message.command || null); + } + return; + case 'loadMCPServers': + this._loadMCPServers(); + return; + case 'saveMCPServer': + if (message.name && message.config) { + this._saveMCPServer(message.name, message.config); + } + return; + case 'deleteMCPServer': + if (message.name) { + this._deleteMCPServer(message.name); + } + return; + case 'getCustomSnippets': + this._sendCustomSnippets(); + return; + case 'saveCustomSnippet': + if (message.snippet) { + this._saveCustomSnippet(message.snippet); + } + return; + case 'deleteCustomSnippet': + if (message.snippetId) { + this._deleteCustomSnippet(message.snippetId); + } + return; + case 'enableYoloMode': + this._enableYoloMode(); + return; + case 'saveInputText': + if (message.text !== undefined) { + this._saveInputText(message.text); + } + return; + } + } + + private _setupWebviewMessageHandler(webview: vscode.Webview) { + // Dispose of any existing message handler + if (this._messageHandlerDisposable) { + this._messageHandlerDisposable.dispose(); + } + + // Set up new message handler + this._messageHandlerDisposable = webview.onDidReceiveMessage( + message => this._handleWebviewMessage(message), + null, + this._disposables + ); + } + + private _closeSidebar() { + if (this._webviewView) { + // Switch VS Code to show Explorer view instead of chat sidebar + vscode.commands.executeCommand('workbench.view.explorer'); + } + } + + public showInWebview(webview: vscode.Webview, webviewView?: vscode.WebviewView) { + // Close main panel if it's open + if (this._panel) { + console.log('Closing main panel because sidebar is opening'); + this._panel.dispose(); + this._panel = undefined; + } + + this._webview = webview; + this._webviewView = webviewView; + this._webview.html = this._getHtmlForWebview(); + + this._setupWebviewMessageHandler(this._webview); + + // Initialize the webview + this._initializeWebview(); + } + + private _initializeWebview() { + // Resume session from latest conversation + const latestConversation = this._conversationService.getLatestConversation(); + this._currentSessionId = latestConversation?.sessionId; + + // Load latest conversation history if available + if (latestConversation) { + this._loadConversationHistory(latestConversation.filename); + } else { + // If no conversation to load, send ready immediately + setTimeout(() => { + this._sendReadyMessage(); + }, 100); + } + } + + public reinitializeWebview() { + // Only reinitialize if we have a webview (sidebar) + if (this._webview) { + this._initializeWebview(); + // Set up message handler for the webview + this._setupWebviewMessageHandler(this._webview); + } + } + + private async _sendMessageToClaude(message: string, planMode?: boolean, thinkingMode?: boolean) { + // Get thinking intensity setting + const configThink = vscode.workspace.getConfiguration('claudeCodeChat'); + const thinkingIntensity = configThink.get('thinking.intensity', 'think'); + + // Prepend mode instructions if enabled + let actualMessage = message; + if (planMode) { + actualMessage = 'PLAN FIRST FOR THIS MESSAGE ONLY: Plan first before making any changes. Show me in detail what you will change and wait for my explicit approval in a separate message before proceeding. Do not implement anything until I confirm. This planning requirement applies ONLY to this current message. \n\n' + message; + } + if (thinkingMode) { + let thinkingPrompt = ''; + const thinkingMesssage = ' THROUGH THIS STEP BY STEP: \n'; + switch (thinkingIntensity) { + case 'think': + thinkingPrompt = 'THINK'; + break; + case 'think-hard': + thinkingPrompt = 'THINK HARD'; + break; + case 'think-harder': + thinkingPrompt = 'THINK HARDER'; + break; + case 'ultrathink': + thinkingPrompt = 'ULTRATHINK'; + break; + default: + thinkingPrompt = 'THINK'; + } + actualMessage = thinkingPrompt + thinkingMesssage + actualMessage; + } + + this._isProcessing = true; + + // Clear draft message since we're sending it + this._draftMessage = ''; + + // Show original user input in chat and save to conversation (without mode prefixes) + this._sendAndSaveMessage({ + type: 'userInput', + data: message + }); + + // Set processing state to true + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: true } + }); + + // Create backup commit before Claude makes changes + try { + const commitInfo = await this._backupService.createBackupCommit(message); + if (commitInfo) { + this._sendAndSaveMessage({ + type: 'showRestoreOption', + data: commitInfo + }); + } + } catch (e) { + console.log("error", e); + } + + // Show loading indicator + this._postMessage({ + type: 'loading', + data: 'Claude is working...' + }); + + // Get configuration + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const yoloMode = config.get('permissions.yoloMode', false); + const wslEnabled = config.get('wsl.enabled', false); + const wslDistro = config.get('wsl.distro', 'Ubuntu'); + const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); + const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); + + // Start Claude process + this._claudeProcessService.startClaudeProcess( + { + message: actualMessage, + sessionId: this._currentSessionId, + selectedModel: this._settingsService.selectedModel, + yoloMode, + mcpConfigPath: this._permissionService.getMCPConfigPath(), + wslConfig: wslEnabled ? { + enabled: wslEnabled, + distro: wslDistro, + nodePath, + claudePath + } : undefined + }, + (data: JsonStreamData) => this._processJsonStreamData(data), + (code: number | null, errorOutput: string) => this._handleProcessClose(code, errorOutput), + (error: Error) => this._handleProcessError(error) + ); + } + + private _processJsonStreamData(jsonData: JsonStreamData) { + switch (jsonData.type) { + case 'system': + if (jsonData.subtype === 'init') { + // System initialization message - session ID will be captured from final result + console.log('System initialized'); + this._currentSessionId = jsonData.session_id; + + // Show session info in UI + this._sendAndSaveMessage({ + type: 'sessionInfo', + data: { + sessionId: jsonData.session_id, + tools: jsonData.tools || [], + mcpServers: jsonData.mcp_servers || [] + } + }); + } + break; + + case 'assistant': + if (jsonData.message && jsonData.message.content) { + // Track token usage in real-time if available + if (jsonData.message.usage) { + this._totalTokensInput += jsonData.message.usage.input_tokens || 0; + this._totalTokensOutput += jsonData.message.usage.output_tokens || 0; + + // Send real-time token update to webview + this._sendAndSaveMessage({ + type: 'updateTokens', + data: { + totalTokensInput: this._totalTokensInput, + totalTokensOutput: this._totalTokensOutput, + currentInputTokens: jsonData.message.usage.input_tokens || 0, + currentOutputTokens: jsonData.message.usage.output_tokens || 0, + cacheCreationTokens: jsonData.message.usage.cache_creation_input_tokens || 0, + cacheReadTokens: jsonData.message.usage.cache_read_input_tokens || 0 + } + }); + } + + // Process each content item in the assistant message + for (const content of jsonData.message.content) { + if (content.type === 'text' && content.text.trim()) { + // Show text content and save to conversation + this._sendAndSaveMessage({ + type: 'output', + data: content.text.trim() + }); + } else if (content.type === 'thinking' && content.thinking.trim()) { + // Show thinking content and save to conversation + this._sendAndSaveMessage({ + type: 'thinking', + data: content.thinking.trim() + }); + } else if (content.type === 'tool_use') { + // Prepare tool execution information with better formatting + let toolInfo = `๐Ÿ”ง Executing: ${content.name}`; + + // For file-related tools, show just the filename in the header + if (content.input && content.input.file_path) { + const filePath = content.input.file_path; + const fileName = filePath.split(/[/\\]/).pop(); + toolInfo = `${content.name} ${fileName}`; + } + + let toolInput = ''; + + if (content.input) { + // Special formatting for TodoWrite to make it more readable + if (content.name === 'TodoWrite' && content.input.todos) { + toolInput = ''; + for (let i = 0; i < content.input.todos.length; i++) { + const todo = content.input.todos[i]; + const status = todo.status === 'completed' ? 'โœ“' : + todo.status === 'in_progress' ? 'โ—Œ' : 'โ—‹'; + const strikethrough = todo.status === 'completed' ? '~~' : ''; + const prefix = i > 0 ? '\n' : ''; + toolInput += `${prefix}${status} ${strikethrough}${todo.content}${strikethrough}${todo.priority ? ` (priority: ${todo.priority})` : ''}`; + } + } else { + // Send raw input to UI for formatting + toolInput = ''; + } + } + + // Show tool use immediately - permission will be requested separately if needed + const toolUseData = { + toolInfo: toolInfo, + toolInput: toolInput, + rawInput: content.input, + toolName: content.name, + toolUseId: content.id, + filePath: content.input && content.input.file_path ? content.input.file_path : null + }; + + this._sendAndSaveMessage({ + type: 'toolUse', + data: toolUseData + }); + } + } + } + break; + + case 'user': + if (jsonData.message && jsonData.message.content) { + // Process tool results from user messages + for (const content of jsonData.message.content) { + if (content.type === 'tool_result') { + let resultContent = content.content || 'Tool executed successfully'; + + // Stringify if content is an object or array + if (typeof resultContent === 'object' && resultContent !== null) { + resultContent = JSON.stringify(resultContent, null, 2); + } + + const isError = content.is_error || false; + + // Find the last tool use to get the tool name + const lastToolUse = this._conversationService.currentConversation[this._conversationService.currentConversation.length - 1]; + const toolName = lastToolUse?.data?.toolName; + + // Don't send tool result for Read and Edit tools unless there's an error + if ((toolName === 'Read' || toolName === 'Edit' || toolName === 'TodoWrite' || toolName === 'MultiEdit') && !isError) { + // Still send to UI to hide loading state, but mark it as hidden + this._sendAndSaveMessage({ + type: 'toolResult', + data: { + content: resultContent, + isError: isError, + toolUseId: content.tool_use_id, + toolName: toolName, + hidden: true + } + }); + } else { + // Show tool result and save to conversation + this._sendAndSaveMessage({ + type: 'toolResult', + data: { + content: resultContent, + isError: isError, + toolUseId: content.tool_use_id, + toolName: toolName + } + }); + } + } + } + } + break; + + case 'result': + if (jsonData.subtype === 'success') { + // Check for login errors + if (jsonData.is_error && jsonData.result && jsonData.result.includes('Invalid API key')) { + this._handleLoginRequired(); + return; + } + + this._isProcessing = false; + + // Capture session ID from final result + if (jsonData.session_id) { + const isNewSession = !this._currentSessionId; + const sessionChanged = this._currentSessionId && this._currentSessionId !== jsonData.session_id; + + console.log('Session ID found in result:', { + sessionId: jsonData.session_id, + isNewSession, + sessionChanged, + currentSessionId: this._currentSessionId + }); + + this._currentSessionId = jsonData.session_id; + + // Show session info in UI + this._sendAndSaveMessage({ + type: 'sessionInfo', + data: { + sessionId: jsonData.session_id, + tools: jsonData.tools || [], + mcpServers: jsonData.mcp_servers || [] + } + }); + } + + // Clear processing state + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: false } + }); + + // Update cumulative tracking + this._requestCount++; + if (jsonData.total_cost_usd) { + this._totalCost += jsonData.total_cost_usd; + } + + console.log('Result received:', { + cost: jsonData.total_cost_usd, + duration: jsonData.duration_ms, + turns: jsonData.num_turns + }); + + // Send updated totals to webview + this._postMessage({ + type: 'updateTotals', + data: { + totalCost: this._totalCost, + totalTokensInput: this._totalTokensInput, + totalTokensOutput: this._totalTokensOutput, + requestCount: this._requestCount, + currentCost: jsonData.total_cost_usd, + currentDuration: jsonData.duration_ms, + currentTurns: jsonData.num_turns + } + }); + } + break; + } + } + + private _handleProcessClose(code: number | null, errorOutput: string) { + // Clear loading indicator and set processing to false + this._postMessage({ + type: 'clearLoading' + }); + + // Reset processing state + this._isProcessing = false; + + // Clear processing state + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: false } + }); + + if (code !== 0 && errorOutput.trim()) { + // Error with output + this._sendAndSaveMessage({ + type: 'error', + data: errorOutput.trim() + }); + } + } + + private _handleProcessError(error: Error) { + this._postMessage({ + type: 'clearLoading' + }); + + this._isProcessing = false; + + // Clear processing state + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: false } + }); + + // Check if claude command is not installed + if (error.message.includes('ENOENT') || error.message.includes('command not found')) { + this._sendAndSaveMessage({ + type: 'error', + data: 'Install claude code first: https://www.anthropic.com/claude-code' + }); + } else { + this._sendAndSaveMessage({ + type: 'error', + data: `Error running Claude: ${error.message}` + }); + } + } + + private _newSession() { + this._isProcessing = false; + + // Update UI state + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: false } + }); + + // Stop any running process + this._claudeProcessService.stopClaudeProcess(); + + // Clear current session + this._currentSessionId = undefined; + + // Clear services state + this._backupService.clearCommits(); + this._conversationService.clearConversation(); + + // Reset counters + this._totalCost = 0; + this._totalTokensInput = 0; + this._totalTokensOutput = 0; + this._requestCount = 0; + + // Notify webview to clear all messages and reset session + this._postMessage({ + type: 'sessionCleared' + }); + } + + public newSessionOnConfigChange() { + // Reinitialize MCP config with new WSL paths + this._permissionService.initializeMCPConfig(); + + // Start a new session due to configuration change + this._newSession(); + + // Show notification to user + vscode.window.showInformationMessage( + 'WSL configuration changed. Started a new Claude session.', + 'OK' + ); + + // Send message to webview about the config change + this._sendAndSaveMessage({ + type: 'configChanged', + data: 'โš™๏ธ WSL configuration changed. Started a new session.' + }); + } + + private _handleLoginRequired() { + this._isProcessing = false; + + // Clear processing state + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: false } + }); + + // Show login required message + this._postMessage({ + type: 'loginRequired' + }); + + // Get configuration to check if WSL is enabled + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const wslEnabled = config.get('wsl.enabled', false); + const wslDistro = config.get('wsl.distro', 'Ubuntu'); + const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); + const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); + + // Open terminal and run claude login + const terminal = vscode.window.createTerminal('Claude Login'); + if (wslEnabled) { + terminal.sendText(`wsl -d ${wslDistro} ${nodePath} --no-warnings --enable-source-maps ${claudePath}`); + } else { + terminal.sendText('claude'); + } + terminal.show(); + + // Show info message + vscode.window.showInformationMessage( + 'Please login to Claude in the terminal, then come back to this chat to continue.', + 'OK' + ); + + // Send message to UI about terminal + this._postMessage({ + type: 'terminalOpened', + data: `Please login to Claude in the terminal, then come back to this chat to continue.`, + }); + } + + private _sendAndSaveMessage(message: { type: string, data: any }): void { + // Send to UI + this._postMessage(message); + + // Save to conversation + this._conversationService.addMessage(message); + + // Save conversation with current metadata + if (this._currentSessionId) { + this._conversationService.saveConversationWithMetadata( + this._currentSessionId, + this._totalCost, + this._totalTokensInput, + this._totalTokensOutput + ); + } + } + + public async loadConversation(filename: string): Promise { + await this._loadConversationHistory(filename); + } + + private async _loadConversationHistory(filename: string): Promise { + console.log("_loadConversationHistory"); + + const conversationData = await this._conversationService.loadConversation(filename); + if (!conversationData) { return; } + + // Load conversation metadata + this._totalCost = conversationData.totalCost || 0; + this._totalTokensInput = conversationData.totalTokens?.input || 0; + this._totalTokensOutput = conversationData.totalTokens?.output || 0; + + // Clear UI messages first, then send all messages to recreate the conversation + setTimeout(() => { + // Clear existing messages + this._postMessage({ + type: 'sessionCleared' + }); + + let requestStartTime: number; + + // Small delay to ensure messages are cleared before loading new ones + setTimeout(() => { + const messages = this._conversationService.currentConversation; + for (let i = 0; i < messages.length; i++) { + + const message = messages[i]; + + if (message.messageType === 'permissionRequest') { + const isLast = i === messages.length - 1; + if (!isLast) { + continue; + } + } + + this._postMessage({ + type: message.messageType, + data: message.data + }); + if (message.messageType === 'userInput') { + try { + requestStartTime = new Date(message.timestamp).getTime(); + } catch (e) { + console.log(e); + } + } + } + + // Send updated totals + this._postMessage({ + type: 'updateTotals', + data: { + totalCost: this._totalCost, + totalTokensInput: this._totalTokensInput, + totalTokensOutput: this._totalTokensOutput, + requestCount: this._requestCount + } + }); + + // Restore processing state if the conversation was saved while processing + if (this._isProcessing) { + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: this._isProcessing, requestStartTime } + }); + } + // Send ready message after conversation is loaded + this._sendReadyMessage(); + }, 50); + }, 100); // Small delay to ensure webview is ready + + console.log(`Loaded conversation history: ${filename}`); + } + + private _sendConversationList(): void { + this._postMessage({ + type: 'conversationList', + data: this._conversationService.conversationIndex + }); + } + + private async _sendWorkspaceFiles(searchTerm?: string): Promise { + const files = await this._fileService.getWorkspaceFiles(searchTerm); + this._postMessage({ + type: 'workspaceFiles', + data: files + }); + } + + private async _selectImageFile(): Promise { + const filePaths = await this._fileService.selectImageFiles(); + filePaths.forEach(filePath => { + this._postMessage({ + type: 'imagePath', + path: filePath + }); + }); + } + + private _stopClaudeProcess(): void { + const stopped = this._claudeProcessService.stopClaudeProcess(); + + this._isProcessing = false; + + // Update UI state + this._postMessage({ + type: 'setProcessing', + data: { isProcessing: false } + }); + + if (stopped) { + this._postMessage({ + type: 'clearLoading' + }); + + // Send stop confirmation message directly to UI and save + this._sendAndSaveMessage({ + type: 'error', + data: 'โน๏ธ Claude code was stopped.' + }); + } + } + + private _sendCurrentSettings(): void { + this._postMessage({ + type: 'settingsData', + data: this._settingsService.getCurrentSettings() + }); + } + + private async _updateSettings(settings: { [key: string]: any }): Promise { + await this._settingsService.updateSettings(settings); + } + + private async _getClipboardText(): Promise { + const text = await this._fileService.getClipboardText(); + this._postMessage({ + type: 'clipboardText', + data: text + }); + } + + private _setSelectedModel(model: string): void { + this._settingsService.setSelectedModel(model); + } + + private _openModelTerminal(): void { + this._settingsService.openModelTerminal(this._currentSessionId); + this._postMessage({ + type: 'terminalOpened', + data: 'Check the terminal to update your default model configuration. Come back to this chat here after making changes.' + }); + } + + private _executeSlashCommand(command: string): void { + this._settingsService.executeSlashCommand(command, this._currentSessionId); + this._postMessage({ + type: 'terminalOpened', + data: `Executing /${command} command in terminal. Check the terminal output and return when ready.`, + }); + } + + private _dismissWSLAlert() { + this._settingsService.dismissWSLAlert(); + } + + private async _openFileInEditor(filePath: string) { + await this._fileService.openFileInEditor(filePath); + } + + private async _createImageFile(imageData: string, imageType: string) { + const filePath = await this._fileService.createImageFile(imageData, imageType); + if (filePath) { + this._postMessage({ + type: 'imagePath', + data: { + filePath: filePath + } + }); + } + } + + private _handlePermissionRequest(request: PermissionRequest): void { + // Generate pattern for Bash commands + let pattern: string | undefined; + if (request.tool === 'Bash' && request.input?.command) { + pattern = this._permissionService.getCommandPattern(request.input.command); + } + + // Send permission request to webview to show permission dialog in tool card + this._sendAndSaveMessage({ + type: 'permissionRequest', + data: { + id: request.id, + tool: request.tool, + input: request.input, + pattern: pattern, + timestamp: request.timestamp + } + }); + } + + private _handlePermissionResponse(id: string, approved: boolean, alwaysAllow?: boolean): void { + this._permissionService.resolvePermissionRequest(id, approved); + + // Send permission response to UI to update tool use card state + this._sendAndSaveMessage({ + type: 'permissionResponse', + data: { + id: id, + approved: approved, + alwaysAllow: alwaysAllow + } + }); + + // Handle always allow setting + if (alwaysAllow && approved) { + void this._permissionService.saveAlwaysAllowPermission(id); + } + } + + private async _sendPermissions(): Promise { + const permissions = await this._permissionService.getPermissions(); + this._postMessage({ + type: 'permissionsData', + data: permissions + }); + } + + private async _removePermission(toolName: string, command: string | null): Promise { + await this._permissionService.removePermission(toolName, command); + this._sendPermissions(); + } + + private async _addPermission(toolName: string, command: string | null): Promise { + await this._permissionService.addPermission(toolName, command); + this._sendPermissions(); + } + + private async _loadMCPServers(): Promise { + const servers = await this._permissionService.loadMCPServers(); + this._postMessage({ type: 'mcpServers', data: servers }); + } + + private async _saveMCPServer(name: string, config: any): Promise { + const result = await this._permissionService.saveMCPServer(name, config); + if (result.success) { + this._postMessage({ type: 'mcpServerSaved', data: { name } }); + } else { + this._postMessage({ type: 'mcpServerError', data: { error: result.error } }); + } + } + + private async _deleteMCPServer(name: string): Promise { + const result = await this._permissionService.deleteMCPServer(name); + if (result.success) { + this._postMessage({ type: 'mcpServerDeleted', data: { name } }); + } else { + this._postMessage({ type: 'mcpServerError', data: { error: result.error } }); + } + } + + private _sendCustomSnippets(): void { + const snippets = this._settingsService.getCustomSnippets(); + this._postMessage({ + type: 'customSnippetsData', + data: snippets + }); + } + + private async _saveCustomSnippet(snippet: any): Promise { + try { + await this._settingsService.saveCustomSnippet(snippet); + this._postMessage({ + type: 'customSnippetSaved', + data: { snippet } + }); + } catch (error) { + this._postMessage({ + type: 'error', + data: 'Failed to save custom snippet' + }); + } + } + + private async _deleteCustomSnippet(snippetId: string): Promise { + try { + await this._settingsService.deleteCustomSnippet(snippetId); + this._postMessage({ + type: 'customSnippetDeleted', + data: { snippetId } + }); + } catch (error) { + this._postMessage({ + type: 'error', + data: 'Failed to delete custom snippet' + }); + } + } + + private async _enableYoloMode(): Promise { + await this._settingsService.enableYoloMode(); + this._sendCurrentSettings(); + } + + private _saveInputText(text: string): void { + this._draftMessage = text || ''; + } + + private async _restoreToCommit(commitSha: string): Promise { + const result = await this._backupService.restoreToCommit(commitSha); + if (result.success) { + this._sendAndSaveMessage({ + type: 'restoreSuccess', + data: { + message: result.message, + commitSha: commitSha + } + }); + } else { + this._postMessage({ + type: 'restoreError', + data: result.message + }); + } + } + + private _getHtmlForWebview(): string { + return getHtml(vscode.env?.isTelemetryEnabled); + } + + public dispose() { + if (this._panel) { + this._panel.dispose(); + this._panel = undefined; + } + + // Dispose message handler if it exists + if (this._messageHandlerDisposable) { + this._messageHandlerDisposable.dispose(); + this._messageHandlerDisposable = undefined; + } + + // Dispose services + this._permissionService.dispose(); + + while (this._disposables.length) { + const disposable = this._disposables.pop(); + if (disposable) { + disposable.dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/providers/ClaudeChatWebviewProvider.ts b/src/providers/ClaudeChatWebviewProvider.ts new file mode 100644 index 0000000..fc76261 --- /dev/null +++ b/src/providers/ClaudeChatWebviewProvider.ts @@ -0,0 +1,37 @@ +import * as vscode from 'vscode'; +import { ClaudeChatProvider } from './ClaudeChatProvider'; + +export class ClaudeChatWebviewProvider implements vscode.WebviewViewProvider { + constructor( + private readonly _extensionUri: vscode.Uri, + private readonly _context: vscode.ExtensionContext, + private readonly _chatProvider: ClaudeChatProvider + ) { } + + public resolveWebviewView( + webviewView: vscode.WebviewView, + _context: vscode.WebviewViewResolveContext, + _token: vscode.CancellationToken, + ) { + + webviewView.webview.options = { + enableScripts: true, + localResourceRoots: [this._extensionUri] + }; + + // Use the shared chat provider instance for the sidebar + this._chatProvider.showInWebview(webviewView.webview, webviewView); + + // Handle visibility changes to reinitialize when sidebar reopens + webviewView.onDidChangeVisibility(() => { + if (webviewView.visible) { + // Close main panel when sidebar becomes visible + if (this._chatProvider.panel) { + console.log('Closing main panel because sidebar became visible'); + this._chatProvider.panel.dispose(); + } + this._chatProvider.reinitializeWebview(); + } + }); + } +} \ No newline at end of file diff --git a/src/script.ts b/src/script.ts index 871f6ab..bef04bb 100644 --- a/src/script.ts +++ b/src/script.ts @@ -43,8 +43,8 @@ const getScript = (isTelemetryEnabled: boolean) => `` + `; export default getScript; \ No newline at end of file diff --git a/src/services/BackupService.ts b/src/services/BackupService.ts new file mode 100644 index 0000000..011c7bf --- /dev/null +++ b/src/services/BackupService.ts @@ -0,0 +1,143 @@ +import * as vscode from 'vscode'; +import * as cp from 'child_process'; +import * as util from 'util'; +import * as path from 'path'; +import { CommitInfo } from '../types'; + +const exec = util.promisify(cp.exec); + +export class BackupService { + private _backupRepoPath: string | undefined; + private _commits: CommitInfo[] = []; + + constructor( + private readonly _context: vscode.ExtensionContext + ) { + this._initializeBackupRepo(); + } + + public get commits(): CommitInfo[] { + return this._commits; + } + + private async _initializeBackupRepo(): Promise { + try { + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + if (!workspaceFolder) { return; } + + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) { + console.error('No workspace storage available'); + return; + } + console.log('Workspace storage path:', storagePath); + this._backupRepoPath = path.join(storagePath, 'backups', '.git'); + + // Create backup git directory if it doesn't exist + try { + await vscode.workspace.fs.stat(vscode.Uri.file(this._backupRepoPath)); + } catch { + await vscode.workspace.fs.createDirectory(vscode.Uri.file(this._backupRepoPath)); + + const workspacePath = workspaceFolder.uri.fsPath; + + // Initialize git repo with workspace as work-tree + await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" init`); + await exec(`git --git-dir="${this._backupRepoPath}" config user.name "Claude Code Chat"`); + await exec(`git --git-dir="${this._backupRepoPath}" config user.email "claude@anthropic.com"`); + + console.log(`Initialized backup repository at: ${this._backupRepoPath}`); + } + } catch (error: any) { + console.error('Failed to initialize backup repository:', error.message); + } + } + + public async createBackupCommit(userMessage: string): Promise { + try { + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + if (!workspaceFolder || !this._backupRepoPath) { return; } + + const workspacePath = workspaceFolder.uri.fsPath; + const now = new Date(); + const timestamp = now.toISOString().replace(/[:.]/g, '-'); + const displayTimestamp = now.toISOString(); + const commitMessage = `Before: ${userMessage.substring(0, 50)}${userMessage.length > 50 ? '...' : ''}`; + + // Add all files using git-dir and work-tree (excludes .git automatically) + await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" add -A`); + + // Check if this is the first commit (no HEAD exists yet) + let isFirstCommit = false; + try { + await exec(`git --git-dir="${this._backupRepoPath}" rev-parse HEAD`); + } catch { + isFirstCommit = true; + } + + // Check if there are changes to commit + const { stdout: status } = await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" status --porcelain`); + + // Always create a checkpoint, even if no files changed + let actualMessage; + if (isFirstCommit) { + actualMessage = `Initial backup: ${userMessage.substring(0, 50)}${userMessage.length > 50 ? '...' : ''}`; + } else if (status.trim()) { + actualMessage = commitMessage; + } else { + actualMessage = `Checkpoint (no changes): ${userMessage.substring(0, 50)}${userMessage.length > 50 ? '...' : ''}`; + } + + // Create commit with --allow-empty to ensure checkpoint is always created + await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" commit --allow-empty -m "${actualMessage}"`); + const { stdout: sha } = await exec(`git --git-dir="${this._backupRepoPath}" rev-parse HEAD`); + + // Store commit info + const commitInfo: CommitInfo = { + id: `commit-${timestamp}`, + sha: sha.trim(), + message: actualMessage, + timestamp: displayTimestamp + }; + + this._commits.push(commitInfo); + + console.log(`Created backup commit: ${commitInfo.sha.substring(0, 8)} - ${actualMessage}`); + return commitInfo; + } catch (error: any) { + console.error('Failed to create backup commit:', error.message); + return undefined; + } + } + + public async restoreToCommit(commitSha: string): Promise<{ success: boolean; message: string }> { + try { + const commit = this._commits.find(c => c.sha === commitSha); + if (!commit) { + return { success: false, message: 'Commit not found' }; + } + + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + if (!workspaceFolder || !this._backupRepoPath) { + return { success: false, message: 'No workspace folder or backup repository available' }; + } + + const workspacePath = workspaceFolder.uri.fsPath; + + // Restore files directly to workspace using git checkout + await exec(`git --git-dir="${this._backupRepoPath}" --work-tree="${workspacePath}" checkout ${commitSha} -- .`); + + vscode.window.showInformationMessage(`Restored to commit: ${commit.message}`); + return { success: true, message: `Successfully restored to: ${commit.message}` }; + + } catch (error: any) { + console.error('Failed to restore commit:', error.message); + vscode.window.showErrorMessage(`Failed to restore commit: ${error.message}`); + return { success: false, message: `Failed to restore: ${error.message}` }; + } + } + + public clearCommits(): void { + this._commits = []; + } +} \ No newline at end of file diff --git a/src/services/ClaudeProcessService.ts b/src/services/ClaudeProcessService.ts new file mode 100644 index 0000000..571f830 --- /dev/null +++ b/src/services/ClaudeProcessService.ts @@ -0,0 +1,224 @@ +import * as vscode from 'vscode'; +import * as cp from 'child_process'; +import { TokenUsage } from '../types'; + +export interface ClaudeProcessOptions { + message: string; + sessionId?: string; + selectedModel?: string; + yoloMode?: boolean; + mcpConfigPath?: string; + wslConfig?: { + enabled: boolean; + distro: string; + nodePath: string; + claudePath: string; + }; +} + +export interface JsonStreamData { + type: string; + subtype?: string; + session_id?: string; + tools?: any[]; + mcp_servers?: any[]; + message?: { + content: any[]; + usage?: TokenUsage; + }; + is_error?: boolean; + result?: string; + total_cost_usd?: number; + duration_ms?: number; + num_turns?: number; +} + +export class ClaudeProcessService { + private _currentClaudeProcess: cp.ChildProcess | undefined; + + public startClaudeProcess( + options: ClaudeProcessOptions, + onData: (data: JsonStreamData) => void, + onClose: (code: number | null, errorOutput: string) => void, + onError: (error: Error) => void + ): void { + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + const cwd = workspaceFolder ? workspaceFolder.uri.fsPath : process.cwd(); + + // Build command arguments with session management + const args = [ + '-p', + '--output-format', 'stream-json', '--verbose' + ]; + + if (options.yoloMode) { + // Yolo mode: skip all permissions regardless of MCP config + args.push('--dangerously-skip-permissions'); + } else if (options.mcpConfigPath) { + // Add MCP configuration for permissions + const convertedPath = this._convertToWSLPath(options.mcpConfigPath, options.wslConfig?.enabled || false); + args.push('--mcp-config', convertedPath); + args.push('--allowedTools', 'mcp__claude-code-chat-permissions__approval_prompt'); + args.push('--permission-prompt-tool', 'mcp__claude-code-chat-permissions__approval_prompt'); + } + + // Add model selection if not using default + if (options.selectedModel && options.selectedModel !== 'default') { + args.push('--model', options.selectedModel); + } + + // Add session resume if we have a current session + if (options.sessionId) { + args.push('--resume', options.sessionId); + console.log('Resuming session:', options.sessionId); + } else { + console.log('Starting new session'); + } + + console.log('Claude command args:', args); + + let claudeProcess: cp.ChildProcess; + + if (options.wslConfig?.enabled) { + // Use WSL with bash -ic for proper environment loading + console.log('Using WSL configuration:', options.wslConfig); + const wslCommand = `"${options.wslConfig.nodePath}" --no-warnings --enable-source-maps "${options.wslConfig.claudePath}" ${args.join(' ')}`; + + claudeProcess = cp.spawn('wsl', ['-d', options.wslConfig.distro, 'bash', '-ic', wslCommand], { + cwd: cwd, + stdio: ['pipe', 'pipe', 'pipe'], + env: { + ...process.env, + FORCE_COLOR: '0', + NO_COLOR: '1' + } + }); + } else { + // Use native claude command + console.log('Using native Claude command'); + // On Windows with shell:true, we need to properly quote arguments with spaces + const quotedArgs = args.map(arg => { + // Quote arguments that contain spaces + if (arg.includes(' ') && !arg.startsWith('"')) { + return `"${arg}"`; + } + return arg; + }); + claudeProcess = cp.spawn('claude', quotedArgs, { + shell: process.platform === 'win32', + cwd: cwd, + stdio: ['pipe', 'pipe', 'pipe'], + env: { + ...process.env, + FORCE_COLOR: '0', + NO_COLOR: '1' + } + }); + } + + // Store process reference for potential termination + this._currentClaudeProcess = claudeProcess; + + // Send the message to Claude's stdin + if (claudeProcess.stdin) { + claudeProcess.stdin.write(options.message + '\n'); + claudeProcess.stdin.end(); + } + + let rawOutput = ''; + let errorOutput = ''; + + if (claudeProcess.stdout) { + claudeProcess.stdout.on('data', (data) => { + rawOutput += data.toString(); + + // Process JSON stream line by line + const lines = rawOutput.split('\n'); + rawOutput = lines.pop() || ''; // Keep incomplete line for next chunk + + for (const line of lines) { + if (line.trim()) { + try { + const jsonData: JsonStreamData = JSON.parse(line.trim()); + onData(jsonData); + } catch (error) { + console.log('Failed to parse JSON line:', line, error); + } + } + } + }); + } + + if (claudeProcess.stderr) { + claudeProcess.stderr.on('data', (data) => { + errorOutput += data.toString(); + }); + } + + claudeProcess.on('close', (code) => { + console.log('Claude process closed with code:', code); + console.log('Claude stderr output:', errorOutput); + + if (!this._currentClaudeProcess) { + return; + } + + // Clear process reference + this._currentClaudeProcess = undefined; + onClose(code, errorOutput); + }); + + claudeProcess.on('error', (error) => { + console.log('Claude process error:', error.message); + + if (!this._currentClaudeProcess) { + return; + } + + // Clear process reference + this._currentClaudeProcess = undefined; + onError(error); + }); + } + + public stopClaudeProcess(): boolean { + console.log('Stop request received'); + + if (this._currentClaudeProcess) { + console.log('Terminating Claude process...'); + + // Try graceful termination first + this._currentClaudeProcess.kill('SIGTERM'); + + // Force kill after 2 seconds if still running + setTimeout(() => { + if (this._currentClaudeProcess && !this._currentClaudeProcess.killed) { + console.log('Force killing Claude process...'); + this._currentClaudeProcess.kill('SIGKILL'); + } + }, 2000); + + // Clear process reference + this._currentClaudeProcess = undefined; + + console.log('Claude process termination initiated'); + return true; + } else { + console.log('No Claude process running to stop'); + return false; + } + } + + public isProcessRunning(): boolean { + return !!this._currentClaudeProcess; + } + + private _convertToWSLPath(windowsPath: string, wslEnabled: boolean): string { + if (wslEnabled && windowsPath.match(/^[a-zA-Z]:/)) { + // Convert C:\Users\... to /mnt/c/Users/... + return windowsPath.replace(/^([a-zA-Z]):/, '/mnt/$1').toLowerCase().replace(/\\/g, '/'); + } + + return windowsPath; + } +} \ No newline at end of file diff --git a/src/services/ConversationService.ts b/src/services/ConversationService.ts new file mode 100644 index 0000000..cd4512d --- /dev/null +++ b/src/services/ConversationService.ts @@ -0,0 +1,225 @@ +import * as vscode from 'vscode'; +import * as path from 'path'; +import { ConversationData, ConversationIndexEntry } from '../types'; + +export class ConversationService { + private _conversationsPath: string | undefined; + private _currentConversation: Array<{ timestamp: string, messageType: string, data: any }> = []; + private _conversationStartTime: string | undefined; + private _conversationIndex: ConversationIndexEntry[] = []; + + constructor( + private readonly _context: vscode.ExtensionContext + ) { + this._initializeConversations(); + this._conversationIndex = this._context.workspaceState.get('claude.conversationIndex', []); + } + + public get currentConversation(): Array<{ timestamp: string, messageType: string, data: any }> { + return this._currentConversation; + } + + public get conversationIndex(): ConversationIndexEntry[] { + return this._conversationIndex; + } + + public get conversationStartTime(): string | undefined { + return this._conversationStartTime; + } + + private async _initializeConversations(): Promise { + try { + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + if (!workspaceFolder) { return; } + + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) { return; } + + this._conversationsPath = path.join(storagePath, 'conversations'); + + // Create conversations directory if it doesn't exist + try { + await vscode.workspace.fs.stat(vscode.Uri.file(this._conversationsPath)); + } catch { + await vscode.workspace.fs.createDirectory(vscode.Uri.file(this._conversationsPath)); + console.log(`Created conversations directory at: ${this._conversationsPath}`); + } + } catch (error: any) { + console.error('Failed to initialize conversations directory:', error.message); + } + } + + public addMessage(message: { type: string, data: any }): void { + // Initialize conversation if this is the first message + if (this._currentConversation.length === 0) { + this._conversationStartTime = new Date().toISOString(); + } + + // Save to conversation + this._currentConversation.push({ + timestamp: new Date().toISOString(), + messageType: message.type, + data: message.data + }); + + // Persist conversation + void this._saveCurrentConversation(); + } + + private async _saveCurrentConversation(): Promise { + if (!this._conversationsPath || this._currentConversation.length === 0) { return; } + + try { + // Create filename from first user message and timestamp + const firstUserMessage = this._currentConversation.find(m => m.messageType === 'userInput'); + const firstMessage = firstUserMessage ? firstUserMessage.data : 'conversation'; + const startTime = this._conversationStartTime || new Date().toISOString(); + + // Clean and truncate first message for filename + const cleanMessage = firstMessage + .replace(/[^a-zA-Z0-9\s]/g, '') // Remove special chars + .replace(/\s+/g, '-') // Replace spaces with dashes + .substring(0, 50) // Limit length + .toLowerCase(); + + const datePrefix = startTime.substring(0, 16).replace('T', '_').replace(/:/g, '-'); + const filename = `${datePrefix}_${cleanMessage}.json`; + + const conversationData: ConversationData = { + sessionId: '', // Will be set by calling code + startTime: this._conversationStartTime, + endTime: new Date().toISOString(), + messageCount: this._currentConversation.length, + totalCost: 0, // Will be set by calling code + totalTokens: { + input: 0, // Will be set by calling code + output: 0 // Will be set by calling code + }, + messages: this._currentConversation, + filename + }; + + const filePath = path.join(this._conversationsPath, filename); + const content = new TextEncoder().encode(JSON.stringify(conversationData, null, 2)); + await vscode.workspace.fs.writeFile(vscode.Uri.file(filePath), content); + + console.log(`Saved conversation: ${filename}`, this._conversationsPath); + } catch (error: any) { + console.error('Failed to save conversation:', error.message); + } + } + + public async saveConversationWithMetadata( + sessionId: string, + totalCost: number, + totalTokensInput: number, + totalTokensOutput: number + ): Promise { + if (!this._conversationsPath || this._currentConversation.length === 0 || !sessionId) { return; } + + try { + // Create filename from first user message and timestamp + const firstUserMessage = this._currentConversation.find(m => m.messageType === 'userInput'); + const firstMessage = firstUserMessage ? firstUserMessage.data : 'conversation'; + const startTime = this._conversationStartTime || new Date().toISOString(); + + // Clean and truncate first message for filename + const cleanMessage = firstMessage + .replace(/[^a-zA-Z0-9\s]/g, '') + .replace(/\s+/g, '-') + .substring(0, 50) + .toLowerCase(); + + const datePrefix = startTime.substring(0, 16).replace('T', '_').replace(/:/g, '-'); + const filename = `${datePrefix}_${cleanMessage}.json`; + + const conversationData: ConversationData = { + sessionId, + startTime: this._conversationStartTime, + endTime: new Date().toISOString(), + messageCount: this._currentConversation.length, + totalCost, + totalTokens: { + input: totalTokensInput, + output: totalTokensOutput + }, + messages: this._currentConversation, + filename + }; + + const filePath = path.join(this._conversationsPath, filename); + const content = new TextEncoder().encode(JSON.stringify(conversationData, null, 2)); + await vscode.workspace.fs.writeFile(vscode.Uri.file(filePath), content); + + // Update conversation index + this._updateConversationIndex(filename, conversationData); + + console.log(`Saved conversation: ${filename}`, this._conversationsPath); + } catch (error: any) { + console.error('Failed to save conversation:', error.message); + } + } + + public async loadConversation(filename: string): Promise { + if (!this._conversationsPath) { return; } + + try { + const filePath = path.join(this._conversationsPath, filename); + const fileUri = vscode.Uri.file(filePath); + const content = await vscode.workspace.fs.readFile(fileUri); + const conversationData: ConversationData = JSON.parse(new TextDecoder().decode(content)); + + // Load conversation into current state + this._currentConversation = conversationData.messages || []; + this._conversationStartTime = conversationData.startTime; + + console.log(`Loaded conversation history: ${filename}`); + return conversationData; + } catch (error: any) { + console.error('Failed to load conversation history:', error.message); + return undefined; + } + } + + public getLatestConversation(): ConversationIndexEntry | undefined { + return this._conversationIndex.length > 0 ? this._conversationIndex[0] : undefined; + } + + public clearConversation(): void { + this._currentConversation = []; + this._conversationStartTime = undefined; + } + + private _updateConversationIndex(filename: string, conversationData: ConversationData): void { + // Extract first and last user messages + const userMessages = conversationData.messages.filter((m: any) => m.messageType === 'userInput'); + const firstUserMessage = userMessages.length > 0 ? userMessages[0].data : 'No user message'; + const lastUserMessage = userMessages.length > 0 ? userMessages[userMessages.length - 1].data : firstUserMessage; + + // Create or update index entry + const indexEntry: ConversationIndexEntry = { + filename: filename, + sessionId: conversationData.sessionId, + startTime: conversationData.startTime || '', + endTime: conversationData.endTime, + messageCount: conversationData.messageCount, + totalCost: conversationData.totalCost, + firstUserMessage: firstUserMessage.substring(0, 100), + lastUserMessage: lastUserMessage.substring(0, 100) + }; + + // Remove any existing entry for this session (in case of updates) + this._conversationIndex = this._conversationIndex.filter(entry => entry.filename !== conversationData.filename); + + // Add new entry at the beginning (most recent first) + this._conversationIndex.unshift(indexEntry); + + // Keep only last 50 conversations to avoid workspace state bloat + if (this._conversationIndex.length > 50) { + this._conversationIndex = this._conversationIndex.slice(0, 50); + } + + // Save to workspace state + this._context.workspaceState.update('claude.conversationIndex', this._conversationIndex); + } +} \ No newline at end of file diff --git a/src/services/FileService.ts b/src/services/FileService.ts new file mode 100644 index 0000000..c090545 --- /dev/null +++ b/src/services/FileService.ts @@ -0,0 +1,136 @@ +import * as vscode from 'vscode'; +import * as path from 'path'; +import { WorkspaceFile } from '../types'; + +export class FileService { + + public async getWorkspaceFiles(searchTerm?: string): Promise { + try { + // Always get all files and filter on the backend for better search results + const files = await vscode.workspace.findFiles( + '**/*', + '{**/node_modules/**,**/.git/**,**/dist/**,**/build/**,**/.next/**,**/.nuxt/**,**/target/**,**/bin/**,**/obj/**}', + 500 // Reasonable limit for filtering + ); + + let fileList: WorkspaceFile[] = files.map(file => { + const relativePath = vscode.workspace.asRelativePath(file); + return { + name: file.path.split('/').pop() || '', + path: relativePath, + fsPath: file.fsPath + }; + }); + + // Filter results based on search term + if (searchTerm && searchTerm.trim()) { + const term = searchTerm.toLowerCase(); + fileList = fileList.filter(file => { + const fileName = file.name.toLowerCase(); + const filePath = file.path.toLowerCase(); + + // Check if term matches filename or any part of the path + return fileName.includes(term) || + filePath.includes(term) || + filePath.split('/').some(segment => segment.includes(term)); + }); + } + + // Sort and limit results + fileList = fileList + .sort((a, b) => a.name.localeCompare(b.name)) + .slice(0, 50); + + return fileList; + } catch (error) { + console.error('Error getting workspace files:', error); + return []; + } + } + + public async selectImageFiles(): Promise { + try { + // Show VS Code's native file picker for images + const result = await vscode.window.showOpenDialog({ + canSelectFiles: true, + canSelectFolders: false, + canSelectMany: true, + title: 'Select image files', + filters: { + 'Images': ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'bmp'] + } + }); + + if (result && result.length > 0) { + return result.map(uri => uri.fsPath); + } + + return []; + } catch (error) { + console.error('Error selecting image files:', error); + return []; + } + } + + public async openFileInEditor(filePath: string): Promise { + try { + const uri = vscode.Uri.file(filePath); + const document = await vscode.workspace.openTextDocument(uri); + await vscode.window.showTextDocument(document, vscode.ViewColumn.One); + } catch (error) { + vscode.window.showErrorMessage(`Failed to open file: ${filePath}`); + console.error('Error opening file:', error); + } + } + + public async createImageFile(imageData: string, imageType: string): Promise { + try { + const workspaceFolder = vscode.workspace.workspaceFolders?.[0]; + if (!workspaceFolder) { return; } + + // Extract base64 data from data URL + const base64Data = imageData.split(',')[1]; + const buffer = Buffer.from(base64Data, 'base64'); + + // Get file extension from image type + const extension = imageType.split('/')[1] || 'png'; + + // Create unique filename with timestamp + const timestamp = Date.now(); + const imageFileName = `image_${timestamp}.${extension}`; + + // Create images folder in workspace .claude directory + const imagesDir = vscode.Uri.joinPath(workspaceFolder.uri, '.claude', 'claude-code-chat-images'); + await vscode.workspace.fs.createDirectory(imagesDir); + + // Create .gitignore to ignore all images + const gitignorePath = vscode.Uri.joinPath(imagesDir, '.gitignore'); + try { + await vscode.workspace.fs.stat(gitignorePath); + } catch { + // .gitignore doesn't exist, create it + const gitignoreContent = new TextEncoder().encode('*\n'); + await vscode.workspace.fs.writeFile(gitignorePath, gitignoreContent); + } + + // Create the image file + const imagePath = vscode.Uri.joinPath(imagesDir, imageFileName); + await vscode.workspace.fs.writeFile(imagePath, buffer); + + return imagePath.fsPath; + } catch (error) { + console.error('Error creating image file:', error); + vscode.window.showErrorMessage('Failed to create image file'); + return undefined; + } + } + + public async getClipboardText(): Promise { + try { + return await vscode.env.clipboard.readText(); + } catch (error) { + console.error('Failed to read clipboard:', error); + return ''; + } + } +} \ No newline at end of file diff --git a/src/services/PermissionService.ts b/src/services/PermissionService.ts new file mode 100644 index 0000000..0f0fb12 --- /dev/null +++ b/src/services/PermissionService.ts @@ -0,0 +1,605 @@ +import * as vscode from 'vscode'; +import * as path from 'path'; +import { PermissionRequest, PermissionResponse, Permissions } from '../types'; + +export class PermissionService { + private _permissionRequestsPath: string | undefined; + private _permissionWatcher: vscode.FileSystemWatcher | undefined; + private _pendingPermissionResolvers: Map void> = new Map(); + private _disposables: vscode.Disposable[] = []; + private _permissionRequestCallback: ((request: PermissionRequest) => void) | undefined; + + constructor( + private readonly _context: vscode.ExtensionContext + ) { + this._initializePermissions(); + } + + public setPermissionRequestCallback(callback: (request: PermissionRequest) => void): void { + this._permissionRequestCallback = callback; + } + + private async _initializePermissions(): Promise { + try { + if (this._permissionWatcher) { + this._permissionWatcher.dispose(); + this._permissionWatcher = undefined; + } + + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) { return; } + + // Create permission requests directory + this._permissionRequestsPath = path.join(storagePath, 'permission-requests'); + try { + await vscode.workspace.fs.stat(vscode.Uri.file(this._permissionRequestsPath)); + } catch { + await vscode.workspace.fs.createDirectory(vscode.Uri.file(this._permissionRequestsPath)); + console.log(`Created permission requests directory at: ${this._permissionRequestsPath}`); + } + + console.log("DIRECTORY-----", this._permissionRequestsPath); + + // Set up file watcher for *.request files + this._permissionWatcher = vscode.workspace.createFileSystemWatcher( + new vscode.RelativePattern(this._permissionRequestsPath, '*.request') + ); + + this._permissionWatcher.onDidCreate(async (uri) => { + // Only handle file scheme URIs, ignore vscode-userdata scheme + if (uri.scheme === 'file') { + await this._handlePermissionRequest(uri); + } + }); + + this._disposables.push(this._permissionWatcher); + + } catch (error: any) { + console.error('Failed to initialize permissions:', error.message); + } + } + + private async _handlePermissionRequest(requestUri: vscode.Uri): Promise { + try { + // Read the request file + const content = await vscode.workspace.fs.readFile(requestUri); + const request = JSON.parse(new TextDecoder().decode(content)); + + // Show permission dialog + const approved = await this._showPermissionDialog(request); + + // Write response file + const responseFile = requestUri.fsPath.replace('.request', '.response'); + const response: PermissionResponse = { + id: request.id, + approved: approved, + timestamp: new Date().toISOString() + }; + + const responseContent = new TextEncoder().encode(JSON.stringify(response)); + await vscode.workspace.fs.writeFile(vscode.Uri.file(responseFile), responseContent); + + // Clean up request file + await vscode.workspace.fs.delete(requestUri); + + } catch (error: any) { + console.error('Failed to handle permission request:', error.message); + } + } + + private async _showPermissionDialog(request: PermissionRequest): Promise { + // Store the resolver for when the permission response comes back + const promise = new Promise((resolve) => { + this._pendingPermissionResolvers.set(request.id, resolve); + }); + + // Send permission request to webview via callback + if (this._permissionRequestCallback) { + this._permissionRequestCallback(request); + } else { + console.error('No permission request callback set - permission dialog will not be shown'); + // Default to deny if no callback is set + this.resolvePermissionRequest(request.id, false); + } + + return promise; + } + + public resolvePermissionRequest(id: string, approved: boolean): void { + if (this._pendingPermissionResolvers.has(id)) { + const resolver = this._pendingPermissionResolvers.get(id); + if (resolver) { + resolver(approved); + this._pendingPermissionResolvers.delete(id); + } + } + } + + public async saveAlwaysAllowPermission(requestId: string): Promise { + try { + // Read the original request to get tool name and input + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) {return;} + + const requestFileUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', `${requestId}.request`)); + + let requestContent: Uint8Array; + try { + requestContent = await vscode.workspace.fs.readFile(requestFileUri); + } catch { + return; // Request file doesn't exist + } + + const request = JSON.parse(new TextDecoder().decode(requestContent)); + + // Load existing workspace permissions + const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); + let permissions: Permissions = { alwaysAllow: {} }; + + try { + const content = await vscode.workspace.fs.readFile(permissionsUri); + permissions = JSON.parse(new TextDecoder().decode(content)); + } catch { + // File doesn't exist yet, use default permissions + } + + // Add the new permission + const toolName = request.tool; + if (toolName === 'Bash' && request.input?.command) { + // For Bash, store the command pattern + if (!permissions.alwaysAllow[toolName]) { + permissions.alwaysAllow[toolName] = []; + } + if (Array.isArray(permissions.alwaysAllow[toolName])) { + const command = request.input.command.trim(); + const pattern = this.getCommandPattern(command); + if (!permissions.alwaysAllow[toolName].includes(pattern)) { + permissions.alwaysAllow[toolName].push(pattern); + } + } + } else { + // For other tools, allow all instances + permissions.alwaysAllow[toolName] = true; + } + + // Ensure permissions directory exists + const permissionsDir = vscode.Uri.file(path.dirname(permissionsUri.fsPath)); + try { + await vscode.workspace.fs.stat(permissionsDir); + } catch { + await vscode.workspace.fs.createDirectory(permissionsDir); + } + + // Save the permissions + const permissionsContent = new TextEncoder().encode(JSON.stringify(permissions, null, 2)); + await vscode.workspace.fs.writeFile(permissionsUri, permissionsContent); + + console.log(`Saved always-allow permission for ${toolName}`); + } catch (error) { + console.error('Error saving always-allow permission:', error); + } + } + + public async getPermissions(): Promise { + try { + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) { + return { alwaysAllow: {} }; + } + + const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); + let permissions: Permissions = { alwaysAllow: {} }; + + try { + const content = await vscode.workspace.fs.readFile(permissionsUri); + permissions = JSON.parse(new TextDecoder().decode(content)); + } catch { + // File doesn't exist or can't be read, use default permissions + } + + return permissions; + } catch (error) { + console.error('Error getting permissions:', error); + return { alwaysAllow: {} }; + } + } + + public async removePermission(toolName: string, command: string | null): Promise { + try { + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) {return;} + + const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); + let permissions: Permissions = { alwaysAllow: {} }; + + try { + const content = await vscode.workspace.fs.readFile(permissionsUri); + permissions = JSON.parse(new TextDecoder().decode(content)); + } catch { + // File doesn't exist or can't be read, nothing to remove + return; + } + + // Remove the permission + if (command === null) { + // Remove entire tool permission + delete permissions.alwaysAllow[toolName]; + } else { + // Remove specific command from tool permissions + if (Array.isArray(permissions.alwaysAllow[toolName])) { + permissions.alwaysAllow[toolName] = permissions.alwaysAllow[toolName].filter( + (cmd: string) => cmd !== command + ); + // If no commands left, remove the tool entirely + if (permissions.alwaysAllow[toolName].length === 0) { + delete permissions.alwaysAllow[toolName]; + } + } + } + + // Save updated permissions + const permissionsContent = new TextEncoder().encode(JSON.stringify(permissions, null, 2)); + await vscode.workspace.fs.writeFile(permissionsUri, permissionsContent); + + console.log(`Removed permission for ${toolName}${command ? ` command: ${command}` : ''}`); + } catch (error) { + console.error('Error removing permission:', error); + } + } + + public async addPermission(toolName: string, command: string | null): Promise { + try { + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) {return;} + + const permissionsUri = vscode.Uri.file(path.join(storagePath, 'permission-requests', 'permissions.json')); + let permissions: Permissions = { alwaysAllow: {} }; + + try { + const content = await vscode.workspace.fs.readFile(permissionsUri); + permissions = JSON.parse(new TextDecoder().decode(content)); + } catch { + // File doesn't exist, use default permissions + } + + // Add the new permission + if (command === null || command === '') { + // Allow all commands for this tool + permissions.alwaysAllow[toolName] = true; + } else { + // Add specific command pattern + if (!permissions.alwaysAllow[toolName]) { + permissions.alwaysAllow[toolName] = []; + } + + // Convert to array if it's currently set to true + if (permissions.alwaysAllow[toolName] === true) { + permissions.alwaysAllow[toolName] = []; + } + + if (Array.isArray(permissions.alwaysAllow[toolName])) { + // For Bash commands, convert to pattern using existing logic + let commandToAdd = command; + if (toolName === 'Bash') { + commandToAdd = this.getCommandPattern(command); + } + + // Add if not already present + if (!permissions.alwaysAllow[toolName].includes(commandToAdd)) { + permissions.alwaysAllow[toolName].push(commandToAdd); + } + } + } + + // Ensure permissions directory exists + const permissionsDir = vscode.Uri.file(path.dirname(permissionsUri.fsPath)); + try { + await vscode.workspace.fs.stat(permissionsDir); + } catch { + await vscode.workspace.fs.createDirectory(permissionsDir); + } + + // Save updated permissions + const permissionsContent = new TextEncoder().encode(JSON.stringify(permissions, null, 2)); + await vscode.workspace.fs.writeFile(permissionsUri, permissionsContent); + + console.log(`Added permission for ${toolName}${command ? ` command: ${command}` : ' (all commands)'}`); + } catch (error) { + console.error('Error adding permission:', error); + } + } + + public getCommandPattern(command: string): string { + const parts = command.trim().split(/\s+/); + if (parts.length === 0) {return command;} + + const baseCmd = parts[0]; + const subCmd = parts.length > 1 ? parts[1] : ''; + + // Common patterns that should use wildcards + const patterns = [ + // Package managers + ['npm', 'install', 'npm install *'], + ['npm', 'i', 'npm i *'], + ['npm', 'add', 'npm add *'], + ['npm', 'remove', 'npm remove *'], + ['npm', 'uninstall', 'npm uninstall *'], + ['npm', 'update', 'npm update *'], + ['npm', 'run', 'npm run *'], + ['yarn', 'add', 'yarn add *'], + ['yarn', 'remove', 'yarn remove *'], + ['yarn', 'install', 'yarn install *'], + ['pnpm', 'install', 'pnpm install *'], + ['pnpm', 'add', 'pnpm add *'], + ['pnpm', 'remove', 'pnpm remove *'], + + // Git commands + ['git', 'add', 'git add *'], + ['git', 'commit', 'git commit *'], + ['git', 'push', 'git push *'], + ['git', 'pull', 'git pull *'], + ['git', 'checkout', 'git checkout *'], + ['git', 'branch', 'git branch *'], + ['git', 'merge', 'git merge *'], + ['git', 'clone', 'git clone *'], + ['git', 'reset', 'git reset *'], + ['git', 'rebase', 'git rebase *'], + ['git', 'tag', 'git tag *'], + + // Docker commands + ['docker', 'run', 'docker run *'], + ['docker', 'build', 'docker build *'], + ['docker', 'exec', 'docker exec *'], + ['docker', 'logs', 'docker logs *'], + ['docker', 'stop', 'docker stop *'], + ['docker', 'start', 'docker start *'], + ['docker', 'rm', 'docker rm *'], + ['docker', 'rmi', 'docker rmi *'], + ['docker', 'pull', 'docker pull *'], + ['docker', 'push', 'docker push *'], + + // Build tools + ['make', '', 'make *'], + ['cargo', 'build', 'cargo build *'], + ['cargo', 'run', 'cargo run *'], + ['cargo', 'test', 'cargo test *'], + ['cargo', 'install', 'cargo install *'], + ['mvn', 'compile', 'mvn compile *'], + ['mvn', 'test', 'mvn test *'], + ['mvn', 'package', 'mvn package *'], + ['gradle', 'build', 'gradle build *'], + ['gradle', 'test', 'gradle test *'], + + // System commands + ['curl', '', 'curl *'], + ['wget', '', 'wget *'], + ['ssh', '', 'ssh *'], + ['scp', '', 'scp *'], + ['rsync', '', 'rsync *'], + ['tar', '', 'tar *'], + ['zip', '', 'zip *'], + ['unzip', '', 'unzip *'], + + // Development tools + ['node', '', 'node *'], + ['python', '', 'python *'], + ['python3', '', 'python3 *'], + ['pip', 'install', 'pip install *'], + ['pip3', 'install', 'pip3 install *'], + ['composer', 'install', 'composer install *'], + ['composer', 'require', 'composer require *'], + ['bundle', 'install', 'bundle install *'], + ['gem', 'install', 'gem install *'], + ]; + + // Find matching pattern + for (const [cmd, sub, pattern] of patterns) { + if (baseCmd === cmd && (sub === '' || subCmd === sub)) { + return pattern; + } + } + + // Default: return exact command + return command; + } + + public async initializeMCPConfig(): Promise { + try { + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) { return; } + + // Create MCP config directory + const mcpConfigDir = path.join(storagePath, 'mcp'); + try { + await vscode.workspace.fs.stat(vscode.Uri.file(mcpConfigDir)); + } catch { + await vscode.workspace.fs.createDirectory(vscode.Uri.file(mcpConfigDir)); + console.log(`Created MCP config directory at: ${mcpConfigDir}`); + } + + // Create or update mcp-servers.json with permissions server, preserving existing servers + const mcpConfigPath = path.join(mcpConfigDir, 'mcp-servers.json'); + const mcpPermissionsPath = this.convertToWSLPath(path.join(this._context.extensionUri.fsPath, 'mcp-permissions.js')); + const permissionRequestsPath = this.convertToWSLPath(path.join(storagePath, 'permission-requests')); + + // Load existing config or create new one + let mcpConfig: any = { mcpServers: {} }; + const mcpConfigUri = vscode.Uri.file(mcpConfigPath); + + try { + const existingContent = await vscode.workspace.fs.readFile(mcpConfigUri); + mcpConfig = JSON.parse(new TextDecoder().decode(existingContent)); + console.log('Loaded existing MCP config, preserving user servers'); + } catch { + console.log('No existing MCP config found, creating new one'); + } + + // Ensure mcpServers exists + if (!mcpConfig.mcpServers) { + mcpConfig.mcpServers = {}; + } + + // Add or update the permissions server entry + mcpConfig.mcpServers['claude-code-chat-permissions'] = { + command: 'node', + args: [mcpPermissionsPath], + env: { + CLAUDE_PERMISSIONS_PATH: permissionRequestsPath + } + }; + + const configContent = new TextEncoder().encode(JSON.stringify(mcpConfig, null, 2)); + await vscode.workspace.fs.writeFile(mcpConfigUri, configContent); + + console.log(`Updated MCP config at: ${mcpConfigPath}`); + } catch (error: any) { + console.error('Failed to initialize MCP config:', error.message); + } + } + + public getMCPConfigPath(): string | undefined { + const storagePath = this._context.storageUri?.fsPath; + if (!storagePath) { return undefined; } + + const configPath = path.join(storagePath, 'mcp', 'mcp-servers.json'); + return configPath; + } + + public async loadMCPServers(): Promise<{ [name: string]: any }> { + try { + const mcpConfigPath = this.getMCPConfigPath(); + if (!mcpConfigPath) { + return {}; + } + + const mcpConfigUri = vscode.Uri.file(mcpConfigPath); + let mcpConfig: any = { mcpServers: {} }; + + try { + const content = await vscode.workspace.fs.readFile(mcpConfigUri); + mcpConfig = JSON.parse(new TextDecoder().decode(content)); + } catch (error) { + console.log('MCP config file not found or error reading:', error); + return {}; + } + + // Filter out internal servers before returning + const filteredServers = Object.fromEntries( + Object.entries(mcpConfig.mcpServers || {}).filter(([name]) => name !== 'claude-code-chat-permissions') + ); + return filteredServers; + } catch (error) { + console.error('Error loading MCP servers:', error); + return {}; + } + } + + public async saveMCPServer(name: string, config: any): Promise<{ success: boolean; error?: string }> { + try { + const mcpConfigPath = this.getMCPConfigPath(); + if (!mcpConfigPath) { + return { success: false, error: 'Storage path not available' }; + } + + const mcpConfigUri = vscode.Uri.file(mcpConfigPath); + let mcpConfig: any = { mcpServers: {} }; + + // Load existing config + try { + const content = await vscode.workspace.fs.readFile(mcpConfigUri); + mcpConfig = JSON.parse(new TextDecoder().decode(content)); + } catch { + // File doesn't exist, use default structure + } + + // Ensure mcpServers exists + if (!mcpConfig.mcpServers) { + mcpConfig.mcpServers = {}; + } + + // Add/update the server + mcpConfig.mcpServers[name] = config; + + // Ensure directory exists + const mcpDir = vscode.Uri.file(path.dirname(mcpConfigPath)); + try { + await vscode.workspace.fs.stat(mcpDir); + } catch { + await vscode.workspace.fs.createDirectory(mcpDir); + } + + // Save the config + const configContent = new TextEncoder().encode(JSON.stringify(mcpConfig, null, 2)); + await vscode.workspace.fs.writeFile(mcpConfigUri, configContent); + + console.log(`Saved MCP server: ${name}`); + return { success: true }; + } catch (error) { + console.error('Error saving MCP server:', error); + return { success: false, error: 'Failed to save MCP server' }; + } + } + + public async deleteMCPServer(name: string): Promise<{ success: boolean; error?: string }> { + try { + const mcpConfigPath = this.getMCPConfigPath(); + if (!mcpConfigPath) { + return { success: false, error: 'Storage path not available' }; + } + + const mcpConfigUri = vscode.Uri.file(mcpConfigPath); + let mcpConfig: any = { mcpServers: {} }; + + // Load existing config + try { + const content = await vscode.workspace.fs.readFile(mcpConfigUri); + mcpConfig = JSON.parse(new TextDecoder().decode(content)); + } catch { + return { success: false, error: 'MCP config file not found' }; + } + + // Delete the server + if (mcpConfig.mcpServers && mcpConfig.mcpServers[name]) { + delete mcpConfig.mcpServers[name]; + + // Save the updated config + const configContent = new TextEncoder().encode(JSON.stringify(mcpConfig, null, 2)); + await vscode.workspace.fs.writeFile(mcpConfigUri, configContent); + + console.log(`Deleted MCP server: ${name}`); + return { success: true }; + } else { + return { success: false, error: `Server '${name}' not found` }; + } + } catch (error) { + console.error('Error deleting MCP server:', error); + return { success: false, error: 'Failed to delete MCP server' }; + } + } + + private convertToWSLPath(windowsPath: string): string { + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const wslEnabled = config.get('wsl.enabled', false); + + if (wslEnabled && windowsPath.match(/^[a-zA-Z]:/)) { + // Convert C:\Users\... to /mnt/c/Users/... + return windowsPath.replace(/^([a-zA-Z]):/, '/mnt/$1').toLowerCase().replace(/\\/g, '/'); + } + + return windowsPath; + } + + public dispose(): void { + if (this._permissionWatcher) { + this._permissionWatcher.dispose(); + this._permissionWatcher = undefined; + } + + while (this._disposables.length) { + const disposable = this._disposables.pop(); + if (disposable) { + disposable.dispose(); + } + } + } +} \ No newline at end of file diff --git a/src/services/SettingsService.ts b/src/services/SettingsService.ts new file mode 100644 index 0000000..bf895e1 --- /dev/null +++ b/src/services/SettingsService.ts @@ -0,0 +1,218 @@ +import * as vscode from 'vscode'; +import { ClaudeSettings, PlatformInfo } from '../types'; + +export class SettingsService { + private _selectedModel: string = 'default'; + + constructor( + private readonly _context: vscode.ExtensionContext + ) { + // Load saved model preference + this._selectedModel = this._context.workspaceState.get('claude.selectedModel', 'default'); + } + + public get selectedModel(): string { + return this._selectedModel; + } + + public getCurrentSettings(): ClaudeSettings { + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + return { + 'thinking.intensity': config.get('thinking.intensity', 'think'), + 'wsl.enabled': config.get('wsl.enabled', false), + 'wsl.distro': config.get('wsl.distro', 'Ubuntu'), + 'wsl.nodePath': config.get('wsl.nodePath', '/usr/bin/node'), + 'wsl.claudePath': config.get('wsl.claudePath', '/usr/local/bin/claude'), + 'permissions.yoloMode': config.get('permissions.yoloMode', false) + }; + } + + public async updateSettings(settings: { [key: string]: any }): Promise { + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + + try { + for (const [key, value] of Object.entries(settings)) { + if (key === 'permissions.yoloMode') { + // YOLO mode is workspace-specific + await config.update(key, value, vscode.ConfigurationTarget.Workspace); + } else { + // Other settings are global (user-wide) + await config.update(key, value, vscode.ConfigurationTarget.Global); + } + } + + console.log('Settings updated:', settings); + } catch (error) { + console.error('Failed to update settings:', error); + vscode.window.showErrorMessage('Failed to update settings'); + } + } + + public setSelectedModel(model: string): boolean { + // Validate model name to prevent issues mentioned in the GitHub issue + const validModels = ['opus', 'sonnet', 'default']; + if (validModels.includes(model)) { + this._selectedModel = model; + console.log('Model selected:', model); + + // Store the model preference in workspace state + this._context.workspaceState.update('claude.selectedModel', model); + + // Show confirmation + vscode.window.showInformationMessage(`Claude model switched to: ${model.charAt(0).toUpperCase() + model.slice(1)}`); + return true; + } else { + console.error('Invalid model selected:', model); + vscode.window.showErrorMessage(`Invalid model: ${model}. Please select Opus, Sonnet, or Default.`); + return false; + } + } + + public async enableYoloMode(): Promise { + try { + // Update VS Code configuration to enable YOLO mode + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + + // Clear any global setting and set workspace setting + await config.update('permissions.yoloMode', true, vscode.ConfigurationTarget.Workspace); + + console.log('YOLO Mode enabled - all future permissions will be skipped'); + } catch (error) { + console.error('Error enabling YOLO mode:', error); + } + } + + public dismissWSLAlert(): void { + this._context.globalState.update('wslAlertDismissed', true); + } + + public getPlatformInfo(): PlatformInfo { + const platform = process.platform; + const dismissed = this._context.globalState.get('wslAlertDismissed', false); + + // Get WSL configuration + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const wslEnabled = config.get('wsl.enabled', false); + + return { + platform: platform, + isWindows: platform === 'win32', + wslAlertDismissed: dismissed, + wslEnabled: wslEnabled + }; + } + + public openModelTerminal(currentSessionId?: string): void { + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const wslEnabled = config.get('wsl.enabled', false); + const wslDistro = config.get('wsl.distro', 'Ubuntu'); + const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); + const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); + + // Build command arguments + const args = ['/model']; + + // Add session resume if we have a current session + if (currentSessionId) { + args.push('--resume', currentSessionId); + } + + // Create terminal with the claude /model command + const terminal = vscode.window.createTerminal('Claude Model Selection'); + if (wslEnabled) { + terminal.sendText(`wsl -d ${wslDistro} ${nodePath} --no-warnings --enable-source-maps ${claudePath} ${args.join(' ')}`); + } else { + terminal.sendText(`claude ${args.join(' ')}`); + } + terminal.show(); + + // Show info message + vscode.window.showInformationMessage( + 'Check the terminal to update your default model configuration. Come back to this chat here after making changes.', + 'OK' + ); + } + + public executeSlashCommand(command: string, currentSessionId?: string): void { + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const wslEnabled = config.get('wsl.enabled', false); + const wslDistro = config.get('wsl.distro', 'Ubuntu'); + const nodePath = config.get('wsl.nodePath', '/usr/bin/node'); + const claudePath = config.get('wsl.claudePath', '/usr/local/bin/claude'); + + // Build command arguments + const args = [`/${command}`]; + + // Add session resume if we have a current session + if (currentSessionId) { + args.push('--resume', currentSessionId); + } + + // Create terminal with the claude command + const terminal = vscode.window.createTerminal(`Claude /${command}`); + if (wslEnabled) { + terminal.sendText(`wsl -d ${wslDistro} ${nodePath} --no-warnings --enable-source-maps ${claudePath} ${args.join(' ')}`); + } else { + terminal.sendText(`claude ${args.join(' ')}`); + } + terminal.show(); + + // Show info message + vscode.window.showInformationMessage( + `Executing /${command} command in terminal. Check the terminal output and return when ready.`, + 'OK' + ); + } + + public async saveCustomSnippet(snippet: any): Promise { + try { + const customSnippets = this._context.globalState.get<{ [key: string]: any }>('customPromptSnippets', {}); + customSnippets[snippet.id] = snippet; + + await this._context.globalState.update('customPromptSnippets', customSnippets); + console.log('Saved custom snippet:', snippet.name); + } catch (error) { + console.error('Error saving custom snippet:', error); + throw new Error('Failed to save custom snippet'); + } + } + + public async deleteCustomSnippet(snippetId: string): Promise { + try { + const customSnippets = this._context.globalState.get<{ [key: string]: any }>('customPromptSnippets', {}); + + if (customSnippets[snippetId]) { + delete customSnippets[snippetId]; + await this._context.globalState.update('customPromptSnippets', customSnippets); + console.log('Deleted custom snippet:', snippetId); + } else { + throw new Error('Snippet not found'); + } + } catch (error) { + console.error('Error deleting custom snippet:', error); + throw new Error('Failed to delete custom snippet'); + } + } + + public getCustomSnippets(): { [key: string]: any } { + return this._context.globalState.get<{ [key: string]: any }>('customPromptSnippets', {}); + } + + public isPermissionSystemEnabled(): boolean { + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const yoloMode = config.get('permissions.yoloMode', false); + return !yoloMode; + } + + public convertToWSLPath(windowsPath: string): string { + const config = vscode.workspace.getConfiguration('claudeCodeChat'); + const wslEnabled = config.get('wsl.enabled', false); + + if (wslEnabled && windowsPath.match(/^[a-zA-Z]:/)) { + // Convert C:\Users\... to /mnt/c/Users/... + return windowsPath.replace(/^([a-zA-Z]):/, '/mnt/$1').toLowerCase().replace(/\\/g, '/'); + } + + return windowsPath; + } +} \ No newline at end of file diff --git a/src/styles/animation-styles.ts b/src/styles/animation-styles.ts new file mode 100644 index 0000000..e52f6ee --- /dev/null +++ b/src/styles/animation-styles.ts @@ -0,0 +1,414 @@ +export const animationStyles = ` + @keyframes pulse { + 0%, 100% { + opacity: 0.6; + transform: scale(1); + box-shadow: 0 0 4px rgba(0, 122, 204, 0.4); + } + 50% { + opacity: 1; + transform: scale(1.3); + box-shadow: 0 0 8px rgba(0, 122, 204, 0.6); + } + } + + @keyframes bounce { + 0%, 80%, 100% { + transform: scale(0.6); + opacity: 0.5; + } + 40% { + transform: scale(1); + opacity: 1; + } + } + + @keyframes slideUp { + 0% { + opacity: 0; + transform: translateY(10px); + } + 100% { + opacity: 1; + transform: translateY(0); + } + } + + @keyframes slideDown { + 0% { + opacity: 0; + max-height: 0; + padding: 0; + } + 100% { + opacity: 1; + max-height: 500px; + padding: initial; + } + } + + /* Tool loading animation */ + .tool-loading { + padding: 16px 12px; + display: flex; + align-items: center; + gap: 12px; + background-color: var(--vscode-panel-background); + border-top: 1px solid var(--vscode-panel-border); + } + + .loading-spinner { + display: flex; + gap: 4px; + } + + .loading-ball { + width: 8px; + height: 8px; + border-radius: 50%; + background-color: var(--vscode-button-background); + animation: bounce 1.4s ease-in-out infinite both; + } + + .loading-ball:nth-child(1) { animation-delay: -0.32s; } + .loading-ball:nth-child(2) { animation-delay: -0.16s; } + .loading-ball:nth-child(3) { animation-delay: 0s; } + + .loading-text { + font-size: 12px; + color: var(--vscode-descriptionForeground); + font-style: italic; + } + + /* Tool completion indicator */ + .tool-completion { + padding: 8px 12px; + display: flex; + align-items: center; + gap: 6px; + background-color: rgba(76, 175, 80, 0.1); + border-top: 1px solid rgba(76, 175, 80, 0.2); + font-size: 12px; + } + + .completion-icon { + color: #4caf50; + font-weight: bold; + } + + .completion-text { + color: var(--vscode-foreground); + opacity: 0.8; + } + + .status { + padding: 12px 16px 6px 16px; + background: transparent; + color: #808080; + font-size: 12px; + border: none; + display: flex; + align-items: center; + justify-content: space-between; + font-weight: 400; + } + + .status-left { + display: flex; + align-items: center; + gap: 16px; + } + + .status-right { + display: flex; + align-items: center; + gap: 6px; + } + + .status-indicator { + width: 6px; + height: 6px; + border-radius: 50%; + flex-shrink: 0; + } + + .status.ready .status-indicator { + background-color: rgba(255, 255, 255, 0.3); + box-shadow: none; + } + + .status.processing .status-indicator { + background-color: var(--vscode-charts-blue); + box-shadow: 0 0 4px rgba(0, 122, 204, 0.4); + animation: pulse 1.2s ease-in-out infinite; + } + + .status.error .status-indicator { + background-color: #ff453a; + box-shadow: 0 0 6px rgba(255, 69, 58, 0.5); + } + + .status-text { + flex: 1; + } + + pre { + white-space: pre-wrap; + word-wrap: break-word; + margin: 0; + } + + .session-badge { + margin-left: 16px; + background-color: var(--vscode-badge-background); + color: var(--vscode-badge-foreground); + padding: 4px 8px; + border-radius: 12px; + font-size: 11px; + font-weight: 500; + display: flex; + align-items: center; + gap: 4px; + transition: background-color 0.2s, transform 0.1s; + } + + .session-badge:hover { + background-color: var(--vscode-button-hoverBackground); + transform: scale(1.02); + } + + .session-icon { + font-size: 10px; + } + + .session-label { + opacity: 0.8; + font-size: 10px; + } + + .session-status { + font-size: 12px; + color: var(--vscode-descriptionForeground); + padding: 2px 6px; + border-radius: 4px; + background-color: var(--vscode-badge-background); + border: 1px solid var(--vscode-panel-border); + } + + .session-status.active { + color: var(--vscode-terminal-ansiGreen); + background-color: rgba(0, 210, 106, 0.1); + border-color: var(--vscode-terminal-ansiGreen); + } + + .workspace-info { + margin-left: 12px; + padding: 2px 8px; + background-color: rgba(255, 255, 255, 0.05); + border-radius: 4px; + font-size: 11px; + color: var(--vscode-descriptionForeground); + border: 1px solid rgba(255, 255, 255, 0.08); + } + + .workspace-icon { + margin-right: 4px; + font-size: 10px; + } + + .user-copy-btn { + position: absolute; + top: 8px; + right: 8px; + background: rgba(255, 255, 255, 0.1); + border: 1px solid rgba(255, 255, 255, 0.2); + border-radius: 4px; + color: var(--vscode-foreground); + cursor: pointer; + padding: 4px; + opacity: 0; + transition: opacity 0.2s ease, background-color 0.2s ease; + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + } + + .user-copy-btn:hover { + background: rgba(255, 255, 255, 0.2); + border-color: rgba(255, 255, 255, 0.3); + } + + .message.user:hover .user-copy-btn { + opacity: 1; + } + + /* Markdown content styles */ + .message h1, .message h2, .message h3, .message h4 { + margin: 0.8em 0 0.4em 0; + font-weight: 600; + line-height: 1.3; + } + + .message h1 { + font-size: 1.5em; + border-bottom: 2px solid var(--vscode-panel-border); + padding-bottom: 0.3em; + } + + .message h2 { + font-size: 1.3em; + border-bottom: 1px solid var(--vscode-panel-border); + padding-bottom: 0.2em; + } + + .message h3 { + font-size: 1.1em; + } + + .message h4 { + font-size: 1.05em; + } + + .message strong { + font-weight: 600; + color: var(--vscode-terminal-ansiBrightWhite); + } + + .message em { + font-style: italic; + } + + .message ul, .message ol { + margin: 0.6em 0; + padding-left: 1.5em; + } + + .message li { + margin: 0.3em 0; + line-height: 1.4; + } + + .message ul li { + list-style-type: disc; + } + + .message ol li { + list-style-type: decimal; + } + + .message p { + margin: 0; + line-height: 1.5; + } + + .message p:first-child { + margin-top: 0; + } + + .message p:last-child { + margin-bottom: 0; + } + + .message br { + line-height: 1.2; + } + + .restore-container { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 10px + } + + .restore-btn { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); + border: none; + padding: 4px 10px; + border-radius: 4px; + cursor: pointer; + font-size: 12px; + font-weight: 500; + } + + .restore-btn.dark { + background-color: #2d2d30; + color: #999999; + } + + .restore-btn:hover { + background-color: var(--vscode-button-hoverBackground); + } + + .restore-btn.dark:hover { + background-color: #3e3e42; + } + + .restore-date { + font-size: 10px; + color: var(--vscode-descriptionForeground); + opacity: 0.8; + } + + .conversation-history { + position: absolute; + top: 60px; + left: 0; + right: 0; + bottom: 60px; + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-widget-border); + z-index: 1000; + } + + .conversation-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 12px 16px; + border-bottom: 1px solid var(--vscode-widget-border); + } + + .conversation-header h3 { + margin: 0; + font-size: 16px; + } + + .conversation-list { + padding: 8px; + overflow-y: auto; + height: calc(100% - 60px); + } + + .conversation-item { + padding: 12px; + margin: 4px 0; + border: 1px solid var(--vscode-widget-border); + border-radius: 6px; + cursor: pointer; + background-color: var(--vscode-list-inactiveSelectionBackground); + } + + .conversation-item:hover { + background-color: var(--vscode-list-hoverBackground); + } + + .conversation-title { + font-weight: 500; + margin-bottom: 4px; + } + + .conversation-meta { + font-size: 12px; + color: var(--vscode-descriptionForeground); + margin-bottom: 4px; + } + + .conversation-preview { + font-size: 11px; + color: var(--vscode-descriptionForeground); + opacity: 0.8; + } +`; \ No newline at end of file diff --git a/src/styles/base-styles.ts b/src/styles/base-styles.ts new file mode 100644 index 0000000..1e692e2 --- /dev/null +++ b/src/styles/base-styles.ts @@ -0,0 +1,67 @@ +export const baseStyles = ` + body { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + background-color: #1a1a1a; + color: #cccccc; + margin: 0; + padding: 0; + height: 100vh; + display: flex; + flex-direction: column; + } + + .header { + padding: 8px 16px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + background-color: #1a1a1a; + display: flex; + justify-content: space-between; + align-items: center; + } + + .header h2 { + margin: 0; + font-size: 12px; + font-weight: 400; + color: #808080; + letter-spacing: 0; + } + + .controls { + display: flex; + gap: 6px; + align-items: center; + } + + .btn { + background-color: transparent; + color: #808080; + border: 1px solid rgba(255, 255, 255, 0.08); + padding: 4px 8px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 400; + transition: all 0.15s ease; + display: flex; + align-items: center; + gap: 4px; + } + + .btn:hover { + background-color: rgba(255, 255, 255, 0.05); + color: #cccccc; + border-color: rgba(255, 255, 255, 0.12); + } + + .btn.outlined { + background-color: transparent; + color: var(--vscode-foreground); + border-color: var(--vscode-panel-border); + } + + .btn.outlined:hover { + background-color: var(--vscode-list-hoverBackground); + border-color: var(--vscode-focusBorder); + } +`; \ No newline at end of file diff --git a/src/styles/chat-styles.ts b/src/styles/chat-styles.ts new file mode 100644 index 0000000..5aedaba --- /dev/null +++ b/src/styles/chat-styles.ts @@ -0,0 +1,560 @@ +export const chatStyles = ` + .chat-container { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; + } + + .messages { + flex: 1; + padding: 12px 16px; + overflow-y: auto; + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace; + font-size: 12px; + line-height: 1.6; + } + + .message { + margin-bottom: 12px; + padding: 12px; + border-radius: 6px; + } + + .message.user { + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; + color: #e0e0e0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + position: relative; + overflow: hidden; + background-color: #242424; + padding: 14px; + } + + .message.user::before { + display: none; + } + + .message.claude { + border: none; + border-radius: 0; + color: #d4d4d4; + position: relative; + overflow: hidden; + background-color: transparent; + padding: 4px 0; + font-size: 13px; + line-height: 1.5; + font-weight: 400; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + } + + .message.claude::before { + display: none; + } + + .message.error { + border: 1px solid rgba(231, 76, 60, 0.3); + border-radius: 8px; + color: var(--vscode-editor-foreground); + position: relative; + overflow: hidden; + } + + .message.error::before { + content: ''; + position: absolute; + left: 0; + top: 0; + bottom: 0; + width: 4px; + background: linear-gradient(180deg, #e74c3c 0%, #c0392b 100%); + } + + .message.system { + background-color: var(--vscode-panel-background); + color: var(--vscode-descriptionForeground); + font-style: italic; + } + + .message.tool { + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 6px; + color: #999999; + position: relative; + overflow: hidden; + background-color: #212121; + padding: 12px; + font-size: 11px; + margin-bottom: 8px; + } + + .message.tool::before { + display: none; + } + + .message.tool-result { + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 6px; + color: #cccccc; + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace; + white-space: pre-wrap; + position: relative; + overflow: hidden; + background-color: #212121; + padding: 12px; + font-size: 12px; + margin-bottom: 8px; + } + + .message.tool-result::before { + display: none; + } + + .message.thinking { + border: none; + border-radius: 0; + color: #999999; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + font-style: italic; + opacity: 0.8; + position: relative; + overflow: hidden; + background-color: transparent; + padding: 4px 0; + font-size: 13px; + } + + .message.thinking::before { + content: 'thinking... '; + color: #808080; + font-style: normal; + font-weight: 400; + } + + .message.thinking::before { + display: none; + } + + .message-header { + display: none; + } + + .message.user .message-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 8px; + opacity: 0; + transition: opacity 0.2s ease; + } + + .message.user:hover .message-header { + opacity: 1; + } + + .message.claude .message-header { + display: none; + } + + .copy-btn { + background: transparent; + border: none; + color: var(--vscode-descriptionForeground); + cursor: pointer; + padding: 2px; + border-radius: 3px; + opacity: 0; + transition: opacity 0.2s ease; + margin-left: auto; + display: flex; + align-items: center; + justify-content: center; + } + + .message:hover .copy-btn { + opacity: 0.7; + } + + .copy-btn:hover { + opacity: 1; + background-color: var(--vscode-list-hoverBackground); + } + + .message-icon { + width: 16px; + height: 16px; + border-radius: 2px; + display: flex; + align-items: center; + justify-content: center; + font-size: 9px; + color: #808080; + font-weight: 400; + flex-shrink: 0; + margin-left: 0; + } + + .message-icon.user { + background: rgba(255, 255, 255, 0.06); + } + + .message-icon.claude { + background: transparent; + } + + .message-icon.system { + background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%); + } + + .message-icon.error { + background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); + } + + .message-label { + font-weight: 400; + font-size: 11px; + opacity: 0.5; + text-transform: none; + letter-spacing: 0; + color: #606060; + } + + .message-content { + padding-left: 6px; + } + + /* Code blocks generated by markdown parser only */ + .message-content pre.code-block { + background-color: #242424; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 6px; + padding: 12px; + margin: 8px 0; + overflow-x: auto; + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace; + font-size: 12px; + line-height: 1.5; + white-space: pre; + } + + .message-content pre.code-block code { + background: none; + border: none; + padding: 0; + color: var(--vscode-editor-foreground); + } + + .code-line { + white-space: pre-wrap; + word-break: break-word; + } + + /* Code block container and header */ + .code-block-container { + margin: 8px 0; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 6px; + background-color: #242424; + overflow: hidden; + } + + .code-block-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 4px 6px; + background-color: var(--vscode-editor-background); + border-bottom: 1px solid var(--vscode-panel-border); + font-size: 10px; + } + + .code-block-language { + color: var(--vscode-descriptionForeground); + font-family: var(--vscode-editor-font-family); + font-weight: 500; + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .code-copy-btn { + background: none; + border: none; + color: var(--vscode-descriptionForeground); + cursor: pointer; + padding: 4px; + border-radius: 3px; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + opacity: 0.7; + } + + .code-copy-btn:hover { + background-color: var(--vscode-list-hoverBackground); + opacity: 1; + } + + .code-block-container .code-block { + margin: 0; + border: none; + border-radius: 0; + background: none; + } + + /* Inline code */ + .message-content code { + background-color: rgba(255, 255, 255, 0.06); + border: none; + border-radius: 3px; + padding: 2px 4px; + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', monospace; + font-size: 0.9em; + color: #cccccc; + } + + .priority-badge { + display: inline-block; + padding: 2px 6px; + border-radius: 12px; + font-size: 10px; + font-weight: 500; + text-transform: uppercase; + letter-spacing: 0.5px; + margin-left: 6px; + } + + .priority-badge.high { + background: rgba(231, 76, 60, 0.15); + color: #e74c3c; + border: 1px solid rgba(231, 76, 60, 0.3); + } + + .priority-badge.medium { + background: rgba(243, 156, 18, 0.15); + color: #f39c12; + border: 1px solid rgba(243, 156, 18, 0.3); + } + + .priority-badge.low { + background: rgba(149, 165, 166, 0.15); + color: #95a5a6; + border: 1px solid rgba(149, 165, 166, 0.3); + } + + /* Diff display styles for Edit tool */ + .diff-container { + border: 1px solid var(--vscode-panel-border); + border-radius: 4px; + overflow: hidden; + } + + .diff-header { + background-color: var(--vscode-panel-background); + padding: 6px 12px; + font-size: 11px; + font-weight: 600; + color: var(--vscode-foreground); + border-bottom: 1px solid var(--vscode-panel-border); + } + + .diff-removed, + .diff-added { + font-family: var(--vscode-editor-font-family); + font-size: 12px; + line-height: 1.4; + } + + .diff-line { + padding: 2px 12px; + white-space: pre-wrap; + word-break: break-word; + } + + .diff-line.removed { + background-color: rgba(244, 67, 54, 0.1); + border-left: 3px solid rgba(244, 67, 54, 0.6); + color: var(--vscode-foreground); + } + + .diff-line.added { + background-color: rgba(76, 175, 80, 0.1); + border-left: 3px solid rgba(76, 175, 80, 0.6); + color: var(--vscode-foreground); + } + + .diff-line.removed::before { + content: ''; + color: rgba(244, 67, 54, 0.8); + font-weight: 600; + margin-right: 8px; + } + + .diff-line.added::before { + content: ''; + color: rgba(76, 175, 80, 0.8); + font-weight: 600; + margin-right: 8px; + } + + .diff-expand-container { + padding: 8px 12px; + text-align: center; + border-top: 1px solid var(--vscode-panel-border); + background-color: var(--vscode-editor-background); + } + + .diff-expand-btn { + background: linear-gradient(135deg, rgba(64, 165, 255, 0.15) 0%, rgba(64, 165, 255, 0.1) 100%); + border: 1px solid rgba(64, 165, 255, 0.3); + color: #40a5ff; + padding: 4px 12px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 500; + transition: all 0.2s ease; + } + + .diff-expand-btn:hover { + background: linear-gradient(135deg, rgba(64, 165, 255, 0.25) 0%, rgba(64, 165, 255, 0.15) 100%); + border-color: rgba(64, 165, 255, 0.5); + } + + .diff-expand-btn:active { + transform: translateY(1px); + } + + /* MultiEdit specific styles */ + .single-edit { + margin-bottom: 12px; + } + + .edit-number { + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.15); + color: var(--vscode-descriptionForeground); + padding: 4px 8px; + border-radius: 4px; + font-size: 11px; + font-weight: 600; + margin-top: 6px; + display: inline-block; + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .diff-edit-separator { + height: 1px; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent); + margin: 12px 0; + } + + /* File path display styles */ + .diff-file-path { + padding: 8px 12px; + border: 1px solid var(--vscode-panel-border); + border-radius: 4px; + font-size: 12px; + cursor: pointer; + transition: all 0.2s ease; + } + + .diff-file-path:hover { + background-color: var(--vscode-list-hoverBackground); + border-color: var(--vscode-focusBorder); + } + + .diff-file-path:active { + transform: translateY(1px); + } + + .file-path-short, + .file-path-truncated { + font-family: var(--vscode-editor-font-family); + color: var(--vscode-foreground); + font-weight: 500; + } + + .file-path-truncated { + display: inline-flex; + align-items: center; + gap: 6px; + cursor: pointer; + transition: all 0.2s ease; + padding: 2px 4px; + border-radius: 3px; + } + + .file-path-truncated .file-icon { + font-size: 14px; + opacity: 0.7; + transition: opacity 0.2s ease; + } + + .file-path-truncated:hover { + color: var(--vscode-textLink-foreground); + background-color: var(--vscode-list-hoverBackground); + } + + .file-path-truncated:hover .file-icon { + opacity: 1; + } + + .file-path-truncated:active { + transform: translateY(1px); + } + + .expand-btn { + background: linear-gradient(135deg, rgba(64, 165, 255, 0.15) 0%, rgba(64, 165, 255, 0.1) 100%); + border: 1px solid rgba(64, 165, 255, 0.3); + color: #40a5ff; + padding: 4px 8px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 500; + margin-left: 6px; + display: inline-block; + } + + /* Conversation History Styles */ + #conversationHistory { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; + background-color: var(--vscode-editor-background); + height: 100%; + min-height: 0; + } + + .history-content { + flex: 1; + display: flex; + flex-direction: column; + padding: 16px; + overflow: hidden; + height: 100%; + min-height: 0; + } + + .history-content h3 { + margin: 0 0 16px 0; + color: var(--vscode-foreground); + font-size: 16px; + font-weight: 600; + flex-shrink: 0; + } + + #conversationList { + flex: 1; + overflow-y: auto; + min-height: 0; + height: 0; + padding-bottom: 16px; + } + +`; \ No newline at end of file diff --git a/src/styles/index.ts b/src/styles/index.ts new file mode 100644 index 0000000..aaef7f2 --- /dev/null +++ b/src/styles/index.ts @@ -0,0 +1,22 @@ +import { baseStyles } from './base-styles'; +import { permissionStyles } from './permission-styles'; +import { chatStyles } from './chat-styles'; +import { toolStyles } from './tool-styles'; +import { inputStyles } from './input-styles'; +import { modalStyles } from './modal-styles'; +import { mcpStyles } from './mcp-styles'; +import { animationStyles } from './animation-styles'; + +export const combinedStyles = ` +`; + +export default combinedStyles; \ No newline at end of file diff --git a/src/styles/input-styles.ts b/src/styles/input-styles.ts new file mode 100644 index 0000000..481b5ad --- /dev/null +++ b/src/styles/input-styles.ts @@ -0,0 +1,323 @@ +export const inputStyles = ` + .input-container { + padding: 0; + border-top: 1px solid rgba(255, 255, 255, 0.06); + background-color: #1a1a1a; + display: flex; + flex-direction: column; + position: relative; + } + + .input-modes { + display: flex; + gap: 16px; + align-items: center; + padding-bottom: 5px; + font-size: 9.5px; + } + + .mode-toggle { + display: flex; + align-items: center; + gap: 6px; + color: var(--vscode-foreground); + opacity: 0.8; + transition: opacity 0.2s ease; + font-size: 12px; + } + + .mode-toggle span { + cursor: pointer; + transition: opacity 0.2s ease; + } + + .mode-toggle span:hover { + opacity: 1; + } + + .mode-toggle:hover { + opacity: 1; + } + + .mode-switch { + position: relative; + width: 22px; + height: 12px; + background-color: var(--vscode-panel-border); + border-radius: 6px; + cursor: pointer; + transition: background-color 0.2s ease; + } + + .mode-switch.active { + background-color: var(--vscode-button-background); + } + + .mode-switch::after { + content: ''; + position: absolute; + top: 2px; + left: 2px; + width: 8px; + height: 8px; + background-color: var(--vscode-foreground); + border-radius: 50%; + transition: transform 0.2s ease; + } + + .mode-switch.active::after { + transform: translateX(8px); + background-color: var(--vscode-button-foreground); + } + + .textarea-container { + display: flex; + gap: 10px; + align-items: flex-end; + padding: 6px 16px 12px 16px; + } + + .textarea-wrapper { + flex: 1; + background-color: #242424; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; + overflow: hidden; + } + + .textarea-wrapper:focus-within { + border-color: rgba(255, 255, 255, 0.12); + background-color: #282828; + } + + .input-field { + width: 100%; + box-sizing: border-box; + background-color: transparent; + color: #cccccc; + border: none; + padding: 10px; + outline: none; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + font-size: 13px; + min-height: 60px; + line-height: 1.5; + overflow-y: hidden; + resize: none; + } + + .input-field:focus { + border: none; + outline: none; + } + + .input-field::placeholder { + color: #606060; + border: none; + outline: none; + } + + .input-controls { + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + padding: 4px 6px; + border-top: 1px solid rgba(255, 255, 255, 0.03); + background-color: transparent; + flex-wrap: nowrap; + min-height: 32px; + } + + .left-controls { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: nowrap; + flex-shrink: 0; + } + + .right-controls { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: nowrap; + flex-shrink: 0; + } + + .model-selector { + background-color: transparent; + color: #606060; + border: none; + padding: 3px 6px; + border-radius: 3px; + cursor: pointer; + font-size: 10px; + font-weight: 400; + transition: all 0.15s ease; + opacity: 0.8; + display: flex; + align-items: center; + gap: 3px; + } + + .model-selector:hover { + background-color: rgba(255, 255, 255, 0.04); + color: #999999; + opacity: 1; + } + + .tools-btn { + background-color: rgba(128, 128, 128, 0.15); + color: var(--vscode-foreground); + border: none; + padding: 3px 7px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 500; + transition: all 0.2s ease; + opacity: 0.9; + display: flex; + align-items: center; + gap: 4px; + } + + .tools-btn:hover { + background-color: rgba(128, 128, 128, 0.25); + opacity: 1; + } + + .slash-btn, + .at-btn { + background-color: transparent; + color: #606060; + border: none; + padding: 3px 5px; + border-radius: 3px; + cursor: pointer; + font-size: 11px; + font-weight: 400; + transition: all 0.15s ease; + opacity: 0.8; + } + + .slash-btn:hover, + .at-btn:hover { + background-color: rgba(255, 255, 255, 0.04); + color: #999999; + opacity: 1; + } + + .image-btn { + background-color: transparent; + color: #606060; + border: none; + padding: 3px; + border-radius: 3px; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + transition: all 0.15s ease; + opacity: 0.8; + } + + .image-btn:hover { + background-color: rgba(255, 255, 255, 0.04); + color: #999999; + opacity: 1; + } + + .send-btn { + background-color: rgba(255, 255, 255, 0.06); + color: #999999; + border: none; + padding: 4px 8px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 400; + transition: all 0.15s ease; + } + + .send-btn div { + display: flex; + align-items: center; + justify-content: center; + gap: 2px; + } + + .send-btn span { + line-height: 1; + } + + .send-btn:hover { + background-color: rgba(255, 255, 255, 0.08); + color: #cccccc; + } + + .send-btn:disabled { + opacity: 0.3; + cursor: not-allowed; + } + + .send-btn.stop-mode { + background-color: rgba(255, 99, 71, 0.1); + color: #ff6347; + border: 1px solid rgba(255, 99, 71, 0.2); + } + + .send-btn.stop-mode:hover { + background-color: rgba(255, 99, 71, 0.2); + color: #ff6347; + } + + .expand-btn { + background: linear-gradient(135deg, rgba(64, 165, 255, 0.15) 0%, rgba(64, 165, 255, 0.1) 100%); + border: 1px solid rgba(64, 165, 255, 0.3); + color: #40a5ff; + padding: 4px 8px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 500; + margin-left: 6px; + display: inline-block; + transition: all 0.2s ease; + } + + .expand-btn:hover { + background: linear-gradient(135deg, rgba(64, 165, 255, 0.25) 0%, rgba(64, 165, 255, 0.15) 100%); + border-color: rgba(64, 165, 255, 0.5); + transform: translateY(-1px); + } + + .expanded-content { + margin-top: 8px; + padding: 12px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 6px; + position: relative; + } + + .expanded-content::before { + content: ''; + position: absolute; + left: 0; + top: 0; + bottom: 0; + width: 3px; + background: linear-gradient(180deg, #40a5ff 0%, #0078d4 100%); + border-radius: 0 0 0 6px; + } + + .expanded-content pre { + margin: 0; + white-space: pre-wrap; + word-wrap: break-word; + } +`; \ No newline at end of file diff --git a/src/styles/mcp-styles.ts b/src/styles/mcp-styles.ts new file mode 100644 index 0000000..f8d793d --- /dev/null +++ b/src/styles/mcp-styles.ts @@ -0,0 +1,298 @@ +export const mcpStyles = ` + /* MCP Modal content area improvements */ + #mcpModal * { + box-sizing: border-box; + } + + #mcpModal .tools-list { + padding: 24px; + max-height: calc(80vh - 120px); + overflow-y: auto; + width: 100%; + } + + #mcpModal .mcp-servers-list { + padding: 0; + } + + #mcpModal .mcp-add-server { + padding: 0; + } + + #mcpModal .mcp-add-form { + padding: 12px; + } + + /* MCP Servers styles */ + .mcp-servers-list { + padding: 4px; + } + + .mcp-server-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px 24px; + border: 1px solid var(--vscode-panel-border); + border-radius: 8px; + margin-bottom: 16px; + background-color: var(--vscode-editor-background); + transition: all 0.2s ease; + } + + .mcp-server-item:hover { + border-color: var(--vscode-focusBorder); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + } + + .server-info { + flex: 1; + } + + .server-name { + font-weight: 600; + font-size: 16px; + color: var(--vscode-foreground); + margin-bottom: 8px; + } + + .server-type { + display: inline-block; + background-color: var(--vscode-badge-background); + color: var(--vscode-badge-foreground); + padding: 4px 8px; + border-radius: 4px; + font-size: 11px; + font-weight: 500; + margin-bottom: 8px; + } + + .server-config { + font-size: 13px; + color: var(--vscode-descriptionForeground); + opacity: 0.9; + line-height: 1.4; + } + + .server-delete-btn { + padding: 8px 16px; + font-size: 13px; + color: var(--vscode-errorForeground); + border-color: var(--vscode-errorForeground); + min-width: 80px; + justify-content: center; + } + + .server-delete-btn:hover { + background-color: var(--vscode-inputValidation-errorBackground); + border-color: var(--vscode-errorForeground); + } + + .server-actions { + display: flex; + gap: 8px; + align-items: center; + flex-shrink: 0; + } + + .server-edit-btn { + padding: 8px 16px; + font-size: 13px; + color: var(--vscode-foreground); + border-color: var(--vscode-panel-border); + min-width: 80px; + transition: all 0.2s ease; + justify-content: center; + } + + .server-edit-btn:hover { + background-color: var(--vscode-list-hoverBackground); + border-color: var(--vscode-focusBorder); + } + + .mcp-add-server { + text-align: center; + margin-bottom: 24px; + padding: 0 4px; + } + + .mcp-add-form { + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-panel-border); + border-radius: 8px; + padding: 24px; + margin-top: 20px; + box-sizing: border-box; + width: 100%; + } + + .form-group { + margin-bottom: 20px; + box-sizing: border-box; + width: 100%; + } + + .form-group label { + display: block; + margin-bottom: 6px; + font-weight: 500; + font-size: 13px; + color: var(--vscode-foreground); + } + + .form-group input, + .form-group select, + .form-group textarea { + width: 100%; + max-width: 100%; + padding: 8px 12px; + border: 1px solid var(--vscode-input-border); + border-radius: 4px; + background-color: var(--vscode-input-background); + color: var(--vscode-input-foreground); + font-size: 13px; + font-family: var(--vscode-font-family); + box-sizing: border-box; + resize: vertical; + } + + .form-group input:focus, + .form-group select:focus, + .form-group textarea:focus { + outline: none; + border-color: var(--vscode-focusBorder); + box-shadow: 0 0 0 1px var(--vscode-focusBorder); + } + + .form-group textarea { + resize: vertical; + min-height: 60px; + } + + .form-buttons { + display: flex; + gap: 8px; + justify-content: flex-end; + margin-top: 20px; + } + + .no-servers { + text-align: center; + color: var(--vscode-descriptionForeground); + font-style: italic; + padding: 40px 20px; + } + + /* Popular MCP Servers */ + .mcp-popular-servers { + margin-top: 32px; + padding-top: 24px; + border-top: 1px solid var(--vscode-panel-border); + } + + .mcp-popular-servers h4 { + margin: 0 0 16px 0; + font-size: 14px; + font-weight: 600; + color: var(--vscode-foreground); + opacity: 0.9; + } + + .popular-servers-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 12px; + } + + .popular-server-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 16px; + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-panel-border); + border-radius: 6px; + cursor: pointer; + transition: all 0.2s ease; + } + + .popular-server-item:hover { + border-color: var(--vscode-focusBorder); + background-color: var(--vscode-list-hoverBackground); + transform: translateY(-1px); + } + + .popular-server-icon { + font-size: 24px; + flex-shrink: 0; + } + + .popular-server-info { + flex: 1; + min-width: 0; + } + + .popular-server-name { + font-weight: 600; + font-size: 13px; + color: var(--vscode-foreground); + margin-bottom: 2px; + } + + .popular-server-desc { + font-size: 11px; + color: var(--vscode-descriptionForeground); + opacity: 0.8; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .yolo-warning { + font-size: 12px; + color: var(--vscode-foreground); + text-align: center; + font-weight: 500; + background-color: rgba(255, 99, 71, 0.08); + border: 1px solid rgba(255, 99, 71, 0.2); + padding: 8px 12px; + margin: 4px 4px; + border-radius: 4px; + animation: slideDown 0.3s ease; + } + + .yolo-suggestion { + margin-top: 12px; + padding: 12px; + background-color: rgba(0, 122, 204, 0.1); + border: 1px solid rgba(0, 122, 204, 0.3); + border-radius: 6px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + } + + .yolo-suggestion-text { + font-size: 12px; + color: var(--vscode-foreground); + flex-grow: 1; + } + + .yolo-suggestion-btn { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); + border: none; + border-radius: 4px; + padding: 6px 12px; + font-size: 11px; + cursor: pointer; + transition: background-color 0.2s ease; + font-weight: 500; + flex-shrink: 0; + } + + .yolo-suggestion-btn:hover { + background-color: var(--vscode-button-hoverBackground); + } +`; \ No newline at end of file diff --git a/src/styles/modal-styles.ts b/src/styles/modal-styles.ts new file mode 100644 index 0000000..23c6e89 --- /dev/null +++ b/src/styles/modal-styles.ts @@ -0,0 +1,721 @@ +export const modalStyles = ` + .file-picker-modal { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.5); + z-index: 1000; + display: flex; + align-items: center; + justify-content: center; + } + + .file-picker-content { + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-panel-border); + border-radius: 4px; + width: 400px; + max-height: 500px; + display: flex; + flex-direction: column; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + } + + .file-picker-header { + padding: 12px; + border-bottom: 1px solid var(--vscode-panel-border); + display: flex; + flex-direction: column; + gap: 8px; + } + + .file-picker-header span { + font-weight: 500; + color: var(--vscode-foreground); + } + + .file-search-input { + background-color: var(--vscode-input-background); + color: var(--vscode-input-foreground); + border: 1px solid var(--vscode-input-border); + padding: 6px 8px; + border-radius: 3px; + outline: none; + font-size: 13px; + } + + .file-search-input:focus { + border-color: var(--vscode-focusBorder); + } + + .file-list { + max-height: 400px; + overflow-y: auto; + padding: 4px; + } + + .file-item { + display: flex; + align-items: center; + padding: 8px 12px; + cursor: pointer; + border-radius: 3px; + font-size: 13px; + gap: 8px; + } + + .file-item:hover { + background-color: var(--vscode-list-hoverBackground); + } + + .file-item.selected { + background-color: var(--vscode-list-activeSelectionBackground); + color: var(--vscode-list-activeSelectionForeground); + } + + .file-icon { + font-size: 16px; + flex-shrink: 0; + } + + .file-info { + flex: 1; + display: flex; + flex-direction: column; + } + + .file-name { + font-weight: 500; + } + + .file-path { + font-size: 11px; + color: var(--vscode-descriptionForeground); + } + + .file-thumbnail { + width: 32px; + height: 32px; + border-radius: 4px; + overflow: hidden; + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-panel-border); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + } + + .thumbnail-img { + max-width: 100%; + max-height: 100%; + object-fit: cover; + } + + .tools-modal { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.5); + z-index: 1000; + display: flex; + align-items: center; + justify-content: center; + } + + .tools-modal-content { + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-panel-border); + border-radius: 8px; + width: 700px; + max-width: 90vw; + max-height: 80vh; + display: flex; + flex-direction: column; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3); + overflow: hidden; + } + + .tools-modal-header { + padding: 16px 20px; + border-bottom: 1px solid var(--vscode-panel-border); + display: flex; + justify-content: space-between; + align-items: center; + flex-shrink: 0; + } + + .tools-modal-body { + flex: 1; + overflow-y: auto; + overflow-x: hidden; + } + + .tools-modal-header span { + font-weight: 600; + font-size: 14px; + color: var(--vscode-foreground); + } + + .tools-close-btn { + background: none; + border: none; + color: var(--vscode-foreground); + cursor: pointer; + font-size: 16px; + padding: 4px; + } + + .tools-beta-warning { + padding: 12px 16px; + background-color: var(--vscode-notifications-warningBackground); + color: var(--vscode-notifications-warningForeground); + font-size: 12px; + border-bottom: 1px solid var(--vscode-panel-border); + } + + .tools-list { + padding: 20px; + max-height: 400px; + overflow-y: auto; + } + + .tool-item { + display: flex; + align-items: flex-start; + gap: 12px; + padding: 16px 0; + cursor: pointer; + border-radius: 6px; + transition: background-color 0.2s ease; + } + + .tool-item:last-child { + border-bottom: none; + } + + .tool-item:hover { + background-color: var(--vscode-list-hoverBackground); + padding: 16px 12px; + margin: 0 -12px; + } + + .tool-item input[type="checkbox"], + .tool-item input[type="radio"] { + margin: 0; + margin-top: 2px; + flex-shrink: 0; + } + + .tool-item label { + color: var(--vscode-foreground); + font-size: 13px; + cursor: pointer; + flex: 1; + line-height: 1.4; + } + + .tool-item input[type="checkbox"]:disabled + label { + opacity: 0.7; + } + + /* Model selection specific styles */ + .model-explanatory-text { + padding: 20px; + padding-bottom: 0px; + font-size: 12px; + color: var(--vscode-descriptionForeground); + line-height: 1.4; + } + + .model-title { + font-weight: 600; + margin-bottom: 4px; + } + + .model-description { + font-size: 11px; + color: var(--vscode-descriptionForeground); + line-height: 1.3; + } + + .model-option-content { + flex: 1; + } + + .default-model-layout { + cursor: pointer; + display: flex; + align-items: flex-start; + justify-content: space-between; + width: 100%; + } + + .configure-button { + margin-left: 12px; + flex-shrink: 0; + align-self: flex-start; + } + + /* Thinking intensity slider */ + .thinking-slider-container { + position: relative; + padding: 0px 16px; + margin: 12px 0; + } + + .thinking-slider { + width: 100%; + height: 4px; + -webkit-appearance: none; + appearance: none; + background: var(--vscode-panel-border); + outline: none !important; + border: none; + cursor: pointer; + border-radius: 2px; + } + + .thinking-slider::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 16px; + height: 16px; + background: var(--vscode-foreground); + cursor: pointer; + border-radius: 50%; + transition: transform 0.2s ease; + } + + .thinking-slider::-webkit-slider-thumb:hover { + transform: scale(1.2); + } + + .thinking-slider::-moz-range-thumb { + width: 16px; + height: 16px; + background: var(--vscode-foreground); + cursor: pointer; + border-radius: 50%; + border: none; + transition: transform 0.2s ease; + } + + .thinking-slider::-moz-range-thumb:hover { + transform: scale(1.2); + } + + .slider-labels { + display: flex; + justify-content: space-between; + margin-top: 12px; + padding: 0 8px; + } + + .slider-label { + font-size: 12px; + color: var(--vscode-descriptionForeground); + opacity: 0.7; + transition: all 0.2s ease; + text-align: center; + width: 100px; + cursor: pointer; + } + + .slider-label:hover { + opacity: 1; + color: var(--vscode-foreground); + } + + .slider-label.active { + opacity: 1; + color: var(--vscode-foreground); + font-weight: 500; + } + + .slider-label:first-child { + margin-left: -50px; + } + + .slider-label:last-child { + margin-right: -50px; + } + + .settings-group { + padding-bottom: 20px; + margin-bottom: 40px; + border-bottom: 1px solid rgba(255, 255, 255, 0.05); + } + + .settings-group h3 { + margin: 0 0 12px 0; + font-size: 13px; + font-weight: 600; + color: var(--vscode-foreground); + } + + /* Thinking intensity modal */ + .thinking-modal-description { + padding: 0px 20px; + font-size: 12px; + color: var(--vscode-descriptionForeground); + line-height: 1.5; + text-align: center; + margin: 20px; + margin-bottom: 0px; + } + + .thinking-modal-actions { + padding-top: 20px; + text-align: right; + border-top: 1px solid var(--vscode-widget-border); + } + + .confirm-btn { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); + border: 1px solid var(--vscode-panel-border); + padding: 6px 12px; + border-radius: 4px; + cursor: pointer; + font-size: 12px; + font-weight: 400; + transition: all 0.2s ease; + display: inline-flex; + align-items: center; + gap: 5px; + } + + .confirm-btn:hover { + background-color: var(--vscode-button-background); + border-color: var(--vscode-focusBorder); + } + + /* Slash commands modal */ + .slash-commands-search { + padding: 16px 20px; + border-bottom: 1px solid var(--vscode-panel-border); + position: sticky; + top: 0; + background-color: var(--vscode-editor-background); + z-index: 10; + } + + .search-input-wrapper { + display: flex; + align-items: center; + border: 1px solid var(--vscode-input-border); + border-radius: 6px; + background-color: var(--vscode-input-background); + transition: all 0.2s ease; + position: relative; + } + + .search-input-wrapper:focus-within { + border-color: var(--vscode-focusBorder); + box-shadow: 0 0 0 1px var(--vscode-focusBorder); + } + + .search-prefix { + display: flex; + align-items: center; + justify-content: center; + min-width: 32px; + height: 32px; + background-color: var(--vscode-button-secondaryBackground); + color: var(--vscode-button-secondaryForeground); + font-size: 13px; + font-weight: 600; + border-radius: 4px 0 0 4px; + border-right: 1px solid var(--vscode-input-border); + } + + .slash-commands-search input { + flex: 1; + padding: 8px 12px; + border: none !important; + background: transparent; + color: var(--vscode-input-foreground); + font-size: 13px; + outline: none !important; + box-shadow: none !important; + } + + .slash-commands-search input:focus { + border: none !important; + outline: none !important; + box-shadow: none !important; + } + + .slash-commands-search input::placeholder { + color: var(--vscode-input-placeholderForeground); + } + + .command-input-wrapper { + display: flex; + align-items: center; + border: 1px solid var(--vscode-input-border); + border-radius: 6px; + background-color: var(--vscode-input-background); + transition: all 0.2s ease; + width: 100%; + position: relative; + } + + .command-input-wrapper:focus-within { + border-color: var(--vscode-focusBorder); + box-shadow: 0 0 0 1px var(--vscode-focusBorder); + } + + .command-prefix { + display: flex; + align-items: center; + justify-content: center; + min-width: 32px; + height: 32px; + background-color: var(--vscode-button-secondaryBackground); + color: var(--vscode-button-secondaryForeground); + font-size: 12px; + font-weight: 600; + border-radius: 4px 0 0 4px; + border-right: 1px solid var(--vscode-input-border); + } + + .slash-commands-section { + margin-bottom: 32px; + } + + .slash-commands-section:last-child { + margin-bottom: 16px; + } + + .slash-commands-section h3 { + margin: 16px 20px 12px 20px; + font-size: 14px; + font-weight: 600; + color: var(--vscode-foreground); + } + + .slash-commands-info { + padding: 12px 20px; + background-color: rgba(255, 149, 0, 0.1); + border: 1px solid rgba(255, 149, 0, 0.2); + border-radius: 4px; + margin: 0 20px 16px 20px; + } + + .slash-commands-info p { + margin: 0; + font-size: 11px; + color: var(--vscode-descriptionForeground); + text-align: center; + opacity: 0.9; + } + + .prompt-snippet-item { + border-left: 2px solid var(--vscode-charts-blue); + background-color: rgba(0, 122, 204, 0.03); + } + + .prompt-snippet-item:hover { + background-color: rgba(0, 122, 204, 0.08); + } + + .add-snippet-item { + border-left: 2px solid var(--vscode-charts-green); + background-color: rgba(0, 200, 83, 0.03); + border-style: dashed; + } + + .add-snippet-item:hover { + background-color: rgba(0, 200, 83, 0.08); + border-style: solid; + } + + .add-snippet-form { + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-panel-border); + border-radius: 6px; + padding: 16px; + margin: 8px 0; + animation: slideDown 0.2s ease; + } + + .add-snippet-form .form-group { + margin-bottom: 12px; + } + + .add-snippet-form label { + display: block; + margin-bottom: 4px; + font-weight: 500; + font-size: 12px; + color: var(--vscode-foreground); + } + + .add-snippet-form textarea { + width: 100%; + padding: 6px 8px; + border: 1px solid var(--vscode-input-border); + border-radius: 3px; + background-color: var(--vscode-input-background); + color: var(--vscode-input-foreground); + font-size: 12px; + font-family: var(--vscode-font-family); + box-sizing: border-box; + } + + .add-snippet-form .command-input-wrapper input { + flex: 1; + padding: 6px 8px; + border: none !important; + background: transparent; + color: var(--vscode-input-foreground); + font-size: 12px; + font-family: var(--vscode-font-family); + outline: none !important; + box-shadow: none !important; + } + + .add-snippet-form .command-input-wrapper input:focus { + border: none !important; + outline: none !important; + box-shadow: none !important; + } + + .add-snippet-form textarea:focus { + outline: none; + border-color: var(--vscode-focusBorder); + } + + .add-snippet-form input::placeholder, + .add-snippet-form textarea::placeholder { + color: var(--vscode-input-placeholderForeground); + } + + .add-snippet-form textarea { + resize: vertical; + min-height: 60px; + } + + .add-snippet-form .form-buttons { + display: flex; + gap: 8px; + justify-content: flex-end; + margin-top: 12px; + } + + .custom-snippet-item { + position: relative; + } + + .snippet-actions { + display: flex; + align-items: center; + opacity: 0; + transition: opacity 0.2s ease; + margin-left: 8px; + } + + .custom-snippet-item:hover .snippet-actions { + opacity: 1; + } + + .snippet-delete-btn { + background: none; + border: none; + color: var(--vscode-descriptionForeground); + cursor: pointer; + padding: 4px; + border-radius: 3px; + font-size: 12px; + transition: all 0.2s ease; + opacity: 0.7; + } + + .snippet-delete-btn:hover { + background-color: rgba(231, 76, 60, 0.1); + color: var(--vscode-errorForeground); + opacity: 1; + } + + .slash-commands-list { + display: grid; + gap: 6px; + padding: 0 20px; + } + + .slash-command-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 14px; + border-radius: 4px; + cursor: pointer; + transition: all 0.15s ease; + border: 1px solid transparent; + background-color: transparent; + } + + .slash-command-item:hover { + background-color: var(--vscode-list-hoverBackground); + border-color: var(--vscode-list-hoverBackground); + } + + .slash-command-icon { + font-size: 16px; + min-width: 20px; + text-align: center; + opacity: 0.8; + } + + .slash-command-content { + flex: 1; + } + + .slash-command-title { + font-size: 13px; + font-weight: 500; + color: var(--vscode-foreground); + margin-bottom: 2px; + } + + .slash-command-description { + font-size: 11px; + color: var(--vscode-descriptionForeground); + opacity: 0.7; + line-height: 1.3; + } + + /* Quick command input */ + .custom-command-item { + cursor: default; + } + + .custom-command-item .command-input-wrapper { + margin-top: 4px; + max-width: 200px; + } + + .secondary-button { + background-color: var(--vscode-button-secondaryBackground, rgba(128, 128, 128, 0.2)); + color: var(--vscode-button-secondaryForeground, var(--vscode-foreground)); + border: 1px solid var(--vscode-panel-border); + padding: 6px 12px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 500; + transition: all 0.2s ease; + white-space: nowrap; + } + + .secondary-button:hover { + background-color: var(--vscode-button-secondaryHoverBackground, rgba(128, 128, 128, 0.3)); + border-color: var(--vscode-focusBorder); + } +`; \ No newline at end of file diff --git a/src/styles/permission-styles.ts b/src/styles/permission-styles.ts new file mode 100644 index 0000000..9fc9232 --- /dev/null +++ b/src/styles/permission-styles.ts @@ -0,0 +1,627 @@ +export const permissionStyles = ` + /* Permission Request */ + .permission-request { + margin: 8px 16px; + background-color: #242424; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 6px; + padding: 12px; + animation: slideUp 0.2s ease; + } + + .permission-header { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 8px; + font-weight: 400; + color: #cccccc; + font-size: 12px; + } + + .permission-header .icon { + font-size: 12px; + opacity: 0.6; + } + + .permission-menu { + position: relative; + margin-left: auto; + } + + .permission-menu-btn { + background: none; + border: none; + color: var(--vscode-descriptionForeground); + cursor: pointer; + padding: 4px 8px; + border-radius: 4px; + font-size: 16px; + font-weight: bold; + transition: all 0.2s ease; + line-height: 1; + } + + .permission-menu-btn:hover { + background-color: var(--vscode-list-hoverBackground); + color: var(--vscode-foreground); + } + + .permission-menu-dropdown { + position: absolute; + top: 100%; + right: 0; + background-color: var(--vscode-menu-background); + border: 1px solid var(--vscode-menu-border); + border-radius: 6px; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); + z-index: 1000; + min-width: 220px; + padding: 4px 0; + margin-top: 4px; + } + + .permission-menu-item { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 12px 16px; + background: none; + border: none; + width: 100%; + text-align: left; + cursor: pointer; + color: var(--vscode-foreground); + transition: background-color 0.2s ease; + } + + .permission-menu-item:hover { + background-color: var(--vscode-list-hoverBackground); + } + + .permission-menu-item .menu-icon { + font-size: 16px; + margin-top: 1px; + flex-shrink: 0; + } + + .permission-menu-item .menu-content { + display: flex; + flex-direction: column; + gap: 2px; + } + + .permission-menu-item .menu-title { + font-weight: 500; + font-size: 13px; + line-height: 1.2; + } + + .permission-menu-item .menu-subtitle { + font-size: 11px; + color: var(--vscode-descriptionForeground); + opacity: 0.8; + line-height: 1.2; + } + + .permission-content { + font-size: 11px; + line-height: 1.4; + color: #808080; + } + + .permission-tool { + font-family: var(--vscode-editor-font-family); + background-color: var(--vscode-editor-background); + border: 1px solid var(--vscode-panel-border); + border-radius: 4px; + padding: 8px 10px; + margin: 8px 0; + font-size: 12px; + color: var(--vscode-editor-foreground); + } + + .permission-buttons { + margin-top: 2px; + display: flex; + gap: 8px; + justify-content: flex-end; + flex-wrap: wrap; + } + + .permission-buttons .btn { + background-color: transparent; + color: #808080; + border: 1px solid rgba(255, 255, 255, 0.08); + padding: 4px 8px; + border-radius: 4px; + cursor: pointer; + font-size: 11px; + font-weight: 400; + transition: all 0.15s ease; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + min-width: 50px; + height: 26px; + white-space: nowrap; + box-sizing: border-box; + } + + .permission-buttons .btn:hover { + background-color: rgba(255, 255, 255, 0.05); + color: #cccccc; + border-color: rgba(255, 255, 255, 0.12); + } + + .permission-buttons .btn.allow { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); + border-color: var(--vscode-button-background); + } + + .permission-buttons .btn.allow:hover { + background-color: var(--vscode-button-hoverBackground); + border-color: var(--vscode-button-hoverBackground); + } + + .permission-buttons .btn.deny { + /* Uses base styles from above */ + } + + .permission-buttons .btn.always-allow { + background-color: rgba(0, 122, 204, 0.1); + color: var(--vscode-charts-blue); + border-color: rgba(0, 122, 204, 0.3); + font-weight: 500; + min-width: auto; + padding: 6px 14px; + height: 28px; + } + + .permission-buttons .btn.always-allow:hover { + background-color: rgba(0, 122, 204, 0.2); + border-color: rgba(0, 122, 204, 0.5); + transform: translateY(-1px); + } + + .permission-buttons .btn.always-allow code { + background-color: rgba(0, 0, 0, 0.2); + padding: 2px 4px; + border-radius: 3px; + font-family: var(--vscode-editor-font-family); + font-size: 11px; + color: var(--vscode-editor-foreground); + margin-left: 4px; + display: inline; + line-height: 1; + vertical-align: baseline; + } + + .permission-decision { + font-size: 13px; + font-weight: 600; + padding: 8px 12px; + text-align: center; + border-radius: 4px; + margin-top: 8px; + } + + .permission-decision.allowed { + background-color: rgba(0, 122, 204, 0.15); + color: var(--vscode-charts-blue); + border: 1px solid rgba(0, 122, 204, 0.3); + } + + .permission-decision.denied { + background-color: rgba(231, 76, 60, 0.15); + color: #e74c3c; + border: 1px solid rgba(231, 76, 60, 0.3); + } + + .permission-decided { + opacity: 0.7; + pointer-events: none; + } + + .permission-decided .permission-buttons { + display: none; + } + + .permission-decided.allowed { + border-color: var(--vscode-inputValidation-infoBackground); + background-color: rgba(0, 122, 204, 0.1); + } + + .permission-decided.denied { + border-color: var(--vscode-inputValidation-errorBorder); + background-color: var(--vscode-inputValidation-errorBackground); + } + + /* Permissions Management */ + .permissions-list { + max-height: 300px; + overflow-y: auto; + border: 1px solid var(--vscode-panel-border); + border-radius: 6px; + background-color: var(--vscode-input-background); + margin-top: 8px; + } + + .permission-item { + display: flex; + justify-content: space-between; + align-items: center; + padding-left: 6px; + padding-right: 6px; + border-bottom: 1px solid var(--vscode-panel-border); + transition: background-color 0.2s ease; + min-height: 32px; + } + + .permission-item:hover { + background-color: var(--vscode-list-hoverBackground); + } + + .permission-item:last-child { + border-bottom: none; + } + + .permission-info { + display: flex; + align-items: center; + gap: 8px; + flex-grow: 1; + min-width: 0; + } + + .permission-command { + font-size: 12px; + color: var(--vscode-foreground); + flex-grow: 1; + } + + .permission-command code { + background-color: var(--vscode-textCodeBlock-background); + padding: 3px 6px; + border-radius: 3px; + font-family: var(--vscode-editor-font-family); + color: var(--vscode-textLink-foreground); + font-size: 11px; + height: 18px; + display: inline-flex; + align-items: center; + line-height: 1; + } + + .permission-desc { + color: var(--vscode-descriptionForeground); + font-size: 11px; + font-style: italic; + flex-grow: 1; + height: 18px; + display: inline-flex; + align-items: center; + line-height: 1; + } + + .permission-remove-btn { + background-color: transparent; + color: var(--vscode-descriptionForeground); + border: none; + padding: 4px 8px; + border-radius: 3px; + cursor: pointer; + font-size: 10px; + transition: all 0.2s ease; + font-weight: 500; + flex-shrink: 0; + opacity: 0.7; + } + + .permission-remove-btn:hover { + background-color: rgba(231, 76, 60, 0.1); + color: var(--vscode-errorForeground); + opacity: 1; + } + + .permissions-empty { + padding: 16px; + text-align: center; + color: var(--vscode-descriptionForeground); + font-style: italic; + font-size: 13px; + } + + .permissions-empty::before { + display: none; + } + + /* Add Permission Form */ + .permissions-add-section { + margin-top: 6px; + } + + .permissions-show-add-btn { + background-color: transparent; + color: var(--vscode-descriptionForeground); + border: 1px solid var(--vscode-panel-border); + border-radius: 3px; + padding: 6px 8px; + font-size: 11px; + cursor: pointer; + transition: all 0.2s ease; + font-weight: 400; + opacity: 0.7; + } + + .permissions-show-add-btn:hover { + background-color: var(--vscode-list-hoverBackground); + opacity: 1; + } + + .permissions-add-form { + margin-top: 8px; + padding: 12px; + border: 1px solid var(--vscode-panel-border); + border-radius: 6px; + background-color: var(--vscode-input-background); + animation: slideDown 0.2s ease; + } + + .permissions-form-row { + display: flex; + gap: 8px; + align-items: center; + margin-bottom: 8px; + } + + .permissions-tool-select { + background-color: var(--vscode-input-background); + color: var(--vscode-input-foreground); + border: 1px solid var(--vscode-panel-border); + border-radius: 3px; + padding: 4px 8px; + font-size: 12px; + min-width: 100px; + height: 24px; + flex-shrink: 0; + } + + .permissions-command-input { + background-color: var(--vscode-input-background); + color: var(--vscode-input-foreground); + border: 1px solid var(--vscode-panel-border); + border-radius: 3px; + padding: 4px 8px; + font-size: 12px; + flex-grow: 1; + height: 24px; + font-family: var(--vscode-editor-font-family); + } + + .permissions-command-input::placeholder { + color: var(--vscode-input-placeholderForeground); + } + + .permissions-add-btn { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); + border: none; + border-radius: 3px; + padding: 4px 12px; + font-size: 12px; + cursor: pointer; + transition: background-color 0.2s ease; + height: 24px; + font-weight: 500; + flex-shrink: 0; + } + + .permissions-add-btn:hover { + background-color: var(--vscode-button-hoverBackground); + } + + .permissions-add-btn:disabled { + background-color: var(--vscode-button-secondaryBackground); + color: var(--vscode-button-secondaryForeground); + cursor: not-allowed; + opacity: 0.5; + } + + .permissions-cancel-btn { + background-color: transparent; + color: var(--vscode-foreground); + border: 1px solid var(--vscode-panel-border); + border-radius: 3px; + padding: 4px 12px; + font-size: 12px; + cursor: pointer; + transition: all 0.2s ease; + height: 24px; + font-weight: 500; + } + + .permissions-cancel-btn:hover { + background-color: var(--vscode-list-hoverBackground); + border-color: var(--vscode-focusBorder); + } + + .permissions-form-hint { + font-size: 11px; + color: var(--vscode-descriptionForeground); + font-style: italic; + line-height: 1.3; + } + + .yolo-mode-section { + display: flex; + align-items: center; + gap: 6px; + margin-top: 12px; + opacity: 1; + transition: opacity 0.2s ease; + } + + .yolo-mode-section:hover { + opacity: 1; + } + + .yolo-mode-section input[type="checkbox"] { + transform: scale(0.9); + margin: 0; + } + + .yolo-mode-section label { + font-size: 12px; + color: var(--vscode-descriptionForeground); + cursor: pointer; + font-weight: 400; + } + + /* Minimal Permission Request */ + .permission-request-minimal { + margin: 3px 16px; + background-color: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(100, 149, 237, 0.4); + border-radius: 4px; + padding: 6px 10px; + font-size: 12px; + color: var(--vscode-descriptionForeground); + animation: slideUp 0.15s ease; + } + + .permission-minimal-content { + display: flex; + flex-direction: column; + gap: 6px; + } + + .permission-minimal-buttons { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 6px; + align-self: flex-end; + width: 100%; + } + + .btn-minimal { + background-color: transparent; + color: #808080; + border: 1px solid rgba(255, 255, 255, 0.08); + padding: 4px 6px; + border-radius: 3px; + cursor: pointer; + font-size: 11px; + font-weight: 400; + transition: all 0.15s ease; + height: 22px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; + min-width: 40px; + } + + .btn-minimal:hover { + background-color: rgba(255, 255, 255, 0.05); + color: #cccccc; + border-color: rgba(255, 255, 255, 0.12); + } + + .btn-minimal.allow { + background-color: var(--vscode-button-background); + color: var(--vscode-button-foreground); + border-color: var(--vscode-button-background); + } + + .btn-minimal.allow:hover { + background-color: var(--vscode-button-hoverBackground); + border-color: var(--vscode-button-hoverBackground); + } + + .btn-minimal.deny { + /* Uses base styles from above */ + } + + .allow-button-group { + position: relative; + display: flex; + align-items: center; + } + + .allow-dropdown-btn { + background: transparent; + border: 1px solid rgba(255, 255, 255, 0.12); + border-left: none; + border-radius: 0 3px 3px 0; + padding: 4px 3px; + cursor: pointer; + color: var(--vscode-descriptionForeground); + height: 22px; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.15s ease; + margin-left: -1px; + } + + .allow-dropdown-btn:hover { + background-color: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.16); + color: var(--vscode-foreground); + } + + .allow-button-group .btn-minimal.allow { + border-radius: 3px 0 0 3px; + } + + .always-allow-dropdown { + position: absolute; + bottom: 100%; + right: 0; + background-color: var(--vscode-menu-background); + border: 1px solid var(--vscode-menu-border); + border-radius: 3px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + z-index: 1000; + margin-bottom: 2px; + } + + .always-allow-option { + display: block; + width: 100%; + padding: 6px 10px; + background: none; + border: none; + text-align: left; + cursor: pointer; + color: var(--vscode-foreground); + font-size: 11px; + transition: background-color 0.15s ease; + white-space: nowrap; + } + + .always-allow-option:hover { + background-color: var(--vscode-list-hoverBackground); + } + + .permission-minimal-decision { + font-size: 11px; + font-weight: 500; + padding: 4px 8px; + border-radius: 3px; + } + + .permission-minimal-decision.allowed { + color: var(--vscode-charts-blue); + background-color: rgba(0, 122, 204, 0.1); + } + + .permission-minimal-decision.denied { + color: #e74c3c; + background-color: rgba(231, 76, 60, 0.1); + } +`; \ No newline at end of file diff --git a/src/styles/tool-styles.ts b/src/styles/tool-styles.ts new file mode 100644 index 0000000..1ae8b0c --- /dev/null +++ b/src/styles/tool-styles.ts @@ -0,0 +1,76 @@ +export const toolStyles = ` + .tool-icon { + width: 14px; + height: 14px; + border-radius: 2px; + background: rgba(255, 255, 255, 0.1); + display: flex; + align-items: center; + justify-content: center; + font-size: 8px; + color: #999999; + font-weight: 400; + flex-shrink: 0; + margin-left: 0; + } + + .tool-info { + font-weight: 400; + font-size: 11px; + color: #999999; + opacity: 0.8; + cursor: default; /* Ensure tool name is not clickable */ + } + + .clickable-filename { + cursor: pointer; + color: var(--vscode-textLink-foreground); + text-decoration: underline; + text-decoration-color: transparent; + transition: all 0.2s ease; + border-radius: 2px; + padding: 1px 2px; + } + + .clickable-filename:hover { + color: var(--vscode-textLink-activeForeground); + text-decoration-color: currentColor; + background-color: var(--vscode-textLink-foreground); + color: var(--vscode-editor-background); + } + + .tool-input { + padding: 0; + font-family: var(--vscode-editor-font-family); + font-size: 12px; + line-height: 1.4; + white-space: pre-line; + } + + .tool-input-label { + color: var(--vscode-descriptionForeground); + font-size: 11px; + font-weight: 500; + margin-bottom: 6px; + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .tool-input-content { + color: var(--vscode-editor-foreground); + opacity: 0.95; + } + + /* Todo list styling */ + .tool-input-content span { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 12px; + } + + /* Completed todo strikethrough positioning */ + .tool-input-content span[style*="line-through"] { + text-decoration-thickness: 1px; + text-underline-offset: 0.2em; + text-decoration-skip-ink: none; + } +`; \ No newline at end of file diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 0000000..0bd9268 --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1,109 @@ +import * as vscode from 'vscode'; + +export interface ConversationData { + sessionId: string; + startTime: string | undefined; + endTime: string; + messageCount: number; + totalCost: number; + totalTokens: { + input: number; + output: number; + }; + messages: Array<{ timestamp: string, messageType: string, data: any }>; + filename: string; +} + +export interface ConversationIndexEntry { + filename: string; + sessionId: string; + startTime: string; + endTime: string; + messageCount: number; + totalCost: number; + firstUserMessage: string; + lastUserMessage: string; +} + +export interface CommitInfo { + id: string; + sha: string; + message: string; + timestamp: string; +} + +export interface TokenUsage { + input_tokens?: number; + output_tokens?: number; + cache_creation_input_tokens?: number; + cache_read_input_tokens?: number; +} + +export interface WebviewMessage { + type: string; + data?: any; + text?: string; + planMode?: boolean; + thinkingMode?: boolean; + model?: string; + command?: string; + filename?: string; + settings?: { [key: string]: any }; + searchTerm?: string; + filePath?: string; + imageData?: string; + imageType?: string; + id?: string; + approved?: boolean; + alwaysAllow?: boolean; + toolName?: string; + name?: string; + config?: any; + snippetId?: string; + snippet?: any; +} + +export interface PermissionRequest { + id: string; + tool: string; + input: any; + timestamp: string; +} + +export interface PermissionResponse { + id: string; + approved: boolean; + timestamp: string; +} + +export interface Permissions { + alwaysAllow: { [toolName: string]: boolean | string[] }; +} + +export interface MCPServerConfig { + command: string; + args: string[]; + env?: { [key: string]: string }; +} + +export interface WorkspaceFile { + name: string; + path: string; + fsPath: string; +} + +export interface ClaudeSettings { + 'thinking.intensity': string; + 'wsl.enabled': boolean; + 'wsl.distro': string; + 'wsl.nodePath': string; + 'wsl.claudePath': string; + 'permissions.yoloMode': boolean; +} + +export interface PlatformInfo { + platform: string; + isWindows: boolean; + wslAlertDismissed: boolean; + wslEnabled: boolean; +} \ No newline at end of file diff --git a/src/ui-components/index.ts b/src/ui-components/index.ts new file mode 100644 index 0000000..cd03fec --- /dev/null +++ b/src/ui-components/index.ts @@ -0,0 +1,20 @@ +import { getCoreTemplate } from './ui-core'; +import { getHeaderHtml } from './ui-header'; +import { getChatContainerHtml } from './ui-chat'; +import { getInputControlsHtml } from './ui-input'; +import { getNotificationsHtml } from './ui-notifications'; +import { getModalsHtml } from './ui-modals'; + +export const getHtml = (isTelemetryEnabled: boolean) => { + const bodyContent = ` + ${getHeaderHtml()} + ${getChatContainerHtml()} + ${getNotificationsHtml()} + ${getInputControlsHtml()} + ${getModalsHtml()} + `; + + return getCoreTemplate(isTelemetryEnabled, bodyContent); +}; + +export default getHtml; \ No newline at end of file diff --git a/src/ui-components/ui-chat.ts b/src/ui-components/ui-chat.ts new file mode 100644 index 0000000..c3514d3 --- /dev/null +++ b/src/ui-components/ui-chat.ts @@ -0,0 +1,11 @@ +export const getChatContainerHtml = () => ` +
+
+
+ +`; \ No newline at end of file diff --git a/src/ui-components/ui-core.ts b/src/ui-components/ui-core.ts new file mode 100644 index 0000000..339fc85 --- /dev/null +++ b/src/ui-components/ui-core.ts @@ -0,0 +1,28 @@ +import getScript from '../script'; +import styles from '../ui-styles'; + +export const getCoreTemplate = (isTelemetryEnabled: boolean, bodyContent: string) => ` + + + + + Claude Code Chat + ${styles} + + + ${bodyContent} + + ${getScript(isTelemetryEnabled)} + + + ${isTelemetryEnabled ? '' : ''} + +`; \ No newline at end of file diff --git a/src/ui-components/ui-header.ts b/src/ui-components/ui-header.ts new file mode 100644 index 0000000..b639a4f --- /dev/null +++ b/src/ui-components/ui-header.ts @@ -0,0 +1,17 @@ +export const getHeaderHtml = () => ` +
+
+

Claude Code Chat

+ +
+
+ + + + +
+
+`; \ No newline at end of file diff --git a/src/ui-components/ui-input.ts b/src/ui-components/ui-input.ts new file mode 100644 index 0000000..fb06e34 --- /dev/null +++ b/src/ui-components/ui-input.ts @@ -0,0 +1,80 @@ +export const getInputControlsHtml = () => ` +
+
+
+
+ Plan First +
+
+
+ Thinking Mode +
+
+
+
+
+
Initializing...
+
+
+
+
+ +
+
+ + +
+
+ + + + +
+
+
+
+
+`; \ No newline at end of file diff --git a/src/ui-components/ui-modals.ts b/src/ui-components/ui-modals.ts new file mode 100644 index 0000000..1d989e3 --- /dev/null +++ b/src/ui-components/ui-modals.ts @@ -0,0 +1,562 @@ +export const getModalsHtml = () => ` + + + + + + + + + + + + + + + + +