logseq-mcp 0.0.18 → 0.1.3

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 +139 -150
  2. package/dist/index.js +55 -0
  3. package/package.json +18 -1
package/README.md CHANGED
@@ -1,47 +1,56 @@
1
- # Logseq Agent
1
+ # Logseq MCP Agent
2
2
 
3
- A powerful Model Context Protocol (MCP) agent for interacting with Logseq, allowing AI assistants like Claude to access and manipulate your Logseq graph with fine-grained control.
3
+ A powerful AI assistant that connects Logseq with Claude and other LLMs using the Model Context Protocol (MCP).
4
4
 
5
- ## Installation
5
+ ## What is it?
6
6
 
7
- You can install the Logseq Agent via npm:
7
+ Logseq MCP Agent lets AI assistants like Claude directly interact with your Logseq knowledge graph - search your notes, create content, organize information, and manage tasks.
8
8
 
9
- ```bash
10
- npx logseq-mcp
11
- ```
9
+ MCP (Model Context Protocol) works like a "USB-C port for AI" - providing a standardized way for AI models to connect with your applications and data. This agent implements MCP to give Claude and other LLMs a direct, structured interface to your Logseq knowledge base.
12
10
 
13
- Or install it globally:
11
+ Think of it as giving Claude direct access to your second brain.
14
12
 
15
- ```bash
16
- npm install -g logseq-mcp
17
- ```
13
+ ## Key Features
18
14
 
19
- ## Quick Setup
15
+ ### 📝 Knowledge Management
16
+ - Search your entire graph for information
17
+ - Generate summaries of pages and content
18
+ - Create daily notes with custom sections
19
+ - Organize flat pages into nested structures
20
20
 
21
- 1. **Prerequisites:**
22
- - Logseq with HTTP API enabled
23
- - A valid Logseq API token
21
+ ### ✅ Task Management
22
+ - Find all tasks with specific statuses (TODO, DOING, etc.)
23
+ - Extract tasks from meeting notes
24
+ - Create and organize task lists
25
+ - Track task progress
24
26
 
25
- 2. **Configure your environment:**
26
- Create a `.env` file with:
27
- ```
28
- LOGSEQ_PORT=12315
29
- LOGSEQ_HOST=127.0.0.1
30
- LOGSEQ_TOKEN=your_logseq_token
31
- ```
27
+ ### 🔍 Search & Query
28
+ - Natural language search across your graph
29
+ - Find blocks by content
30
+ - Run advanced Datalog queries
32
31
 
33
- 3. **Start the agent:**
34
- ```bash
35
- logseq-mcp
36
- ```
32
+ ### 📊 Content Organization
33
+ - Restructure content hierarchically
34
+ - Organize blocks by any criteria
35
+ - Transform flat content into nested structures
36
+
37
+ ## Quick Setup
37
38
 
38
- ## Setup with Claude Desktop
39
+ ### Prerequisites
40
+ - [Logseq](https://logseq.com/) with HTTP API enabled
41
+ - A Logseq API token
42
+ - Claude Desktop or other MCP-compatible AI assistant
39
43
 
40
- To use the Logseq Agent with Claude Desktop:
44
+ ### Enabling Logseq HTTP API
45
+ 1. In Logseq → Settings → Advanced: Enable "Developer mode"
46
+ 2. Restart Logseq
47
+ 3. In Settings: Enable "HTTP API server"
48
+ 4. Copy your API token
41
49
 
50
+ ### Setup with Claude Desktop
42
51
  1. Open Claude Desktop settings
43
52
  2. Navigate to MCP Servers
44
- 3. Add a new server with the following configuration:
53
+ 3. Add a new server:
45
54
  ```json
46
55
  {
47
56
  "mcpServers": {
@@ -57,165 +66,145 @@ To use the Logseq Agent with Claude Desktop:
57
66
  }
58
67
  }
59
68
  ```
60
- 4. Save and restart Claude Desktop
61
- 5. You can now ask Claude to interact with your Logseq graph
62
-
63
- ## Features
64
-
65
- ### Block Management
66
-
67
- - **Get Block**: Retrieve a block by UUID
68
- - **Create Block**: Create a new block in a page
69
- - **Update Block**: Update an existing block
70
- - **Remove Block**: Remove a block by UUID
71
- - **Get/Set Block Properties**: Manage block properties
72
- - **Create Nested Blocks**: Create hierarchical block structures
73
- - **Edit/Select Blocks**: Manipulate blocks in the UI
69
+ 4. Replace `your_logseq_token` with your actual token
70
+ 5. Save and restart Claude
74
71
 
75
- ### Block Navigation & Organization
72
+ ### Using Claude with Logseq
73
+ Try asking:
74
+ - "Find all my TODO tasks in Logseq"
75
+ - "Create a daily note with sections for Tasks, Notes, and Journal"
76
+ - "Summarize my 'Research' page"
77
+ - "Search my notes for information about machine learning"
76
78
 
77
- - **Navigate Siblings**: Move between sibling blocks
78
- - **Move Block**: Reposition blocks within your graph
79
- - **Collapse/Expand**: Control block visibility
80
- - **Scroll to Block**: Navigate to specific blocks
81
- - **Right Sidebar**: Open blocks in the sidebar
79
+ ## Alternative Installation
82
80
 
83
- ### Page Management
84
-
85
- - **Create Page**: Add new pages to your graph
86
- - **Get Page**: Retrieve page content by name
87
- - **Get Current Page**: Access the active page
88
- - **Get All Pages**: List all pages in your graph
89
- - **Get Page Blocks**: Access all blocks in a page
90
- - **Get Linked References**: See all references to a page
91
-
92
- ### Search & Query
93
-
94
- - **Query Logseq**: Run powerful Datalog queries
95
- - **Search Blocks**: Find blocks matching criteria
96
- - **Get Tasks**: Retrieve and filter task blocks
97
-
98
- ## Built-in Prompts
99
-
100
- The agent includes several pre-configured prompt templates:
101
-
102
- ### Task Management
103
- - **query-tasks**: Find tasks with specific status (TODO, DOING, etc.)
104
- - **extract-tasks**: Extract and organize tasks from notes
105
-
106
- ### Content Creation & Organization
107
- - **create-daily-note**: Generate a daily note with customizable sections
108
- - **create-nested-content**: Create structured hierarchical content
109
- - **summarize-page**: Generate concise summaries of pages
110
-
111
- ### Knowledge Management
112
- - **search-knowledge**: Search your knowledge base
113
- - **organize-blocks**: Organize blocks by specified criteria
114
- - **organize-blocks-as-nested**: Restructure content hierarchically
115
- - **convert-flat-to-nested**: Transform flat pages into nested structures
116
-
117
- ## Usage Examples
118
-
119
- Here are some examples of how to use the Logseq Agent with Claude:
81
+ Install via npm:
82
+ ```bash
83
+ npx logseq-mcp
84
+ ```
120
85
 
121
- 1. **Create a daily note:**
122
- ```
123
- Please create a daily note for today with sections for Tasks, Notes, and Journal.
124
- ```
86
+ Or install globally:
87
+ ```bash
88
+ npm install -g logseq-mcp
89
+ ```
125
90
 
126
- 2. **Find and organize tasks:**
127
- ```
128
- Find all my TODO tasks and organize them by project.
129
- ```
91
+ Configure with a `.env` file:
92
+ ```
93
+ LOGSEQ_PORT=12315
94
+ LOGSEQ_HOST=127.0.0.1
95
+ LOGSEQ_TOKEN=your_logseq_token
96
+ ```
130
97
 
131
- 3. **Search my knowledge base:**
132
- ```
133
- Search my notes for information about "machine learning".
134
- ```
98
+ Run with:
99
+ ```bash
100
+ logseq-mcp
101
+ ```
135
102
 
136
- 4. **Summarize a page:**
137
- ```
138
- Can you summarize my "Project Ideas" page?
139
- ```
103
+ ## Troubleshooting
140
104
 
141
- 5. **Organize content:**
142
- ```
143
- Take my "Research Notes" page and organize it into a proper nested structure.
144
- ```
105
+ - Ensure Logseq is running before starting the agent
106
+ - Verify your API token is correct
107
+ - Check that the Logseq HTTP API is enabled
108
+ - Try debug mode: `DEBUG=true logseq-mcp`
145
109
 
146
- ## Troubleshooting
110
+ ### Debugging
111
+ Since MCP servers run over stdio, debugging can be challenging. For the best debugging experience, we recommend using the MCP Inspector.
147
112
 
148
- If you encounter connection issues:
113
+ You can launch the MCP Inspector via npm with:
149
114
 
150
- 1. **Enable the Logseq HTTP API:**
151
- - Open Logseq
152
- - Go to Settings
153
- - Navigate to 'Advanced'
154
- - Enable 'Developer mode'
155
- - Restart Logseq
156
- - Go to Settings again
157
- - Find and enable 'HTTP API server'
115
+ ```bash
116
+ npx @modelcontextprotocol/inspector uv --directory /path/to/mcp-logseq run mcp-logseq
117
+ ```
158
118
 
159
- 2. **Check your configuration:**
160
- - Ensure Logseq is running before starting the agent
161
- - Verify your LOGSEQ_TOKEN in the .env file
162
- - Make sure the port isn't blocked by your firewall
119
+ ## Technical Details
163
120
 
164
- 3. **Debug mode:**
165
- Add `DEBUG=true` to your .env file for more detailed logs:
166
- ```
167
- DEBUG=true
168
- LOGSEQ_PORT=12315
169
- LOGSEQ_HOST=127.0.0.1
170
- LOGSEQ_TOKEN=your_logseq_token
171
- ```
121
+ Built using the Model Context Protocol (MCP), an open standard for connecting AI models with external tools and data sources. The agent acts as an MCP server that provides structured access to your Logseq graph via the Logseq HTTP API.
172
122
 
173
123
  ## Development
174
124
 
175
- ### Running from source
125
+ ### Setup Development Environment
176
126
 
177
127
  1. Clone the repository:
178
128
  ```bash
179
- git clone https://github.com/yourusername/logseq-mcp.git
129
+ git clone https://github.com/briansunter/logseq-mcp.git
180
130
  cd logseq-mcp
181
131
  ```
182
132
 
183
133
  2. Install dependencies:
184
134
  ```bash
135
+ # Using npm
185
136
  npm install
137
+
138
+ # Using Bun (recommended)
139
+ bun install
186
140
  ```
187
141
 
188
- 3. Run the agent:
189
- ```bash
190
- npm start
191
- ```
142
+ ### Running Tests
192
143
 
193
- ### Testing
144
+ The project includes unit and end-to-end tests:
194
145
 
195
- Run the integration tests with:
196
146
  ```bash
197
- npm test
147
+ # Run all tests
148
+ bun test tests/
149
+
150
+ # Run unit tests only
151
+ bun test:unit
152
+
153
+ # Run e2e tests only
154
+ bun test:e2e
155
+
156
+ # Run tests in watch mode
157
+ bun test:watch
198
158
  ```
199
159
 
200
- ## For Developers
160
+ ### Building
201
161
 
202
- ### Releasing New Versions
162
+ ```bash
163
+ # Standard build
164
+ bun run build
165
+
166
+ # Build for Node.js
167
+ bun run build:node
168
+
169
+ # Build for Bun
170
+ bun run build:bun
171
+
172
+ # Build binaries for various platforms
173
+ bun run build:binary # Current platform
174
+ bun run build:macos-arm # macOS ARM
175
+ bun run build:macos-intel # macOS Intel
176
+ bun run build:linux-x64 # Linux x64
177
+ bun run build:linux-arm64 # Linux ARM64
178
+ bun run build:windows # Windows
179
+ bun run build:all-binaries # All platforms
180
+ ```
203
181
 
204
- To release a new version to npm:
182
+ ### Contributing Guidelines
205
183
 
206
- 1. Update your code and make sure all tests pass with `bun test`
207
- 2. Create a new GitHub release with a semantic version tag (e.g., `v1.0.1`)
208
- 3. The GitHub Action will automatically:
209
- - Build the package
210
- - Update the version number from the tag
211
- - Publish to npm
184
+ 1. Fork the repository
185
+ 2. Create a feature branch: `git checkout -b feature/your-feature-name`
186
+ 3. Commit your changes: `git commit -m 'Add some feature'`
187
+ 4. Push to the branch: `git push origin feature/your-feature-name`
188
+ 5. Submit a pull request
212
189
 
213
- Note: Make sure you have set the `NPM_TOKEN` secret in your GitHub repository settings.
190
+ Please make sure your code passes all tests and follows the existing code style. Add tests for new features.
214
191
 
215
- ## License
192
+ ## Contributing & License
216
193
 
217
- MIT
194
+ Contributions welcome! MIT License.
218
195
 
219
196
  ## Contributing
220
197
 
221
- Contributions are welcome! Please feel free to submit a Pull Request.
198
+ ### Semantic Versioning
199
+
200
+ This project uses semantic-release to automatically manage version numbers and create GitHub releases. Version numbers are determined by PR titles using the following conventions:
201
+
202
+ | PR Title Format | Example | Result |
203
+ |-----------------|---------|--------|
204
+ | `feat: ...` | `feat: add new search feature` | Minor version increase (0.X.0) |
205
+ | `fix: ...` | `fix: resolve search bug` | Patch version increase (0.0.X) |
206
+ | `feat(breaking): ...` | `feat(breaking): change API format` | Major version increase (X.0.0) |
207
+
208
+ Other valid prefixes: `docs:`, `style:`, `refactor:`, `perf:`, `test:`, `chore:`, `ci:`, `build:` (all result in patch versions).
209
+
210
+ When merging PRs to master, please follow these conventions in your PR titles to ensure proper versioning.
package/dist/index.js ADDED
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as h4}from"node:module";var v4=Object.create;var{getPrototypeOf:P4,defineProperty:e1,getOwnPropertyNames:k4}=Object;var T4=Object.prototype.hasOwnProperty;var x4=($,X,W)=>{W=$!=null?v4(P4($)):{};let J=X||!$||!$.__esModule?e1(W,"default",{value:$,enumerable:!0}):W;for(let Y of k4($))if(!T4.call(J,Y))e1(J,Y,{get:()=>$[Y],enumerable:!0});return J};var $2=($,X)=>()=>(X||$((X={exports:{}}).exports,X),X.exports);var a0=h4(import.meta.url);var w4=$2((E8,u6)=>{u6.exports={name:"dotenv",version:"16.4.7",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var V4=$2((b8,w0)=>{var i1=a0("fs"),d1=a0("path"),c6=a0("os"),p6=a0("crypto"),i6=w4(),o1=i6.version,d6=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function o6($){let X={},W=$.toString();W=W.replace(/\r\n?/mg,`
3
+ `);let J;while((J=d6.exec(W))!=null){let Y=J[1],H=J[2]||"";H=H.trim();let G=H[0];if(H=H.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),G==='"')H=H.replace(/\\n/g,`
4
+ `),H=H.replace(/\\r/g,"\r");X[Y]=H}return X}function r6($){let X=M4($),W=P.configDotenv({path:X});if(!W.parsed){let G=new Error(`MISSING_DATA: Cannot parse ${X} for an unknown reason`);throw G.code="MISSING_DATA",G}let J=B4($).split(","),Y=J.length,H;for(let G=0;G<Y;G++)try{let D=J[G].trim(),w=s6(W,D);H=P.decrypt(w.ciphertext,w.key);break}catch(D){if(G+1>=Y)throw D}return P.parse(H)}function a6($){console.log(`[dotenv@${o1}][INFO] ${$}`)}function t6($){console.log(`[dotenv@${o1}][WARN] ${$}`)}function R1($){console.log(`[dotenv@${o1}][DEBUG] ${$}`)}function B4($){if($&&$.DOTENV_KEY&&$.DOTENV_KEY.length>0)return $.DOTENV_KEY;if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0)return process.env.DOTENV_KEY;return""}function s6($,X){let W;try{W=new URL(X)}catch(D){if(D.code==="ERR_INVALID_URL"){let w=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw w.code="INVALID_DOTENV_KEY",w}throw D}let J=W.password;if(!J){let D=new Error("INVALID_DOTENV_KEY: Missing key part");throw D.code="INVALID_DOTENV_KEY",D}let Y=W.searchParams.get("environment");if(!Y){let D=new Error("INVALID_DOTENV_KEY: Missing environment part");throw D.code="INVALID_DOTENV_KEY",D}let H=`DOTENV_VAULT_${Y.toUpperCase()}`,G=$.parsed[H];if(!G){let D=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${H} in your .env.vault file.`);throw D.code="NOT_FOUND_DOTENV_ENVIRONMENT",D}return{ciphertext:G,key:J}}function M4($){let X=null;if($&&$.path&&$.path.length>0)if(Array.isArray($.path)){for(let W of $.path)if(i1.existsSync(W))X=W.endsWith(".vault")?W:`${W}.vault`}else X=$.path.endsWith(".vault")?$.path:`${$.path}.vault`;else X=d1.resolve(process.cwd(),".env.vault");if(i1.existsSync(X))return X;return null}function D4($){return $[0]==="~"?d1.join(c6.homedir(),$.slice(1)):$}function e6($){a6("Loading env from encrypted .env.vault");let X=P._parseVault($),W=process.env;if($&&$.processEnv!=null)W=$.processEnv;return P.populate(W,X,$),{parsed:X}}function $$($){let X=d1.resolve(process.cwd(),".env"),W="utf8",J=Boolean($&&$.debug);if($&&$.encoding)W=$.encoding;else if(J)R1("No encoding is specified. UTF-8 is used by default");let Y=[X];if($&&$.path)if(!Array.isArray($.path))Y=[D4($.path)];else{Y=[];for(let w of $.path)Y.push(D4(w))}let H,G={};for(let w of Y)try{let B=P.parse(i1.readFileSync(w,{encoding:W}));P.populate(G,B,$)}catch(B){if(J)R1(`Failed to load ${w} ${B.message}`);H=B}let D=process.env;if($&&$.processEnv!=null)D=$.processEnv;if(P.populate(D,G,$),H)return{parsed:G,error:H};else return{parsed:G}}function X$($){if(B4($).length===0)return P.configDotenv($);let X=M4($);if(!X)return t6(`You set DOTENV_KEY but you are missing a .env.vault file at ${X}. Did you forget to build it?`),P.configDotenv($);return P._configVault($)}function W$($,X){let W=Buffer.from(X.slice(-64),"hex"),J=Buffer.from($,"base64"),Y=J.subarray(0,12),H=J.subarray(-16);J=J.subarray(12,-16);try{let G=p6.createDecipheriv("aes-256-gcm",W,Y);return G.setAuthTag(H),`${G.update(J)}${G.final()}`}catch(G){let D=G instanceof RangeError,w=G.message==="Invalid key length",B=G.message==="Unsupported state or unable to authenticate data";if(D||w){let j=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw j.code="INVALID_DOTENV_KEY",j}else if(B){let j=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw j.code="DECRYPTION_FAILED",j}else throw G}}function J$($,X,W={}){let J=Boolean(W&&W.debug),Y=Boolean(W&&W.override);if(typeof X!=="object"){let H=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw H.code="OBJECT_REQUIRED",H}for(let H of Object.keys(X))if(Object.prototype.hasOwnProperty.call($,H)){if(Y===!0)$[H]=X[H];if(J)if(Y===!0)R1(`"${H}" is already defined and WAS overwritten`);else R1(`"${H}" is already defined and was NOT overwritten`)}else $[H]=X[H]}var P={configDotenv:$$,_configVault:e6,_parseVault:r6,config:X$,decrypt:W$,parse:o6,populate:J$};b8.configDotenv=P.configDotenv;b8._configVault=P._configVault;b8._parseVault=P._parseVault;b8.config=P.config;b8.decrypt=P.decrypt;b8.parse=P.parse;b8.populate=P.populate;w0.exports=P});var L;(function($){$.assertEqual=(Y)=>Y;function X(Y){}$.assertIs=X;function W(Y){throw new Error}$.assertNever=W,$.arrayToEnum=(Y)=>{let H={};for(let G of Y)H[G]=G;return H},$.getValidEnumValues=(Y)=>{let H=$.objectKeys(Y).filter((D)=>typeof Y[Y[D]]!=="number"),G={};for(let D of H)G[D]=Y[D];return $.objectValues(G)},$.objectValues=(Y)=>{return $.objectKeys(Y).map(function(H){return Y[H]})},$.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let H=[];for(let G in Y)if(Object.prototype.hasOwnProperty.call(Y,G))H.push(G);return H},$.find=(Y,H)=>{for(let G of Y)if(H(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&isFinite(Y)&&Math.floor(Y)===Y;function J(Y,H=" | "){return Y.map((G)=>typeof G==="string"?`'${G}'`:G).join(H)}$.joinValues=J,$.jsonStringifyReplacer=(Y,H)=>{if(typeof H==="bigint")return H.toString();return H}})(L||(L={}));var E1;(function($){$.mergeShapes=(X,W)=>{return{...X,...W}}})(E1||(E1={}));var z=L.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Q0=($)=>{switch(typeof $){case"undefined":return z.undefined;case"string":return z.string;case"number":return isNaN($)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":if(Array.isArray($))return z.array;if($===null)return z.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return z.promise;if(typeof Map!=="undefined"&&$ instanceof Map)return z.map;if(typeof Set!=="undefined"&&$ instanceof Set)return z.set;if(typeof Date!=="undefined"&&$ instanceof Date)return z.date;return z.object;default:return z.unknown}},M=L.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"]),g4=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class n extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(W)=>{this.issues=[...this.issues,W]},this.addIssues=(W=[])=>{this.issues=[...this.issues,...W]};let X=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,X);else this.__proto__=X;this.name="ZodError",this.issues=$}format($){let X=$||function(Y){return Y.message},W={_errors:[]},J=(Y)=>{for(let H of Y.issues)if(H.code==="invalid_union")H.unionErrors.map(J);else if(H.code==="invalid_return_type")J(H.returnTypeError);else if(H.code==="invalid_arguments")J(H.argumentsError);else if(H.path.length===0)W._errors.push(X(H));else{let G=W,D=0;while(D<H.path.length){let w=H.path[D];if(D!==H.path.length-1)G[w]=G[w]||{_errors:[]};else G[w]=G[w]||{_errors:[]},G[w]._errors.push(X(H));G=G[w],D++}}};return J(this),W}static assert($){if(!($ instanceof n))throw new Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,L.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(X)=>X.message){let X={},W=[];for(let J of this.issues)if(J.path.length>0)X[J.path[0]]=X[J.path[0]]||[],X[J.path[0]].push($(J));else W.push($(J));return{formErrors:W,fieldErrors:X}}get formErrors(){return this.flatten()}}n.create=($)=>{return new n($)};var _0=($,X)=>{let W;switch($.code){case M.invalid_type:if($.received===z.undefined)W="Required";else W=`Expected ${$.expected}, received ${$.received}`;break;case M.invalid_literal:W=`Invalid literal value, expected ${JSON.stringify($.expected,L.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:W=`Unrecognized key(s) in object: ${L.joinValues($.keys,", ")}`;break;case M.invalid_union:W="Invalid input";break;case M.invalid_union_discriminator:W=`Invalid discriminator value. Expected ${L.joinValues($.options)}`;break;case M.invalid_enum_value:W=`Invalid enum value. Expected ${L.joinValues($.options)}, received '${$.received}'`;break;case M.invalid_arguments:W="Invalid function arguments";break;case M.invalid_return_type:W="Invalid function return type";break;case M.invalid_date:W="Invalid date";break;case M.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(W=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")W=`${W} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)W=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)W=`Invalid input: must end with "${$.validation.endsWith}"`;else L.assertNever($.validation);else if($.validation!=="regex")W=`Invalid ${$.validation}`;else W="Invalid";break;case M.too_small:if($.type==="array")W=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")W=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")W=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")W=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else W="Invalid input";break;case M.too_big:if($.type==="array")W=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")W=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")W=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")W=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")W=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else W="Invalid input";break;case M.custom:W="Invalid input";break;case M.invalid_intersection_types:W="Intersection results could not be merged";break;case M.not_multiple_of:W=`Number must be a multiple of ${$.multipleOf}`;break;case M.not_finite:W="Number must be finite";break;default:W=X.defaultError,L.assertNever($)}return{message:W}},Y2=_0;function y4($){Y2=$}function t0(){return Y2}var s0=($)=>{let{data:X,path:W,errorMaps:J,issueData:Y}=$,H=[...W,...Y.path||[]],G={...Y,path:H};if(Y.message!==void 0)return{...Y,path:H,message:Y.message};let D="",w=J.filter((B)=>!!B).slice().reverse();for(let B of w)D=B(G,{data:X,defaultError:D}).message;return{...Y,path:H,message:D}},Z4=[];function O($,X){let W=t0(),J=s0({issueData:X,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,W,W===_0?void 0:_0].filter((Y)=>!!Y)});$.common.issues.push(J)}class T{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,X){let W=[];for(let J of X){if(J.status==="aborted")return K;if(J.status==="dirty")$.dirty();W.push(J.value)}return{status:$.value,value:W}}static async mergeObjectAsync($,X){let W=[];for(let J of X){let Y=await J.key,H=await J.value;W.push({key:Y,value:H})}return T.mergeObjectSync($,W)}static mergeObjectSync($,X){let W={};for(let J of X){let{key:Y,value:H}=J;if(Y.status==="aborted")return K;if(H.status==="aborted")return K;if(Y.status==="dirty")$.dirty();if(H.status==="dirty")$.dirty();if(Y.value!=="__proto__"&&(typeof H.value!=="undefined"||J.alwaysSet))W[Y.value]=H.value}return{status:$.value,value:W}}}var K=Object.freeze({status:"aborted"}),L0=($)=>({status:"dirty",value:$}),h=($)=>({status:"valid",value:$}),b1=($)=>$.status==="aborted",f1=($)=>$.status==="dirty",O0=($)=>$.status==="valid",m0=($)=>typeof Promise!=="undefined"&&$ instanceof Promise;function e0($,X,W,J){if(W==="a"&&!J)throw new TypeError("Private accessor was defined without a getter");if(typeof X==="function"?$!==X||!J:!X.has($))throw new TypeError("Cannot read private member from an object whose class did not declare it");return W==="m"?J:W==="a"?J.call($):J?J.value:X.get($)}function Q2($,X,W,J,Y){if(J==="m")throw new TypeError("Private method is not writable");if(J==="a"&&!Y)throw new TypeError("Private accessor was defined without a setter");if(typeof X==="function"?$!==X||!Y:!X.has($))throw new TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?Y.call($,W):Y?Y.value=W:X.set($,W),W}var A;(function($){$.errToObj=(X)=>typeof X==="string"?{message:X}:X||{},$.toString=(X)=>typeof X==="string"?X:X===null||X===void 0?void 0:X.message})(A||(A={}));var y0,Z0;class o{constructor($,X,W,J){this._cachedPath=[],this.parent=$,this.data=X,this._path=W,this._key=J}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var X2=($,X)=>{if(O0(X))return{success:!0,data:X.value};else{if(!$.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let W=new n($.common.issues);return this._error=W,this._error}}}};function N($){if(!$)return{};let{errorMap:X,invalid_type_error:W,required_error:J,description:Y}=$;if(X&&(W||J))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(X)return{errorMap:X,description:Y};return{errorMap:(G,D)=>{var w,B;let{message:j}=$;if(G.code==="invalid_enum_value")return{message:j!==null&&j!==void 0?j:D.defaultError};if(typeof D.data==="undefined")return{message:(w=j!==null&&j!==void 0?j:J)!==null&&w!==void 0?w:D.defaultError};if(G.code!=="invalid_type")return{message:D.defaultError};return{message:(B=j!==null&&j!==void 0?j:W)!==null&&B!==void 0?B:D.defaultError}},description:Y}}class q{get description(){return this._def.description}_getType($){return Q0($.data)}_getOrReturnCtx($,X){return X||{common:$.parent.common,data:$.data,parsedType:Q0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new T,ctx:{common:$.parent.common,data:$.data,parsedType:Q0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let X=this._parse($);if(m0(X))throw new Error("Synchronous parse encountered promise.");return X}_parseAsync($){let X=this._parse($);return Promise.resolve(X)}parse($,X){let W=this.safeParse($,X);if(W.success)return W.data;throw W.error}safeParse($,X){var W;let J={common:{issues:[],async:(W=X===null||X===void 0?void 0:X.async)!==null&&W!==void 0?W:!1,contextualErrorMap:X===null||X===void 0?void 0:X.errorMap},path:(X===null||X===void 0?void 0:X.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:Q0($)},Y=this._parseSync({data:$,path:J.path,parent:J});return X2(J,Y)}"~validate"($){var X,W;let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:Q0($)};if(!this["~standard"].async)try{let Y=this._parseSync({data:$,path:[],parent:J});return O0(Y)?{value:Y.value}:{issues:J.common.issues}}catch(Y){if((W=(X=Y===null||Y===void 0?void 0:Y.message)===null||X===void 0?void 0:X.toLowerCase())===null||W===void 0?void 0:W.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((Y)=>O0(Y)?{value:Y.value}:{issues:J.common.issues})}async parseAsync($,X){let W=await this.safeParseAsync($,X);if(W.success)return W.data;throw W.error}async safeParseAsync($,X){let W={common:{issues:[],contextualErrorMap:X===null||X===void 0?void 0:X.errorMap,async:!0},path:(X===null||X===void 0?void 0:X.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:Q0($)},J=this._parse({data:$,path:W.path,parent:W}),Y=await(m0(J)?J:Promise.resolve(J));return X2(W,Y)}refine($,X){let W=(J)=>{if(typeof X==="string"||typeof X==="undefined")return{message:X};else if(typeof X==="function")return X(J);else return X};return this._refinement((J,Y)=>{let H=$(J),G=()=>Y.addIssue({code:M.custom,...W(J)});if(typeof Promise!=="undefined"&&H instanceof Promise)return H.then((D)=>{if(!D)return G(),!1;else return!0});if(!H)return G(),!1;else return!0})}refinement($,X){return this._refinement((W,J)=>{if(!$(W))return J.addIssue(typeof X==="function"?X(W,J):X),!1;else return!0})}_refinement($){return new p({schema:this,typeName:V.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(X)=>this["~validate"](X)}}optional(){return u.create(this,this._def)}nullable(){return H0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return d.create(this)}promise(){return F0.create(this,this._def)}or($){return C0.create([this,$],this._def)}and($){return I0.create(this,$,this._def)}transform($){return new p({...N(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:$}})}default($){let X=typeof $==="function"?$:()=>$;return new T0({...N(this._def),innerType:this,defaultValue:X,typeName:V.ZodDefault})}brand(){return new X1({typeName:V.ZodBranded,type:this,...N(this._def)})}catch($){let X=typeof $==="function"?$:()=>$;return new x0({...N(this._def),innerType:this,catchValue:X,typeName:V.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return i0.create(this,$)}readonly(){return h0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var m4=/^c[^\s-]{8,}$/i,l4=/^[0-9a-z]+$/,n4=/^[0-9A-HJKMNP-TV-Z]{26}$/i,u4=/^[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,c4=/^[a-z0-9_-]{21}$/i,p4=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,i4=/^[-+]?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)?)??$/,d4=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,o4="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",_1,r4=/^(?:(?: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])$/,a4=/^(?:(?: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])$/,t4=/^(([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]))$/,s4=/^(([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])$/,e4=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,$3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,H2="((\\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])))",X3=new RegExp(`^${H2}$`);function G2($){let X="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if($.precision)X=`${X}\\.\\d{${$.precision}}`;else if($.precision==null)X=`${X}(\\.\\d+)?`;return X}function W3($){return new RegExp(`^${G2($)}$`)}function w2($){let X=`${H2}T${G2($)}`,W=[];if(W.push($.local?"Z?":"Z"),$.offset)W.push("([+-]\\d{2}:?\\d{2})");return X=`${X}(${W.join("|")})`,new RegExp(`^${X}$`)}function J3($,X){if((X==="v4"||!X)&&r4.test($))return!0;if((X==="v6"||!X)&&t4.test($))return!0;return!1}function Y3($,X){if(!p4.test($))return!1;try{let[W]=$.split("."),J=W.replace(/-/g,"+").replace(/_/g,"/").padEnd(W.length+(4-W.length%4)%4,"="),Y=JSON.parse(atob(J));if(typeof Y!=="object"||Y===null)return!1;if(!Y.typ||!Y.alg)return!1;if(X&&Y.alg!==X)return!1;return!0}catch(W){return!1}}function Q3($,X){if((X==="v4"||!X)&&a4.test($))return!0;if((X==="v6"||!X)&&s4.test($))return!0;return!1}class i extends q{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==z.string){let Y=this._getOrReturnCtx($);return O(Y,{code:M.invalid_type,expected:z.string,received:Y.parsedType}),K}let W=new T,J=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.length<Y.value)J=this._getOrReturnCtx($,J),O(J,{code:M.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),W.dirty()}else if(Y.kind==="max"){if($.data.length>Y.value)J=this._getOrReturnCtx($,J),O(J,{code:M.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),W.dirty()}else if(Y.kind==="length"){let H=$.data.length>Y.value,G=$.data.length<Y.value;if(H||G){if(J=this._getOrReturnCtx($,J),H)O(J,{code:M.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(G)O(J,{code:M.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});W.dirty()}}else if(Y.kind==="email"){if(!d4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"email",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="emoji"){if(!_1)_1=new RegExp(o4,"u");if(!_1.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"emoji",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="uuid"){if(!u4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"uuid",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="nanoid"){if(!c4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"nanoid",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="cuid"){if(!m4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"cuid",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="cuid2"){if(!l4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"cuid2",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="ulid"){if(!n4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"ulid",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="url")try{new URL($.data)}catch(H){J=this._getOrReturnCtx($,J),O(J,{validation:"url",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"regex",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="trim")$.data=$.data.trim();else if(Y.kind==="includes"){if(!$.data.includes(Y.value,Y.position))J=this._getOrReturnCtx($,J),O(J,{code:M.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),W.dirty()}else if(Y.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(Y.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(Y.kind==="startsWith"){if(!$.data.startsWith(Y.value))J=this._getOrReturnCtx($,J),O(J,{code:M.invalid_string,validation:{startsWith:Y.value},message:Y.message}),W.dirty()}else if(Y.kind==="endsWith"){if(!$.data.endsWith(Y.value))J=this._getOrReturnCtx($,J),O(J,{code:M.invalid_string,validation:{endsWith:Y.value},message:Y.message}),W.dirty()}else if(Y.kind==="datetime"){if(!w2(Y).test($.data))J=this._getOrReturnCtx($,J),O(J,{code:M.invalid_string,validation:"datetime",message:Y.message}),W.dirty()}else if(Y.kind==="date"){if(!X3.test($.data))J=this._getOrReturnCtx($,J),O(J,{code:M.invalid_string,validation:"date",message:Y.message}),W.dirty()}else if(Y.kind==="time"){if(!W3(Y).test($.data))J=this._getOrReturnCtx($,J),O(J,{code:M.invalid_string,validation:"time",message:Y.message}),W.dirty()}else if(Y.kind==="duration"){if(!i4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"duration",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="ip"){if(!J3($.data,Y.version))J=this._getOrReturnCtx($,J),O(J,{validation:"ip",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="jwt"){if(!Y3($.data,Y.alg))J=this._getOrReturnCtx($,J),O(J,{validation:"jwt",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="cidr"){if(!Q3($.data,Y.version))J=this._getOrReturnCtx($,J),O(J,{validation:"cidr",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="base64"){if(!e4.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"base64",code:M.invalid_string,message:Y.message}),W.dirty()}else if(Y.kind==="base64url"){if(!$3.test($.data))J=this._getOrReturnCtx($,J),O(J,{validation:"base64url",code:M.invalid_string,message:Y.message}),W.dirty()}else L.assertNever(Y);return{status:W.value,value:$.data}}_regex($,X,W){return this.refinement((J)=>$.test(J),{validation:X,code:M.invalid_string,...A.errToObj(W)})}_addCheck($){return new i({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...A.errToObj($)})}url($){return this._addCheck({kind:"url",...A.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...A.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...A.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...A.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...A.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...A.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...A.errToObj($)})}base64($){return this._addCheck({kind:"base64",...A.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...A.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...A.errToObj($)})}ip($){return this._addCheck({kind:"ip",...A.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...A.errToObj($)})}datetime($){var X,W;if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof($===null||$===void 0?void 0:$.precision)==="undefined"?null:$===null||$===void 0?void 0:$.precision,offset:(X=$===null||$===void 0?void 0:$.offset)!==null&&X!==void 0?X:!1,local:(W=$===null||$===void 0?void 0:$.local)!==null&&W!==void 0?W:!1,...A.errToObj($===null||$===void 0?void 0:$.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof($===null||$===void 0?void 0:$.precision)==="undefined"?null:$===null||$===void 0?void 0:$.precision,...A.errToObj($===null||$===void 0?void 0:$.message)})}duration($){return this._addCheck({kind:"duration",...A.errToObj($)})}regex($,X){return this._addCheck({kind:"regex",regex:$,...A.errToObj(X)})}includes($,X){return this._addCheck({kind:"includes",value:$,position:X===null||X===void 0?void 0:X.position,...A.errToObj(X===null||X===void 0?void 0:X.message)})}startsWith($,X){return this._addCheck({kind:"startsWith",value:$,...A.errToObj(X)})}endsWith($,X){return this._addCheck({kind:"endsWith",value:$,...A.errToObj(X)})}min($,X){return this._addCheck({kind:"min",value:$,...A.errToObj(X)})}max($,X){return this._addCheck({kind:"max",value:$,...A.errToObj(X)})}length($,X){return this._addCheck({kind:"length",value:$,...A.errToObj(X)})}nonempty($){return this.min(1,A.errToObj($))}trim(){return new i({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new i({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new i({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $}get maxLength(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $}}i.create=($)=>{var X;return new i({checks:[],typeName:V.ZodString,coerce:(X=$===null||$===void 0?void 0:$.coerce)!==null&&X!==void 0?X:!1,...N($)})};function H3($,X){let W=($.toString().split(".")[1]||"").length,J=(X.toString().split(".")[1]||"").length,Y=W>J?W:J,H=parseInt($.toFixed(Y).replace(".","")),G=parseInt(X.toFixed(Y).replace(".",""));return H%G/Math.pow(10,Y)}class M0 extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==z.number){let Y=this._getOrReturnCtx($);return O(Y,{code:M.invalid_type,expected:z.number,received:Y.parsedType}),K}let W=void 0,J=new T;for(let Y of this._def.checks)if(Y.kind==="int"){if(!L.isInteger($.data))W=this._getOrReturnCtx($,W),O(W,{code:M.invalid_type,expected:"integer",received:"float",message:Y.message}),J.dirty()}else if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)W=this._getOrReturnCtx($,W),O(W,{code:M.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),J.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)W=this._getOrReturnCtx($,W),O(W,{code:M.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),J.dirty()}else if(Y.kind==="multipleOf"){if(H3($.data,Y.value)!==0)W=this._getOrReturnCtx($,W),O(W,{code:M.not_multiple_of,multipleOf:Y.value,message:Y.message}),J.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite($.data))W=this._getOrReturnCtx($,W),O(W,{code:M.not_finite,message:Y.message}),J.dirty()}else L.assertNever(Y);return{status:J.value,value:$.data}}gte($,X){return this.setLimit("min",$,!0,A.toString(X))}gt($,X){return this.setLimit("min",$,!1,A.toString(X))}lte($,X){return this.setLimit("max",$,!0,A.toString(X))}lt($,X){return this.setLimit("max",$,!1,A.toString(X))}setLimit($,X,W,J){return new M0({...this._def,checks:[...this._def.checks,{kind:$,value:X,inclusive:W,message:A.toString(J)}]})}_addCheck($){return new M0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:A.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString($)})}multipleOf($,X){return this._addCheck({kind:"multipleOf",value:$,message:A.toString(X)})}finite($){return this._addCheck({kind:"finite",message:A.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString($)})}get minValue(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $}get maxValue(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&L.isInteger($.value))}get isFinite(){let $=null,X=null;for(let W of this._def.checks)if(W.kind==="finite"||W.kind==="int"||W.kind==="multipleOf")return!0;else if(W.kind==="min"){if(X===null||W.value>X)X=W.value}else if(W.kind==="max"){if($===null||W.value<$)$=W.value}return Number.isFinite(X)&&Number.isFinite($)}}M0.create=($)=>{return new M0({checks:[],typeName:V.ZodNumber,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...N($)})};class V0 extends q{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch(Y){return this._getInvalidInput($)}if(this._getType($)!==z.bigint)return this._getInvalidInput($);let W=void 0,J=new T;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)W=this._getOrReturnCtx($,W),O(W,{code:M.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),J.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)W=this._getOrReturnCtx($,W),O(W,{code:M.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),J.dirty()}else if(Y.kind==="multipleOf"){if($.data%Y.value!==BigInt(0))W=this._getOrReturnCtx($,W),O(W,{code:M.not_multiple_of,multipleOf:Y.value,message:Y.message}),J.dirty()}else L.assertNever(Y);return{status:J.value,value:$.data}}_getInvalidInput($){let X=this._getOrReturnCtx($);return O(X,{code:M.invalid_type,expected:z.bigint,received:X.parsedType}),K}gte($,X){return this.setLimit("min",$,!0,A.toString(X))}gt($,X){return this.setLimit("min",$,!1,A.toString(X))}lte($,X){return this.setLimit("max",$,!0,A.toString(X))}lt($,X){return this.setLimit("max",$,!1,A.toString(X))}setLimit($,X,W,J){return new V0({...this._def,checks:[...this._def.checks,{kind:$,value:X,inclusive:W,message:A.toString(J)}]})}_addCheck($){return new V0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString($)})}multipleOf($,X){return this._addCheck({kind:"multipleOf",value:$,message:A.toString(X)})}get minValue(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $}get maxValue(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $}}V0.create=($)=>{var X;return new V0({checks:[],typeName:V.ZodBigInt,coerce:(X=$===null||$===void 0?void 0:$.coerce)!==null&&X!==void 0?X:!1,...N($)})};class E0 extends q{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==z.boolean){let W=this._getOrReturnCtx($);return O(W,{code:M.invalid_type,expected:z.boolean,received:W.parsedType}),K}return h($.data)}}E0.create=($)=>{return new E0({typeName:V.ZodBoolean,coerce:($===null||$===void 0?void 0:$.coerce)||!1,...N($)})};class z0 extends q{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==z.date){let Y=this._getOrReturnCtx($);return O(Y,{code:M.invalid_type,expected:z.date,received:Y.parsedType}),K}if(isNaN($.data.getTime())){let Y=this._getOrReturnCtx($);return O(Y,{code:M.invalid_date}),K}let W=new T,J=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.getTime()<Y.value)J=this._getOrReturnCtx($,J),O(J,{code:M.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),W.dirty()}else if(Y.kind==="max"){if($.data.getTime()>Y.value)J=this._getOrReturnCtx($,J),O(J,{code:M.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),W.dirty()}else L.assertNever(Y);return{status:W.value,value:new Date($.data.getTime())}}_addCheck($){return new z0({...this._def,checks:[...this._def.checks,$]})}min($,X){return this._addCheck({kind:"min",value:$.getTime(),message:A.toString(X)})}max($,X){return this._addCheck({kind:"max",value:$.getTime(),message:A.toString(X)})}get minDate(){let $=null;for(let X of this._def.checks)if(X.kind==="min"){if($===null||X.value>$)$=X.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let X of this._def.checks)if(X.kind==="max"){if($===null||X.value<$)$=X.value}return $!=null?new Date($):null}}z0.create=($)=>{return new z0({checks:[],coerce:($===null||$===void 0?void 0:$.coerce)||!1,typeName:V.ZodDate,...N($)})};class l0 extends q{_parse($){if(this._getType($)!==z.symbol){let W=this._getOrReturnCtx($);return O(W,{code:M.invalid_type,expected:z.symbol,received:W.parsedType}),K}return h($.data)}}l0.create=($)=>{return new l0({typeName:V.ZodSymbol,...N($)})};class b0 extends q{_parse($){if(this._getType($)!==z.undefined){let W=this._getOrReturnCtx($);return O(W,{code:M.invalid_type,expected:z.undefined,received:W.parsedType}),K}return h($.data)}}b0.create=($)=>{return new b0({typeName:V.ZodUndefined,...N($)})};class f0 extends q{_parse($){if(this._getType($)!==z.null){let W=this._getOrReturnCtx($);return O(W,{code:M.invalid_type,expected:z.null,received:W.parsedType}),K}return h($.data)}}f0.create=($)=>{return new f0({typeName:V.ZodNull,...N($)})};class A0 extends q{constructor(){super(...arguments);this._any=!0}_parse($){return h($.data)}}A0.create=($)=>{return new A0({typeName:V.ZodAny,...N($)})};class B0 extends q{constructor(){super(...arguments);this._unknown=!0}_parse($){return h($.data)}}B0.create=($)=>{return new B0({typeName:V.ZodUnknown,...N($)})};class X0 extends q{_parse($){let X=this._getOrReturnCtx($);return O(X,{code:M.invalid_type,expected:z.never,received:X.parsedType}),K}}X0.create=($)=>{return new X0({typeName:V.ZodNever,...N($)})};class n0 extends q{_parse($){if(this._getType($)!==z.undefined){let W=this._getOrReturnCtx($);return O(W,{code:M.invalid_type,expected:z.void,received:W.parsedType}),K}return h($.data)}}n0.create=($)=>{return new n0({typeName:V.ZodVoid,...N($)})};class d extends q{_parse($){let{ctx:X,status:W}=this._processInputParams($),J=this._def;if(X.parsedType!==z.array)return O(X,{code:M.invalid_type,expected:z.array,received:X.parsedType}),K;if(J.exactLength!==null){let H=X.data.length>J.exactLength.value,G=X.data.length<J.exactLength.value;if(H||G)O(X,{code:H?M.too_big:M.too_small,minimum:G?J.exactLength.value:void 0,maximum:H?J.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:J.exactLength.message}),W.dirty()}if(J.minLength!==null){if(X.data.length<J.minLength.value)O(X,{code:M.too_small,minimum:J.minLength.value,type:"array",inclusive:!0,exact:!1,message:J.minLength.message}),W.dirty()}if(J.maxLength!==null){if(X.data.length>J.maxLength.value)O(X,{code:M.too_big,maximum:J.maxLength.value,type:"array",inclusive:!0,exact:!1,message:J.maxLength.message}),W.dirty()}if(X.common.async)return Promise.all([...X.data].map((H,G)=>{return J.type._parseAsync(new o(X,H,X.path,G))})).then((H)=>{return T.mergeArray(W,H)});let Y=[...X.data].map((H,G)=>{return J.type._parseSync(new o(X,H,X.path,G))});return T.mergeArray(W,Y)}get element(){return this._def.type}min($,X){return new d({...this._def,minLength:{value:$,message:A.toString(X)}})}max($,X){return new d({...this._def,maxLength:{value:$,message:A.toString(X)}})}length($,X){return new d({...this._def,exactLength:{value:$,message:A.toString(X)}})}nonempty($){return this.min(1,$)}}d.create=($,X)=>{return new d({type:$,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...N(X)})};function S0($){if($ instanceof v){let X={};for(let W in $.shape){let J=$.shape[W];X[W]=u.create(S0(J))}return new v({...$._def,shape:()=>X})}else if($ instanceof d)return new d({...$._def,type:S0($.element)});else if($ instanceof u)return u.create(S0($.unwrap()));else if($ instanceof H0)return H0.create(S0($.unwrap()));else if($ instanceof W0)return W0.create($.items.map((X)=>S0(X)));else return $}class v extends q{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),X=L.objectKeys($);return this._cached={shape:$,keys:X}}_parse($){if(this._getType($)!==z.object){let w=this._getOrReturnCtx($);return O(w,{code:M.invalid_type,expected:z.object,received:w.parsedType}),K}let{status:W,ctx:J}=this._processInputParams($),{shape:Y,keys:H}=this._getCached(),G=[];if(!(this._def.catchall instanceof X0&&this._def.unknownKeys==="strip")){for(let w in J.data)if(!H.includes(w))G.push(w)}let D=[];for(let w of H){let B=Y[w],j=J.data[w];D.push({key:{status:"valid",value:w},value:B._parse(new o(J,j,J.path,w)),alwaysSet:w in J.data})}if(this._def.catchall instanceof X0){let w=this._def.unknownKeys;if(w==="passthrough")for(let B of G)D.push({key:{status:"valid",value:B},value:{status:"valid",value:J.data[B]}});else if(w==="strict"){if(G.length>0)O(J,{code:M.unrecognized_keys,keys:G}),W.dirty()}else if(w==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let w=this._def.catchall;for(let B of G){let j=J.data[B];D.push({key:{status:"valid",value:B},value:w._parse(new o(J,j,J.path,B)),alwaysSet:B in J.data})}}if(J.common.async)return Promise.resolve().then(async()=>{let w=[];for(let B of D){let j=await B.key,R=await B.value;w.push({key:j,value:R,alwaysSet:B.alwaysSet})}return w}).then((w)=>{return T.mergeObjectSync(W,w)});else return T.mergeObjectSync(W,D)}get shape(){return this._def.shape()}strict($){return A.errToObj,new v({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(X,W)=>{var J,Y,H,G;let D=(H=(Y=(J=this._def).errorMap)===null||Y===void 0?void 0:Y.call(J,X,W).message)!==null&&H!==void 0?H:W.defaultError;if(X.code==="unrecognized_keys")return{message:(G=A.errToObj($).message)!==null&&G!==void 0?G:D};return{message:D}}}:{}})}strip(){return new v({...this._def,unknownKeys:"strip"})}passthrough(){return new v({...this._def,unknownKeys:"passthrough"})}extend($){return new v({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new v({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:V.ZodObject})}setKey($,X){return this.augment({[$]:X})}catchall($){return new v({...this._def,catchall:$})}pick($){let X={};return L.objectKeys($).forEach((W)=>{if($[W]&&this.shape[W])X[W]=this.shape[W]}),new v({...this._def,shape:()=>X})}omit($){let X={};return L.objectKeys(this.shape).forEach((W)=>{if(!$[W])X[W]=this.shape[W]}),new v({...this._def,shape:()=>X})}deepPartial(){return S0(this)}partial($){let X={};return L.objectKeys(this.shape).forEach((W)=>{let J=this.shape[W];if($&&!$[W])X[W]=J;else X[W]=J.optional()}),new v({...this._def,shape:()=>X})}required($){let X={};return L.objectKeys(this.shape).forEach((W)=>{if($&&!$[W])X[W]=this.shape[W];else{let Y=this.shape[W];while(Y instanceof u)Y=Y._def.innerType;X[W]=Y}}),new v({...this._def,shape:()=>X})}keyof(){return D2(L.objectKeys(this.shape))}}v.create=($,X)=>{return new v({shape:()=>$,unknownKeys:"strip",catchall:X0.create(),typeName:V.ZodObject,...N(X)})};v.strictCreate=($,X)=>{return new v({shape:()=>$,unknownKeys:"strict",catchall:X0.create(),typeName:V.ZodObject,...N(X)})};v.lazycreate=($,X)=>{return new v({shape:$,unknownKeys:"strip",catchall:X0.create(),typeName:V.ZodObject,...N(X)})};class C0 extends q{_parse($){let{ctx:X}=this._processInputParams($),W=this._def.options;function J(Y){for(let G of Y)if(G.result.status==="valid")return G.result;for(let G of Y)if(G.result.status==="dirty")return X.common.issues.push(...G.ctx.common.issues),G.result;let H=Y.map((G)=>new n(G.ctx.common.issues));return O(X,{code:M.invalid_union,unionErrors:H}),K}if(X.common.async)return Promise.all(W.map(async(Y)=>{let H={...X,common:{...X.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:X.data,path:X.path,parent:H}),ctx:H}})).then(J);else{let Y=void 0,H=[];for(let D of W){let w={...X,common:{...X.common,issues:[]},parent:null},B=D._parseSync({data:X.data,path:X.path,parent:w});if(B.status==="valid")return B;else if(B.status==="dirty"&&!Y)Y={result:B,ctx:w};if(w.common.issues.length)H.push(w.common.issues)}if(Y)return X.common.issues.push(...Y.ctx.common.issues),Y.result;let G=H.map((D)=>new n(D));return O(X,{code:M.invalid_union,unionErrors:G}),K}}get options(){return this._def.options}}C0.create=($,X)=>{return new C0({options:$,typeName:V.ZodUnion,...N(X)})};var Y0=($)=>{if($ instanceof v0)return Y0($.schema);else if($ instanceof p)return Y0($.innerType());else if($ instanceof P0)return[$.value];else if($ instanceof j0)return $.options;else if($ instanceof k0)return L.objectValues($.enum);else if($ instanceof T0)return Y0($._def.innerType);else if($ instanceof b0)return[void 0];else if($ instanceof f0)return[null];else if($ instanceof u)return[void 0,...Y0($.unwrap())];else if($ instanceof H0)return[null,...Y0($.unwrap())];else if($ instanceof X1)return Y0($.unwrap());else if($ instanceof h0)return Y0($.unwrap());else if($ instanceof x0)return Y0($._def.innerType);else return[]};class $1 extends q{_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==z.object)return O(X,{code:M.invalid_type,expected:z.object,received:X.parsedType}),K;let W=this.discriminator,J=X.data[W],Y=this.optionsMap.get(J);if(!Y)return O(X,{code:M.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[W]}),K;if(X.common.async)return Y._parseAsync({data:X.data,path:X.path,parent:X});else return Y._parseSync({data:X.data,path:X.path,parent:X})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,X,W){let J=new Map;for(let Y of X){let H=Y0(Y.shape[$]);if(!H.length)throw new Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of H){if(J.has(G))throw new Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);J.set(G,Y)}}return new $1({typeName:V.ZodDiscriminatedUnion,discriminator:$,options:X,optionsMap:J,...N(W)})}}function C1($,X){let W=Q0($),J=Q0(X);if($===X)return{valid:!0,data:$};else if(W===z.object&&J===z.object){let Y=L.objectKeys(X),H=L.objectKeys($).filter((D)=>Y.indexOf(D)!==-1),G={...$,...X};for(let D of H){let w=C1($[D],X[D]);if(!w.valid)return{valid:!1};G[D]=w.data}return{valid:!0,data:G}}else if(W===z.array&&J===z.array){if($.length!==X.length)return{valid:!1};let Y=[];for(let H=0;H<$.length;H++){let G=$[H],D=X[H],w=C1(G,D);if(!w.valid)return{valid:!1};Y.push(w.data)}return{valid:!0,data:Y}}else if(W===z.date&&J===z.date&&+$===+X)return{valid:!0,data:$};else return{valid:!1}}class I0 extends q{_parse($){let{status:X,ctx:W}=this._processInputParams($),J=(Y,H)=>{if(b1(Y)||b1(H))return K;let G=C1(Y.value,H.value);if(!G.valid)return O(W,{code:M.invalid_intersection_types}),K;if(f1(Y)||f1(H))X.dirty();return{status:X.value,value:G.data}};if(W.common.async)return Promise.all([this._def.left._parseAsync({data:W.data,path:W.path,parent:W}),this._def.right._parseAsync({data:W.data,path:W.path,parent:W})]).then(([Y,H])=>J(Y,H));else return J(this._def.left._parseSync({data:W.data,path:W.path,parent:W}),this._def.right._parseSync({data:W.data,path:W.path,parent:W}))}}I0.create=($,X,W)=>{return new I0({left:$,right:X,typeName:V.ZodIntersection,...N(W)})};class W0 extends q{_parse($){let{status:X,ctx:W}=this._processInputParams($);if(W.parsedType!==z.array)return O(W,{code:M.invalid_type,expected:z.array,received:W.parsedType}),K;if(W.data.length<this._def.items.length)return O(W,{code:M.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;if(!this._def.rest&&W.data.length>this._def.items.length)O(W,{code:M.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X.dirty();let Y=[...W.data].map((H,G)=>{let D=this._def.items[G]||this._def.rest;if(!D)return null;return D._parse(new o(W,H,W.path,G))}).filter((H)=>!!H);if(W.common.async)return Promise.all(Y).then((H)=>{return T.mergeArray(X,H)});else return T.mergeArray(X,Y)}get items(){return this._def.items}rest($){return new W0({...this._def,rest:$})}}W0.create=($,X)=>{if(!Array.isArray($))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new W0({items:$,typeName:V.ZodTuple,rest:null,...N(X)})};class u0 extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:X,ctx:W}=this._processInputParams($);if(W.parsedType!==z.object)return O(W,{code:M.invalid_type,expected:z.object,received:W.parsedType}),K;let J=[],Y=this._def.keyType,H=this._def.valueType;for(let G in W.data)J.push({key:Y._parse(new o(W,G,W.path,G)),value:H._parse(new o(W,W.data[G],W.path,G)),alwaysSet:G in W.data});if(W.common.async)return T.mergeObjectAsync(X,J);else return T.mergeObjectSync(X,J)}get element(){return this._def.valueType}static create($,X,W){if(X instanceof q)return new u0({keyType:$,valueType:X,typeName:V.ZodRecord,...N(W)});return new u0({keyType:i.create(),valueType:$,typeName:V.ZodRecord,...N(X)})}}class c0 extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:X,ctx:W}=this._processInputParams($);if(W.parsedType!==z.map)return O(W,{code:M.invalid_type,expected:z.map,received:W.parsedType}),K;let J=this._def.keyType,Y=this._def.valueType,H=[...W.data.entries()].map(([G,D],w)=>{return{key:J._parse(new o(W,G,W.path,[w,"key"])),value:Y._parse(new o(W,D,W.path,[w,"value"]))}});if(W.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let D of H){let w=await D.key,B=await D.value;if(w.status==="aborted"||B.status==="aborted")return K;if(w.status==="dirty"||B.status==="dirty")X.dirty();G.set(w.value,B.value)}return{status:X.value,value:G}})}else{let G=new Map;for(let D of H){let{key:w,value:B}=D;if(w.status==="aborted"||B.status==="aborted")return K;if(w.status==="dirty"||B.status==="dirty")X.dirty();G.set(w.value,B.value)}return{status:X.value,value:G}}}}c0.create=($,X,W)=>{return new c0({valueType:X,keyType:$,typeName:V.ZodMap,...N(W)})};class U0 extends q{_parse($){let{status:X,ctx:W}=this._processInputParams($);if(W.parsedType!==z.set)return O(W,{code:M.invalid_type,expected:z.set,received:W.parsedType}),K;let J=this._def;if(J.minSize!==null){if(W.data.size<J.minSize.value)O(W,{code:M.too_small,minimum:J.minSize.value,type:"set",inclusive:!0,exact:!1,message:J.minSize.message}),X.dirty()}if(J.maxSize!==null){if(W.data.size>J.maxSize.value)O(W,{code:M.too_big,maximum:J.maxSize.value,type:"set",inclusive:!0,exact:!1,message:J.maxSize.message}),X.dirty()}let Y=this._def.valueType;function H(D){let w=new Set;for(let B of D){if(B.status==="aborted")return K;if(B.status==="dirty")X.dirty();w.add(B.value)}return{status:X.value,value:w}}let G=[...W.data.values()].map((D,w)=>Y._parse(new o(W,D,W.path,w)));if(W.common.async)return Promise.all(G).then((D)=>H(D));else return H(G)}min($,X){return new U0({...this._def,minSize:{value:$,message:A.toString(X)}})}max($,X){return new U0({...this._def,maxSize:{value:$,message:A.toString(X)}})}size($,X){return this.min($,X).max($,X)}nonempty($){return this.min(1,$)}}U0.create=($,X)=>{return new U0({valueType:$,minSize:null,maxSize:null,typeName:V.ZodSet,...N(X)})};class R0 extends q{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==z.function)return O(X,{code:M.invalid_type,expected:z.function,received:X.parsedType}),K;function W(G,D){return s0({data:G,path:X.path,errorMaps:[X.common.contextualErrorMap,X.schemaErrorMap,t0(),_0].filter((w)=>!!w),issueData:{code:M.invalid_arguments,argumentsError:D}})}function J(G,D){return s0({data:G,path:X.path,errorMaps:[X.common.contextualErrorMap,X.schemaErrorMap,t0(),_0].filter((w)=>!!w),issueData:{code:M.invalid_return_type,returnTypeError:D}})}let Y={errorMap:X.common.contextualErrorMap},H=X.data;if(this._def.returns instanceof F0){let G=this;return h(async function(...D){let w=new n([]),B=await G._def.args.parseAsync(D,Y).catch((C)=>{throw w.addIssue(W(D,C)),w}),j=await Reflect.apply(H,this,B);return await G._def.returns._def.type.parseAsync(j,Y).catch((C)=>{throw w.addIssue(J(j,C)),w})})}else{let G=this;return h(function(...D){let w=G._def.args.safeParse(D,Y);if(!w.success)throw new n([W(D,w.error)]);let B=Reflect.apply(H,this,w.data),j=G._def.returns.safeParse(B,Y);if(!j.success)throw new n([J(B,j.error)]);return j.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new R0({...this._def,args:W0.create($).rest(B0.create())})}returns($){return new R0({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,X,W){return new R0({args:$?$:W0.create([]).rest(B0.create()),returns:X||B0.create(),typeName:V.ZodFunction,...N(W)})}}class v0 extends q{get schema(){return this._def.getter()}_parse($){let{ctx:X}=this._processInputParams($);return this._def.getter()._parse({data:X.data,path:X.path,parent:X})}}v0.create=($,X)=>{return new v0({getter:$,typeName:V.ZodLazy,...N(X)})};class P0 extends q{_parse($){if($.data!==this._def.value){let X=this._getOrReturnCtx($);return O(X,{received:X.data,code:M.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:$.data}}get value(){return this._def.value}}P0.create=($,X)=>{return new P0({value:$,typeName:V.ZodLiteral,...N(X)})};function D2($,X){return new j0({values:$,typeName:V.ZodEnum,...N(X)})}class j0 extends q{constructor(){super(...arguments);y0.set(this,void 0)}_parse($){if(typeof $.data!=="string"){let X=this._getOrReturnCtx($),W=this._def.values;return O(X,{expected:L.joinValues(W),received:X.parsedType,code:M.invalid_type}),K}if(!e0(this,y0,"f"))Q2(this,y0,new Set(this._def.values),"f");if(!e0(this,y0,"f").has($.data)){let X=this._getOrReturnCtx($),W=this._def.values;return O(X,{received:X.data,code:M.invalid_enum_value,options:W}),K}return h($.data)}get options(){return this._def.values}get enum(){let $={};for(let X of this._def.values)$[X]=X;return $}get Values(){let $={};for(let X of this._def.values)$[X]=X;return $}get Enum(){let $={};for(let X of this._def.values)$[X]=X;return $}extract($,X=this._def){return j0.create($,{...this._def,...X})}exclude($,X=this._def){return j0.create(this.options.filter((W)=>!$.includes(W)),{...this._def,...X})}}y0=new WeakMap;j0.create=D2;class k0 extends q{constructor(){super(...arguments);Z0.set(this,void 0)}_parse($){let X=L.getValidEnumValues(this._def.values),W=this._getOrReturnCtx($);if(W.parsedType!==z.string&&W.parsedType!==z.number){let J=L.objectValues(X);return O(W,{expected:L.joinValues(J),received:W.parsedType,code:M.invalid_type}),K}if(!e0(this,Z0,"f"))Q2(this,Z0,new Set(L.getValidEnumValues(this._def.values)),"f");if(!e0(this,Z0,"f").has($.data)){let J=L.objectValues(X);return O(W,{received:W.data,code:M.invalid_enum_value,options:J}),K}return h($.data)}get enum(){return this._def.values}}Z0=new WeakMap;k0.create=($,X)=>{return new k0({values:$,typeName:V.ZodNativeEnum,...N(X)})};class F0 extends q{unwrap(){return this._def.type}_parse($){let{ctx:X}=this._processInputParams($);if(X.parsedType!==z.promise&&X.common.async===!1)return O(X,{code:M.invalid_type,expected:z.promise,received:X.parsedType}),K;let W=X.parsedType===z.promise?X.data:Promise.resolve(X.data);return h(W.then((J)=>{return this._def.type.parseAsync(J,{path:X.path,errorMap:X.common.contextualErrorMap})}))}}F0.create=($,X)=>{return new F0({type:$,typeName:V.ZodPromise,...N(X)})};class p extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:X,ctx:W}=this._processInputParams($),J=this._def.effect||null,Y={addIssue:(H)=>{if(O(W,H),H.fatal)X.abort();else X.dirty()},get path(){return W.path}};if(Y.addIssue=Y.addIssue.bind(Y),J.type==="preprocess"){let H=J.transform(W.data,Y);if(W.common.async)return Promise.resolve(H).then(async(G)=>{if(X.value==="aborted")return K;let D=await this._def.schema._parseAsync({data:G,path:W.path,parent:W});if(D.status==="aborted")return K;if(D.status==="dirty")return L0(D.value);if(X.value==="dirty")return L0(D.value);return D});else{if(X.value==="aborted")return K;let G=this._def.schema._parseSync({data:H,path:W.path,parent:W});if(G.status==="aborted")return K;if(G.status==="dirty")return L0(G.value);if(X.value==="dirty")return L0(G.value);return G}}if(J.type==="refinement"){let H=(G)=>{let D=J.refinement(G,Y);if(W.common.async)return Promise.resolve(D);if(D instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(W.common.async===!1){let G=this._def.schema._parseSync({data:W.data,path:W.path,parent:W});if(G.status==="aborted")return K;if(G.status==="dirty")X.dirty();return H(G.value),{status:X.value,value:G.value}}else return this._def.schema._parseAsync({data:W.data,path:W.path,parent:W}).then((G)=>{if(G.status==="aborted")return K;if(G.status==="dirty")X.dirty();return H(G.value).then(()=>{return{status:X.value,value:G.value}})})}if(J.type==="transform")if(W.common.async===!1){let H=this._def.schema._parseSync({data:W.data,path:W.path,parent:W});if(!O0(H))return H;let G=J.transform(H.value,Y);if(G instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:X.value,value:G}}else return this._def.schema._parseAsync({data:W.data,path:W.path,parent:W}).then((H)=>{if(!O0(H))return H;return Promise.resolve(J.transform(H.value,Y)).then((G)=>({status:X.value,value:G}))});L.assertNever(J)}}p.create=($,X,W)=>{return new p({schema:$,typeName:V.ZodEffects,effect:X,...N(W)})};p.createWithPreprocess=($,X,W)=>{return new p({schema:X,effect:{type:"preprocess",transform:$},typeName:V.ZodEffects,...N(W)})};class u extends q{_parse($){if(this._getType($)===z.undefined)return h(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}u.create=($,X)=>{return new u({innerType:$,typeName:V.ZodOptional,...N(X)})};class H0 extends q{_parse($){if(this._getType($)===z.null)return h(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}H0.create=($,X)=>{return new H0({innerType:$,typeName:V.ZodNullable,...N(X)})};class T0 extends q{_parse($){let{ctx:X}=this._processInputParams($),W=X.data;if(X.parsedType===z.undefined)W=this._def.defaultValue();return this._def.innerType._parse({data:W,path:X.path,parent:X})}removeDefault(){return this._def.innerType}}T0.create=($,X)=>{return new T0({innerType:$,typeName:V.ZodDefault,defaultValue:typeof X.default==="function"?X.default:()=>X.default,...N(X)})};class x0 extends q{_parse($){let{ctx:X}=this._processInputParams($),W={...X,common:{...X.common,issues:[]}},J=this._def.innerType._parse({data:W.data,path:W.path,parent:{...W}});if(m0(J))return J.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new n(W.common.issues)},input:W.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new n(W.common.issues)},input:W.data})}}removeCatch(){return this._def.innerType}}x0.create=($,X)=>{return new x0({innerType:$,typeName:V.ZodCatch,catchValue:typeof X.catch==="function"?X.catch:()=>X.catch,...N(X)})};class p0 extends q{_parse($){if(this._getType($)!==z.nan){let W=this._getOrReturnCtx($);return O(W,{code:M.invalid_type,expected:z.nan,received:W.parsedType}),K}return{status:"valid",value:$.data}}}p0.create=($)=>{return new p0({typeName:V.ZodNaN,...N($)})};var G3=Symbol("zod_brand");class X1 extends q{_parse($){let{ctx:X}=this._processInputParams($),W=X.data;return this._def.type._parse({data:W,path:X.path,parent:X})}unwrap(){return this._def.type}}class i0 extends q{_parse($){let{status:X,ctx:W}=this._processInputParams($);if(W.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:W.data,path:W.path,parent:W});if(Y.status==="aborted")return K;if(Y.status==="dirty")return X.dirty(),L0(Y.value);else return this._def.out._parseAsync({data:Y.value,path:W.path,parent:W})})();else{let J=this._def.in._parseSync({data:W.data,path:W.path,parent:W});if(J.status==="aborted")return K;if(J.status==="dirty")return X.dirty(),{status:"dirty",value:J.value};else return this._def.out._parseSync({data:J.value,path:W.path,parent:W})}}static create($,X){return new i0({in:$,out:X,typeName:V.ZodPipeline})}}class h0 extends q{_parse($){let X=this._def.innerType._parse($),W=(J)=>{if(O0(J))J.value=Object.freeze(J.value);return J};return m0(X)?X.then((J)=>W(J)):W(X)}unwrap(){return this._def.innerType}}h0.create=($,X)=>{return new h0({innerType:$,typeName:V.ZodReadonly,...N(X)})};function W2($,X){let W=typeof $==="function"?$(X):typeof $==="string"?{message:$}:$;return typeof W==="string"?{message:W}:W}function B2($,X={},W){if($)return A0.create().superRefine((J,Y)=>{var H,G;let D=$(J);if(D instanceof Promise)return D.then((w)=>{var B,j;if(!w){let R=W2(X,J),C=(j=(B=R.fatal)!==null&&B!==void 0?B:W)!==null&&j!==void 0?j:!0;Y.addIssue({code:"custom",...R,fatal:C})}});if(!D){let w=W2(X,J),B=(G=(H=w.fatal)!==null&&H!==void 0?H:W)!==null&&G!==void 0?G:!0;Y.addIssue({code:"custom",...w,fatal:B})}return});return A0.create()}var w3={object:v.lazycreate},V;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(V||(V={}));var D3=($,X={message:`Input not instance of ${$.name}`})=>B2((W)=>W instanceof $,X),M2=i.create,V2=M0.create,B3=p0.create,M3=V0.create,j2=E0.create,V3=z0.create,j3=l0.create,O3=b0.create,z3=f0.create,A3=A0.create,U3=B0.create,F3=X0.create,K3=n0.create,q3=d.create,N3=v.create,S3=v.strictCreate,L3=C0.create,R3=$1.create,_3=I0.create,E3=W0.create,b3=u0.create,f3=c0.create,C3=U0.create,I3=R0.create,v3=v0.create,P3=P0.create,k3=j0.create,T3=k0.create,x3=F0.create,J2=p.create,h3=u.create,g3=H0.create,y3=p.createWithPreprocess,Z3=i0.create,m3=()=>M2().optional(),l3=()=>V2().optional(),n3=()=>j2().optional(),u3={string:($)=>i.create({...$,coerce:!0}),number:($)=>M0.create({...$,coerce:!0}),boolean:($)=>E0.create({...$,coerce:!0}),bigint:($)=>V0.create({...$,coerce:!0}),date:($)=>z0.create({...$,coerce:!0})},c3=K,Q=Object.freeze({__proto__:null,defaultErrorMap:_0,setErrorMap:y4,getErrorMap:t0,makeIssue:s0,EMPTY_PATH:Z4,addIssueToContext:O,ParseStatus:T,INVALID:K,DIRTY:L0,OK:h,isAborted:b1,isDirty:f1,isValid:O0,isAsync:m0,get util(){return L},get objectUtil(){return E1},ZodParsedType:z,getParsedType:Q0,ZodType:q,datetimeRegex:w2,ZodString:i,ZodNumber:M0,ZodBigInt:V0,ZodBoolean:E0,ZodDate:z0,ZodSymbol:l0,ZodUndefined:b0,ZodNull:f0,ZodAny:A0,ZodUnknown:B0,ZodNever:X0,ZodVoid:n0,ZodArray:d,ZodObject:v,ZodUnion:C0,ZodDiscriminatedUnion:$1,ZodIntersection:I0,ZodTuple:W0,ZodRecord:u0,ZodMap:c0,ZodSet:U0,ZodFunction:R0,ZodLazy:v0,ZodLiteral:P0,ZodEnum:j0,ZodNativeEnum:k0,ZodPromise:F0,ZodEffects:p,ZodTransformer:p,ZodOptional:u,ZodNullable:H0,ZodDefault:T0,ZodCatch:x0,ZodNaN:p0,BRAND:G3,ZodBranded:X1,ZodPipeline:i0,ZodReadonly:h0,custom:B2,Schema:q,ZodSchema:q,late:w3,get ZodFirstPartyTypeKind(){return V},coerce:u3,any:A3,array:q3,bigint:M3,boolean:j2,date:V3,discriminatedUnion:R3,effect:J2,enum:k3,function:I3,instanceof:D3,intersection:_3,lazy:v3,literal:P3,map:f3,nan:B3,nativeEnum:T3,never:F3,null:z3,nullable:g3,number:V2,object:N3,oboolean:n3,onumber:l3,optional:h3,ostring:m3,pipeline:Z3,preprocess:y3,promise:x3,record:b3,set:C3,strictObject:S3,string:M2,symbol:j3,transformer:J2,tuple:E3,undefined:O3,union:L3,unknown:U3,void:K3,NEVER:c3,ZodIssueCode:M,quotelessJson:g4,ZodError:n});var I1="2024-11-05",O2=[I1,"2024-10-07"],W1="2.0",z2=Q.union([Q.string(),Q.number().int()]),A2=Q.string(),r=Q.object({_meta:Q.optional(Q.object({progressToken:Q.optional(z2)}).passthrough())}).passthrough(),c=Q.object({method:Q.string(),params:Q.optional(r)}),d0=Q.object({_meta:Q.optional(Q.object({}).passthrough())}).passthrough(),J0=Q.object({method:Q.string(),params:Q.optional(d0)}),a=Q.object({_meta:Q.optional(Q.object({}).passthrough())}).passthrough(),J1=Q.union([Q.string(),Q.number().int()]),p3=Q.object({jsonrpc:Q.literal(W1),id:J1}).merge(c).strict(),i3=Q.object({jsonrpc:Q.literal(W1)}).merge(J0).strict(),d3=Q.object({jsonrpc:Q.literal(W1),id:J1,result:a}).strict(),k;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError"})(k||(k={}));var o3=Q.object({jsonrpc:Q.literal(W1),id:J1,error:Q.object({code:Q.number().int(),message:Q.string(),data:Q.optional(Q.unknown())})}).strict(),U2=Q.union([p3,i3,d3,o3]),Y1=a.strict(),Q1=J0.extend({method:Q.literal("notifications/cancelled"),params:d0.extend({requestId:J1,reason:Q.string().optional()})}),F2=Q.object({name:Q.string(),version:Q.string()}).passthrough(),r3=Q.object({experimental:Q.optional(Q.object({}).passthrough()),sampling:Q.optional(Q.object({}).passthrough()),roots:Q.optional(Q.object({listChanged:Q.optional(Q.boolean())}).passthrough())}).passthrough(),v1=c.extend({method:Q.literal("initialize"),params:r.extend({protocolVersion:Q.string(),capabilities:r3,clientInfo:F2})}),a3=Q.object({experimental:Q.optional(Q.object({}).passthrough()),logging:Q.optional(Q.object({}).passthrough()),prompts:Q.optional(Q.object({listChanged:Q.optional(Q.boolean())}).passthrough()),resources:Q.optional(Q.object({subscribe:Q.optional(Q.boolean()),listChanged:Q.optional(Q.boolean())}).passthrough()),tools:Q.optional(Q.object({listChanged:Q.optional(Q.boolean())}).passthrough())}).passthrough(),t3=a.extend({protocolVersion:Q.string(),capabilities:a3,serverInfo:F2,instructions:Q.optional(Q.string())}),P1=J0.extend({method:Q.literal("notifications/initialized")}),H1=c.extend({method:Q.literal("ping")}),s3=Q.object({progress:Q.number(),total:Q.optional(Q.number())}).passthrough(),G1=J0.extend({method:Q.literal("notifications/progress"),params:d0.merge(s3).extend({progressToken:z2})}),w1=c.extend({params:r.extend({cursor:Q.optional(A2)}).optional()}),D1=a.extend({nextCursor:Q.optional(A2)}),K2=Q.object({uri:Q.string(),mimeType:Q.optional(Q.string())}).passthrough(),q2=K2.extend({text:Q.string()}),N2=K2.extend({blob:Q.string().base64()}),e3=Q.object({uri:Q.string(),name:Q.string(),description:Q.optional(Q.string()),mimeType:Q.optional(Q.string())}).passthrough(),$6=Q.object({uriTemplate:Q.string(),name:Q.string(),description:Q.optional(Q.string()),mimeType:Q.optional(Q.string())}).passthrough(),B1=w1.extend({method:Q.literal("resources/list")}),X6=D1.extend({resources:Q.array(e3)}),M1=w1.extend({method:Q.literal("resources/templates/list")}),W6=D1.extend({resourceTemplates:Q.array($6)}),V1=c.extend({method:Q.literal("resources/read"),params:r.extend({uri:Q.string()})}),J6=a.extend({contents:Q.array(Q.union([q2,N2]))}),Y6=J0.extend({method:Q.literal("notifications/resources/list_changed")}),Q6=c.extend({method:Q.literal("resources/subscribe"),params:r.extend({uri:Q.string()})}),H6=c.extend({method:Q.literal("resources/unsubscribe"),params:r.extend({uri:Q.string()})}),G6=J0.extend({method:Q.literal("notifications/resources/updated"),params:d0.extend({uri:Q.string()})}),w6=Q.object({name:Q.string(),description:Q.optional(Q.string()),required:Q.optional(Q.boolean())}).passthrough(),D6=Q.object({name:Q.string(),description:Q.optional(Q.string()),arguments:Q.optional(Q.array(w6))}).passthrough(),j1=w1.extend({method:Q.literal("prompts/list")}),B6=D1.extend({prompts:Q.array(D6)}),O1=c.extend({method:Q.literal("prompts/get"),params:r.extend({name:Q.string(),arguments:Q.optional(Q.record(Q.string()))})}),z1=Q.object({type:Q.literal("text"),text:Q.string()}).passthrough(),A1=Q.object({type:Q.literal("image"),data:Q.string().base64(),mimeType:Q.string()}).passthrough(),S2=Q.object({type:Q.literal("resource"),resource:Q.union([q2,N2])}).passthrough(),M6=Q.object({role:Q.enum(["user","assistant"]),content:Q.union([z1,A1,S2])}).passthrough(),V6=a.extend({description:Q.optional(Q.string()),messages:Q.array(M6)}),j6=J0.extend({method:Q.literal("notifications/prompts/list_changed")}),O6=Q.object({name:Q.string(),description:Q.optional(Q.string()),inputSchema:Q.object({type:Q.literal("object"),properties:Q.optional(Q.object({}).passthrough())}).passthrough()}).passthrough(),U1=w1.extend({method:Q.literal("tools/list")}),z6=D1.extend({tools:Q.array(O6)}),L2=a.extend({content:Q.array(Q.union([z1,A1,S2])),isError:Q.boolean().default(!1).optional()}),K$=L2.or(a.extend({toolResult:Q.unknown()})),F1=c.extend({method:Q.literal("tools/call"),params:r.extend({name:Q.string(),arguments:Q.optional(Q.record(Q.unknown()))})}),A6=J0.extend({method:Q.literal("notifications/tools/list_changed")}),R2=Q.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),U6=c.extend({method:Q.literal("logging/setLevel"),params:r.extend({level:R2})}),F6=J0.extend({method:Q.literal("notifications/message"),params:d0.extend({level:R2,logger:Q.optional(Q.string()),data:Q.unknown()})}),K6=Q.object({name:Q.string().optional()}).passthrough(),q6=Q.object({hints:Q.optional(Q.array(K6)),costPriority:Q.optional(Q.number().min(0).max(1)),speedPriority:Q.optional(Q.number().min(0).max(1)),intelligencePriority:Q.optional(Q.number().min(0).max(1))}).passthrough(),N6=Q.object({role:Q.enum(["user","assistant"]),content:Q.union([z1,A1])}).passthrough(),S6=c.extend({method:Q.literal("sampling/createMessage"),params:r.extend({messages:Q.array(N6),systemPrompt:Q.optional(Q.string()),includeContext:Q.optional(Q.enum(["none","thisServer","allServers"])),temperature:Q.optional(Q.number()),maxTokens:Q.number().int(),stopSequences:Q.optional(Q.array(Q.string())),metadata:Q.optional(Q.object({}).passthrough()),modelPreferences:Q.optional(q6)})}),k1=a.extend({model:Q.string(),stopReason:Q.optional(Q.enum(["endTurn","stopSequence","maxTokens"]).or(Q.string())),role:Q.enum(["user","assistant"]),content:Q.discriminatedUnion("type",[z1,A1])}),L6=Q.object({type:Q.literal("ref/resource"),uri:Q.string()}).passthrough(),R6=Q.object({type:Q.literal("ref/prompt"),name:Q.string()}).passthrough(),K1=c.extend({method:Q.literal("completion/complete"),params:r.extend({ref:Q.union([R6,L6]),argument:Q.object({name:Q.string(),value:Q.string()}).passthrough()})}),_6=a.extend({completion:Q.object({values:Q.array(Q.string()).max(100),total:Q.optional(Q.number().int()),hasMore:Q.optional(Q.boolean())}).passthrough()}),E6=Q.object({uri:Q.string().startsWith("file://"),name:Q.optional(Q.string())}).passthrough(),b6=c.extend({method:Q.literal("roots/list")}),T1=a.extend({roots:Q.array(E6)}),f6=J0.extend({method:Q.literal("notifications/roots/list_changed")}),q$=Q.union([H1,v1,K1,U6,O1,j1,B1,M1,V1,Q6,H6,F1,U1]),N$=Q.union([Q1,G1,P1,f6]),S$=Q.union([Y1,k1,T1]),L$=Q.union([H1,S6,b6]),R$=Q.union([Q1,G1,F6,G6,Y6,A6,j6]),_$=Q.union([Y1,t3,_6,V6,B6,X6,W6,J6,L2,z6]);class g extends Error{constructor($,X,W){super(`MCP error ${$}: ${X}`);this.code=$,this.data=W,this.name="McpError"}}var C6=60000;class x1{constructor($){this._options=$,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(Q1,(X)=>{let W=this._requestHandlerAbortControllers.get(X.params.requestId);W===null||W===void 0||W.abort(X.params.reason)}),this.setNotificationHandler(G1,(X)=>{this._onprogress(X)}),this.setRequestHandler(H1,(X)=>({}))}_setupTimeout($,X,W,J){this._timeoutInfo.set($,{timeoutId:setTimeout(J,X),startTime:Date.now(),timeout:X,maxTotalTimeout:W,onTimeout:J})}_resetTimeout($){let X=this._timeoutInfo.get($);if(!X)return!1;let W=Date.now()-X.startTime;if(X.maxTotalTimeout&&W>=X.maxTotalTimeout)throw this._timeoutInfo.delete($),new g(k.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:X.maxTotalTimeout,totalElapsed:W});return clearTimeout(X.timeoutId),X.timeoutId=setTimeout(X.onTimeout,X.timeout),!0}_cleanupTimeout($){let X=this._timeoutInfo.get($);if(X)clearTimeout(X.timeoutId),this._timeoutInfo.delete($)}async connect($){this._transport=$,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=(X)=>{this._onerror(X)},this._transport.onmessage=(X)=>{if(!("method"in X))this._onresponse(X);else if("id"in X)this._onrequest(X);else this._onnotification(X)},await this._transport.start()}_onclose(){var $;let X=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,($=this.onclose)===null||$===void 0||$.call(this);let W=new g(k.ConnectionClosed,"Connection closed");for(let J of X.values())J(W)}_onerror($){var X;(X=this.onerror)===null||X===void 0||X.call(this,$)}_onnotification($){var X;let W=(X=this._notificationHandlers.get($.method))!==null&&X!==void 0?X:this.fallbackNotificationHandler;if(W===void 0)return;Promise.resolve().then(()=>W($)).catch((J)=>this._onerror(new Error(`Uncaught error in notification handler: ${J}`)))}_onrequest($){var X,W,J;let Y=(X=this._requestHandlers.get($.method))!==null&&X!==void 0?X:this.fallbackRequestHandler;if(Y===void 0){(W=this._transport)===null||W===void 0||W.send({jsonrpc:"2.0",id:$.id,error:{code:k.MethodNotFound,message:"Method not found"}}).catch((D)=>this._onerror(new Error(`Failed to send an error response: ${D}`)));return}let H=new AbortController;this._requestHandlerAbortControllers.set($.id,H);let G={signal:H.signal,sessionId:(J=this._transport)===null||J===void 0?void 0:J.sessionId};Promise.resolve().then(()=>Y($,G)).then((D)=>{var w;if(H.signal.aborted)return;return(w=this._transport)===null||w===void 0?void 0:w.send({result:D,jsonrpc:"2.0",id:$.id})},(D)=>{var w,B;if(H.signal.aborted)return;return(w=this._transport)===null||w===void 0?void 0:w.send({jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(D.code)?D.code:k.InternalError,message:(B=D.message)!==null&&B!==void 0?B:"Internal error"}})}).catch((D)=>this._onerror(new Error(`Failed to send response: ${D}`))).finally(()=>{this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:X,...W}=$.params,J=Number(X),Y=this._progressHandlers.get(J);if(!Y){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let H=this._responseHandlers.get(J);if(this._timeoutInfo.has(J)&&H)try{this._resetTimeout(J)}catch(G){H(G);return}Y(W)}_onresponse($){let X=Number($.id),W=this._responseHandlers.get(X);if(W===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}if(this._responseHandlers.delete(X),this._progressHandlers.delete(X),this._cleanupTimeout(X),"result"in $)W($);else{let J=new g($.error.code,$.error.message,$.error.data);W(J)}}get transport(){return this._transport}async close(){var $;await(($=this._transport)===null||$===void 0?void 0:$.close())}request($,X,W){return new Promise((J,Y)=>{var H,G,D,w;if(!this._transport){Y(new Error("Not connected"));return}if(((H=this._options)===null||H===void 0?void 0:H.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod($.method);(G=W===null||W===void 0?void 0:W.signal)===null||G===void 0||G.throwIfAborted();let B=this._requestMessageId++,j={...$,jsonrpc:"2.0",id:B};if(W===null||W===void 0?void 0:W.onprogress)this._progressHandlers.set(B,W.onprogress),j.params={...$.params,_meta:{progressToken:B}};let R=(Z)=>{var e;this._responseHandlers.delete(B),this._progressHandlers.delete(B),this._cleanupTimeout(B),(e=this._transport)===null||e===void 0||e.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:B,reason:String(Z)}}).catch((m)=>this._onerror(new Error(`Failed to send cancellation: ${m}`))),Y(Z)};this._responseHandlers.set(B,(Z)=>{var e;if((e=W===null||W===void 0?void 0:W.signal)===null||e===void 0?void 0:e.aborted)return;if(Z instanceof Error)return Y(Z);try{let m=X.parse(Z.result);J(m)}catch(m){Y(m)}}),(D=W===null||W===void 0?void 0:W.signal)===null||D===void 0||D.addEventListener("abort",()=>{var Z;R((Z=W===null||W===void 0?void 0:W.signal)===null||Z===void 0?void 0:Z.reason)});let C=(w=W===null||W===void 0?void 0:W.timeout)!==null&&w!==void 0?w:C6,q0=()=>R(new g(k.RequestTimeout,"Request timed out",{timeout:C}));this._setupTimeout(B,C,W===null||W===void 0?void 0:W.maxTotalTimeout,q0),this._transport.send(j).catch((Z)=>{this._cleanupTimeout(B),Y(Z)})})}async notification($){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability($.method);let X={...$,jsonrpc:"2.0"};await this._transport.send(X)}setRequestHandler($,X){let W=$.shape.method.value;this.assertRequestHandlerCapability(W),this._requestHandlers.set(W,(J,Y)=>Promise.resolve(X($.parse(J),Y)))}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw new Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,X){this._notificationHandlers.set($.shape.method.value,(W)=>Promise.resolve(X($.parse(W))))}removeNotificationHandler($){this._notificationHandlers.delete($)}}function _2($,X){return Object.entries(X).reduce((W,[J,Y])=>{if(Y&&typeof Y==="object")W[J]=W[J]?{...W[J],...Y}:Y;else W[J]=Y;return W},{...$})}class h1 extends x1{constructor($,X){var W;super(X);this._serverInfo=$,this._capabilities=(W=X===null||X===void 0?void 0:X.capabilities)!==null&&W!==void 0?W:{},this._instructions=X===null||X===void 0?void 0:X.instructions,this.setRequestHandler(v1,(J)=>this._oninitialize(J)),this.setNotificationHandler(P1,()=>{var J;return(J=this.oninitialized)===null||J===void 0?void 0:J.call(this)})}registerCapabilities($){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=_2(this._capabilities,$)}assertCapabilityForMethod($){var X,W;switch($){case"sampling/createMessage":if(!((X=this._clientCapabilities)===null||X===void 0?void 0:X.sampling))throw new Error(`Client does not support sampling (required for ${$})`);break;case"roots/list":if(!((W=this._clientCapabilities)===null||W===void 0?void 0:W.roots))throw new Error(`Client does not support listing roots (required for ${$})`);break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${$})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${$})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${$})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${$})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){switch($){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${$})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${$})`);break;case"ping":case"initialize":break}}async _oninitialize($){let X=$.params.protocolVersion;return this._clientCapabilities=$.params.capabilities,this._clientVersion=$.params.clientInfo,{protocolVersion:O2.includes(X)?X:I1,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Y1)}async createMessage($,X){return this.request({method:"sampling/createMessage",params:$},k1,X)}async listRoots($,X){return this.request({method:"roots/list",params:$},T1,X)}async sendLoggingMessage($){return this.notification({method:"notifications/message",params:$})}async sendResourceUpdated($){return this.notification({method:"notifications/resources/updated",params:$})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var b2=Symbol("Let zodToJsonSchema decide on which parser to use");var E2={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},f2=($)=>typeof $==="string"?{...E2,name:$}:{...E2,...$};var C2=($)=>{let X=f2($),W=X.name!==void 0?[...X.basePath,X.definitionPath,X.name]:X.basePath;return{...X,currentPath:W,propertyPath:void 0,seen:new Map(Object.entries(X.definitions).map(([J,Y])=>[Y._def,{def:Y._def,path:[...X.basePath,X.definitionPath,J],jsonSchema:void 0}]))}};function g1($,X,W,J){if(!J?.errorMessages)return;if(W)$.errorMessage={...$.errorMessage,[X]:W}}function S($,X,W,J,Y){$[X]=W,g1($,X,J,Y)}function I2(){return{}}function v2($,X){let W={type:"array"};if($.type?._def&&$.type?._def?.typeName!==V.ZodAny)W.items=F($.type._def,{...X,currentPath:[...X.currentPath,"items"]});if($.minLength)S(W,"minItems",$.minLength.value,$.minLength.message,X);if($.maxLength)S(W,"maxItems",$.maxLength.value,$.maxLength.message,X);if($.exactLength)S(W,"minItems",$.exactLength.value,$.exactLength.message,X),S(W,"maxItems",$.exactLength.value,$.exactLength.message,X);return W}function P2($,X){let W={type:"integer",format:"int64"};if(!$.checks)return W;for(let J of $.checks)switch(J.kind){case"min":if(X.target==="jsonSchema7")if(J.inclusive)S(W,"minimum",J.value,J.message,X);else S(W,"exclusiveMinimum",J.value,J.message,X);else{if(!J.inclusive)W.exclusiveMinimum=!0;S(W,"minimum",J.value,J.message,X)}break;case"max":if(X.target==="jsonSchema7")if(J.inclusive)S(W,"maximum",J.value,J.message,X);else S(W,"exclusiveMaximum",J.value,J.message,X);else{if(!J.inclusive)W.exclusiveMaximum=!0;S(W,"maximum",J.value,J.message,X)}break;case"multipleOf":S(W,"multipleOf",J.value,J.message,X);break}return W}function k2(){return{type:"boolean"}}function q1($,X){return F($.type._def,X)}var T2=($,X)=>{return F($.innerType._def,X)};function y1($,X,W){let J=W??X.dateStrategy;if(Array.isArray(J))return{anyOf:J.map((Y,H)=>y1($,X,Y))};switch(J){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return I6($,X)}}var I6=($,X)=>{let W={type:"integer",format:"unix-time"};if(X.target==="openApi3")return W;for(let J of $.checks)switch(J.kind){case"min":S(W,"minimum",J.value,J.message,X);break;case"max":S(W,"maximum",J.value,J.message,X);break}return W};function x2($,X){return{...F($.innerType._def,X),default:$.defaultValue()}}function h2($,X){return X.effectStrategy==="input"?F($.schema._def,X):{}}function g2($){return{type:"string",enum:Array.from($.values)}}var v6=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function y2($,X){let W=[F($.left._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),F($.right._def,{...X,currentPath:[...X.currentPath,"allOf","1"]})].filter((H)=>!!H),J=X.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return W.forEach((H)=>{if(v6(H)){if(Y.push(...H.allOf),H.unevaluatedProperties===void 0)J=void 0}else{let G=H;if("additionalProperties"in H&&H.additionalProperties===!1){let{additionalProperties:D,...w}=H;G=w}else J=void 0;Y.push(G)}}),Y.length?{allOf:Y,...J}:void 0}function Z2($,X){let W=typeof $.value;if(W!=="bigint"&&W!=="number"&&W!=="boolean"&&W!=="string")return{type:Array.isArray($.value)?"array":"object"};if(X.target==="openApi3")return{type:W==="bigint"?"integer":W,enum:[$.value]};return{type:W==="bigint"?"integer":W,const:$.value}}var Z1=void 0,t={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Z1===void 0)Z1=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Z1},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function N1($,X){let W={type:"string"};if($.checks)for(let J of $.checks)switch(J.kind){case"min":S(W,"minLength",typeof W.minLength==="number"?Math.max(W.minLength,J.value):J.value,J.message,X);break;case"max":S(W,"maxLength",typeof W.maxLength==="number"?Math.min(W.maxLength,J.value):J.value,J.message,X);break;case"email":switch(X.emailStrategy){case"format:email":s(W,"email",J.message,X);break;case"format:idn-email":s(W,"idn-email",J.message,X);break;case"pattern:zod":y(W,t.email,J.message,X);break}break;case"url":s(W,"uri",J.message,X);break;case"uuid":s(W,"uuid",J.message,X);break;case"regex":y(W,J.regex,J.message,X);break;case"cuid":y(W,t.cuid,J.message,X);break;case"cuid2":y(W,t.cuid2,J.message,X);break;case"startsWith":y(W,RegExp(`^${m1(J.value,X)}`),J.message,X);break;case"endsWith":y(W,RegExp(`${m1(J.value,X)}$`),J.message,X);break;case"datetime":s(W,"date-time",J.message,X);break;case"date":s(W,"date",J.message,X);break;case"time":s(W,"time",J.message,X);break;case"duration":s(W,"duration",J.message,X);break;case"length":S(W,"minLength",typeof W.minLength==="number"?Math.max(W.minLength,J.value):J.value,J.message,X),S(W,"maxLength",typeof W.maxLength==="number"?Math.min(W.maxLength,J.value):J.value,J.message,X);break;case"includes":{y(W,RegExp(m1(J.value,X)),J.message,X);break}case"ip":{if(J.version!=="v6")s(W,"ipv4",J.message,X);if(J.version!=="v4")s(W,"ipv6",J.message,X);break}case"base64url":y(W,t.base64url,J.message,X);break;case"jwt":y(W,t.jwt,J.message,X);break;case"cidr":{if(J.version!=="v6")y(W,t.ipv4Cidr,J.message,X);if(J.version!=="v4")y(W,t.ipv6Cidr,J.message,X);break}case"emoji":y(W,t.emoji(),J.message,X);break;case"ulid":{y(W,t.ulid,J.message,X);break}case"base64":{switch(X.base64Strategy){case"format:binary":{s(W,"binary",J.message,X);break}case"contentEncoding:base64":{S(W,"contentEncoding","base64",J.message,X);break}case"pattern:zod":{y(W,t.base64,J.message,X);break}}break}case"nanoid":y(W,t.nanoid,J.message,X);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(J)}return W}function m1($,X){return X.patternStrategy==="escape"?k6($):$}var P6=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function k6($){let X="";for(let W=0;W<$.length;W++){if(!P6.has($[W]))X+="\\";X+=$[W]}return X}function s($,X,W,J){if($.format||$.anyOf?.some((Y)=>Y.format)){if(!$.anyOf)$.anyOf=[];if($.format){if($.anyOf.push({format:$.format,...$.errorMessage&&J.errorMessages&&{errorMessage:{format:$.errorMessage.format}}}),delete $.format,$.errorMessage){if(delete $.errorMessage.format,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.anyOf.push({format:X,...W&&J.errorMessages&&{errorMessage:{format:W}}})}else S($,"format",X,W,J)}function y($,X,W,J){if($.pattern||$.allOf?.some((Y)=>Y.pattern)){if(!$.allOf)$.allOf=[];if($.pattern){if($.allOf.push({pattern:$.pattern,...$.errorMessage&&J.errorMessages&&{errorMessage:{pattern:$.errorMessage.pattern}}}),delete $.pattern,$.errorMessage){if(delete $.errorMessage.pattern,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.allOf.push({pattern:m2(X,J),...W&&J.errorMessages&&{errorMessage:{pattern:W}}})}else S($,"pattern",m2(X,J),W,J)}function m2($,X){if(!X.applyRegexFlags||!$.flags)return $.source;let W={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},J=W.i?$.source.toLowerCase():$.source,Y="",H=!1,G=!1,D=!1;for(let w=0;w<J.length;w++){if(H){Y+=J[w],H=!1;continue}if(W.i){if(G){if(J[w].match(/[a-z]/)){if(D)Y+=J[w],Y+=`${J[w-2]}-${J[w]}`.toUpperCase(),D=!1;else if(J[w+1]==="-"&&J[w+2]?.match(/[a-z]/))Y+=J[w],D=!0;else Y+=`${J[w]}${J[w].toUpperCase()}`;continue}}else if(J[w].match(/[a-z]/)){Y+=`[${J[w]}${J[w].toUpperCase()}]`;continue}}if(W.m){if(J[w]==="^"){Y+=`(^|(?<=[\r
5
+ ]))`;continue}else if(J[w]==="$"){Y+=`($|(?=[\r
6
+ ]))`;continue}}if(W.s&&J[w]==="."){Y+=G?`${J[w]}\r
7
+ `:`[${J[w]}\r
8
+ ]`;continue}if(Y+=J[w],J[w]==="\\")H=!0;else if(G&&J[w]==="]")G=!1;else if(!G&&J[w]==="[")G=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${X.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return Y}function S1($,X){if(X.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(X.target==="openApi3"&&$.keyType?._def.typeName===V.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((J,Y)=>({...J,[Y]:F($.valueType._def,{...X,currentPath:[...X.currentPath,"properties",Y]})??{}}),{}),additionalProperties:X.rejectedAdditionalProperties};let W={type:"object",additionalProperties:F($.valueType._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]})??X.allowedAdditionalProperties};if(X.target==="openApi3")return W;if($.keyType?._def.typeName===V.ZodString&&$.keyType._def.checks?.length){let{type:J,...Y}=N1($.keyType._def,X);return{...W,propertyNames:Y}}else if($.keyType?._def.typeName===V.ZodEnum)return{...W,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===V.ZodBranded&&$.keyType._def.type._def.typeName===V.ZodString&&$.keyType._def.type._def.checks?.length){let{type:J,...Y}=q1($.keyType._def,X);return{...W,propertyNames:Y}}return W}function l2($,X){if(X.mapStrategy==="record")return S1($,X);let W=F($.keyType._def,{...X,currentPath:[...X.currentPath,"items","items","0"]})||{},J=F($.valueType._def,{...X,currentPath:[...X.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[W,J],minItems:2,maxItems:2}}}function n2($){let X=$.values,J=Object.keys($.values).filter((H)=>{return typeof X[X[H]]!=="number"}).map((H)=>X[H]),Y=Array.from(new Set(J.map((H)=>typeof H)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:J}}function u2(){return{not:{}}}function c2($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var o0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function i2($,X){if(X.target==="openApi3")return p2($,X);let W=$.options instanceof Map?Array.from($.options.values()):$.options;if(W.every((J)=>(J._def.typeName in o0)&&(!J._def.checks||!J._def.checks.length))){let J=W.reduce((Y,H)=>{let G=o0[H._def.typeName];return G&&!Y.includes(G)?[...Y,G]:Y},[]);return{type:J.length>1?J:J[0]}}else if(W.every((J)=>J._def.typeName==="ZodLiteral"&&!J.description)){let J=W.reduce((Y,H)=>{let G=typeof H._def.value;switch(G){case"string":case"number":case"boolean":return[...Y,G];case"bigint":return[...Y,"integer"];case"object":if(H._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(J.length===W.length){let Y=J.filter((H,G,D)=>D.indexOf(H)===G);return{type:Y.length>1?Y:Y[0],enum:W.reduce((H,G)=>{return H.includes(G._def.value)?H:[...H,G._def.value]},[])}}}else if(W.every((J)=>J._def.typeName==="ZodEnum"))return{type:"string",enum:W.reduce((J,Y)=>[...J,...Y._def.values.filter((H)=>!J.includes(H))],[])};return p2($,X)}var p2=($,X)=>{let W=($.options instanceof Map?Array.from($.options.values()):$.options).map((J,Y)=>F(J._def,{...X,currentPath:[...X.currentPath,"anyOf",`${Y}`]})).filter((J)=>!!J&&(!X.strictUnions||typeof J==="object"&&Object.keys(J).length>0));return W.length?{anyOf:W}:void 0};function d2($,X){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(X.target==="openApi3")return{type:o0[$.innerType._def.typeName],nullable:!0};return{type:[o0[$.innerType._def.typeName],"null"]}}if(X.target==="openApi3"){let J=F($.innerType._def,{...X,currentPath:[...X.currentPath]});if(J&&"$ref"in J)return{allOf:[J],nullable:!0};return J&&{...J,nullable:!0}}let W=F($.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","0"]});return W&&{anyOf:[W,{type:"null"}]}}function o2($,X){let W={type:"number"};if(!$.checks)return W;for(let J of $.checks)switch(J.kind){case"int":W.type="integer",g1(W,"type",J.message,X);break;case"min":if(X.target==="jsonSchema7")if(J.inclusive)S(W,"minimum",J.value,J.message,X);else S(W,"exclusiveMinimum",J.value,J.message,X);else{if(!J.inclusive)W.exclusiveMinimum=!0;S(W,"minimum",J.value,J.message,X)}break;case"max":if(X.target==="jsonSchema7")if(J.inclusive)S(W,"maximum",J.value,J.message,X);else S(W,"exclusiveMaximum",J.value,J.message,X);else{if(!J.inclusive)W.exclusiveMaximum=!0;S(W,"maximum",J.value,J.message,X)}break;case"multipleOf":S(W,"multipleOf",J.value,J.message,X);break}return W}function r2($,X){let W=X.target==="openAi",J={type:"object",properties:{}},Y=[],H=$.shape();for(let D in H){let w=H[D];if(w===void 0||w._def===void 0)continue;let B=x6(w);if(B&&W){if(w instanceof u)w=w._def.innerType;if(!w.isNullable())w=w.nullable();B=!1}let j=F(w._def,{...X,currentPath:[...X.currentPath,"properties",D],propertyPath:[...X.currentPath,"properties",D]});if(j===void 0)continue;if(J.properties[D]=j,!B)Y.push(D)}if(Y.length)J.required=Y;let G=T6($,X);if(G!==void 0)J.additionalProperties=G;return J}function T6($,X){if($.catchall._def.typeName!=="ZodNever")return F($.catchall._def,{...X,currentPath:[...X.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return X.allowedAdditionalProperties;case"strict":return X.rejectedAdditionalProperties;case"strip":return X.removeAdditionalStrategy==="strict"?X.allowedAdditionalProperties:X.rejectedAdditionalProperties}}function x6($){try{return $.isOptional()}catch{return!0}}var a2=($,X)=>{if(X.currentPath.toString()===X.propertyPath?.toString())return F($.innerType._def,X);let W=F($.innerType._def,{...X,currentPath:[...X.currentPath,"anyOf","1"]});return W?{anyOf:[{not:{}},W]}:{}};var t2=($,X)=>{if(X.pipeStrategy==="input")return F($.in._def,X);else if(X.pipeStrategy==="output")return F($.out._def,X);let W=F($.in._def,{...X,currentPath:[...X.currentPath,"allOf","0"]}),J=F($.out._def,{...X,currentPath:[...X.currentPath,"allOf",W?"1":"0"]});return{allOf:[W,J].filter((Y)=>Y!==void 0)}};function s2($,X){return F($.type._def,X)}function e2($,X){let J={type:"array",uniqueItems:!0,items:F($.valueType._def,{...X,currentPath:[...X.currentPath,"items"]})};if($.minSize)S(J,"minItems",$.minSize.value,$.minSize.message,X);if($.maxSize)S(J,"maxItems",$.maxSize.value,$.maxSize.message,X);return J}function $4($,X){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((W,J)=>F(W._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce((W,J)=>J===void 0?W:[...W,J],[]),additionalItems:F($.rest._def,{...X,currentPath:[...X.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((W,J)=>F(W._def,{...X,currentPath:[...X.currentPath,"items",`${J}`]})).reduce((W,J)=>J===void 0?W:[...W,J],[])}}function X4(){return{not:{}}}function W4(){return{}}var J4=($,X)=>{return F($.innerType._def,X)};var Y4=($,X,W)=>{switch(X){case V.ZodString:return N1($,W);case V.ZodNumber:return o2($,W);case V.ZodObject:return r2($,W);case V.ZodBigInt:return P2($,W);case V.ZodBoolean:return k2();case V.ZodDate:return y1($,W);case V.ZodUndefined:return X4();case V.ZodNull:return c2(W);case V.ZodArray:return v2($,W);case V.ZodUnion:case V.ZodDiscriminatedUnion:return i2($,W);case V.ZodIntersection:return y2($,W);case V.ZodTuple:return $4($,W);case V.ZodRecord:return S1($,W);case V.ZodLiteral:return Z2($,W);case V.ZodEnum:return g2($);case V.ZodNativeEnum:return n2($);case V.ZodNullable:return d2($,W);case V.ZodOptional:return a2($,W);case V.ZodMap:return l2($,W);case V.ZodSet:return e2($,W);case V.ZodLazy:return()=>$.getter()._def;case V.ZodPromise:return s2($,W);case V.ZodNaN:case V.ZodNever:return u2();case V.ZodEffects:return h2($,W);case V.ZodAny:return I2();case V.ZodUnknown:return W4();case V.ZodDefault:return x2($,W);case V.ZodBranded:return q1($,W);case V.ZodReadonly:return J4($,W);case V.ZodCatch:return T2($,W);case V.ZodPipeline:return t2($,W);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return((J)=>{return})(X)}};function F($,X,W=!1){let J=X.seen.get($);if(X.override){let D=X.override?.($,X,J,W);if(D!==b2)return D}if(J&&!W){let D=h6(J,X);if(D!==void 0)return D}let Y={def:$,path:X.currentPath,jsonSchema:void 0};X.seen.set($,Y);let H=Y4($,$.typeName,X),G=typeof H==="function"?F(H(),X):H;if(G)y6($,X,G);if(X.postProcess){let D=X.postProcess(G,$,X);return Y.jsonSchema=G,D}return Y.jsonSchema=G,G}var h6=($,X)=>{switch(X.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:g6(X.currentPath,$.path)};case"none":case"seen":{if($.path.length<X.currentPath.length&&$.path.every((W,J)=>X.currentPath[J]===W))return console.warn(`Recursive reference detected at ${X.currentPath.join("/")}! Defaulting to any`),{};return X.$refStrategy==="seen"?{}:void 0}}},g6=($,X)=>{let W=0;for(;W<$.length&&W<X.length;W++)if($[W]!==X[W])break;return[($.length-W).toString(),...X.slice(W)].join("/")},y6=($,X,W)=>{if($.description){if(W.description=$.description,X.markdownDescription)W.markdownDescription=$.description}return W};var l1=($,X)=>{let W=C2(X),J=typeof X==="object"&&X.definitions?Object.entries(X.definitions).reduce((w,[B,j])=>({...w,[B]:F(j._def,{...W,currentPath:[...W.basePath,W.definitionPath,B]},!0)??{}}),{}):void 0,Y=typeof X==="string"?X:X?.nameStrategy==="title"?void 0:X?.name,H=F($._def,Y===void 0?W:{...W,currentPath:[...W.basePath,W.definitionPath,Y]},!1)??{},G=typeof X==="object"&&X.name!==void 0&&X.nameStrategy==="title"?X.name:void 0;if(G!==void 0)H.title=G;let D=Y===void 0?J?{...H,[W.definitionPath]:J}:H:{$ref:[...W.$refStrategy==="relative"?[]:W.basePath,W.definitionPath,Y].join("/"),[W.definitionPath]:{...J,[Y]:H}};if(W.target==="jsonSchema7")D.$schema="http://json-schema.org/draft-07/schema#";else if(W.target==="jsonSchema2019-09"||W.target==="openAi")D.$schema="https://json-schema.org/draft/2019-09/schema#";if(W.target==="openAi"&&(("anyOf"in D)||("oneOf"in D)||("allOf"in D)||("type"in D)&&Array.isArray(D.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return D};var n1;(function($){$.Completable="McpCompletable"})(n1||(n1={}));class r0 extends q{_parse($){let{ctx:X}=this._processInputParams($),W=X.data;return this._def.type._parse({data:W,path:X.path,parent:X})}unwrap(){return this._def.type}}r0.create=($,X)=>{return new r0({type:$,typeName:n1.Completable,complete:X.complete,...Z6(X)})};function Z6($){if(!$)return{};let{errorMap:X,invalid_type_error:W,required_error:J,description:Y}=$;if(X&&(W||J))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(X)return{errorMap:X,description:Y};return{errorMap:(G,D)=>{var w,B;let{message:j}=$;if(G.code==="invalid_enum_value")return{message:j!==null&&j!==void 0?j:D.defaultError};if(typeof D.data==="undefined")return{message:(w=j!==null&&j!==void 0?j:J)!==null&&w!==void 0?w:D.defaultError};if(G.code!=="invalid_type")return{message:D.defaultError};return{message:(B=j!==null&&j!==void 0?j:W)!==null&&B!==void 0?B:D.defaultError}},description:Y}}class G0{static isTemplate($){return/\{[^}\s]+\}/.test($)}static validateLength($,X,W){if($.length>X)throw new Error(`${W} exceeds maximum length of ${X} characters (got ${$.length})`)}constructor($){G0.validateLength($,1e6,"Template"),this.template=$,this.parts=this.parse($)}toString(){return this.template}parse($){let X=[],W="",J=0,Y=0;while(J<$.length)if($[J]==="{"){if(W)X.push(W),W="";let H=$.indexOf("}",J);if(H===-1)throw new Error("Unclosed template expression");if(Y++,Y>1e4)throw new Error("Template contains too many expressions (max 10000)");let G=$.slice(J+1,H),D=this.getOperator(G),w=G.includes("*"),B=this.getNames(G),j=B[0];for(let R of B)G0.validateLength(R,1e6,"Variable name");X.push({name:j,operator:D,names:B,exploded:w}),J=H+1}else W+=$[J],J++;if(W)X.push(W);return X}getOperator($){return["+","#",".","/","?","&"].find((W)=>$.startsWith(W))||""}getNames($){let X=this.getOperator($);return $.slice(X.length).split(",").map((W)=>W.replace("*","").trim()).filter((W)=>W.length>0)}encodeValue($,X){if(G0.validateLength($,1e6,"Variable value"),X==="+"||X==="#")return encodeURI($);return encodeURIComponent($)}expandPart($,X){if($.operator==="?"||$.operator==="&"){let H=$.names.map((D)=>{let w=X[D];if(w===void 0)return"";let B=Array.isArray(w)?w.map((j)=>this.encodeValue(j,$.operator)).join(","):this.encodeValue(w.toString(),$.operator);return`${D}=${B}`}).filter((D)=>D.length>0);if(H.length===0)return"";return($.operator==="?"?"?":"&")+H.join("&")}if($.names.length>1){let H=$.names.map((G)=>X[G]).filter((G)=>G!==void 0);if(H.length===0)return"";return H.map((G)=>Array.isArray(G)?G[0]:G).join(",")}let W=X[$.name];if(W===void 0)return"";let Y=(Array.isArray(W)?W:[W]).map((H)=>this.encodeValue(H,$.operator));switch($.operator){case"":return Y.join(",");case"+":return Y.join(",");case"#":return"#"+Y.join(",");case".":return"."+Y.join(".");case"/":return"/"+Y.join("/");default:return Y.join(",")}}expand($){let X="",W=!1;for(let J of this.parts){if(typeof J==="string"){X+=J;continue}let Y=this.expandPart(J,$);if(!Y)continue;if((J.operator==="?"||J.operator==="&")&&W)X+=Y.replace("?","&");else X+=Y;if(J.operator==="?"||J.operator==="&")W=!0}return X}escapeRegExp($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp($){let X=[];for(let Y of $.names)G0.validateLength(Y,1e6,"Variable name");if($.operator==="?"||$.operator==="&"){for(let Y=0;Y<$.names.length;Y++){let H=$.names[Y],G=Y===0?"\\"+$.operator:"&";X.push({pattern:G+this.escapeRegExp(H)+"=([^&]+)",name:H})}return X}let W,J=$.name;switch($.operator){case"":W=$.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":W="(.+)";break;case".":W="\\.([^/,]+)";break;case"/":W="/"+($.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:W="([^/]+)"}return X.push({pattern:W,name:J}),X}match($){G0.validateLength($,1e6,"URI");let X="^",W=[];for(let G of this.parts)if(typeof G==="string")X+=this.escapeRegExp(G);else{let D=this.partToRegExp(G);for(let{pattern:w,name:B}of D)X+=w,W.push({name:B,exploded:G.exploded})}X+="$",G0.validateLength(X,1e6,"Generated regex pattern");let J=new RegExp(X),Y=$.match(J);if(!Y)return null;let H={};for(let G=0;G<W.length;G++){let{name:D,exploded:w}=W[G],B=Y[G+1],j=D.replace("*","");if(w&&B.includes(","))H[j]=B.split(",");else H[j]=B}return H}}class u1{constructor($,X){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new h1($,X)}async connect($){return await this.server.connect($)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(U1.shape.method.value),this.server.assertCanSetRequestHandler(F1.shape.method.value),this.server.registerCapabilities({tools:{}}),this.server.setRequestHandler(U1,()=>({tools:Object.entries(this._registeredTools).map(([$,X])=>{return{name:$,description:X.description,inputSchema:X.inputSchema?l1(X.inputSchema,{strictUnions:!0}):m6}})})),this.server.setRequestHandler(F1,async($,X)=>{let W=this._registeredTools[$.params.name];if(!W)throw new g(k.InvalidParams,`Tool ${$.params.name} not found`);if(W.inputSchema){let J=await W.inputSchema.safeParseAsync($.params.arguments);if(!J.success)throw new g(k.InvalidParams,`Invalid arguments for tool ${$.params.name}: ${J.error.message}`);let Y=J.data,H=W.callback;try{return await Promise.resolve(H(Y,X))}catch(G){return{content:[{type:"text",text:G instanceof Error?G.message:String(G)}],isError:!0}}}else{let J=W.callback;try{return await Promise.resolve(J(X))}catch(Y){return{content:[{type:"text",text:Y instanceof Error?Y.message:String(Y)}],isError:!0}}}}),this._toolHandlersInitialized=!0}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(K1.shape.method.value),this.server.setRequestHandler(K1,async($)=>{switch($.params.ref.type){case"ref/prompt":return this.handlePromptCompletion($,$.params.ref);case"ref/resource":return this.handleResourceCompletion($,$.params.ref);default:throw new g(k.InvalidParams,`Invalid completion reference: ${$.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion($,X){let W=this._registeredPrompts[X.name];if(!W)throw new g(k.InvalidParams,`Prompt ${$.params.ref.name} not found`);if(!W.argsSchema)return L1;let J=W.argsSchema.shape[$.params.argument.name];if(!(J instanceof r0))return L1;let H=await J._def.complete($.params.argument.value);return Q4(H)}async handleResourceCompletion($,X){let W=Object.values(this._registeredResourceTemplates).find((H)=>H.resourceTemplate.uriTemplate.toString()===X.uri);if(!W){if(this._registeredResources[X.uri])return L1;throw new g(k.InvalidParams,`Resource template ${$.params.ref.uri} not found`)}let J=W.resourceTemplate.completeCallback($.params.argument.name);if(!J)return L1;let Y=await J($.params.argument.value);return Q4(Y)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(B1.shape.method.value),this.server.assertCanSetRequestHandler(M1.shape.method.value),this.server.assertCanSetRequestHandler(V1.shape.method.value),this.server.registerCapabilities({resources:{}}),this.server.setRequestHandler(B1,async($,X)=>{let W=Object.entries(this._registeredResources).map(([Y,H])=>({uri:Y,name:H.name,...H.metadata})),J=[];for(let Y of Object.values(this._registeredResourceTemplates)){if(!Y.resourceTemplate.listCallback)continue;let H=await Y.resourceTemplate.listCallback(X);for(let G of H.resources)J.push({...G,...Y.metadata})}return{resources:[...W,...J]}}),this.server.setRequestHandler(M1,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([X,W])=>({name:X,uriTemplate:W.resourceTemplate.uriTemplate.toString(),...W.metadata}))}}),this.server.setRequestHandler(V1,async($,X)=>{let W=new URL($.params.uri),J=this._registeredResources[W.toString()];if(J)return J.readCallback(W,X);for(let Y of Object.values(this._registeredResourceTemplates)){let H=Y.resourceTemplate.uriTemplate.match(W.toString());if(H)return Y.readCallback(W,H,X)}throw new g(k.InvalidParams,`Resource ${W} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(j1.shape.method.value),this.server.assertCanSetRequestHandler(O1.shape.method.value),this.server.registerCapabilities({prompts:{}}),this.server.setRequestHandler(j1,()=>({prompts:Object.entries(this._registeredPrompts).map(([$,X])=>{return{name:$,description:X.description,arguments:X.argsSchema?l6(X.argsSchema):void 0}})})),this.server.setRequestHandler(O1,async($,X)=>{let W=this._registeredPrompts[$.params.name];if(!W)throw new g(k.InvalidParams,`Prompt ${$.params.name} not found`);if(W.argsSchema){let J=await W.argsSchema.safeParseAsync($.params.arguments);if(!J.success)throw new g(k.InvalidParams,`Invalid arguments for prompt ${$.params.name}: ${J.error.message}`);let Y=J.data,H=W.callback;return await Promise.resolve(H(Y,X))}else{let J=W.callback;return await Promise.resolve(J(X))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0}resource($,X,...W){let J;if(typeof W[0]==="object")J=W.shift();let Y=W[0];if(typeof X==="string"){if(this._registeredResources[X])throw new Error(`Resource ${X} is already registered`);this._registeredResources[X]={name:$,metadata:J,readCallback:Y}}else{if(this._registeredResourceTemplates[$])throw new Error(`Resource template ${$} is already registered`);this._registeredResourceTemplates[$]={resourceTemplate:X,metadata:J,readCallback:Y}}this.setResourceRequestHandlers()}tool($,...X){if(this._registeredTools[$])throw new Error(`Tool ${$} is already registered`);let W;if(typeof X[0]==="string")W=X.shift();let J;if(X.length>1)J=X.shift();let Y=X[0];this._registeredTools[$]={description:W,inputSchema:J===void 0?void 0:Q.object(J),callback:Y},this.setToolRequestHandlers()}prompt($,...X){if(this._registeredPrompts[$])throw new Error(`Prompt ${$} is already registered`);let W;if(typeof X[0]==="string")W=X.shift();let J;if(X.length>1)J=X.shift();let Y=X[0];this._registeredPrompts[$]={description:W,argsSchema:J===void 0?void 0:Q.object(J),callback:Y},this.setPromptRequestHandlers()}}class K0{constructor($,X){this._callbacks=X,this._uriTemplate=typeof $==="string"?new G0($):$}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback($){var X;return(X=this._callbacks.complete)===null||X===void 0?void 0:X[$]}}var m6={type:"object"};function l6($){return Object.entries($.shape).map(([X,W])=>({name:X,description:W.description,required:!W.isOptional()}))}function Q4($){return{completion:{values:$.slice(0,100),total:$.length,hasMore:$.length>100}}}var L1={completion:{values:[],hasMore:!1}};import G4 from"node:process";class c1{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
9
+ `);if($===-1)return null;let X=this._buffer.toString("utf8",0,$);return this._buffer=this._buffer.subarray($+1),n6(X)}clear(){this._buffer=void 0}}function n6($){return U2.parse(JSON.parse($))}function H4($){return JSON.stringify($)+`
10
+ `}class p1{constructor($=G4.stdin,X=G4.stdout){this._stdin=$,this._stdout=X,this._readBuffer=new c1,this._started=!1,this._ondata=(W)=>{this._readBuffer.append(W),this.processReadBuffer()},this._onerror=(W)=>{var J;(J=this.onerror)===null||J===void 0||J.call(this,W)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){var $,X;while(!0)try{let W=this._readBuffer.readMessage();if(W===null)break;($=this.onmessage)===null||$===void 0||$.call(this,W)}catch(W){(X=this.onerror)===null||X===void 0||X.call(this,W)}}async close(){var $;if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),($=this.onclose)===null||$===void 0||$.call(this)}send($){return new Promise((X)=>{let W=H4($);if(this._stdout.write(W))X();else this._stdout.once("drain",X)})}}var j4=x4(V4(),1);j4.default.config();var M$=process.env.LOGSEQ_PORT||"12315",V$=process.env.LOGSEQ_HOST||"127.0.0.1",r1=process.env.LOGSEQ_TOKEN||"",O4=`http://${V$}:${M$}/api`;if(!r1&&process.env.TEST_TYPE!=="unit")console.error("Error: LOGSEQ_TOKEN is required. Set it in a .env file or as an environment variable."),process.exit(1);var f=(...$)=>console.error(...$);async function U($,X=[]){try{f(`Calling Logseq API: ${$} with args:`,JSON.stringify(X));let W=await fetch(O4,{method:"POST",headers:{Authorization:`Bearer ${r1}`,"Content-Type":"application/json"},body:JSON.stringify({method:$,args:X})});if(!W.ok)throw new Error(`Logseq API error: ${W.status} ${W.statusText}`);let J;try{let Y=await W.text();if(!Y||Y.trim()==="")return f(`Empty response from Logseq API (${$})`),null;J=JSON.parse(Y)}catch(Y){if(f(`JSON parse error for ${$}:`,Y),$.includes("getBlockProperty")||$.includes("getProperty")||$.includes("removeBlockProperty"))return null;throw new Error(`Failed to parse JSON response: ${Y.message}`)}return f("Logseq API response:",JSON.stringify(J).substring(0,200)+"..."),J}catch(W){throw console.error(`Error calling Logseq API (${$}):`,W),W}}function z4($){$.tool("query","Execute Datalog queries or search across blocks in Logseq. The most flexible way to retrieve information from your graph.",{type:Q.enum(["datalog","search"]).default("datalog").describe("Query type: 'datalog' for Datalog queries, 'search' for text search"),query:Q.string().describe("The query to execute (Datalog query or search term)"),includeChildren:Q.boolean().optional().default(!0).describe("Whether to include child blocks in results"),limit:Q.number().optional().describe("Maximum number of results to return")},async({type:X,query:W,includeChildren:J=!0,limit:Y})=>{try{if(f(`Executing ${X} query: ${W}`),X==="search"){let H=`[:find (pull ?b [*])
11
+ :where
12
+ [?b :block/content ?c]
13
+ [(clojure.string/includes? ?c "${W}")]]`,G=await U("logseq.DB.datascriptQuery",[H]);f(`Search result count: ${Array.isArray(G)?G.length:G?1:0}`);let D=Array.isArray(G)?G:G?[G]:[];if(Y&&Y>0&&D.length>Y)D=D.slice(0,Y);return{isError:!1,content:[{type:"text",text:JSON.stringify(D,null,2)}]}}else{let H=await U("logseq.DB.datascriptQuery",[W]),G=Array.isArray(H)?H:H?[H]:[];if(Y&&Y>0&&G.length>Y)G=G.slice(0,Y);let D=G.some((w)=>w&&(w.uuid||Array.isArray(w)&&w[0]?.uuid));if(J&&D&&G.length>0)G=await Promise.all(G.map(async(B)=>{let j=B.uuid||(Array.isArray(B)?B[0]?.uuid:null);if(!j)return B;try{return await U("logseq.Editor.getBlock",[j,{includeChildren:!0}])||B}catch(R){return B}}));return f(`Query result (processed): ${G.length} items`),{isError:!1,content:[{type:"text",text:JSON.stringify(G,null,2)}]}}}catch(H){return console.error(`Error in query operation: ${H}`),{isError:!0,content:[{type:"text",text:`Error in query operation: ${H}`}]}}})}function A4($){$.tool("block","Get, create, update, or delete blocks. The central tool for block operations. ALWAYS USE nested data structures with the 'blocks' parameter for creating hierarchical content - this is dramatically more efficient than creating individual blocks. The 'blocks' parameter accepts an array of block objects with 'content' and nested 'children' arrays for deeply nested structures. PREFER creating entire hierarchies in a single operation rather than multiple separate calls. Each block object supports unlimited nesting levels through children arrays. Content with leading hyphens (like '- item') will automatically have hyphens removed at all nesting levels and newlines, and Logseq's auto-formatting of blocks is disabled by default. IMPORTANT: When creating content on a page, avoid adding a top-level heading with the page name (e.g., '# Page Name') as the first block since Logseq already displays the page title.",{operation:Q.enum(["get","get-current","get-selected","get-siblings","create","update","remove","move","toggle-collapse","select","edit","open-sidebar","scroll-to","get-property","get-properties","set-property","remove-property"]).describe("Operation to perform on block(s)"),uuid:Q.string().optional().describe("UUID of the block (required for most operations)"),content:Q.string().optional().describe("Content for create/update operations"),properties:Q.record(Q.string(),Q.any()).optional().describe("Properties for the block"),includeChildren:Q.boolean().optional().default(!0).describe("Whether to include child blocks in results"),target:Q.string().optional().describe("Target block UUID or page name for create/move operations"),position:Q.enum(["child","before","after","first","last"]).optional().default("child").describe("Position for create/move operations"),preventAutoFormat:Q.boolean().optional().default(!0).describe("Prevent Logseq from auto-formatting blocks (adding hyphens)"),stripLeadingHyphen:Q.boolean().optional().default(!0).describe("Remove leading hyphens from content at all nesting levels"),collapsed:Q.union([Q.boolean(),Q.literal("toggle")]).optional().describe("Collapsed state for toggle-collapse"),pageName:Q.string().optional().describe("Page name for scroll-to operation"),uuids:Q.array(Q.string()).optional().describe("Array of block UUIDs for batch operations"),blocks:Q.array(Q.any()).optional().describe("Array of blocks for batch operations with unlimited nesting levels"),keepUUID:Q.boolean().optional().default(!1).describe("Keep custom UUIDs if specified in properties"),direction:Q.enum(["previous","next"]).optional().default("next").describe("Direction for sibling operations"),pos:Q.number().optional().describe("Position for edit operation"),propertyKey:Q.string().optional().describe("Property key for property operations"),propertyValue:Q.any().optional().describe("Value for property operations")},async(X)=>{let{operation:W,uuid:J,content:Y,properties:H,includeChildren:G=!0,target:D,position:w="child",collapsed:B,pageName:j,uuids:R,blocks:C,keepUUID:q0=!1,direction:Z="next",pos:e,propertyKey:m,propertyValue:C4,preventAutoFormat:N0=!0,stripLeadingHyphen:I4=!0}=X;try{let D0=(E)=>{if(!I4)return E;return E.split(`
14
+ `).map((_)=>_.replace(/^\s*-\s+/,"")).join(`
15
+ `)},a1=(E)=>{return E.map((_)=>{if(typeof _==="string")return D0(_);if(_&&typeof _==="object"){let b={..._};if(_.content)b.content=D0(_.content);if(_.children&&Array.isArray(_.children)&&_.children.length>0)b.children=a1(_.children);return b}return _})};if(W==="get"&&J){let E=await U("logseq.Editor.getBlock",[J,{includeChildren:G}]);return{isError:!1,content:[{type:"text",text:JSON.stringify(E,null,2)}]}}else if(W==="get-current"){let E=await U("logseq.Editor.getCurrentBlock",[]);return{isError:!1,content:[{type:"text",text:JSON.stringify(E,null,2)}]}}else if(W==="get-selected"){let E=await U("logseq.Editor.getSelectedBlocks",[]);return{isError:!1,content:[{type:"text",text:JSON.stringify(E,null,2)}]}}else if(W==="get-siblings"&&J){let _=await U(Z==="previous"?"logseq.Editor.getPreviousSiblingBlock":"logseq.Editor.getNextSiblingBlock",[J]);return{isError:!1,content:[{type:"text",text:JSON.stringify(_,null,2)}]}}else if(W==="create"){if(!D)return{isError:!0,content:[{type:"text",text:"Target page name or block UUID is required for create operation"}]};if(!Y&&(!C||C.length===0))return{isError:!0,content:[{type:"text",text:"Content or blocks array is required for create operation"}]};if(Y){let _=!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(D),b={properties:H};if(N0)b.preventAutoFormat=!0;let l=D0(Y);if(!l.trim())return{isError:!1,content:[{type:"text",text:"Skipped adding empty block"}]};if(!_){if(w==="before"||w==="after")b.sibling=!0,b.before=w==="before"}else if(b.isPageBlock=!0,w==="first"||w==="last"){let x=await U("logseq.Editor.getPageBlocksTree",[D]),$0=Array.isArray(x)&&x.length>0;if(w==="first"&&$0)b.before=x[0].uuid;else if(w==="last"&&$0)b.after=x[x.length-1].uuid}let I=await U("logseq.Editor.insertBlock",[D,l,b]);return{isError:!1,content:[{type:"text",text:JSON.stringify(I,null,2)}]}}else if(C&&C.length>0){let _=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(D),l=a1(C).filter((I)=>{if(typeof I==="string")return I.trim().length>0;if(I&&typeof I==="object"&&I.content)return I.content.trim().length>0;return!1});if(l.length===0)return{isError:!1,content:[{type:"text",text:"Skipped adding empty blocks"}]};if(_){let x=await U("logseq.Editor.insertBatchBlock",[D,l,{sibling:w==="before"||w==="after",before:w==="before",keepUUID:q0,preventAutoFormat:N0}]);return{isError:!1,content:[{type:"text",text:JSON.stringify(x,null,2)}]}}else{let I=[];for(let x of l){let $0={properties:x.properties,isPageBlock:!0};if(N0)$0.preventAutoFormat=!0;if(w==="first"||w==="last"){let g0=await U("logseq.Editor.getPageBlocksTree",[D]),s1=Array.isArray(g0)&&g0.length>0;if(w==="first"&&s1)if(I.length===0)$0.before=g0[0].uuid;else $0.after=I[I.length-1].uuid;else if(w==="last"&&s1)if(I.length===0)$0.after=g0[g0.length-1].uuid;else $0.after=I[I.length-1].uuid}else if(I.length>0)$0.after=I[I.length-1].uuid;let t1=await U("logseq.Editor.insertBlock",[D,x.content,$0]);if(I.push(t1),x.children&&x.children.length>0)await U("logseq.Editor.insertBatchBlock",[t1.uuid,x.children,{preventAutoFormat:N0,keepUUID:q0}])}return{isError:!1,content:[{type:"text",text:JSON.stringify(I,null,2)}]}}}return{isError:!0,content:[{type:"text",text:"Invalid parameters for create operation"}]}}else if(W==="update")if(J&&Y){let E={};if(H)E.properties=H;if(N0)E.preventAutoFormat=!0;let _=D0(Y);await U("logseq.Editor.updateBlock",[J,_,E]);let b=await U("logseq.Editor.getBlock",[J]);return{isError:!1,content:[{type:"text",text:JSON.stringify(b,null,2)}]}}else if(C&&C.length>0){let E=[],_=[];for(let b of C){if(!b.uuid||!b.content){_.push({uuid:b.uuid||"missing-uuid",error:"Missing required uuid or content"});continue}try{let l={};if(b.properties)l.properties=b.properties;if(N0)l.preventAutoFormat=!0;let I=D0(b.content);await U("logseq.Editor.updateBlock",[b.uuid,I,l]);let x=await U("logseq.Editor.getBlock",[b.uuid]);E.push(x)}catch(l){_.push({uuid:b.uuid,error:`${l}`})}}return{isError:_.length===C.length,content:[{type:"text",text:JSON.stringify({updated:E,failed:_},null,2)}]}}else return{isError:!0,content:[{type:"text",text:"UUID and content are required for update operation"}]};else if(W==="remove")if(J)return await U("logseq.Editor.removeBlock",[J]),{isError:!1,content:[{type:"text",text:`Block ${J} removed successfully`}]};else if(R&&R.length>0){let E=[],_=[];for(let b of R)try{await U("logseq.Editor.removeBlock",[b]),E.push({uuid:b})}catch(l){_.push({uuid:b,error:`${l}`})}return{isError:_.length===R.length,content:[{type:"text",text:JSON.stringify({removed:E,failed:_},null,2)}]}}else return{isError:!0,content:[{type:"text",text:"UUID or uuids array is required for remove operation"}]};else if(W==="move"){if(!J||!D)return{isError:!0,content:[{type:"text",text:"Source UUID and target UUID are required for move operation"}]};return await U("logseq.Editor.moveBlock",[J,D,{before:w==="before",children:G}]),{isError:!1,content:[{type:"text",text:`Block ${J} moved successfully to ${w==="before"?"before":"as child of"} ${D}`}]}}else if(W==="toggle-collapse"&&J&&B!==void 0)return await U("logseq.Editor.setBlockCollapsed",[J,{flag:B}]),{isError:!1,content:[{type:"text",text:`Block ${J} ${B==="toggle"?"toggled":B?"collapsed":"expanded"} successfully`}]};else if(W==="select"&&J)return await U("logseq.Editor.selectBlock",[J]),{isError:!1,content:[{type:"text",text:`Block ${J} selected successfully`}]};else if(W==="edit"&&J)return await U("logseq.Editor.editBlock",[J,e!==void 0?{pos:e}:void 0]),{isError:!1,content:[{type:"text",text:`Block ${J} is now in editing mode`}]};else if(W==="open-sidebar"&&J)return await U("logseq.Editor.openInRightSidebar",[J]),{isError:!1,content:[{type:"text",text:`Block ${J} opened in right sidebar successfully`}]};else if(W==="scroll-to"&&J&&j)return await U("logseq.Editor.scrollToBlockInPage",[j,J]),{isError:!1,content:[{type:"text",text:`Scrolled to block ${J} in page ${j}`}]};else if(W==="get-property"&&J&&m){let E=await U("logseq.Editor.getBlockProperty",[J,m]);return{isError:!1,content:[{type:"text",text:JSON.stringify(E===void 0?null:E,null,2)}]}}else if(W==="get-properties"&&J){let E=await U("logseq.Editor.getBlockProperties",[J]);return{isError:!1,content:[{type:"text",text:JSON.stringify(E,null,2)}]}}else if(W==="set-property"&&J&&m)return await U("logseq.Editor.upsertBlockProperty",[J,m,C4]),{isError:!1,content:[{type:"text",text:`Property '${m}' set for block ${J} successfully`}]};else if(W==="remove-property"&&J&&m)return await U("logseq.Editor.removeBlockProperty",[J,m]),{isError:!1,content:[{type:"text",text:`Property '${m}' removed from block ${J} successfully`}]};return{isError:!0,content:[{type:"text",text:`Invalid operation or missing required parameters for operation: ${W}`}]}}catch(D0){return console.error(`Error in block operation (${W}):`,D0),{isError:!0,content:[{type:"text",text:`Error in block operation (${W}): ${D0}`}]}}})}function U4($){$.tool("page","Create, retrieve, and manage pages in Logseq. The central tool for page operations.",{operation:Q.enum(["create","get","get-current","get-all","get-blocks","get-linked-references"]).describe("Operation to perform on page(s)"),pageName:Q.string().optional().describe("Name of the page (required for most operations)"),properties:Q.record(Q.string(),Q.any()).optional().describe("Properties for page creation/update"),includeChildren:Q.boolean().optional().default(!0).describe("Whether to include page blocks in results"),includeProperties:Q.boolean().optional().default(!0).describe("Whether to include page properties in results (for get-all)"),limit:Q.number().optional().describe("Maximum number of pages to return (for get-all)"),redirect:Q.boolean().optional().default(!1).describe("Whether to redirect to the page after creation")},async(X)=>{let{operation:W,pageName:J,properties:Y,includeChildren:H=!0,includeProperties:G=!0,limit:D,redirect:w=!1}=X;try{if(W==="create"){if(!J)return{isError:!0,content:[{type:"text",text:"Page name is required for create operation"}]};return await U("logseq.Editor.createPage",[J,Y||{},{redirect:w}]),{isError:!1,content:[{type:"text",text:`Page "${J}" created successfully`}]}}else if(W==="get"&&J){let B=await U("logseq.Editor.getPage",[J]);if(!B)return{isError:!0,content:[{type:"text",text:`Page "${J}" not found`}]};let j={...B};if(H){let R=await U("logseq.Editor.getPageBlocksTree",[J]);j.blocks=R}return{isError:!1,content:[{type:"text",text:JSON.stringify(j,null,2)}]}}else if(W==="get-current"){let B=await U("logseq.Editor.getCurrentPage",[]);if(!B)return{isError:!0,content:[{type:"text",text:"No active page found"}]};let j={...B};if(H){let R=await U("logseq.Editor.getPageBlocksTree",[B.name]);j.blocks=R}return{isError:!1,content:[{type:"text",text:JSON.stringify(j,null,2)}]}}else if(W==="get-all"){let B=await U("logseq.Editor.getAllPages",[]);if(D&&D>0&&Array.isArray(B)&&B.length>D)B=B.slice(0,D);if(G&&Array.isArray(B))B=await Promise.all(B.map(async(R)=>{try{return await U("logseq.Editor.getPage",[R.name])||R}catch(C){return R}}));return{isError:!1,content:[{type:"text",text:JSON.stringify(B,null,2)}]}}else if(W==="get-blocks"&&J){if(!await U("logseq.Editor.getPage",[J]))return{isError:!0,content:[{type:"text",text:`Page "${J}" not found`}]};let j=await U("logseq.Editor.getPageBlocksTree",[J]);return{isError:!1,content:[{type:"text",text:JSON.stringify(j,null,2)}]}}else if(W==="get-linked-references"&&J){let B=await U("logseq.Editor.getPageLinkedReferences",[J]);return{isError:!1,content:[{type:"text",text:JSON.stringify(B,null,2)}]}}return{isError:!0,content:[{type:"text",text:`Invalid operation or missing required parameters for operation: ${W}`}]}}catch(B){return console.error(`Error in page operation (${W}):`,B),{isError:!0,content:[{type:"text",text:`Error in page operation (${W}): ${B}`}]}}})}function F4($){$.tool("tasks","Find and manage task blocks with specific markers (TODO, DOING, DONE, etc.) across the graph.",{operation:Q.enum(["get"]).default("get").describe("Operation to perform on tasks"),markers:Q.array(Q.string()).describe("Task markers to search for (e.g., 'TODO', 'DOING', 'DONE')"),includeChildren:Q.boolean().optional().default(!0).describe("Whether to include child blocks in results"),limit:Q.number().optional().describe("Maximum number of tasks to return")},async(X)=>{let{operation:W,markers:J,includeChildren:Y=!0,limit:H}=X;try{if(W==="get"){f(`Getting tasks with markers: ${J.join(", ")}`);let D=`[:find (pull ?b [*])
16
+ :where
17
+ [?b :block/content ?c]
18
+ (or ${J.map((j)=>`[(clojure.string/includes? ?c "${j}")]`).join(`
19
+ `)})]`;f(`Executing task query: ${D}`);let w=await U("logseq.DB.datascriptQuery",[D]);f(`Task query result count: ${Array.isArray(w)?w.length:w?1:0}`);let B=Array.isArray(w)?w:w?[w]:[];if(H&&H>0&&B.length>H)B=B.slice(0,H);if(Y&&B.length>0)B=await Promise.all(B.map(async(R)=>{let C=R.uuid||(Array.isArray(R)?R[0]?.uuid:null);if(!C)return R;try{return await U("logseq.Editor.getBlock",[C,{includeChildren:!0}])||R}catch(q0){return R}}));return{isError:!1,content:[{type:"text",text:JSON.stringify(B,null,2)}]}}return{isError:!0,content:[{type:"text",text:`Invalid operation for tasks: ${W}`}]}}catch(G){return console.error(`Error in tasks operation (${W}):`,G),{isError:!0,content:[{type:"text",text:`Error in tasks operation (${W}): ${G}`}]}}})}function K4($){z4($),A4($),U4($),F4($)}function q4($){$.resource("pages",new K0("logseq:page:{pageName}",{list:async()=>{try{return{resources:(await U("logseq.Editor.getAllPages",[])).map((W)=>({uri:`logseq:page:${encodeURIComponent(W.originalName||W.name)}`,name:W.originalName||W.name,description:`Page: ${W.originalName||W.name}`,mimeType:"application/json",uriTemplate:"logseq:page:{pageName}"}))}}catch(X){return console.error("Error listing resources:",X),{resources:[]}}}}),async(X,{pageName:W})=>{try{let J=decodeURIComponent(W);f(`Reading page resource for: "${J}"`);let Y=await U("logseq.Editor.getPage",[J]);if(!Y)return f(`Page not found: "${J}"`),{contents:[{uri:X.href,mimeType:"text/plain",text:`Page "${J}" not found`}]};f(`Getting blocks for page: "${J}"`);let H=await U("logseq.Editor.getPageBlocksTree",[J]),G={...Y,blocks:H};return f(`Successfully retrieved page resource: "${J}"`),{contents:[{uri:X.href,mimeType:"application/json",text:JSON.stringify(G,null,2)}]}}catch(J){return console.error(`Error reading page resource (${X}):`,J),{contents:[{uri:X.href,mimeType:"text/plain",text:`Error reading page: ${J}`}]}}})}function N4($){$.resource("blocks",new K0("logseq:block:{uuid}",{list:void 0}),async(X,{uuid:W})=>{try{let J=await U("logseq.Editor.getBlock",[W]);if(J)return{contents:[{uri:X.href,mimeType:"application/json",text:JSON.stringify(J,null,2)}]};return{contents:[]}}catch(J){return console.error(`Error reading block resource (${X}):`,J),{contents:[]}}})}function S4($){$.resource("query",new K0("logseq:query:{query}",{list:void 0}),async(X,{query:W})=>{try{let J=decodeURIComponent(W),Y=await U("logseq.DB.q",[J]);return{contents:[{uri:X.href,mimeType:"application/json",text:JSON.stringify(Y,null,2)}]}}catch(J){return console.error(`Error executing query resource (${X}):`,J),{contents:[]}}})}function L4($){q4($),N4($),S4($)}function R4($){$.prompt("query-tasks",{status:Q.string().optional()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Find all tasks with status ${X.status||"TODO"} in my Logseq graph. Here's the Datalog query to use:
20
+
21
+ \`\`\`clojure
22
+ {:title "Tasks with status ${X.status||"TODO"}"
23
+ :query [:find (pull ?b [*])
24
+ :where
25
+ (task ?b #{"${X.status||"TODO"}"})]
26
+ }
27
+ \`\`\``}}]})),$.prompt("extract-tasks",{source:Q.string().optional(),status:Q.string().optional()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Extract all ${X.status||""} tasks from ${X.source||"my notes"} and organize them into a structured list. First search for task blocks, then analyze and group them by project, priority, or other relevant criteria.`}}]}))}function _4($){$.prompt("create-daily-note",{sections:Q.string().optional()},(X)=>{return{messages:[{role:"user",content:{type:"text",text:`Create a daily note for today with the following sections:
28
+
29
+ ${(X.sections||"Tasks,Notes,Journal").split(",").map((H)=>H.trim()).map((H)=>`## ${H}
30
+
31
+ `).join("")}
32
+ This will help me organize my day and keep track of important information.`}}]}}),$.prompt("search-knowledge",{query:Q.string().optional()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Search my Logseq knowledge base for information about "${X.query||""}". Use the search-blocks tool with the query parameter set to "${X.query||""}" to find relevant blocks, then summarize the findings.`}}]})),$.prompt("summarize-page",{pageName:Q.string()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Create a concise summary of the "${X.pageName}" page. First get the full page content, analyze it, and then generate a summary that captures the main points, key insights, and important details.`}}]})),$.prompt("create-nested-content",{pageName:Q.string(),content:Q.string()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Create a well-structured nested hierarchy of blocks in page "${X.pageName}" from the following content:
33
+
34
+ ${X.content}
35
+
36
+ Please organize this content with all section headers at the same level (as siblings) and nest related content as children underneath them. Use the create-nested-blocks tool since it's specifically designed for hierarchical content. Use page properties for page metadata instead of creating an overall page header. Never use bullet points (dashes) at the beginning of blocks.`}}]}))}function E4($){$.prompt("organize-blocks",{pageOrBlockId:Q.string(),criteria:Q.string().optional()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Organize the blocks${X.pageOrBlockId?` in ${X.pageOrBlockId}`:""} ${X.criteria?`by ${X.criteria}`:""}. First get the blocks, then analyze them, and finally create a structured hierarchy by moving blocks appropriately.`}}]})),$.prompt("organize-blocks-as-nested",{pageName:Q.string(),structure:Q.string().optional()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Analyze the page "${X.pageName}" and reorganize its content into a well-structured nested hierarchy of blocks.${X.structure?`
37
+
38
+ Use the following structure as a guide:
39
+ ${X.structure}`:""}
40
+
41
+ Always use the create-nested-blocks tool which is specifically designed for hierarchical content. Keep all section headers at the same level (as siblings) and nest related content as children underneath these headers. Use page properties for page metadata instead of creating an overall page header. Never use bullet points (dashes) at the beginning of blocks.`}}]})),$.prompt("convert-flat-to-nested",{pageName:Q.string(),structureCriteria:Q.string().optional()},(X)=>({messages:[{role:"user",content:{type:"text",text:`Convert the flat content of page "${X.pageName}" into a proper nested structure. ${X.structureCriteria?`Use ${X.structureCriteria} as the criteria for organizing the content.`:""}
42
+
43
+ Please follow these guidelines:
44
+ 1. Use the get-full-page tool to retrieve all content from the page
45
+ 2. Analyze the content to identify logical hierarchy and grouping
46
+ 3. Keep all section headers at the same level (as siblings)
47
+ 4. Nest related content as children underneath these headers
48
+ 5. Use page properties for page metadata instead of creating an overall page header
49
+ 6. Break down long paragraphs into shorter, focused blocks
50
+ 7. Never use bullet points (dashes) at the beginning of blocks
51
+ 8. Always use the create-nested-blocks tool which is specifically designed for hierarchical content
52
+
53
+ Focus on creating a clear hierarchical structure that enhances readability and navigation.`}}]}))}function b4($){R4($),_4($),E4($)}function j$(){let $=new u1({name:"logseq-mcp-server",version:"1.0.0"});return K4($),L4($),b4($),$}async function f4(){try{f("Checking Logseq API connection..."),await U("logseq.App.getInfo",[]),f("Successfully connected to Logseq API!")}catch(X){console.error("Failed to connect to Logseq API. Make sure Logseq is running with HTTP API enabled."),console.error("Error details:",X),console.error(`
54
+ ====== TROUBLESHOOTING STEPS ======`),console.error("1. Ensure Logseq is running before starting this application"),console.error("2. Enable the Logseq HTTP API:"),console.error(" - Open Logseq"),console.error(" - Go to Settings (using the three dots in top-right)"),console.error(" - Navigate to 'Advanced'"),console.error(" - Enable 'Developer mode'"),console.error(" - Restart Logseq"),console.error(" - Go to Settings again"),console.error(" - Find and enable 'HTTP API server'"),console.error("3. Make sure the port isn't blocked by your firewall"),console.error("4. Check that your LOGSEQ_TOKEN is correct in your .env file"),console.error(`=====================================
55
+ `),process.exit(1)}let $=j$();try{let X=new p1;await $.connect(X),f("Logseq MCP Server connected to stdio transport"),process.on("SIGINT",()=>{f("Received SIGINT signal, shutting down server..."),process.exit(0)}),f("Server running. Press Ctrl+C to exit.")}catch(X){console.error("Error connecting server to transport:",X),process.exit(1)}}async function O$(){try{await f4()}catch($){console.error("Fatal error:",$),process.exit(1)}}O$().catch(($)=>{console.error("Fatal error:",$),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logseq-mcp",
3
- "version": "0.0.18",
3
+ "version": "0.1.3",
4
4
  "description": "Logseq Model Context Protocol Agent",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -19,6 +19,10 @@
19
19
  "test:watch": "bun test --watch tests/",
20
20
  "test:unit:watch": "TEST_TYPE=unit bun test --watch tests/unit/",
21
21
  "test:e2e:watch": "TEST_TYPE=e2e bun test --watch tests/e2e/",
22
+ "typecheck": "bun --bun tsc --noEmit",
23
+ "lint": "bun eslint",
24
+ "check": "bun --bun tsc --noEmit && bun eslint",
25
+ "lint:fix": "bun eslint --fix",
22
26
  "build": "bun run build.ts",
23
27
  "build:node": "bun run build.ts node",
24
28
  "build:bun": "bun run build.ts bun",
@@ -40,6 +44,19 @@
40
44
  "dotenv": "^16.3.1",
41
45
  "zod": "^3.22.4"
42
46
  },
47
+ "devDependencies": {
48
+ "@semantic-release/commit-analyzer": "^11.1.0",
49
+ "@semantic-release/github": "^9.2.0",
50
+ "@semantic-release/release-notes-generator": "^12.1.0",
51
+ "@types/node": "^22.13.11",
52
+ "@typescript-eslint/eslint-plugin": "^6.10.0",
53
+ "@typescript-eslint/parser": "^6.10.0",
54
+ "bun-types": "^1.2.5",
55
+ "eslint": "^9.23.0",
56
+ "globals": "^13.24.0",
57
+ "semantic-release": "^23.0.0",
58
+ "typescript": "^5.2.2"
59
+ },
43
60
  "files": [
44
61
  "dist",
45
62
  "README.md"