@aicloud360/mcp-server-disk 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +219 -0
  2. package/build/index.js +2 -0
  3. package/package.json +52 -0
package/README.md ADDED
@@ -0,0 +1,219 @@
1
+ # 360 AI 云盘 MCP
2
+
3
+ 360 AI 云盘的 Model Context Protocol 接入服务,让 AI 模型能够通过 MCP 协议直接操作云盘,提供完整的云盘文件管理能力。
4
+
5
+ <div align="center">
6
+ </div>
7
+
8
+ ## 📚 简介
9
+
10
+ 本项目为 360 AI 云盘的 MCP(Model Context Protocol)服务实现,允许各类 AI 模型(如大语言模型)通过标准的 MCP 协议与 360 AI 云盘进行交互。通过这种方式,AI 模型可以帮助用户管理云盘文件,极大地提升了文件管理的智能化和便捷性。
11
+
12
+ ## 🔧 在 Cursor 中配置
13
+
14
+ 在 `~/.cursor/mcp.json` 文件中添加以下配置,连接 360 AI 云盘 MCP 服务:
15
+
16
+ ```json
17
+ {
18
+ "mcpServers": {
19
+ "360-mcp-server-disk": {
20
+ "command": "npx",
21
+ "args": [
22
+ "-y",
23
+ "@aicloud360/mcp-server-disk"
24
+ ],
25
+ "env": {
26
+ "API_KEY": "_xxxxxxxxx"
27
+ }
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ ## 🔐 认证配置
34
+
35
+ 使用 360 AI 云盘 MCP 服务需要以下认证信息:
36
+
37
+ - `API_KEY`:360AI云盘 API 密钥,格式为 "yunpan_" 开头的字符串
38
+
39
+ 您可以通过以下方式获取API_KEY:
40
+ - 参照 [快速接入](https://qa-open.yunpan.360.cn/metro/docs/mcp-server/preparation) MCP Server
41
+
42
+ ### 360 AI 云盘开放平台优势
43
+
44
+ 360 AI 云盘开放平台提供了多元化的产品能力和一站式文件服务:
45
+
46
+ - **账号一键关联**:无需重新注册账号,现有360 AI 云盘账号一键关联,实现"多平台,一账号"的无缝登录体验
47
+ - **支持 MCP 协议接入**:支持 Stdio/SSH/Streamable HTTP 协议,通过 MCP Client 轻松接入
48
+ - **丰富接口能力**:提供文件上传、下载、搜索、新建、重命名、移动、分享等 API,满足不同场景需求
49
+
50
+ 访问 [360 AI 云盘开放平台官网](https://qa-open.yunpan.360.cn/metro/) 获取更多详细信息和最新的开发文档。
51
+
52
+ ## ✨ 功能概览
53
+
54
+ 本 MCP 服务提供与 360AI 云盘交互的多种操作,包括:
55
+
56
+ - 📁 文件列表浏览 - 查看云盘目录内容
57
+ - 🔍 文件搜索 - 根据关键词搜索云盘文件
58
+ - ⬆️ 文件上传 - 将文件上传至 360 云盘
59
+ - 📂 目录创建 - 在云盘中创建新文件夹
60
+ - ✏️ 文件重命名 - 修改云盘文件或文件夹名称
61
+ - 🚚 文件移动 - 将文件移动到其他位置
62
+ - 🗑️ 文件分享 - 将指定文件生成分享链接
63
+ - 🔑 用户个人信息 - 获取用户信息
64
+
65
+ ## 🛠️ 工具使用指南
66
+
67
+ 当连接到 360 AI 云盘 MCP 服务后,可以使用以下工具与云盘交互:
68
+
69
+ ### 文件列表查询 (file-list)
70
+
71
+ 获取 360 AI云盘指定路径下的文件和文件夹列表。
72
+
73
+ **参数:**
74
+ - `path`: 要查询的路径,默认为根目录 `/`
75
+ - `page`: 页码,默认为 0
76
+ - `page_size`: 每页显示条数,默认为 50
77
+
78
+ **示例:**
79
+ ```json
80
+ {
81
+ "path": "/文档",
82
+ "page": 1,
83
+ "page_size": 20
84
+ }
85
+ ```
86
+
87
+ ### 文件搜索 (file-search)
88
+
89
+ 根据关键词搜索 360 AI云盘文件。
90
+
91
+ **参数:**
92
+ - `key`: 搜索关键词(必填)
93
+ - `file_category`: 文件类型(-1:全部,0:其他,1:图片,2:文档,3:音乐,4:视频),默认为 -1
94
+ - `page`: 页码,默认为 1
95
+ - `page_size`: 每页显示条数,默认为 20
96
+
97
+ **示例:**
98
+ ```json
99
+ {
100
+ "key": "报告",
101
+ "file_category": 2,
102
+ "page": 1
103
+ }
104
+ ```
105
+
106
+ ### 文件上传 (upload-file)
107
+
108
+ 将本地文件上传到 360 AI云盘指定路径。
109
+
110
+ **参数:**
111
+ - `filePaths`: 本地文件的完整路径(必填,可以是字符串数组包含多个文件)
112
+ - `uploadPath`: 上传到云盘的目标目录,默认为根目录 `/`
113
+
114
+ **示例:**
115
+ ```json
116
+ {
117
+ "filePaths": ["/Users/username/Documents/报告.docx", "/Users/username/Documents/数据.xlsx"],
118
+ "uploadPath": "/工作文件"
119
+ }
120
+ ```
121
+
122
+ **单文件上传示例:**
123
+ ```json
124
+ {
125
+ "filePaths": "/Users/username/Desktop/测试文档.pdf",
126
+ "uploadPath": "/文档"
127
+ }
128
+ ```
129
+
130
+ ### 创建文件夹 (make-dir)
131
+
132
+ 在 360 AI云盘中创建新文件夹。
133
+
134
+ **参数:**
135
+ - `fname`: 文件夹路径,例如:`/新文件夹/`(必填)
136
+
137
+ **示例:**
138
+ ```json
139
+ {
140
+ "fname": "/工作文件/项目A/"
141
+ }
142
+ ```
143
+
144
+ ### 文件分享 (file-share)
145
+
146
+ 将指定文件生成分享链接。
147
+
148
+ **参数:**
149
+ - `paths`: 要分享的文件路径,多个文件路径用竖线(|)隔开(必填)
150
+
151
+ **示例:**
152
+ ```json
153
+ {
154
+ "paths": "/文档/报告.docx|/文档/数据.xlsx"
155
+ }
156
+ ```
157
+
158
+ ### 移动文件 (file-move)
159
+
160
+ 移动 360 AI云盘中的文件或文件夹到新位置。
161
+
162
+ **参数:**
163
+ - `src_name`: 文件原路径,多个路径用竖线隔开(必填)
164
+ - `new_name`: 目标路径(必填)
165
+
166
+ **示例:**
167
+ ```json
168
+ {
169
+ "src_name": "/文档/报告.docx|/文档/数据.xlsx",
170
+ "new_name": "/归档文件夹/"
171
+ }
172
+ ```
173
+
174
+ ### 重命名文件 (file-rename)
175
+
176
+ 重命名 360AI 云盘中的文件或文件夹。
177
+
178
+ **参数:**
179
+ - `src_name`: 原路径名称,如:`/文件夹/旧文件名.txt`(必填)
180
+ - `new_name`: 新名称,如:`新文件名.txt`(必填)
181
+
182
+ **示例:**
183
+ ```json
184
+ {
185
+ "src_name": "/文档/草稿.docx",
186
+ "new_name": "最终报告.docx"
187
+ }
188
+ ```
189
+
190
+ ### 用户个人信息 (user-info)
191
+
192
+ 获取 360 AI云盘用户个人信息。
193
+
194
+ **参数:**
195
+ - 无
196
+
197
+
198
+ ## 🧠 AI 应用场景
199
+
200
+ 通过 360 AI 云盘 MCP 接入,AI 可以帮助用户实现以下场景:
201
+
202
+ - **智能文件整理**:AI 可以分析用户文件内容,并自动归类整理
203
+ - **文档智能检索**:使用自然语言描述查找云盘内的文档
204
+ - **自动文件备份**:根据用户习惯,提供智能备份建议
205
+ - **文件内容分析**:分析文档内容并提供摘要或见解
206
+ - **基于对话的文件操作**:用户可以通过对话方式管理云盘文件
207
+ - **文件上传及分享**:用户可以通过对话方式保存文件到云盘,并生成文件分享链接,方便把文件分享给他人。
208
+
209
+ ## 🔑 关键词
210
+
211
+ - 360 AI 云盘
212
+ - mcp
213
+ - modelcontextprotocol
214
+ - ai助手
215
+ - 文件管理
216
+
217
+ ## 📄 许可证
218
+
219
+ Apache-2.0
package/build/index.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import e from"node:process";import t from"dotenv";import r from"crypto";import n from"fs";import s from"path";import{fileURLToPath as i}from"url";var a,o;!function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(a||(a={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(o||(o={}));const c=a.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),u=e=>{switch(typeof e){case"undefined":return c.undefined;case"string":return c.string;case"number":return isNaN(e)?c.nan:c.number;case"boolean":return c.boolean;case"function":return c.function;case"bigint":return c.bigint;case"symbol":return c.symbol;case"object":return Array.isArray(e)?c.array:null===e?c.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?c.promise:"undefined"!=typeof Map&&e instanceof Map?c.map:"undefined"!=typeof Set&&e instanceof Set?c.set:"undefined"!=typeof Date&&e instanceof Date?c.date:c.object;default:return c.unknown}},h=a.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"]);class d extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={t:[]},n=e=>{for(const s of e.issues)if("invalid_union"===s.code)s.unionErrors.map(n);else if("invalid_return_type"===s.code)n(s.returnTypeError);else if("invalid_arguments"===s.code)n(s.argumentsError);else if(0===s.path.length)r.t.push(t(s));else{let e=r,n=0;for(;n<s.path.length;){const r=s.path[n];n===s.path.length-1?(e[r]=e[r]||{t:[]},e[r].t.push(t(s))):e[r]=e[r]||{t:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof d))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,a.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}d.create=e=>new d(e);const l=(e,t)=>{let r;switch(e.code){case h.invalid_type:r=e.received===c.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case h.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,a.jsonStringifyReplacer)}`;break;case h.unrecognized_keys:r=`Unrecognized key(s) in object: ${a.joinValues(e.keys,", ")}`;break;case h.invalid_union:r="Invalid input";break;case h.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${a.joinValues(e.options)}`;break;case h.invalid_enum_value:r=`Invalid enum value. Expected ${a.joinValues(e.options)}, received '${e.received}'`;break;case h.invalid_arguments:r="Invalid function arguments";break;case h.invalid_return_type:r="Invalid function return type";break;case h.invalid_date:r="Invalid date";break;case h.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:a.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case h.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case h.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case h.custom:r="Invalid input";break;case h.invalid_intersection_types:r="Intersection results could not be merged";break;case h.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case h.not_finite:r="Number must be finite";break;default:r=t.defaultError,a.assertNever(e)}return{message:r}};let p=l;function m(){return p}const f=e=>{const{data:t,path:r,errorMaps:n,issueData:s}=e,i=[...r,...s.path||[]],a={...s,path:i};if(void 0!==s.message)return{...s,path:i,message:s.message};let o="";const c=n.filter((e=>!!e)).slice().reverse();for(const e of c)o=e(a,{data:t,defaultError:o}).message;return{...s,path:i,message:o}};function y(e,t){const r=m(),n=f({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===l?void 0:l].filter((e=>!!e))});e.common.issues.push(n)}class g{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return v;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const e of t){const t=await e.key,n=await e.value;r.push({key:t,value:n})}return g.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:s}=n;if("aborted"===t.status)return v;if("aborted"===s.status)return v;"dirty"===t.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===t.value||void 0===s.value&&!n.alwaysSet||(r[t.value]=s.value)}return{status:e.value,value:r}}}const v=Object.freeze({status:"aborted"}),w=e=>({status:"dirty",value:e}),b=e=>({status:"valid",value:e}),x=e=>"aborted"===e.status,$=e=>"dirty"===e.status,k=e=>"valid"===e.status,_=e=>"undefined"!=typeof Promise&&e instanceof Promise;function A(e,t,r,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function E(e,t,r,n,s){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var P,I,S;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(P||(P={}));class Z{constructor(e,t,r,n){this.i=[],this.parent=e,this.data=t,this.o=r,this.u=n}get path(){return this.i.length||(this.u instanceof Array?this.i.push(...this.o,...this.u):this.i.push(...this.o,this.u)),this.i}}const N=(e,t)=>{if(k(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this.h)return this.h;const t=new d(e.common.issues);return this.h=t,this.h}}};function j(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{var i,a;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:s.defaultError}:void 0===s.data?{message:null!==(i=null!=o?o:n)&&void 0!==i?i:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(a=null!=o?o:r)&&void 0!==a?a:s.defaultError}},description:s}}class O{get description(){return this.l.description}p(e){return u(e.data)}m(e,t){return t||{common:e.parent.common,data:e.data,parsedType:u(e.data),schemaErrorMap:this.l.errorMap,path:e.path,parent:e.parent}}v(e){return{status:new g,ctx:{common:e.parent.common,data:e.data,parsedType:u(e.data),schemaErrorMap:this.l.errorMap,path:e.path,parent:e.parent}}}$(e){const t=this.k(e);if(_(t))throw new Error("Synchronous parse encountered promise.");return t}_(e){const t=this.k(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this.l.errorMap,parent:null,data:e,parsedType:u(e)},s=this.$({data:e,path:n.path,parent:n});return N(n,s)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this.l.errorMap,parent:null,data:e,parsedType:u(e)};if(!this["~standard"].async)try{const t=this.$({data:e,path:[],parent:n});return k(t)?{value:t.value}:{issues:n.common.issues}}catch(e){(null===(r=null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._({data:e,path:[],parent:n}).then((e=>k(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this.l.errorMap,parent:null,data:e,parsedType:u(e)},n=this.k({data:e,path:r.path,parent:r}),s=await(_(n)?n:Promise.resolve(n));return N(r,s)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this.A(((t,n)=>{const s=e(t),i=()=>n.addIssue({code:h.custom,...r(t)});return"undefined"!=typeof Promise&&s instanceof Promise?s.then((e=>!!e||(i(),!1))):!!s||(i(),!1)}))}refinement(e,t){return this.A(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}A(e){return new Oe({schema:this,typeName:Je.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this.A(e)}constructor(e){this.spa=this.safeParseAsync,this.l=e,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:e=>this["~validate"](e)}}optional(){return Te.create(this,this.l)}nullable(){return Fe.create(this,this.l)}nullish(){return this.nullable().optional()}array(){return me.create(this)}promise(){return je.create(this,this.l)}or(e){return ge.create([this,e],this.l)}and(e){return xe.create(this,e,this.l)}transform(e){return new Oe({...j(this.l),schema:this,typeName:Je.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Me({...j(this.l),innerType:this,defaultValue:t,typeName:Je.ZodDefault})}brand(){return new ze({typeName:Je.ZodBranded,type:this,...j(this.l)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ce({...j(this.l),innerType:this,catchValue:t,typeName:Je.ZodCatch})}describe(e){return new(0,this.constructor)({...this.l,description:e})}pipe(e){return De.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const T=/^c[^\s-]{8,}$/i,F=/^[0-9a-z]+$/,M=/^[0-9A-HJKMNP-TV-Z]{26}$/i,C=/^[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,R=/^[a-z0-9_-]{21}$/i,q=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,z=/^[-+]?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)?)??$/,D=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let L;const U=/^(?:(?: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])$/,B=/^(?:(?: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])$/,K=/^(([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]))$/,J=/^(([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])$/,V=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,H=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,W="((\\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])))",Y=new RegExp(`^${W}$`);function G(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function Q(e){let t=`${W}T${G(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function X(e,t){if(!q.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return"object"==typeof s&&null!==s&&(!(!s.typ||!s.alg)&&(!t||s.alg===t))}catch(e){return!1}}function ee(e,t){return!("v4"!==t&&t||!B.test(e))||!("v6"!==t&&t||!J.test(e))}class te extends O{k(e){this.l.coerce&&(e.data=String(e.data));if(this.p(e)!==c.string){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.string,received:t.parsedType}),v}const t=new g;let r;for(const i of this.l.checks)if("min"===i.kind)e.data.length<i.value&&(r=this.m(e,r),y(r,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(r=this.m(e,r),y(r,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const n=e.data.length>i.value,s=e.data.length<i.value;(n||s)&&(r=this.m(e,r),n?y(r,{code:h.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&y(r,{code:h.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)D.test(e.data)||(r=this.m(e,r),y(r,{validation:"email",code:h.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)L||(L=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),L.test(e.data)||(r=this.m(e,r),y(r,{validation:"emoji",code:h.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)C.test(e.data)||(r=this.m(e,r),y(r,{validation:"uuid",code:h.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)R.test(e.data)||(r=this.m(e,r),y(r,{validation:"nanoid",code:h.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)T.test(e.data)||(r=this.m(e,r),y(r,{validation:"cuid",code:h.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)F.test(e.data)||(r=this.m(e,r),y(r,{validation:"cuid2",code:h.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)M.test(e.data)||(r=this.m(e,r),y(r,{validation:"ulid",code:h.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch(n){r=this.m(e,r),y(r,{validation:"url",code:h.invalid_string,message:i.message}),t.dirty()}else if("regex"===i.kind){i.regex.lastIndex=0;i.regex.test(e.data)||(r=this.m(e,r),y(r,{validation:"regex",code:h.invalid_string,message:i.message}),t.dirty())}else if("trim"===i.kind)e.data=e.data.trim();else if("includes"===i.kind)e.data.includes(i.value,i.position)||(r=this.m(e,r),y(r,{code:h.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty());else if("toLowerCase"===i.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===i.kind)e.data=e.data.toUpperCase();else if("startsWith"===i.kind)e.data.startsWith(i.value)||(r=this.m(e,r),y(r,{code:h.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty());else if("endsWith"===i.kind)e.data.endsWith(i.value)||(r=this.m(e,r),y(r,{code:h.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty());else if("datetime"===i.kind){Q(i).test(e.data)||(r=this.m(e,r),y(r,{code:h.invalid_string,validation:"datetime",message:i.message}),t.dirty())}else if("date"===i.kind){Y.test(e.data)||(r=this.m(e,r),y(r,{code:h.invalid_string,validation:"date",message:i.message}),t.dirty())}else if("time"===i.kind){new RegExp(`^${G(i)}$`).test(e.data)||(r=this.m(e,r),y(r,{code:h.invalid_string,validation:"time",message:i.message}),t.dirty())}else"duration"===i.kind?z.test(e.data)||(r=this.m(e,r),y(r,{validation:"duration",code:h.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(n=e.data,("v4"!==(s=i.version)&&s||!U.test(n))&&("v6"!==s&&s||!K.test(n))&&(r=this.m(e,r),y(r,{validation:"ip",code:h.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?X(e.data,i.alg)||(r=this.m(e,r),y(r,{validation:"jwt",code:h.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?ee(e.data,i.version)||(r=this.m(e,r),y(r,{validation:"cidr",code:h.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?V.test(e.data)||(r=this.m(e,r),y(r,{validation:"base64",code:h.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?H.test(e.data)||(r=this.m(e,r),y(r,{validation:"base64url",code:h.invalid_string,message:i.message}),t.dirty()):a.assertNever(i);var n,s;return{status:t.value,value:e.data}}P(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:h.invalid_string,...P.errToObj(r)})}I(e){return new te({...this.l,checks:[...this.l.checks,e]})}email(e){return this.I({kind:"email",...P.errToObj(e)})}url(e){return this.I({kind:"url",...P.errToObj(e)})}emoji(e){return this.I({kind:"emoji",...P.errToObj(e)})}uuid(e){return this.I({kind:"uuid",...P.errToObj(e)})}nanoid(e){return this.I({kind:"nanoid",...P.errToObj(e)})}cuid(e){return this.I({kind:"cuid",...P.errToObj(e)})}cuid2(e){return this.I({kind:"cuid2",...P.errToObj(e)})}ulid(e){return this.I({kind:"ulid",...P.errToObj(e)})}base64(e){return this.I({kind:"base64",...P.errToObj(e)})}base64url(e){return this.I({kind:"base64url",...P.errToObj(e)})}jwt(e){return this.I({kind:"jwt",...P.errToObj(e)})}ip(e){return this.I({kind:"ip",...P.errToObj(e)})}cidr(e){return this.I({kind:"cidr",...P.errToObj(e)})}datetime(e){var t,r;return this.I("string"==typeof e?{kind:"datetime",precision:null,offset:!1,local:!1,message:e}:{kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...P.errToObj(null==e?void 0:e.message)})}date(e){return this.I({kind:"date",message:e})}time(e){return this.I("string"==typeof e?{kind:"time",precision:null,message:e}:{kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...P.errToObj(null==e?void 0:e.message)})}duration(e){return this.I({kind:"duration",...P.errToObj(e)})}regex(e,t){return this.I({kind:"regex",regex:e,...P.errToObj(t)})}includes(e,t){return this.I({kind:"includes",value:e,position:null==t?void 0:t.position,...P.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this.I({kind:"startsWith",value:e,...P.errToObj(t)})}endsWith(e,t){return this.I({kind:"endsWith",value:e,...P.errToObj(t)})}min(e,t){return this.I({kind:"min",value:e,...P.errToObj(t)})}max(e,t){return this.I({kind:"max",value:e,...P.errToObj(t)})}length(e,t){return this.I({kind:"length",value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new te({...this.l,checks:[...this.l.checks,{kind:"trim"}]})}toLowerCase(){return new te({...this.l,checks:[...this.l.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new te({...this.l,checks:[...this.l.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this.l.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this.l.checks.find((e=>"date"===e.kind))}get isTime(){return!!this.l.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this.l.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this.l.checks.find((e=>"email"===e.kind))}get isURL(){return!!this.l.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this.l.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this.l.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this.l.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this.l.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this.l.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this.l.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this.l.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this.l.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this.l.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this.l.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this.l.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this.l.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function re(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,s=r>n?r:n;return parseInt(e.toFixed(s).replace(".",""))%parseInt(t.toFixed(s).replace(".",""))/Math.pow(10,s)}te.create=e=>{var t;return new te({checks:[],typeName:Je.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...j(e)})};class ne extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}k(e){this.l.coerce&&(e.data=Number(e.data));if(this.p(e)!==c.number){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.number,received:t.parsedType}),v}let t;const r=new g;for(const n of this.l.checks)if("int"===n.kind)a.isInteger(e.data)||(t=this.m(e,t),y(t,{code:h.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this.m(e,t),y(t,{code:h.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this.m(e,t),y(t,{code:h.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==re(e.data,n.value)&&(t=this.m(e,t),y(t,{code:h.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this.m(e,t),y(t,{code:h.not_finite,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,r,n){return new ne({...this.l,checks:[...this.l.checks,{kind:e,value:t,inclusive:r,message:P.toString(n)}]})}I(e){return new ne({...this.l,checks:[...this.l.checks,e]})}int(e){return this.I({kind:"int",message:P.toString(e)})}positive(e){return this.I({kind:"min",value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this.I({kind:"max",value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this.I({kind:"max",value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this.I({kind:"min",value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this.I({kind:"multipleOf",value:e,message:P.toString(t)})}finite(e){return this.I({kind:"finite",message:P.toString(e)})}safe(e){return this.I({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:P.toString(e)}).I({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:P.toString(e)})}get minValue(){let e=null;for(const t of this.l.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this.l.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this.l.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&a.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this.l.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ne.create=e=>new ne({checks:[],typeName:Je.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...j(e)});class se extends O{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}k(e){if(this.l.coerce)try{e.data=BigInt(e.data)}catch(t){return this.S(e)}if(this.p(e)!==c.bigint)return this.S(e);let t;const r=new g;for(const n of this.l.checks)if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this.m(e,t),y(t,{code:h.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this.m(e,t),y(t,{code:h.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this.m(e,t),y(t,{code:h.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):a.assertNever(n);return{status:r.value,value:e.data}}S(e){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,!0,P.toString(t))}gt(e,t){return this.setLimit("min",e,!1,P.toString(t))}lte(e,t){return this.setLimit("max",e,!0,P.toString(t))}lt(e,t){return this.setLimit("max",e,!1,P.toString(t))}setLimit(e,t,r,n){return new se({...this.l,checks:[...this.l.checks,{kind:e,value:t,inclusive:r,message:P.toString(n)}]})}I(e){return new se({...this.l,checks:[...this.l.checks,e]})}positive(e){return this.I({kind:"min",value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this.I({kind:"max",value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this.I({kind:"max",value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this.I({kind:"min",value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this.I({kind:"multipleOf",value:e,message:P.toString(t)})}get minValue(){let e=null;for(const t of this.l.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this.l.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}se.create=e=>{var t;return new se({checks:[],typeName:Je.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...j(e)})};class ie extends O{k(e){this.l.coerce&&(e.data=Boolean(e.data));if(this.p(e)!==c.boolean){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.boolean,received:t.parsedType}),v}return b(e.data)}}ie.create=e=>new ie({typeName:Je.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...j(e)});class ae extends O{k(e){this.l.coerce&&(e.data=new Date(e.data));if(this.p(e)!==c.date){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.date,received:t.parsedType}),v}if(isNaN(e.data.getTime())){return y(this.m(e),{code:h.invalid_date}),v}const t=new g;let r;for(const n of this.l.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this.m(e,r),y(r,{code:h.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this.m(e,r),y(r,{code:h.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):a.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}I(e){return new ae({...this.l,checks:[...this.l.checks,e]})}min(e,t){return this.I({kind:"min",value:e.getTime(),message:P.toString(t)})}max(e,t){return this.I({kind:"max",value:e.getTime(),message:P.toString(t)})}get minDate(){let e=null;for(const t of this.l.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this.l.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ae.create=e=>new ae({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:Je.ZodDate,...j(e)});class oe extends O{k(e){if(this.p(e)!==c.symbol){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.symbol,received:t.parsedType}),v}return b(e.data)}}oe.create=e=>new oe({typeName:Je.ZodSymbol,...j(e)});class ce extends O{k(e){if(this.p(e)!==c.undefined){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.undefined,received:t.parsedType}),v}return b(e.data)}}ce.create=e=>new ce({typeName:Je.ZodUndefined,...j(e)});class ue extends O{k(e){if(this.p(e)!==c.null){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.null,received:t.parsedType}),v}return b(e.data)}}ue.create=e=>new ue({typeName:Je.ZodNull,...j(e)});class he extends O{constructor(){super(...arguments),this.Z=!0}k(e){return b(e.data)}}he.create=e=>new he({typeName:Je.ZodAny,...j(e)});class de extends O{constructor(){super(...arguments),this.N=!0}k(e){return b(e.data)}}de.create=e=>new de({typeName:Je.ZodUnknown,...j(e)});class le extends O{k(e){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.never,received:t.parsedType}),v}}le.create=e=>new le({typeName:Je.ZodNever,...j(e)});class pe extends O{k(e){if(this.p(e)!==c.undefined){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.void,received:t.parsedType}),v}return b(e.data)}}pe.create=e=>new pe({typeName:Je.ZodVoid,...j(e)});class me extends O{k(e){const{ctx:t,status:r}=this.v(e),n=this.l;if(t.parsedType!==c.array)return y(t,{code:h.invalid_type,expected:c.array,received:t.parsedType}),v;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,s=t.data.length<n.exactLength.value;(e||s)&&(y(t,{code:e?h.too_big:h.too_small,minimum:s?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(y(t,{code:h.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(y(t,{code:h.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._(new Z(t,e,t.path,r))))).then((e=>g.mergeArray(r,e)));const s=[...t.data].map(((e,r)=>n.type.$(new Z(t,e,t.path,r))));return g.mergeArray(r,s)}get element(){return this.l.type}min(e,t){return new me({...this.l,minLength:{value:e,message:P.toString(t)}})}max(e,t){return new me({...this.l,maxLength:{value:e,message:P.toString(t)}})}length(e,t){return new me({...this.l,exactLength:{value:e,message:P.toString(t)}})}nonempty(e){return this.min(1,e)}}function fe(e){if(e instanceof ye){const t={};for(const r in e.shape){t[r]=Te.create(fe(e.shape[r]))}return new ye({...e.l,shape:()=>t})}return e instanceof me?new me({...e.l,type:fe(e.element)}):e instanceof Te?Te.create(fe(e.unwrap())):e instanceof Fe?Fe.create(fe(e.unwrap())):e instanceof $e?$e.create(e.items.map((e=>fe(e)))):e}me.create=(e,t)=>new me({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Je.ZodArray,...j(t)});class ye extends O{constructor(){super(...arguments),this.j=null,this.nonstrict=this.passthrough,this.augment=this.extend}O(){if(null!==this.j)return this.j;const e=this.l.shape(),t=a.objectKeys(e);return this.j={shape:e,keys:t}}k(e){if(this.p(e)!==c.object){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.object,received:t.parsedType}),v}const{status:t,ctx:r}=this.v(e),{shape:n,keys:s}=this.O(),i=[];if(!(this.l.catchall instanceof le&&"strip"===this.l.unknownKeys))for(const e in r.data)s.includes(e)||i.push(e);const a=[];for(const e of s){a.push({key:{status:"valid",value:e},value:n[e].k(new Z(r,r.data[e],r.path,e)),alwaysSet:e in r.data})}if(this.l.catchall instanceof le){const e=this.l.unknownKeys;if("passthrough"===e)for(const e of i)a.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if("strict"===e)i.length>0&&(y(r,{code:h.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this.l.catchall;for(const t of i){a.push({key:{status:"valid",value:t},value:e.k(new Z(r,r.data[t],r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>g.mergeObjectSync(t,e))):g.mergeObjectSync(t,a)}get shape(){return this.l.shape()}strict(e){return new ye({...this.l,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,i,a;const o=null!==(i=null===(s=(n=this.l).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=P.errToObj(e).message)&&void 0!==a?a:o}:{message:o}}}:{}})}strip(){return new ye({...this.l,unknownKeys:"strip"})}passthrough(){return new ye({...this.l,unknownKeys:"passthrough"})}extend(e){return new ye({...this.l,shape:()=>({...this.l.shape(),...e})})}merge(e){return new ye({unknownKeys:e.l.unknownKeys,catchall:e.l.catchall,shape:()=>({...this.l.shape(),...e.l.shape()}),typeName:Je.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ye({...this.l,catchall:e})}pick(e){const t={};return a.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new ye({...this.l,shape:()=>t})}omit(e){const t={};return a.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new ye({...this.l,shape:()=>t})}deepPartial(){return fe(this)}partial(e){const t={};return a.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];t[r]=e&&!e[r]?n:n.optional()})),new ye({...this.l,shape:()=>t})}required(e){const t={};return a.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof Te;)e=e.l.innerType;t[r]=e}})),new ye({...this.l,shape:()=>t})}keyof(){return Se(a.objectKeys(this.shape))}}ye.create=(e,t)=>new ye({shape:()=>e,unknownKeys:"strip",catchall:le.create(),typeName:Je.ZodObject,...j(t)}),ye.strictCreate=(e,t)=>new ye({shape:()=>e,unknownKeys:"strict",catchall:le.create(),typeName:Je.ZodObject,...j(t)}),ye.lazycreate=(e,t)=>new ye({shape:e,unknownKeys:"strip",catchall:le.create(),typeName:Je.ZodObject,...j(t)});class ge extends O{k(e){const{ctx:t}=this.v(e),r=this.l.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const r of e)if("dirty"===r.result.status)return t.common.issues.push(...r.ctx.common.issues),r.result;const r=e.map((e=>new d(e.ctx.common.issues)));return y(t,{code:h.invalid_union,unionErrors:r}),v}));{let e;const n=[];for(const s of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=s.$({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const s=n.map((e=>new d(e)));return y(t,{code:h.invalid_union,unionErrors:s}),v}}get options(){return this.l.options}}ge.create=(e,t)=>new ge({options:e,typeName:Je.ZodUnion,...j(t)});const ve=e=>e instanceof Pe?ve(e.schema):e instanceof Oe?ve(e.innerType()):e instanceof Ie?[e.value]:e instanceof Ze?e.options:e instanceof Ne?a.objectValues(e.enum):e instanceof Me?ve(e.l.innerType):e instanceof ce?[void 0]:e instanceof ue?[null]:e instanceof Te?[void 0,...ve(e.unwrap())]:e instanceof Fe?[null,...ve(e.unwrap())]:e instanceof ze||e instanceof Le?ve(e.unwrap()):e instanceof Ce?ve(e.l.innerType):[];class we extends O{k(e){const{ctx:t}=this.v(e);if(t.parsedType!==c.object)return y(t,{code:h.invalid_type,expected:c.object,received:t.parsedType}),v;const r=this.discriminator,n=this.optionsMap.get(t.data[r]);return n?t.common.async?n._({data:t.data,path:t.path,parent:t}):n.$({data:t.data,path:t.path,parent:t}):(y(t,{code:h.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),v)}get discriminator(){return this.l.discriminator}get options(){return this.l.options}get optionsMap(){return this.l.optionsMap}static create(e,t,r){const n=new Map;for(const r of t){const t=ve(r.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const s of t){if(n.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);n.set(s,r)}}return new we({typeName:Je.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...j(r)})}}function be(e,t){const r=u(e),n=u(t);if(e===t)return{valid:!0,data:e};if(r===c.object&&n===c.object){const r=a.objectKeys(t),n=a.objectKeys(e).filter((e=>-1!==r.indexOf(e))),s={...e,...t};for(const r of n){const n=be(e[r],t[r]);if(!n.valid)return{valid:!1};s[r]=n.data}return{valid:!0,data:s}}if(r===c.array&&n===c.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const s=be(e[n],t[n]);if(!s.valid)return{valid:!1};r.push(s.data)}return{valid:!0,data:r}}return r===c.date&&n===c.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class xe extends O{k(e){const{status:t,ctx:r}=this.v(e),n=(e,n)=>{if(x(e)||x(n))return v;const s=be(e.value,n.value);return s.valid?(($(e)||$(n))&&t.dirty(),{status:t.value,value:s.data}):(y(r,{code:h.invalid_intersection_types}),v)};return r.common.async?Promise.all([this.l.left._({data:r.data,path:r.path,parent:r}),this.l.right._({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this.l.left.$({data:r.data,path:r.path,parent:r}),this.l.right.$({data:r.data,path:r.path,parent:r}))}}xe.create=(e,t,r)=>new xe({left:e,right:t,typeName:Je.ZodIntersection,...j(r)});class $e extends O{k(e){const{status:t,ctx:r}=this.v(e);if(r.parsedType!==c.array)return y(r,{code:h.invalid_type,expected:c.array,received:r.parsedType}),v;if(r.data.length<this.l.items.length)return y(r,{code:h.too_small,minimum:this.l.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this.l.rest&&r.data.length>this.l.items.length&&(y(r,{code:h.too_big,maximum:this.l.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this.l.items[t]||this.l.rest;return n?n.k(new Z(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>g.mergeArray(t,e))):g.mergeArray(t,n)}get items(){return this.l.items}rest(e){return new $e({...this.l,rest:e})}}$e.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new $e({items:e,typeName:Je.ZodTuple,rest:null,...j(t)})};class ke extends O{get keySchema(){return this.l.keyType}get valueSchema(){return this.l.valueType}k(e){const{status:t,ctx:r}=this.v(e);if(r.parsedType!==c.object)return y(r,{code:h.invalid_type,expected:c.object,received:r.parsedType}),v;const n=[],s=this.l.keyType,i=this.l.valueType;for(const e in r.data)n.push({key:s.k(new Z(r,e,r.path,e)),value:i.k(new Z(r,r.data[e],r.path,e)),alwaysSet:e in r.data});return r.common.async?g.mergeObjectAsync(t,n):g.mergeObjectSync(t,n)}get element(){return this.l.valueType}static create(e,t,r){return new ke(t instanceof O?{keyType:e,valueType:t,typeName:Je.ZodRecord,...j(r)}:{keyType:te.create(),valueType:e,typeName:Je.ZodRecord,...j(t)})}}class _e extends O{get keySchema(){return this.l.keyType}get valueSchema(){return this.l.valueType}k(e){const{status:t,ctx:r}=this.v(e);if(r.parsedType!==c.map)return y(r,{code:h.invalid_type,expected:c.map,received:r.parsedType}),v;const n=this.l.keyType,s=this.l.valueType,i=[...r.data.entries()].map((([e,t],i)=>({key:n.k(new Z(r,e,r.path,[i,"key"])),value:s.k(new Z(r,t,r.path,[i,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const n=await r.key,s=await r.value;if("aborted"===n.status||"aborted"===s.status)return v;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const n=r.key,s=r.value;if("aborted"===n.status||"aborted"===s.status)return v;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}_e.create=(e,t,r)=>new _e({valueType:t,keyType:e,typeName:Je.ZodMap,...j(r)});class Ae extends O{k(e){const{status:t,ctx:r}=this.v(e);if(r.parsedType!==c.set)return y(r,{code:h.invalid_type,expected:c.set,received:r.parsedType}),v;const n=this.l;null!==n.minSize&&r.data.size<n.minSize.value&&(y(r,{code:h.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(y(r,{code:h.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const s=this.l.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return v;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map(((e,t)=>s.k(new Z(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>i(e))):i(a)}min(e,t){return new Ae({...this.l,minSize:{value:e,message:P.toString(t)}})}max(e,t){return new Ae({...this.l,maxSize:{value:e,message:P.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ae.create=(e,t)=>new Ae({valueType:e,minSize:null,maxSize:null,typeName:Je.ZodSet,...j(t)});class Ee extends O{constructor(){super(...arguments),this.validate=this.implement}k(e){const{ctx:t}=this.v(e);if(t.parsedType!==c.function)return y(t,{code:h.invalid_type,expected:c.function,received:t.parsedType}),v;function r(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter((e=>!!e)),issueData:{code:h.invalid_arguments,argumentsError:r}})}function n(e,r){return f({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,m(),l].filter((e=>!!e)),issueData:{code:h.invalid_return_type,returnTypeError:r}})}const s={errorMap:t.common.contextualErrorMap},i=t.data;if(this.l.returns instanceof je){const e=this;return b((async function(...t){const a=new d([]),o=await e.l.args.parseAsync(t,s).catch((e=>{throw a.addIssue(r(t,e)),a})),c=await Reflect.apply(i,this,o);return await e.l.returns.l.type.parseAsync(c,s).catch((e=>{throw a.addIssue(n(c,e)),a}))}))}{const e=this;return b((function(...t){const a=e.l.args.safeParse(t,s);if(!a.success)throw new d([r(t,a.error)]);const o=Reflect.apply(i,this,a.data),c=e.l.returns.safeParse(o,s);if(!c.success)throw new d([n(o,c.error)]);return c.data}))}}parameters(){return this.l.args}returnType(){return this.l.returns}args(...e){return new Ee({...this.l,args:$e.create(e).rest(de.create())})}returns(e){return new Ee({...this.l,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new Ee({args:e||$e.create([]).rest(de.create()),returns:t||de.create(),typeName:Je.ZodFunction,...j(r)})}}class Pe extends O{get schema(){return this.l.getter()}k(e){const{ctx:t}=this.v(e);return this.l.getter().k({data:t.data,path:t.path,parent:t})}}Pe.create=(e,t)=>new Pe({getter:e,typeName:Je.ZodLazy,...j(t)});class Ie extends O{k(e){if(e.data!==this.l.value){const t=this.m(e);return y(t,{received:t.data,code:h.invalid_literal,expected:this.l.value}),v}return{status:"valid",value:e.data}}get value(){return this.l.value}}function Se(e,t){return new Ze({values:e,typeName:Je.ZodEnum,...j(t)})}Ie.create=(e,t)=>new Ie({value:e,typeName:Je.ZodLiteral,...j(t)});class Ze extends O{constructor(){super(...arguments),I.set(this,void 0)}k(e){if("string"!=typeof e.data){const t=this.m(e);return y(t,{expected:a.joinValues(this.l.values),received:t.parsedType,code:h.invalid_type}),v}if(A(this,I)||E(this,I,new Set(this.l.values)),!A(this,I).has(e.data)){const t=this.m(e);return y(t,{received:t.data,code:h.invalid_enum_value,options:this.l.values}),v}return b(e.data)}get options(){return this.l.values}get enum(){const e={};for(const t of this.l.values)e[t]=t;return e}get Values(){const e={};for(const t of this.l.values)e[t]=t;return e}get Enum(){const e={};for(const t of this.l.values)e[t]=t;return e}extract(e,t=this.l){return Ze.create(e,{...this.l,...t})}exclude(e,t=this.l){return Ze.create(this.options.filter((t=>!e.includes(t))),{...this.l,...t})}}I=new WeakMap,Ze.create=Se;class Ne extends O{constructor(){super(...arguments),S.set(this,void 0)}k(e){const t=a.getValidEnumValues(this.l.values),r=this.m(e);if(r.parsedType!==c.string&&r.parsedType!==c.number){const e=a.objectValues(t);return y(r,{expected:a.joinValues(e),received:r.parsedType,code:h.invalid_type}),v}if(A(this,S)||E(this,S,new Set(a.getValidEnumValues(this.l.values))),!A(this,S).has(e.data)){const e=a.objectValues(t);return y(r,{received:r.data,code:h.invalid_enum_value,options:e}),v}return b(e.data)}get enum(){return this.l.values}}S=new WeakMap,Ne.create=(e,t)=>new Ne({values:e,typeName:Je.ZodNativeEnum,...j(t)});class je extends O{unwrap(){return this.l.type}k(e){const{ctx:t}=this.v(e);if(t.parsedType!==c.promise&&!1===t.common.async)return y(t,{code:h.invalid_type,expected:c.promise,received:t.parsedType}),v;const r=t.parsedType===c.promise?t.data:Promise.resolve(t.data);return b(r.then((e=>this.l.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}je.create=(e,t)=>new je({type:e,typeName:Je.ZodPromise,...j(t)});class Oe extends O{innerType(){return this.l.schema}sourceType(){return this.l.schema.l.typeName===Je.ZodEffects?this.l.schema.sourceType():this.l.schema}k(e){const{status:t,ctx:r}=this.v(e),n=this.l.effect||null,s={addIssue:e=>{y(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),"preprocess"===n.type){const e=n.transform(r.data,s);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return v;const n=await this.l.schema._({data:e,path:r.path,parent:r});return"aborted"===n.status?v:"dirty"===n.status||"dirty"===t.value?w(n.value):n}));{if("aborted"===t.value)return v;const n=this.l.schema.$({data:e,path:r.path,parent:r});return"aborted"===n.status?v:"dirty"===n.status||"dirty"===t.value?w(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,s);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this.l.schema.$({data:r.data,path:r.path,parent:r});return"aborted"===n.status?v:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this.l.schema._({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?v:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===n.type){if(!1===r.common.async){const e=this.l.schema.$({data:r.data,path:r.path,parent:r});if(!k(e))return e;const i=n.transform(e.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this.l.schema._({data:r.data,path:r.path,parent:r}).then((e=>k(e)?Promise.resolve(n.transform(e.value,s)).then((e=>({status:t.value,value:e}))):e))}a.assertNever(n)}}Oe.create=(e,t,r)=>new Oe({schema:e,typeName:Je.ZodEffects,effect:t,...j(r)}),Oe.createWithPreprocess=(e,t,r)=>new Oe({schema:t,effect:{type:"preprocess",transform:e},typeName:Je.ZodEffects,...j(r)});class Te extends O{k(e){return this.p(e)===c.undefined?b(void 0):this.l.innerType.k(e)}unwrap(){return this.l.innerType}}Te.create=(e,t)=>new Te({innerType:e,typeName:Je.ZodOptional,...j(t)});class Fe extends O{k(e){return this.p(e)===c.null?b(null):this.l.innerType.k(e)}unwrap(){return this.l.innerType}}Fe.create=(e,t)=>new Fe({innerType:e,typeName:Je.ZodNullable,...j(t)});class Me extends O{k(e){const{ctx:t}=this.v(e);let r=t.data;return t.parsedType===c.undefined&&(r=this.l.defaultValue()),this.l.innerType.k({data:r,path:t.path,parent:t})}removeDefault(){return this.l.innerType}}Me.create=(e,t)=>new Me({innerType:e,typeName:Je.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...j(t)});class Ce extends O{k(e){const{ctx:t}=this.v(e),r={...t,common:{...t.common,issues:[]}},n=this.l.innerType.k({data:r.data,path:r.path,parent:{...r}});return _(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this.l.catchValue({get error(){return new d(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this.l.catchValue({get error(){return new d(r.common.issues)},input:r.data})}}removeCatch(){return this.l.innerType}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:Je.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...j(t)});class Re extends O{k(e){if(this.p(e)!==c.nan){const t=this.m(e);return y(t,{code:h.invalid_type,expected:c.nan,received:t.parsedType}),v}return{status:"valid",value:e.data}}}Re.create=e=>new Re({typeName:Je.ZodNaN,...j(e)});const qe=Symbol("zod_brand");class ze extends O{k(e){const{ctx:t}=this.v(e);return this.l.type.k({data:t.data,path:t.path,parent:t})}unwrap(){return this.l.type}}class De extends O{k(e){const{status:t,ctx:r}=this.v(e);if(r.common.async){return(async()=>{const e=await this.l.in._({data:r.data,path:r.path,parent:r});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),w(e.value)):this.l.out._({data:e.value,path:r.path,parent:r})})()}{const e=this.l.in.$({data:r.data,path:r.path,parent:r});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this.l.out.$({data:e.value,path:r.path,parent:r})}}static create(e,t){return new De({in:e,out:t,typeName:Je.ZodPipeline})}}class Le extends O{k(e){const t=this.l.innerType.k(e),r=e=>(k(e)&&(e.value=Object.freeze(e.value)),e);return _(t)?t.then((e=>r(e))):r(t)}unwrap(){return this.l.innerType}}function Ue(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function Be(e,t={},r){return e?he.create().superRefine(((n,s)=>{var i,a;const o=e(n);if(o instanceof Promise)return o.then((e=>{var i,a;if(!e){const e=Ue(t,n),o=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;s.addIssue({code:"custom",...e,fatal:o})}}));if(!o){const e=Ue(t,n),o=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;s.addIssue({code:"custom",...e,fatal:o})}})):he.create()}Le.create=(e,t)=>new Le({innerType:e,typeName:Je.ZodReadonly,...j(t)});const Ke={object:ye.lazycreate};var Je;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Je||(Je={}));const Ve=te.create,He=ne.create,We=Re.create,Ye=se.create,Ge=ie.create,Qe=ae.create,Xe=oe.create,et=ce.create,tt=ue.create,rt=he.create,nt=de.create,st=le.create,it=pe.create,at=me.create,ot=ye.create,ct=ye.strictCreate,ut=ge.create,ht=we.create,dt=xe.create,lt=$e.create,pt=ke.create,mt=_e.create,ft=Ae.create,yt=Ee.create,gt=Pe.create,vt=Ie.create,wt=Ze.create,bt=Ne.create,xt=je.create,$t=Oe.create,kt=Te.create,_t=Fe.create,At=Oe.createWithPreprocess,Et=De.create,Pt={string:e=>te.create({...e,coerce:!0}),number:e=>ne.create({...e,coerce:!0}),boolean:e=>ie.create({...e,coerce:!0}),bigint:e=>se.create({...e,coerce:!0}),date:e=>ae.create({...e,coerce:!0})},It=v;var St=Object.freeze({__proto__:null,defaultErrorMap:l,setErrorMap:function(e){p=e},getErrorMap:m,makeIssue:f,EMPTY_PATH:[],addIssueToContext:y,ParseStatus:g,INVALID:v,DIRTY:w,OK:b,isAborted:x,isDirty:$,isValid:k,isAsync:_,get util(){return a},get objectUtil(){return o},ZodParsedType:c,getParsedType:u,ZodType:O,datetimeRegex:Q,ZodString:te,ZodNumber:ne,ZodBigInt:se,ZodBoolean:ie,ZodDate:ae,ZodSymbol:oe,ZodUndefined:ce,ZodNull:ue,ZodAny:he,ZodUnknown:de,ZodNever:le,ZodVoid:pe,ZodArray:me,ZodObject:ye,ZodUnion:ge,ZodDiscriminatedUnion:we,ZodIntersection:xe,ZodTuple:$e,ZodRecord:ke,ZodMap:_e,ZodSet:Ae,ZodFunction:Ee,ZodLazy:Pe,ZodLiteral:Ie,ZodEnum:Ze,ZodNativeEnum:Ne,ZodPromise:je,ZodEffects:Oe,ZodTransformer:Oe,ZodOptional:Te,ZodNullable:Fe,ZodDefault:Me,ZodCatch:Ce,ZodNaN:Re,BRAND:qe,ZodBranded:ze,ZodPipeline:De,ZodReadonly:Le,custom:Be,Schema:O,ZodSchema:O,late:Ke,get ZodFirstPartyTypeKind(){return Je},coerce:Pt,any:rt,array:at,bigint:Ye,boolean:Ge,date:Qe,discriminatedUnion:ht,effect:$t,enum:wt,function:yt,instanceof:(e,t={message:`Input not instance of ${e.name}`})=>Be((t=>t instanceof e),t),intersection:dt,lazy:gt,literal:vt,map:mt,nan:We,nativeEnum:bt,never:st,null:tt,nullable:_t,number:He,object:ot,oboolean:()=>Ge().optional(),onumber:()=>He().optional(),optional:kt,ostring:()=>Ve().optional(),pipeline:Et,preprocess:At,promise:xt,record:pt,set:ft,strictObject:ct,string:Ve,symbol:Xe,transformer:$t,tuple:lt,undefined:et,union:ut,unknown:nt,void:it,NEVER:It,ZodIssueCode:h,quotelessJson:e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),ZodError:d});const Zt="2024-11-05",Nt=[Zt,"2024-10-07"],jt="2.0",Ot=St.union([St.string(),St.number().int()]),Tt=St.string(),Ft=St.object({T:St.optional(St.object({progressToken:St.optional(Ot)}).passthrough())}).passthrough(),Mt=St.object({method:St.string(),params:St.optional(Ft)}),Ct=St.object({T:St.optional(St.object({}).passthrough())}).passthrough(),Rt=St.object({method:St.string(),params:St.optional(Ct)}),qt=St.object({T:St.optional(St.object({}).passthrough())}).passthrough(),zt=St.union([St.string(),St.number().int()]),Dt=St.object({jsonrpc:St.literal(jt),id:zt}).merge(Mt).strict(),Lt=St.object({jsonrpc:St.literal(jt)}).merge(Rt).strict(),Ut=St.object({jsonrpc:St.literal(jt),id:zt,result:qt}).strict();var Bt;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(Bt||(Bt={}));const Kt=St.object({jsonrpc:St.literal(jt),id:zt,error:St.object({code:St.number().int(),message:St.string(),data:St.optional(St.unknown())})}).strict(),Jt=St.union([Dt,Lt,Ut,Kt]),Vt=qt.strict(),Ht=Rt.extend({method:St.literal("notifications/cancelled"),params:Ct.extend({requestId:zt,reason:St.string().optional()})}),Wt=St.object({name:St.string(),version:St.string()}).passthrough(),Yt=St.object({experimental:St.optional(St.object({}).passthrough()),sampling:St.optional(St.object({}).passthrough()),roots:St.optional(St.object({listChanged:St.optional(St.boolean())}).passthrough())}).passthrough(),Gt=Mt.extend({method:St.literal("initialize"),params:Ft.extend({protocolVersion:St.string(),capabilities:Yt,clientInfo:Wt})}),Qt=St.object({experimental:St.optional(St.object({}).passthrough()),logging:St.optional(St.object({}).passthrough()),prompts:St.optional(St.object({listChanged:St.optional(St.boolean())}).passthrough()),resources:St.optional(St.object({subscribe:St.optional(St.boolean()),listChanged:St.optional(St.boolean())}).passthrough()),tools:St.optional(St.object({listChanged:St.optional(St.boolean())}).passthrough())}).passthrough(),Xt=qt.extend({protocolVersion:St.string(),capabilities:Qt,serverInfo:Wt,instructions:St.optional(St.string())}),er=Rt.extend({method:St.literal("notifications/initialized")}),tr=Mt.extend({method:St.literal("ping")}),rr=St.object({progress:St.number(),total:St.optional(St.number())}).passthrough(),nr=Rt.extend({method:St.literal("notifications/progress"),params:Ct.merge(rr).extend({progressToken:Ot})}),sr=Mt.extend({params:Ft.extend({cursor:St.optional(Tt)}).optional()}),ir=qt.extend({nextCursor:St.optional(Tt)}),ar=St.object({uri:St.string(),mimeType:St.optional(St.string())}).passthrough(),or=ar.extend({text:St.string()}),cr=ar.extend({blob:St.string().base64()}),ur=St.object({uri:St.string(),name:St.string(),description:St.optional(St.string()),mimeType:St.optional(St.string())}).passthrough(),hr=St.object({uriTemplate:St.string(),name:St.string(),description:St.optional(St.string()),mimeType:St.optional(St.string())}).passthrough(),dr=sr.extend({method:St.literal("resources/list")}),lr=ir.extend({resources:St.array(ur)}),pr=sr.extend({method:St.literal("resources/templates/list")}),mr=ir.extend({resourceTemplates:St.array(hr)}),fr=Mt.extend({method:St.literal("resources/read"),params:Ft.extend({uri:St.string()})}),yr=qt.extend({contents:St.array(St.union([or,cr]))}),gr=Rt.extend({method:St.literal("notifications/resources/list_changed")}),vr=Mt.extend({method:St.literal("resources/subscribe"),params:Ft.extend({uri:St.string()})}),wr=Mt.extend({method:St.literal("resources/unsubscribe"),params:Ft.extend({uri:St.string()})}),br=Rt.extend({method:St.literal("notifications/resources/updated"),params:Ct.extend({uri:St.string()})}),xr=St.object({name:St.string(),description:St.optional(St.string()),required:St.optional(St.boolean())}).passthrough(),$r=St.object({name:St.string(),description:St.optional(St.string()),arguments:St.optional(St.array(xr))}).passthrough(),kr=sr.extend({method:St.literal("prompts/list")}),_r=ir.extend({prompts:St.array($r)}),Ar=Mt.extend({method:St.literal("prompts/get"),params:Ft.extend({name:St.string(),arguments:St.optional(St.record(St.string()))})}),Er=St.object({type:St.literal("text"),text:St.string()}).passthrough(),Pr=St.object({type:St.literal("image"),data:St.string().base64(),mimeType:St.string()}).passthrough(),Ir=St.object({type:St.literal("resource"),resource:St.union([or,cr])}).passthrough(),Sr=St.object({role:St.enum(["user","assistant"]),content:St.union([Er,Pr,Ir])}).passthrough(),Zr=qt.extend({description:St.optional(St.string()),messages:St.array(Sr)}),Nr=Rt.extend({method:St.literal("notifications/prompts/list_changed")}),jr=St.object({name:St.string(),description:St.optional(St.string()),inputSchema:St.object({type:St.literal("object"),properties:St.optional(St.object({}).passthrough())}).passthrough()}).passthrough(),Or=sr.extend({method:St.literal("tools/list")}),Tr=ir.extend({tools:St.array(jr)}),Fr=qt.extend({content:St.array(St.union([Er,Pr,Ir])),isError:St.boolean().default(!1).optional()});Fr.or(qt.extend({toolResult:St.unknown()}));const Mr=Mt.extend({method:St.literal("tools/call"),params:Ft.extend({name:St.string(),arguments:St.optional(St.record(St.unknown()))})}),Cr=Rt.extend({method:St.literal("notifications/tools/list_changed")}),Rr=St.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),qr=Mt.extend({method:St.literal("logging/setLevel"),params:Ft.extend({level:Rr})}),zr=Rt.extend({method:St.literal("notifications/message"),params:Ct.extend({level:Rr,logger:St.optional(St.string()),data:St.unknown()})}),Dr=St.object({name:St.string().optional()}).passthrough(),Lr=St.object({hints:St.optional(St.array(Dr)),costPriority:St.optional(St.number().min(0).max(1)),speedPriority:St.optional(St.number().min(0).max(1)),intelligencePriority:St.optional(St.number().min(0).max(1))}).passthrough(),Ur=St.object({role:St.enum(["user","assistant"]),content:St.union([Er,Pr])}).passthrough(),Br=Mt.extend({method:St.literal("sampling/createMessage"),params:Ft.extend({messages:St.array(Ur),systemPrompt:St.optional(St.string()),includeContext:St.optional(St.enum(["none","thisServer","allServers"])),temperature:St.optional(St.number()),maxTokens:St.number().int(),stopSequences:St.optional(St.array(St.string())),metadata:St.optional(St.object({}).passthrough()),modelPreferences:St.optional(Lr)})}),Kr=qt.extend({model:St.string(),stopReason:St.optional(St.enum(["endTurn","stopSequence","maxTokens"]).or(St.string())),role:St.enum(["user","assistant"]),content:St.discriminatedUnion("type",[Er,Pr])}),Jr=St.object({type:St.literal("ref/resource"),uri:St.string()}).passthrough(),Vr=St.object({type:St.literal("ref/prompt"),name:St.string()}).passthrough(),Hr=Mt.extend({method:St.literal("completion/complete"),params:Ft.extend({ref:St.union([Vr,Jr]),argument:St.object({name:St.string(),value:St.string()}).passthrough()})}),Wr=qt.extend({completion:St.object({values:St.array(St.string()).max(100),total:St.optional(St.number().int()),hasMore:St.optional(St.boolean())}).passthrough()}),Yr=St.object({uri:St.string().startsWith("file://"),name:St.optional(St.string())}).passthrough(),Gr=Mt.extend({method:St.literal("roots/list")}),Qr=qt.extend({roots:St.array(Yr)}),Xr=Rt.extend({method:St.literal("notifications/roots/list_changed")});St.union([tr,Gt,Hr,qr,Ar,kr,dr,pr,fr,vr,wr,Mr,Or]),St.union([Ht,nr,er,Xr]),St.union([Vt,Kr,Qr]),St.union([tr,Br,Gr]),St.union([Ht,nr,zr,br,gr,Cr,Nr]),St.union([Vt,Xt,Wr,Zr,_r,lr,mr,yr,Fr,Tr]);class en extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r}}class tn{constructor(e){this.F=e,this.M=0,this.C=new Map,this.R=new Map,this.q=new Map,this.D=new Map,this.L=new Map,this.setNotificationHandler(Ht,(e=>{const t=this.R.get(e.params.requestId);null==t||t.abort(e.params.reason)})),this.setNotificationHandler(nr,(e=>{this.U(e)})),this.setRequestHandler(tr,(e=>({})))}async connect(e){this.B=e,this.B.onclose=()=>{this.K()},this.B.onerror=e=>{this.J(e)},this.B.onmessage=e=>{"method"in e?"id"in e?this.V(e):this.H(e):this.W(e)},await this.B.start()}K(){var e;const t=this.D;this.D=new Map,this.L.clear(),this.B=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const r=new en(Bt.ConnectionClosed,"Connection closed");for(const e of t.values())e(r)}J(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}H(e){var t;const r=null!==(t=this.q.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==r&&Promise.resolve().then((()=>r(e))).catch((e=>this.J(new Error(`Uncaught error in notification handler: ${e}`))))}V(e){var t,r;const n=null!==(t=this.C.get(e.method))&&void 0!==t?t:this.fallbackRequestHandler;if(void 0===n)return void(null===(r=this.B)||void 0===r||r.send({jsonrpc:"2.0",id:e.id,error:{code:Bt.MethodNotFound,message:"Method not found"}}).catch((e=>this.J(new Error(`Failed to send an error response: ${e}`)))));const s=new AbortController;this.R.set(e.id,s),Promise.resolve().then((()=>n(e,{signal:s.signal}))).then((t=>{var r;if(!s.signal.aborted)return null===(r=this.B)||void 0===r?void 0:r.send({result:t,jsonrpc:"2.0",id:e.id})}),(t=>{var r,n;if(!s.signal.aborted)return null===(r=this.B)||void 0===r?void 0:r.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Bt.InternalError,message:null!==(n=t.message)&&void 0!==n?n:"Internal error"}})})).catch((e=>this.J(new Error(`Failed to send response: ${e}`)))).finally((()=>{this.R.delete(e.id)}))}U(e){const{progressToken:t,...r}=e.params,n=this.L.get(Number(t));void 0!==n?n(r):this.J(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`))}W(e){const t=e.id,r=this.D.get(Number(t));if(void 0!==r)if(this.D.delete(Number(t)),this.L.delete(Number(t)),"result"in e)r(e);else{r(new en(e.error.code,e.error.message,e.error.data))}else this.J(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`))}get transport(){return this.B}async close(){var e;await(null===(e=this.B)||void 0===e?void 0:e.close())}request(e,t,r){return new Promise(((n,s)=>{var i,a,o,c;if(!this.B)return void s(new Error("Not connected"));!0===(null===(i=this.F)||void 0===i?void 0:i.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(a=null==r?void 0:r.signal)||void 0===a||a.throwIfAborted();const u=this.M++,h={...e,jsonrpc:"2.0",id:u};let d;(null==r?void 0:r.onprogress)&&(this.L.set(u,r.onprogress),h.params={...e.params,T:{progressToken:u}}),this.D.set(u,(e=>{var i;if(void 0!==d&&clearTimeout(d),!(null===(i=null==r?void 0:r.signal)||void 0===i?void 0:i.aborted)){if(e instanceof Error)return s(e);try{const r=t.parse(e.result);n(r)}catch(e){s(e)}}}));const l=e=>{var t;this.D.delete(u),this.L.delete(u),null===(t=this.B)||void 0===t||t.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:u,reason:String(e)}}).catch((e=>this.J(new Error(`Failed to send cancellation: ${e}`)))),s(e)};null===(o=null==r?void 0:r.signal)||void 0===o||o.addEventListener("abort",(()=>{var e;void 0!==d&&clearTimeout(d),l(null===(e=null==r?void 0:r.signal)||void 0===e?void 0:e.reason)}));const p=null!==(c=null==r?void 0:r.timeout)&&void 0!==c?c:6e4;d=setTimeout((()=>l(new en(Bt.RequestTimeout,"Request timed out",{timeout:p}))),p),this.B.send(h).catch((e=>{void 0!==d&&clearTimeout(d),s(e)}))}))}async notification(e){if(!this.B)throw new Error("Not connected");this.assertNotificationCapability(e.method);const t={...e,jsonrpc:"2.0"};await this.B.send(t)}setRequestHandler(e,t){const r=e.shape.method.value;this.assertRequestHandlerCapability(r),this.C.set(r,((r,n)=>Promise.resolve(t(e.parse(r),n))))}removeRequestHandler(e){this.C.delete(e)}assertCanSetRequestHandler(e){if(this.C.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){this.q.set(e.shape.method.value,(r=>Promise.resolve(t(e.parse(r)))))}removeNotificationHandler(e){this.q.delete(e)}}class rn extends tn{constructor(e,t){var r;super(t),this.Y=e,this.G=null!==(r=null==t?void 0:t.capabilities)&&void 0!==r?r:{},this.X=null==t?void 0:t.instructions,this.setRequestHandler(Gt,(e=>this.ee(e))),this.setNotificationHandler(er,(()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)}))}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");var t;this.G=(t=this.G,Object.entries(e).reduce(((e,[t,r])=>(e[t]=r&&"object"==typeof r&&e[t]?{...e[t],...r}:r,e)),{...t}))}assertCapabilityForMethod(e){var t,r;switch(e){case"sampling/createMessage":if(!(null===(t=this.te)||void 0===t?void 0:t.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(null===(r=this.te)||void 0===r?void 0:r.roots))throw new Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this.G.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this.G.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this.G.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this.G.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this.G.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this.G.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this.G.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this.G.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this.G.tools)throw new Error(`Server does not support tools (required for ${e})`)}}async ee(e){const t=e.params.protocolVersion;return this.te=e.params.capabilities,this.re=e.params.clientInfo,{protocolVersion:Nt.includes(t)?t:Zt,capabilities:this.getCapabilities(),serverInfo:this.Y,...this.X&&{instructions:this.X}}}getClientCapabilities(){return this.te}getClientVersion(){return this.re}getCapabilities(){return this.G}async ping(){return this.request({method:"ping"},Vt)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},Kr,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Qr,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}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"})}}const nn=Symbol("Let zodToJsonSchema decide on which parser to use"),sn={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},an=e=>{const t=(e=>({...sn,...e}))(e),r=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map((([e,r])=>[r.l,{def:r.l,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}])))}};function on(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function cn(e,t,r,n,s){e[t]=r,on(e,t,n,s)}function un(e,t){return Tn(e.type.l,t)}function hn(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(((r,n)=>hn(e,t,r)))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return dn(e,t)}}const dn=(e,t)=>{const r={type:"integer",format:"unix-time"};if("openApi3"===t.target)return r;for(const n of e.checks)switch(n.kind){case"min":cn(r,"minimum",n.value,n.message,t);break;case"max":cn(r,"maximum",n.value,n.message,t)}return r};let ln;const pn=/^[cC][^\s-]{8,}$/,mn=/^[0-9a-z]+$/,fn=/^[0-9A-HJKMNP-TV-Z]{26}$/,yn=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,gn=()=>(void 0===ln&&(ln=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ln),vn=/^(?:(?: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])$/,wn=/^(([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])$/,bn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$n=/^[a-zA-Z0-9_-]{21}$/,kn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function _n(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":cn(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":cn(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Pn(r,"email",n.message,t);break;case"format:idn-email":Pn(r,"idn-email",n.message,t);break;case"pattern:zod":In(r,yn,n.message,t)}break;case"url":Pn(r,"uri",n.message,t);break;case"uuid":Pn(r,"uuid",n.message,t);break;case"regex":In(r,n.regex,n.message,t);break;case"cuid":In(r,pn,n.message,t);break;case"cuid2":In(r,mn,n.message,t);break;case"startsWith":In(r,RegExp(`^${An(n.value,t)}`),n.message,t);break;case"endsWith":In(r,RegExp(`${An(n.value,t)}$`),n.message,t);break;case"datetime":Pn(r,"date-time",n.message,t);break;case"date":Pn(r,"date",n.message,t);break;case"time":Pn(r,"time",n.message,t);break;case"duration":Pn(r,"duration",n.message,t);break;case"length":cn(r,"minLength","number"==typeof r.minLength?Math.max(r.minLength,n.value):n.value,n.message,t),cn(r,"maxLength","number"==typeof r.maxLength?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":In(r,RegExp(An(n.value,t)),n.message,t);break;case"ip":"v6"!==n.version&&Pn(r,"ipv4",n.message,t),"v4"!==n.version&&Pn(r,"ipv6",n.message,t);break;case"base64url":In(r,xn,n.message,t);break;case"jwt":In(r,kn,n.message,t);break;case"cidr":"v6"!==n.version&&In(r,vn,n.message,t),"v4"!==n.version&&In(r,wn,n.message,t);break;case"emoji":In(r,gn(),n.message,t);break;case"ulid":In(r,fn,n.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":Pn(r,"binary",n.message,t);break;case"contentEncoding:base64":cn(r,"contentEncoding","base64",n.message,t);break;case"pattern:zod":In(r,bn,n.message,t)}break;case"nanoid":In(r,$n,n.message,t)}return r}function An(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let r=0;r<e.length;r++)En.has(e[r])||(t+="\\"),t+=e[r];return t}(e):e}const En=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Pn(e,t,r,n){e.format||e.anyOf?.some((e=>e.format))?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):cn(e,"format",t,r,n)}function In(e,t,r,n){e.pattern||e.allOf?.some((e=>e.pattern))?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:Sn(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):cn(e,"pattern",Sn(t,n),r,n)}function Sn(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r=e.flags.includes("i"),n=e.flags.includes("m"),s=e.flags.includes("s"),i=r?e.source.toLowerCase():e.source;let a="",o=!1,c=!1,u=!1;for(let e=0;e<i.length;e++)if(o)a+=i[e],o=!1;else{if(r)if(c){if(i[e].match(/[a-z]/)){u?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),u=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(a+=i[e],u=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}if(n){if("^"===i[e]){a+="(^|(?<=[\r\n]))";continue}if("$"===i[e]){a+="($|(?=[\r\n]))";continue}}s&&"."===i[e]?a+=c?`${i[e]}\r\n`:`[${i[e]}\r\n]`:(a+=i[e],"\\"===i[e]?o=!0:c&&"]"===i[e]?c=!1:c||"["!==i[e]||(c=!0))}return a}function Zn(e,t){if("openApi3"===t.target&&e.keyType?.l.typeName===Je.ZodEnum)return{type:"object",required:e.keyType.l.values,properties:e.keyType.l.values.reduce(((r,n)=>({...r,[n]:Tn(e.valueType.l,{...t,currentPath:[...t.currentPath,"properties",n]})??{}})),{}),additionalProperties:!1};const r={type:"object",additionalProperties:Tn(e.valueType.l,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??{}};if("openApi3"===t.target)return r;if(e.keyType?.l.typeName===Je.ZodString&&e.keyType.l.checks?.length){const{type:n,...s}=_n(e.keyType.l,t);return{...r,propertyNames:s}}if(e.keyType?.l.typeName===Je.ZodEnum)return{...r,propertyNames:{enum:e.keyType.l.values}};if(e.keyType?.l.typeName===Je.ZodBranded&&e.keyType.l.type.l.typeName===Je.ZodString&&e.keyType.l.type.l.checks?.length){const{type:n,...s}=un(e.keyType.l,t);return{...r,propertyNames:s}}return r}const Nn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};const jn=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map(((e,r)=>Tn(e.l,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]}))).filter((e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0)));return r.length?{anyOf:r}:void 0};function On(e,t){return"strict"===t.removeAdditionalStrategy?"ZodNever"===e.catchall.l.typeName?"strict"!==e.unknownKeys:Tn(e.catchall.l,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0:"ZodNever"===e.catchall.l.typeName?"passthrough"===e.unknownKeys:Tn(e.catchall.l,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??!0}function Tn(e,t,r=!1){const n=t.seen.get(e);if(t.override){const s=t.override?.(e,t,n,r);if(s!==nn)return s}if(n&&!r){const e=Fn(n,t);if(void 0!==e)return e}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const i=Cn(e,e.typeName,t);return i&&Rn(e,t,i),s.jsonSchema=i,i}const Fn=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Mn(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every(((e,r)=>t.currentPath[r]===e))||"seen"===t.$refStrategy?{}:void 0}},Mn=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")},Cn=(e,t,r)=>{switch(t){case Je.ZodString:return _n(e,r);case Je.ZodNumber:return function(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",on(r,"type",n.message,t);break;case"min":"jsonSchema7"===t.target?cn(r,n.inclusive?"minimum":"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),cn(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?cn(r,n.inclusive?"maximum":"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),cn(r,"maximum",n.value,n.message,t));break;case"multipleOf":cn(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case Je.ZodObject:return function(e,t){const r="openAi"===t.target,n={type:"object",...Object.entries(e.shape()).reduce(((e,[n,s])=>{if(void 0===s||void 0===s.l)return e;let i=s.isOptional();i&&r&&(s instanceof Te&&(s=s.l.innerType),s.isNullable()||(s=s.nullable()),i=!1);const a=Tn(s.l,{...t,currentPath:[...t.currentPath,"properties",n],propertyPath:[...t.currentPath,"properties",n]});return void 0===a?e:{properties:{...e.properties,[n]:a},required:i?e.required:[...e.required,n]}}),{properties:{},required:[]}),additionalProperties:On(e,t)};return n.required.length||delete n.required,n}(e,r);case Je.ZodBigInt:return function(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":"jsonSchema7"===t.target?cn(r,n.inclusive?"minimum":"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),cn(r,"minimum",n.value,n.message,t));break;case"max":"jsonSchema7"===t.target?cn(r,n.inclusive?"maximum":"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),cn(r,"maximum",n.value,n.message,t));break;case"multipleOf":cn(r,"multipleOf",n.value,n.message,t)}return r}(e,r);case Je.ZodBoolean:return{type:"boolean"};case Je.ZodDate:return hn(e,r);case Je.ZodUndefined:return{not:{}};case Je.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(r);case Je.ZodArray:return function(e,t){const r={type:"array"};return e.type?.l&&e.type?.l?.typeName!==Je.ZodAny&&(r.items=Tn(e.type.l,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&cn(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&cn(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(cn(r,"minItems",e.exactLength.value,e.exactLength.message,t),cn(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}(e,r);case Je.ZodUnion:case Je.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return jn(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((e=>e.l.typeName in Nn&&(!e.l.checks||!e.l.checks.length)))){const e=r.reduce(((e,t)=>{const r=Nn[t.l.typeName];return r&&!e.includes(r)?[...e,r]:e}),[]);return{type:e.length>1?e:e[0]}}if(r.every((e=>"ZodLiteral"===e.l.typeName&&!e.description))){const e=r.reduce(((e,t)=>{const r=typeof t.l.value;switch(r){case"string":case"number":case"boolean":return[...e,r];case"bigint":return[...e,"integer"];case"object":if(null===t.l.value)return[...e,"null"];default:return e}}),[]);if(e.length===r.length){const t=e.filter(((e,t,r)=>r.indexOf(e)===t));return{type:t.length>1?t:t[0],enum:r.reduce(((e,t)=>e.includes(t.l.value)?e:[...e,t.l.value]),[])}}}else if(r.every((e=>"ZodEnum"===e.l.typeName)))return{type:"string",enum:r.reduce(((e,t)=>[...e,...t.l.values.filter((t=>!e.includes(t)))]),[])};return jn(e,t)}(e,r);case Je.ZodIntersection:return function(e,t){const r=[Tn(e.left.l,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Tn(e.right.l,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter((e=>!!e));let n="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const s=[];return r.forEach((e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:r,...n}=e;t=n}else n=void 0;s.push(t)}else s.push(...e.allOf),void 0===e.unevaluatedProperties&&(n=void 0);var t})),s.length?{allOf:s,...n}:void 0}(e,r);case Je.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map(((e,r)=>Tn(e.l,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[]),additionalItems:Tn(e.rest.l,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map(((e,r)=>Tn(e.l,{...t,currentPath:[...t.currentPath,"items",`${r}`]}))).reduce(((e,t)=>void 0===t?e:[...e,t]),[])}}(e,r);case Je.ZodRecord:return Zn(e,r);case Je.ZodLiteral:return function(e,t){const r=typeof e.value;return"bigint"!==r&&"number"!==r&&"boolean"!==r&&"string"!==r?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===r?"integer":r,enum:[e.value]}:{type:"bigint"===r?"integer":r,const:e.value}}(e,r);case Je.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case Je.ZodNativeEnum:return function(e){const t=e.values,r=Object.keys(e.values).filter((e=>"number"!=typeof t[t[e]])).map((e=>t[e])),n=Array.from(new Set(r.map((e=>typeof e))));return{type:1===n.length?"string"===n[0]?"string":"number":["string","number"],enum:r}}(e);case Je.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType.l.typeName)&&(!e.innerType.l.checks||!e.innerType.l.checks.length))return"openApi3"===t.target?{type:Nn[e.innerType.l.typeName],nullable:!0}:{type:[Nn[e.innerType.l.typeName],"null"]};if("openApi3"===t.target){const r=Tn(e.innerType.l,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const r=Tn(e.innerType.l,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}(e,r);case Je.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Tn(e.innerType.l,t);const r=Tn(e.innerType.l,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:{}},r]}:{}})(e,r);case Je.ZodMap:return function(e,t){return"record"===t.mapStrategy?Zn(e,t):{type:"array",maxItems:125,items:{type:"array",items:[Tn(e.keyType.l,{...t,currentPath:[...t.currentPath,"items","items","0"]})||{},Tn(e.valueType.l,{...t,currentPath:[...t.currentPath,"items","items","1"]})||{}],minItems:2,maxItems:2}}}(e,r);case Je.ZodSet:return function(e,t){const r={type:"array",uniqueItems:!0,items:Tn(e.valueType.l,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&cn(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&cn(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}(e,r);case Je.ZodLazy:return Tn(e.getter().l,r);case Je.ZodPromise:return function(e,t){return Tn(e.type.l,t)}(e,r);case Je.ZodNaN:case Je.ZodNever:return{not:{}};case Je.ZodEffects:return function(e,t){return"input"===t.effectStrategy?Tn(e.schema.l,t):{}}(e,r);case Je.ZodAny:case Je.ZodUnknown:return{};case Je.ZodDefault:return function(e,t){return{...Tn(e.innerType.l,t),default:e.defaultValue()}}(e,r);case Je.ZodBranded:return un(e,r);case Je.ZodReadonly:case Je.ZodCatch:return((e,t)=>Tn(e.innerType.l,t))(e,r);case Je.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return Tn(e.in.l,t);if("output"===t.pipeStrategy)return Tn(e.out.l,t);const r=Tn(e.in.l,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[r,Tn(e.out.l,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]})].filter((e=>void 0!==e))}})(e,r);default:return}},Rn=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),qn=(e,t)=>{const r=an(t),n=void 0,s=t?.name,i=Tn(e.l,void 0===s?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},a=void 0===s?i:{$ref:[..."relative"===r.$refStrategy?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:i}};return"jsonSchema7"===r.target?a.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==r.target&&"openAi"!==r.target||(a.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===r.target&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type)),a};var zn;!function(e){e.Completable="McpCompletable"}(zn||(zn={}));class Dn extends O{k(e){const{ctx:t}=this.v(e);return this.l.type.k({data:t.data,path:t.path,parent:t})}unwrap(){return this.l.type}}function Ln(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:s}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:s};return{errorMap:(t,s)=>{var i,a;const{message:o}=e;return"invalid_enum_value"===t.code?{message:null!=o?o:s.defaultError}:void 0===s.data?{message:null!==(i=null!=o?o:n)&&void 0!==i?i:s.defaultError}:"invalid_type"!==t.code?{message:s.defaultError}:{message:null!==(a=null!=o?o:r)&&void 0!==a?a:s.defaultError}},description:s}}Dn.create=(e,t)=>new Dn({type:e,typeName:zn.Completable,complete:t.complete,...Ln(t)});const Un={type:"object"};function Bn(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Kn={completion:{values:[],hasMore:!1}};class Jn{append(e){this.ne=this.ne?Buffer.concat([this.ne,e]):e}readMessage(){if(!this.ne)return null;const e=this.ne.indexOf("\n");if(-1===e)return null;const t=this.ne.toString("utf8",0,e);return this.ne=this.ne.subarray(e+1),function(e){return Jt.parse(JSON.parse(e))}(t)}clear(){this.ne=void 0}}class Vn{constructor(t=e.stdin,r=e.stdout){this.se=t,this.ie=r,this.ae=new Jn,this.oe=!1,this.ce=e=>{this.ae.append(e),this.processReadBuffer()},this.J=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}async start(){if(this.oe)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this.oe=!0,this.se.on("data",this.ce),this.se.on("error",this.J)}processReadBuffer(){for(var e,t;;)try{const t=this.ae.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this.se.off("data",this.ce),this.se.off("error",this.J);0===this.se.listenerCount("data")&&this.se.pause(),this.ae.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise((t=>{const r=function(e){return JSON.stringify(e)+"\n"}(e);this.ie.write(r)?t():this.ie.once("drain",t)}))}}const Hn={test:"https://qaopen.eyun.360.cn/intf.php",hgtest:"https://hg-openapi.eyun.360.cn/intf.php",prod:"https://openapi.eyun.360.cn/intf.php"},Wn=process.env.ECS_ENV||"prod",Yn=Hn[Wn]||Hn.prod,Gn="test"===Wn?"b11b8fff1c75a5d227c8cc93aaeb0bb70c8eee47":"885fd3231f1c1e37c9f462261a09b8c38cde0c2b",Qn="注意:如问题中未明确指定,请勿再自行调用其他无关工具。";function Xn(e,t="e7b24b112a44fdd9ee93bdf998c6ca0e"){const n=Object.keys(e).sort().map((t=>{const r=function(e){return encodeURIComponent(e).replace(/%20/g,"+").replace(/[!'()*~]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`))}(e[t]);return`${t}=${r}`}));let s=n.join("&");return s+=t,i=s,r.createHash("md5").update(i,"utf8").digest("hex");var i}async function es(e){const t={apiKey:process.env.API_KEY||"",clientId:"e4757e933b6486c08ed206ecb6d5d9e684fcb4e2",clientSecret:Gn};if(!t.apiKey)throw new Error("未配置YUNPAN_API_KEY环境变量");try{const r=new URL(Yn);let n={};const s=e.extraParams;s&&"file-upload-stdio"===s.toolName?(n.method=s.method,n.client_id=s.clientId,n.client_secret=s.clientSecret,n.qid=s.qid,n.grant_type=s.grantType):(n.method="Oauth.getAccessTokenByApiKey",n.client_id=t.clientId,n.client_secret=t.clientSecret,n.grant_type="authorization_code",n.api_key=t.apiKey),Object.entries(n).forEach((([e,t])=>{r.searchParams.append(e,t)}));const i=await fetch(r.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!i.ok)throw new Error(`鉴权请求失败,状态码: ${i.status}`);const a=await i.json();if(0!==a.errno)throw new Error(`鉴权请求返回错误: ${a.errmsg}`);const{access_token:o,qid:c,token:u}=a.data;return{access_token:o,qid:c,token:u}}catch(e){throw e}}async function ts(e={}){const t=await es(e);if(e.extraParams&&"file-upload-stdio"===e.extraParams.toolName)return t.qid=e.extraParams.qid,t;const r=Xn(function(e,t,r={}){const n={};if(e.access_token&&(n.access_token=String(e.access_token)),t&&(n.method=String(t)),e.qid&&(n.qid=String(e.qid)),r)for(const[e,t]of Object.entries(r))null!=t&&(n[String(e)]=String(t));return{...n}}({access_token:t.access_token,qid:t.qid},e.method||"",e.extraParams));return t.sign=r,t}function rs(e){const t="1"===e.type||!1,r=t?"文件夹":e.name.split(".").pop()||"未知";return[`文件名: ${e.name||"未命名"}`,`类型: ${t?"文件夹":r}`,"大小: "+(n=parseInt(e.count_size||"0")||0,n<1024?n+" B":n<1048576?(n/1024).toFixed(2)+" KB":n<1073741824?(n/1048576).toFixed(2)+" MB":(n/1073741824).toFixed(2)+" GB"),`创建时间: ${new Date(1e3*parseInt(e.create_time||"0")).toLocaleString()}`,`修改时间: ${new Date(1e3*parseInt(e.modify_time||"0")).toLocaleString()}`,`文件nid: ${e.nid||""}`,"---"].join("\n");var n}function ns(e){e.tool("file-list","获取云盘指定路径下的文件和文件夹列表,支持分页查询。返回文件名、大小、创建时间、修改时间等详细信息。",{page:St.number().optional().default(0).describe("页码,默认从0开始。"),page_size:St.number().optional().default(50).describe("每页显示的条目数,默认50条。"),path:St.string().optional().default("/").describe("要查询的云盘路径,默认为根目录'/'")},(async({page:e,page_size:t,path:r})=>{try{let n;const s={path:r||"/",page:e||0,page_size:t||100};try{n=await ts({method:"File.getList",extraParams:s})}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}const i=await async function(e,t){try{const r=new URL(Yn),n={"Access-Token":e.access_token||""},s={};for(const[e,r]of Object.entries(t))"access_token"!==e&&(s[String(e)]=String(r));const i={method:"File.getList",access_token:e.access_token||"",qid:e.qid||"",sign:e.sign||"",...s};Object.entries(i).forEach((([e,t])=>{r.searchParams.append(e,String(t))}));const a=await fetch(r.toString(),{method:"GET",headers:n});if(!a.ok)throw new Error(`API 请求失败,状态码: ${a.status}`);const o=await a.text();try{return JSON.parse(o)}catch(e){throw new Error(`无法解析API响应: ${o.substring(0,100)}...`)}}catch(e){throw e}}(n,s);if(i&&0===i.errno){const e=i.data&&i.data.node_list||[];if(0===e.length)return{content:[{type:"text",text:"没有找到符合条件的文件"}]};const t=e.filter((e=>"1"===e.type)).length,n=e.length-t,s=e.map(rs);return{content:[{type:"text",text:`云盘文件列表 (路径: ${r})\n共 ${e.length} 项 (${t} 个文件夹, ${n} 个文件)\n\n${s.join("\n")}`},{type:"text",text:Qn}]}}throw new Error(i?.errmsg||"API请求失败")}catch(e){return{content:[{type:"text",text:`获取文件列表出错: ${e}`},{type:"text",text:Qn}]}}}))}function ss(e){const t="1"===e.type||!1,r=t?"文件夹":e.name.split(".").pop()||"未知";return[`文件名: ${e.name||"未命名"}`,`类型: ${t?"文件夹":r}`,"大小: "+(n=parseInt(e.count_size||"0")||0,n<1024?n+" B":n<1048576?(n/1024).toFixed(2)+" KB":n<1073741824?(n/1048576).toFixed(2)+" MB":(n/1073741824).toFixed(2)+" GB"),`创建时间: ${new Date(1e3*parseInt(e.create_time||"0")).toLocaleString()}`,`修改时间: ${new Date(1e3*parseInt(e.modify_time||"0")).toLocaleString()}`,`ID: ${e.nid||"未知"}`,"---"].join("\n");var n}function is(e){e.tool("file-search","在云盘中根据关键词搜索文件和文件夹,支持按文件类型筛选和分页查询。返回符合条件的文件详细信息。",{file_category:St.number().optional().default(-1).describe("文件类型筛选:-1(全部)、0(其他)、1(图片)、2(文档)、3(音乐)、4(视频)"),key:St.string().describe("搜索关键词,必填参数"),page:St.number().optional().default(1).describe("页码,从1开始"),page_size:St.number().optional().default(20).describe("每页显示的条目数")},(async({file_category:e,key:t,page:r,page_size:n})=>{try{let s;const i={file_category:e,key:t,page:r||1,page_size:n||20};try{s=await ts({method:"File.searchList",extraParams:i})}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}const a=await async function(e,t){try{const r=new URL(Yn),n={"Access-Token":e.access_token||""},s={};for(const[e,r]of Object.entries(t))"access_token"!==e&&(s[String(e)]=String(r));const i={method:"File.searchList",access_token:e.access_token||"",qid:e.qid||"",sign:e.sign||"",...s};Object.entries(i).forEach((([e,t])=>{r.searchParams.append(e,String(t))}));const a=await fetch(r.toString(),{method:"GET",headers:n});if(!a.ok)throw new Error(`API 请求失败,状态码: ${a.status}`);const o=await a.text();try{return JSON.parse(o)}catch(e){throw new Error(`无法解析API响应: ${o.substring(0,100)}...`)}}catch(e){throw e}}(s,i);if(a&&0===a.errno){const e=a.data&&a.data.node_list||[];if(0===e.length)return{content:[{type:"text",text:"没有找到符合条件的文件"}]};const r=e.filter((e=>"1"===e.type)).length,n=e.length-r,s=e.map(ss);return{content:[{type:"text",text:`云盘文件搜索结果 (关键词: ${t})\n共 ${e.length} 项 (${r} 个文件夹, ${n} 个文件)\n\n${s.join("\n")}`},{type:"text",text:Qn}]}}throw new Error(a?.errmsg||"API请求失败")}catch(e){return{content:[{type:"text",text:`搜索文件时发生错误: ${e.message}`},{type:"text",text:Qn}]}}}))}function as(e){e.tool("make-dir","在云盘中创建新文件夹,支持指定路径。",{fname:St.string().describe("要创建的文件夹完整路径,例如:/新文件夹/ 或 /文档/子文件夹/")},(async({fname:e})=>{try{let t;const r={fname:e};try{t=await ts({method:"File.mkdir",extraParams:r})}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}const n=await async function(e,t){try{const r=new URL(Yn),n={"Access-Token":e.access_token||"","Content-Type":"application/x-www-form-urlencoded"},s={method:"File.mkdir",access_token:e.access_token||"",qid:e.qid||"",sign:e.sign||"",fname:t},i=new URLSearchParams;Object.entries(s).forEach((([e,t])=>{i.append(e,String(t))}));const a=await fetch(r.toString(),{method:"POST",headers:n,body:i});if(!a.ok)throw new Error(`API 请求失败,状态码: ${a.status}`);const o=await a.text();try{return JSON.parse(o)}catch(e){throw new Error(`无法解析API响应: ${o.substring(0,100)}...`)}}catch(e){throw e}}(t,e);if(n&&0===n.errno){return{content:[{type:"text",text:`文件夹"${e}"创建成功!\n文件夹ID: ${(n.data||{}).nid||""}`},{type:"text",text:Qn}]}}throw new Error(n?.errmsg||"API请求失败")}catch(e){return{content:[{type:"text",text:`创建文件夹时发生错误: ${e.message}`},{type:"text",text:Qn}]}}}))}function os(e){e.tool("file-move","移动云盘中的文件或文件夹到指定位置。支持批量移动多个文件。",{src_name:St.string().describe("源文件或文件夹路径,多个文件用竖线(|)分隔,例如:/文件1.txt|/文件2.txt"),new_name:St.string().describe("目标文件夹路径,例如:/目标文件夹/")},(async({src_name:e,new_name:t})=>{try{let r;const n={src_name:e,new_name:t};try{r=await ts({method:"File.move",extraParams:n})}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}const s=await async function(e,t,r){try{const n=new URL(Yn),s={"Access-Token":e.access_token||"","Content-Type":"application/x-www-form-urlencoded"},i={method:"File.move",access_token:e.access_token||"",qid:e.qid||"",sign:e.sign||"",src_name:t,new_name:r},a=new URLSearchParams;Object.entries(i).forEach((([e,t])=>{a.append(e,String(t))}));const o=await fetch(n.toString(),{method:"POST",headers:s,body:a});if(!o.ok)throw new Error(`API 请求失败,状态码: ${o.status}`);const c=await o.text();try{return JSON.parse(c)}catch(e){throw new Error(`无法解析API响应: ${c.substring(0,100)}...`)}}catch(e){throw e}}(r,e,t);if(s&&0===s.errno){const r=e.split("|").length;return{content:[{type:"text",text:`成功将${r}${r>1?"些文件":"个文件"}移动到"${t}"!`},{type:"text",text:Qn}]}}throw new Error(s?.errmsg||"API请求失败")}catch(e){return{content:[{type:"text",text:`移动文件时发生错误: ${e.message}`},{type:"text",text:Qn}]}}}))}function cs(e){e.tool("file-rename","重命名云盘中的文件或文件夹。",{src_name:St.string().describe("原文件或文件夹的完整路径,例如:/我的知识库/111.doc 或 /我的知识库/"),new_name:St.string().describe("新的名称(仅文件名或文件夹名,不含父路径)。文件夹名需以/结尾,例如:222.doc 或 我的知识库/")},(async({src_name:e,new_name:t})=>{try{let r;const n={src_name:e,new_name:t};try{r=await ts({method:"File.rename",extraParams:n})}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}const s=await async function(e,t,r){try{const n=new URL(Yn),s={"Access-Token":e.access_token||"","Content-Type":"application/x-www-form-urlencoded"},i={method:"File.rename",access_token:e.access_token||"",qid:e.qid||"",sign:e.sign||"",src_name:t,new_name:r},a=new URLSearchParams;Object.entries(i).forEach((([e,t])=>{a.append(e,String(t))}));const o=await fetch(n.toString(),{method:"POST",headers:s,body:a});if(!o.ok)throw new Error(`API 请求失败,状态码: ${o.status}`);const c=await o.text();try{return JSON.parse(c)}catch(e){throw new Error(`无法解析API响应: ${c.substring(0,100)}...`)}}catch(e){throw e}}(r,e,t);if(s&&0===s.errno){const r=e.endsWith("/")?"文件夹":"文件",n=e.split("/").filter((e=>""!==e));return{content:[{type:"text",text:`成功将${r}"${n.length>0?n[n.length-1]:e}"重命名为"${t}"!`},{type:"text",text:Qn}]}}throw new Error(s?.errmsg||"API请求失败")}catch(e){return{content:[{type:"text",text:`重命名文件时发生错误: ${e.message}`},{type:"text",text:Qn}]}}}))}function us(e){return e<1024?e+" B":e<1048576?(e/1024).toFixed(2)+" KB":e<1073741824?(e/1048576).toFixed(2)+" MB":(e/1073741824).toFixed(2)+" GB"}function hs(e){return new Date(1e3*e).toLocaleString()}function ds(e){return{"-1":"所有",0:"其他",1:"图片",2:"文档",3:"音乐",4:"视频"}[e]||"未知"}async function ls(e,t,r){return new Promise((async(s,i)=>{try{const a=await async function(){try{return(await import("@aicloud360/sec-sdk-node")).UploadNode}catch(e){throw new Error("请先安装@aicloud360/sec-sdk-node: npm install @aicloud360/sec-sdk-node")}}();for(const e of t)if(!n.existsSync(e))return void i(new Error(`文件不存在: ${e}`));const o={qid:process.env.qid||e.qid||"0",token:process.env.ECS_TOKEN||e.token||"",access_token:process.env.ECS_ACCESS_TOKEN||e.access_token||"",env:process.env.ECS_ENV||"prod",path:r||"/"};let c=[];const u=Date.now();let h=[],d=[];const l={},p={},m=(e,t)=>{let r="",n={};return e&&"object"==typeof e?"errno"in e&&"errmsg"in e?(n=e,r=`错误码: ${n.errno}, 错误信息: ${n.errmsg}`,n.trace_id&&(r+=`, 追踪ID: ${n.trace_id}`)):e instanceof Error?(n={message:e.message,stack:e.stack},r=e.message):e.message?(n={message:e.message},r=e.message):(n=e,r=JSON.stringify(e)):(r=String(e),n={message:r}),{fileName:t?.name||"未知文件",filePath:t?.path||"",originalError:n,formattedMessage:r}};new a(o,{success:e=>{const t=e.fid||e.nid;d.push({...e,uploadEndTime:Date.now(),uploadStartTime:l[t]||u})},progress:(e,t,r,n)=>{t&&(l[e]||(l[e]=Date.now()),p[e]={loaded:t,total:r,name:n.name})},error:(e,t)=>{c.push(m(t,e))},duplicateList:(e,t)=>{h=e.map((e=>({fileName:e.name||"未知",fileId:e.nid||"未知",fileSize:e.count_size?us(parseInt(e.count_size)):"未知",fileType:ds(e.file_category||"0"),createTime:e.create_time?hs(parseInt(e.create_time)):"未知",modifyTime:e.modify_time?hs(parseInt(e.modify_time)):"未知",filePath:e.path||r})))},complete(){if(c.length>0&&0===d.length){const e=c.map((e=>`文件: ${e.fileName} - ${e.formattedMessage}`)).join("; ");return void i(new Error(`所有文件上传失败: ${e}`))}const e=Date.now(),r=((e-u)/1e3).toFixed(2);s({uploadResults:d,totalUploadTime:r,startTime:u,endTime:e,duplicateFiles:h,fileCount:d.length,totalFileCount:t.length,progressInfo:p,uploadErrors:c})}}).addWaitFile(t)}catch(e){i(e)}}))}function ps(e){e.tool("file-share","生成云盘文件的分享链接。支持批量生成多个文件的分享链接。",{paths:St.string().describe("要分享的文件全路径,多个文件用竖线(|)隔开,例如:/文件1.txt|/文件夹2/文件2.txt")},(async({paths:e})=>{try{let t;try{t=await ts({method:"Share.preShare"})}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}const r=await async function(e,t){try{const r=new URL(Yn),n={"Access-Token":e.access_token||"","Content-Type":"application/x-www-form-urlencoded"},s={method:"Share.preShare",access_token:e.access_token||"",qid:e.qid||"",sign:e.sign||""},i=new URLSearchParams;Object.entries(s).forEach((([e,t])=>{i.append(e,String(t))})),i.append("paths",t);const a=await fetch(r.toString(),{method:"POST",headers:n,body:i});if(!a.ok)throw new Error(`API 请求失败,状态码: ${a.status}`);const o=await a.text();try{return JSON.parse(o)}catch(e){throw new Error(`无法解析API响应: ${o.substring(0,100)}...`)}}catch(e){throw e}}(t,e);if(r&&0===r.errno&&r.data&&r.data.share){const e=r.data.share;return{content:[{type:"text",text:`分享链接生成成功!\n链接: ${e.url}\n提取码: ${e.password||"无"}\n短链: ${e.shorturl}\n二维码: ${e.qrcode}`},{type:"text",text:Qn}],shareInfo:e}}throw new Error(r?.errmsg||"API请求失败")}catch(e){return{content:[{type:"text",text:`生成分享链接时发生错误: ${e.message}`},{type:"text",text:Qn}]}}}))}function ms(e){e.tool("user-info","获取360AI云盘用户详细信息。",(async()=>{try{let e;try{e=await ts()}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}const t=await async function(e){try{const t=new URL(Yn),r={"Access-Token":e.access_token||""};Object.entries({method:"User.getUserDetail",access_token:e.access_token||"",qid:e.qid||"",sign:""}).forEach((([e,r])=>{t.searchParams.append(e,String(r))}));const n=await fetch(t.toString(),{method:"GET",headers:r});if(!n.ok)throw new Error(`API 请求失败,状态码: ${n.status}`);const s=await n.text();try{return JSON.parse(s)}catch(e){throw new Error(`无法解析API响应: ${s.substring(0,100)}...`)}}catch(e){throw e}}(e);if(t&&0===t.errno&&t.data){const e=t.data;return{content:[{type:"text",text:`用户信息获取成功!\n${[`昵称: ${e.name}`,`会员: ${e.is_vip?"是":"否"}${e.vip_desc?"("+e.vip_desc+")":""}`,`总空间: ${(parseInt(e.total_size)/1073741824).toFixed(2)} GB`,`已用空间: ${(parseInt(e.used_size)/1073741824).toFixed(2)} GB`,`剩余空间: ${(e.available_size/1073741824).toFixed(2)} GB`,`会员剩余天数: ${e.expire_day}天`,`会员到期时间: ${e.expire?new Date(1e3*parseInt(e.expire)).toLocaleString():"未知"}`].join("\n")}`}],userInfo:e}}throw new Error(t?.errmsg||"API请求失败")}catch(e){return{content:[{type:"text",text:`获取用户信息时发生错误: ${e.message}`},{type:"text",text:Qn}]}}}))}t.config();const fs=i(import.meta.url),ys=s.dirname(fs),gs=JSON.parse(n.readFileSync(s.resolve(ys,"../package.json"),"utf8")),vs=new class{constructor(e,t){this.ue={},this.he={},this.de={},this.le={},this.pe=!1,this.me=!1,this.fe=!1,this.ye=!1,this.server=new rn(e,t)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this.pe||(this.server.assertCanSetRequestHandler(Or.shape.method.value),this.server.assertCanSetRequestHandler(Mr.shape.method.value),this.server.registerCapabilities({tools:{}}),this.server.setRequestHandler(Or,(()=>({tools:Object.entries(this.de).map((([e,t])=>({name:e,description:t.description,inputSchema:t.inputSchema?qn(t.inputSchema):Un})))}))),this.server.setRequestHandler(Mr,(async(e,t)=>{const r=this.de[e.params.name];if(!r)throw new en(Bt.InvalidParams,`Tool ${e.params.name} not found`);if(r.inputSchema){const n=await r.inputSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new en(Bt.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${n.error.message}`);const s=n.data,i=r.callback;try{return await Promise.resolve(i(s,t))}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}else{const e=r.callback;try{return await Promise.resolve(e(t))}catch(e){return{content:[{type:"text",text:e instanceof Error?e.message:String(e)}],isError:!0}}}})),this.pe=!0)}setCompletionRequestHandler(){this.me||(this.server.assertCanSetRequestHandler(Hr.shape.method.value),this.server.setRequestHandler(Hr,(async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new en(Bt.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}})),this.me=!0)}async handlePromptCompletion(e,t){const r=this.le[t.name];if(!r)throw new en(Bt.InvalidParams,`Prompt ${e.params.ref.name} not found`);if(!r.argsSchema)return Kn;const n=r.argsSchema.shape[e.params.argument.name];if(!(n instanceof Dn))return Kn;const s=n.l;return Bn(await s.complete(e.params.argument.value))}async handleResourceCompletion(e,t){const r=Object.values(this.he).find((e=>e.resourceTemplate.uriTemplate.toString()===t.uri));if(!r){if(this.ue[t.uri])return Kn;throw new en(Bt.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Kn;return Bn(await n(e.params.argument.value))}setResourceRequestHandlers(){this.fe||(this.server.assertCanSetRequestHandler(dr.shape.method.value),this.server.assertCanSetRequestHandler(pr.shape.method.value),this.server.assertCanSetRequestHandler(fr.shape.method.value),this.server.registerCapabilities({resources:{}}),this.server.setRequestHandler(dr,(async(e,t)=>{const r=Object.entries(this.ue).map((([e,t])=>({uri:e,name:t.name,...t.metadata}))),n=[];for(const e of Object.values(this.he)){if(!e.resourceTemplate.listCallback)continue;const r=await e.resourceTemplate.listCallback(t);for(const t of r.resources)n.push({...t,...e.metadata})}return{resources:[...r,...n]}})),this.server.setRequestHandler(pr,(async()=>({resourceTemplates:Object.entries(this.he).map((([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata})))}))),this.server.setRequestHandler(fr,(async(e,t)=>{const r=new URL(e.params.uri),n=this.ue[r.toString()];if(n)return n.readCallback(r,t);for(const e of Object.values(this.he)){const n=e.resourceTemplate.uriTemplate.match(r.toString());if(n)return e.readCallback(r,n,t)}throw new en(Bt.InvalidParams,`Resource ${r} not found`)})),this.setCompletionRequestHandler(),this.fe=!0)}setPromptRequestHandlers(){this.ye||(this.server.assertCanSetRequestHandler(kr.shape.method.value),this.server.assertCanSetRequestHandler(Ar.shape.method.value),this.server.registerCapabilities({prompts:{}}),this.server.setRequestHandler(kr,(()=>({prompts:Object.entries(this.le).map((([e,t])=>{return{name:e,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,Object.entries(r.shape).map((([e,t])=>({name:e,description:t.description,required:!t.isOptional()})))):void 0};var r}))}))),this.server.setRequestHandler(Ar,(async(e,t)=>{const r=this.le[e.params.name];if(!r)throw new en(Bt.InvalidParams,`Prompt ${e.params.name} not found`);if(r.argsSchema){const n=await r.argsSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new en(Bt.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n.error.message}`);const s=n.data,i=r.callback;return await Promise.resolve(i(s,t))}{const e=r.callback;return await Promise.resolve(e(t))}})),this.setCompletionRequestHandler(),this.ye=!0)}resource(e,t,...r){let n;"object"==typeof r[0]&&(n=r.shift());const s=r[0];if("string"==typeof t){if(this.ue[t])throw new Error(`Resource ${t} is already registered`);this.ue[t]={name:e,metadata:n,readCallback:s}}else{if(this.he[e])throw new Error(`Resource template ${e} is already registered`);this.he[e]={resourceTemplate:t,metadata:n,readCallback:s}}this.setResourceRequestHandlers()}tool(e,...t){if(this.de[e])throw new Error(`Tool ${e} is already registered`);let r,n;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(n=t.shift());const s=t[0];this.de[e]={description:r,inputSchema:void 0===n?void 0:St.object(n),callback:s},this.setToolRequestHandlers()}prompt(e,...t){if(this.le[e])throw new Error(`Prompt ${e} is already registered`);let r,n;"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(n=t.shift());const s=t[0];this.le[e]={description:r,argsSchema:void 0===n?void 0:St.object(n),callback:s},this.setPromptRequestHandlers()}}({name:gs.name,version:gs.version});!function(e){ns(e),is(e),as(e),os(e),cs(e),function(e){e.tool("file-upload-stdio","将本地文件上传到云盘指定路径。支持批量上传多个文件。",{filePaths:St.array(St.string()).describe("本地文件路径数组,例如:['/本地/文件1.txt', '/本地/文件2.jpg']"),uploadPath:St.string().optional().default("/").describe("云盘上传目标路径,默认为根目录'/'")},(async({filePaths:e,uploadPath:t},r)=>{try{let r;try{r=await ts({extraParams:{method:"Oauth.getAccessToken",toolName:"test-file-upload-stdio",clientId:"440c70f80b19c66206b87c513c5cff26e3c55378",clientSecret:"39bdfd28d9b5211c12ba48f0f5d0a4ee3126335e",qid:"3371683119",grantType:"authorization_code"}})}catch(e){throw new Error("获取鉴权信息失败,请提供有效的API_KEY")}try{if(!e||0===e.length)throw new Error("filePaths为必填参数且不能为空");const n=await ls(r,e,t),s=n.totalUploadTime||"未知",i=n.duplicateFiles||[],a=n.progressInfo||{},o=n.uploadErrors||[],c=(n.uploadResults||[]).map((e=>{const r=e.uploadRes||e||{},n=e.fid||r.nid||"未知",s=r.name||e.name||"未知",i=e.uploadStartTime&&e.uploadEndTime?((e.uploadEndTime-e.uploadStartTime)/1e3).toFixed(2):"未知";let o="未知",c="未知";return a[n]?(o=us(a[n].total),"未知"!==i&&(c=us(a[n].total/parseFloat(i))+"/s")):r.count_size&&(o=us(parseInt(r.count_size)),"未知"!==i&&(c=us(parseInt(r.count_size)/parseFloat(i))+"/s")),{fileName:s,fileId:n,fileSize:o,fileType:ds(r.file_category||"0"),createTime:r.create_time?hs(parseInt(r.create_time)):"未知",modifyTime:r.modify_time?hs(parseInt(r.modify_time)):"未知",filePath:t,fileHash:r.file_hash||void 0,uploadSpeed:c}})),u=[`总计上传文件数: ${c.length}/${e.length}`,`总上传耗时: ${s}秒`,`上传路径: ${t}`].join("\n"),h=c.map(((e,t)=>[`文件 ${t+1}:`,` 文件名: ${e.fileName}`,` 文件ID: ${e.fileId}`,` 文件大小: ${e.fileSize}`,` 文件类型: ${e.fileType}`,` 创建时间: ${e.createTime}`,` 修改时间: ${e.modifyTime}`,` 存储路径: ${e.filePath}`,e.fileHash?` 文件哈希: ${e.fileHash}`:"",` 上传速度: ${e.uploadSpeed||"未知"}`].filter((e=>e)).join("\n"))).join("\n\n");let d="";i.length>0&&(d="\n\n检测到以下文件已存在(重名文件):\n"+i.map(((e,t)=>`${t+1}. 文件名: ${e.fileName}\n 路径: ${e.filePath}\n 大小: ${e.fileSize}\n 创建时间: ${e.createTime}`)).join("\n\n"));let l="";return o.length>0&&(l="\n\n以下文件上传失败:\n"+o.map(((e,t)=>{const r=e.originalError;let n="";return n=r&&"object"==typeof r&&"errno"in r?[` 错误码: ${r.errno}`,` 错误信息: ${r.errmsg||"未知"}`,r.trace_id?` 追踪ID: ${r.trace_id}`:"",r.consume?` 处理耗时: ${r.consume}ms`:""].filter((e=>e)).join("\n"):` 错误信息: ${e.formattedMessage}`,`${t+1}. 文件名: ${e.fileName}\n${n}`})).join("\n\n")),{content:[{type:"text",text:`文件上传完成!\n\n${u}\n\n${h}${d}${l}`},{type:"text",text:Qn}]}}catch(e){throw e}}catch(e){return{content:[{type:"text",text:`上传文件时发生错误: ${e.message}`},{type:"text",text:Qn}]}}}))}(e),ps(e),ms(e)}(vs),async function(){const e=new Vn;await vs.connect(e)}().catch((e=>{process.exit(1)}));
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@aicloud360/mcp-server-disk",
3
+ "version": "0.3.4",
4
+ "main": "build/index.js",
5
+ "type": "module",
6
+ "bin": {
7
+ "mcp-server-disk": "build/index.js"
8
+ },
9
+ "scripts": {
10
+ "clean": "rm -rf build",
11
+ "build:ts": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
12
+ "build": "rollup -c && node scripts/postbuild.js",
13
+ "build:dev": "rollup -c --environment NODE_ENV:development && node scripts/postbuild.js",
14
+ "build:prod": "rollup -c --environment NODE_ENV:production && node scripts/postbuild.js",
15
+ "watch": "rollup -c -w",
16
+ "prepublishOnly": "npm run build:prod"
17
+ },
18
+ "files": [
19
+ "build"
20
+ ],
21
+ "keywords": [
22
+ "mcp",
23
+ "modelcontextprotocol",
24
+ "ecs",
25
+ "uploader"
26
+ ],
27
+ "author": "@aicloud360",
28
+ "license": "Apache-2.0",
29
+ "description": "360 AI 云盘 MCP",
30
+ "devDependencies": {
31
+ "@rollup/plugin-commonjs": "^25.0.7",
32
+ "@rollup/plugin-json": "^6.1.0",
33
+ "@rollup/plugin-node-resolve": "^15.2.3",
34
+ "@rollup/plugin-terser": "^0.4.4",
35
+ "@rollup/plugin-typescript": "^11.1.6",
36
+ "@types/node": "^22.10.0",
37
+ "rollup": "^4.12.0",
38
+ "rollup-plugin-delete": "^2.0.0",
39
+ "tslib": "^2.8.1",
40
+ "typescript": "^5.7.2"
41
+ },
42
+ "dependencies": {
43
+ "@aicloud360/sec-sdk-node": "^0.1.2",
44
+ "@modelcontextprotocol/sdk": "^1.4.0",
45
+ "@types/express": "^5.0.1",
46
+ "dotenv": "^16.5.0",
47
+ "express": "^5.1.0"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }