@elementor/angie-sdk 1.0.0
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.
- package/README.md +329 -0
- package/dist/angie-detector.d.ts +11 -0
- package/dist/angie-mcp-sdk.d.ts +20 -0
- package/dist/browser-context-transport.d.ts +51 -0
- package/dist/client-manager.d.ts +4 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +1 -0
- package/dist/registration-queue.d.ts +13 -0
- package/dist/types.d.ts +49 -0
- package/package.json +52 -0
package/README.md
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
# @elementor/angie-sdk
|
|
2
|
+
|
|
3
|
+
Based on [MCP](https://github.com/modelcontextprotocol/typescript-sdk) version: 1.13.3
|
|
4
|
+
|
|
5
|
+
**An SDK for extending Angie AI Assistant capabilities.**
|
|
6
|
+
|
|
7
|
+
This SDK enables you to create custom MCP servers that Angie can discover and use to run your plugin features.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Table of Contents
|
|
12
|
+
|
|
13
|
+
- [Background](#background)
|
|
14
|
+
- [How It Works](#how-it-works)
|
|
15
|
+
- [Supported MCP Features](#supported-mcp-features)
|
|
16
|
+
- [Installation](#installation)
|
|
17
|
+
- [Quick Start](#quick-start)
|
|
18
|
+
- [MCP Server Example](#mcp-server-example)
|
|
19
|
+
- [Registering Tools](#registering-tools)
|
|
20
|
+
- [Handling Tool Calls](#handling-tool-calls)
|
|
21
|
+
- [Best Practices](#best-practices)
|
|
22
|
+
- [Remote SSE and HTTP Streamable MCP servers](#remote-sse-and-http-streamable-mcp-servers)
|
|
23
|
+
- [Error Handling](#error-handling)
|
|
24
|
+
- [Changelog](#changelog)
|
|
25
|
+
- [Demo Plugin](#demo-plugin)
|
|
26
|
+
- [Debugging & Testing](#debugging--testing)
|
|
27
|
+
- [FAQ](#faq)
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Background
|
|
32
|
+
|
|
33
|
+
Angie is a WordPress AI Assistant that can perform almost any task on a WordPress website.
|
|
34
|
+
|
|
35
|
+
Angie is fully extensible, so plugin developers can easily integrate their own features, allowing Angie to use and control them.
|
|
36
|
+
|
|
37
|
+
Angie is built on an MCP-based architecture, enabling you to create custom MCP servers that expose your plugin's capabilities for Angie to access.
|
|
38
|
+
|
|
39
|
+
To learn about MCP:
|
|
40
|
+
- [MCP Specification](https://modelcontextprotocol.io/)
|
|
41
|
+
- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk)
|
|
42
|
+
- [MCP Documentation](https://modelcontextprotocol.io/docs)
|
|
43
|
+
|
|
44
|
+
The SDK was designed specifically to address these issues:
|
|
45
|
+
|
|
46
|
+
1. **Run MCP in the Browser**
|
|
47
|
+
The SDK allows you to run an MCP server as a JavaScript module in the browser, so there is no need for creating a PHP-based MCP server or creating an external SSE or HTTPStreamable-based MCP Server.
|
|
48
|
+
|
|
49
|
+
All logic runs client-side while you can use WP REST or even adminAjax to communicate with your plugin backend.
|
|
50
|
+
|
|
51
|
+
2. **Register MCP with Angie Without an External Server**
|
|
52
|
+
You can register your MCP directly with Angie using the SDK, even if you don't have an external MCP Gateway. Angie discovers your server through the SDK.
|
|
53
|
+
|
|
54
|
+
3. **Communicate with MCP on the Current Screen**
|
|
55
|
+
The SDK enables Angie to communicate with your plugin's MCP directly on the current page, so Angie will be able to _see_ and _act_ on the current user's screen.
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## How It Works
|
|
60
|
+
Angie SDK allows you to use the official TypeScript MCP SDK to write your MCP Server.
|
|
61
|
+
Then with Angie SDK you can register it and let Angie run your MCP server like other MCP Hosts.
|
|
62
|
+
|
|
63
|
+
The SDK covers three main abilities:
|
|
64
|
+
* Import and use the current supported official MCP SDK
|
|
65
|
+
* Register your MCP Server
|
|
66
|
+
* Run your MCP server in the browser
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
```mermaid
|
|
70
|
+
flowchart LR
|
|
71
|
+
subgraph Browser["Angie SDK Flow"]
|
|
72
|
+
WP["Your WordPress Plugin"]
|
|
73
|
+
MCP["Your MCP Server Instance (JS)"]
|
|
74
|
+
SDK["Angie SDK"]
|
|
75
|
+
Angie["Angie (iframe)"]
|
|
76
|
+
WP -- "enqueue script" --> MCP
|
|
77
|
+
MCP -- "register server" --> SDK
|
|
78
|
+
SDK <-- "Browser Transport" --> Angie
|
|
79
|
+
end
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Supported MCP Features
|
|
83
|
+
* Resources
|
|
84
|
+
* Notifications
|
|
85
|
+
* Tools
|
|
86
|
+
* Sampling
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Installation
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
npm install @elementor/angie-sdk
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Quick Start
|
|
99
|
+
|
|
100
|
+
### 1. Create Your MCP Server
|
|
101
|
+
|
|
102
|
+
Create a TypeScript or a Javascript file (e.g., `demo-mcp-server.ts`):
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
import {
|
|
106
|
+
AngieMcpSdk,
|
|
107
|
+
CallToolRequest,
|
|
108
|
+
CallToolRequestSchema,
|
|
109
|
+
ListToolsRequestSchema,
|
|
110
|
+
McpServer,
|
|
111
|
+
} from '@elementor/angie-sdk';
|
|
112
|
+
|
|
113
|
+
// Define the MCP server
|
|
114
|
+
function createSeoMcpServer() {
|
|
115
|
+
const server = new McpServer(
|
|
116
|
+
{ name: 'my-seo-server', version: '1.0.0' },
|
|
117
|
+
{ capabilities: { tools: {} } }
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
// Add your tools, resources, etc.
|
|
121
|
+
server.tool( ... );
|
|
122
|
+
|
|
123
|
+
return server;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Register the server with Angie
|
|
127
|
+
const server = createSeoMcpServer();
|
|
128
|
+
const sdk = new AngieMcpSdk();
|
|
129
|
+
await sdk.registerServer({
|
|
130
|
+
name: 'my-seo-server',
|
|
131
|
+
version: '1.0.0',
|
|
132
|
+
description: 'SEO tools for Angie',
|
|
133
|
+
server,
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## MCP Server Example
|
|
140
|
+
|
|
141
|
+
A typical project structure:
|
|
142
|
+
|
|
143
|
+
```
|
|
144
|
+
your-plugin/
|
|
145
|
+
├── plugin.php # Main WordPress plugin file
|
|
146
|
+
├── dist/
|
|
147
|
+
│ └── demo-mcp-server.js # Bundled MCP server JS
|
|
148
|
+
├── src/
|
|
149
|
+
│ └── demo-mcp-server.ts # MCP server source
|
|
150
|
+
└── ...
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
- **PHP**: Implements REST API endpoints for your tool - if needed.
|
|
154
|
+
- **JS/TS**: Registers tools and handles requests using the SDK.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## Registering Tools
|
|
159
|
+
|
|
160
|
+
Each tool must be registered with:
|
|
161
|
+
- **name**: Unique string identifier
|
|
162
|
+
- **description**: What the tool does and when to use it
|
|
163
|
+
- **inputSchema**: JSON schema describing required/optional parameters
|
|
164
|
+
|
|
165
|
+
Example:
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
169
|
+
tools: [
|
|
170
|
+
{
|
|
171
|
+
name: 'analyze-page-seo',
|
|
172
|
+
description: 'Analyzes the SEO of a page.',
|
|
173
|
+
inputSchema: {
|
|
174
|
+
type: 'object',
|
|
175
|
+
properties: { url: { type: 'string', description: 'Page URL' } },
|
|
176
|
+
required: ['url'],
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
],
|
|
180
|
+
}));
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Handling Tool Calls
|
|
186
|
+
|
|
187
|
+
Implement a handler for `CallToolRequestSchema`:
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
server.setRequestHandler(CallToolRequestSchema, async (request: CallToolRequest) => {
|
|
191
|
+
const { name, arguments: args } = request.params;
|
|
192
|
+
switch (name) {
|
|
193
|
+
case 'analyze-page-seo':
|
|
194
|
+
// Call your backend or perform logic
|
|
195
|
+
const { root, nonce } = window.wpApiSettings;
|
|
196
|
+
const response = await fetch(`${root}my-plugin/v1/analyze-seo`, {
|
|
197
|
+
method: 'POST',
|
|
198
|
+
headers: {
|
|
199
|
+
'X-WP-Nonce': nonce,
|
|
200
|
+
'Content-Type': 'application/json',
|
|
201
|
+
},
|
|
202
|
+
credentials: 'same-origin',
|
|
203
|
+
body: JSON.stringify(args),
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
if (!response.ok) {
|
|
207
|
+
throw new Error(`API request failed: ${response.statusText}`);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const result = await response.json();
|
|
211
|
+
return {
|
|
212
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
213
|
+
};
|
|
214
|
+
// Add more cases as needed
|
|
215
|
+
default:
|
|
216
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
223
|
+
## Best Practices
|
|
224
|
+
|
|
225
|
+
- **Tool Naming**: Use clear, outcome-focused names (e.g., "analyze-page-seo").
|
|
226
|
+
- **Descriptions**: Clearly describe what the tool does, when to use it, and what it returns.
|
|
227
|
+
- **Input Schemas**: Define precise input schemas for each tool, prefer using Zod.
|
|
228
|
+
- **Error Handling**: Return user-friendly errors in natural language and log details for debugging.
|
|
229
|
+
- **Security**: Use nonces for REST API calls and permission checks in your backend.
|
|
230
|
+
- **Versioning**: Angie SDK exports the current supported MCP SDK, prefer to use the integrated MCP SDK to ensure supported MCP version features.
|
|
231
|
+
|
|
232
|
+
---
|
|
233
|
+
|
|
234
|
+
## Security
|
|
235
|
+
|
|
236
|
+
**⚠️ Security Responsibility**: When you create MCP tools that interact with your WordPress backend, you become responsible for the security of those operations. Angie acts as a channel for user actions, so it's your responsibility to implement proper security measures.
|
|
237
|
+
|
|
238
|
+
### Required Security Measures
|
|
239
|
+
|
|
240
|
+
1. **Permission Checks**: Always verify user permissions on your backend endpoints
|
|
241
|
+
2. **Input Validation**: Sanitize and validate all input data
|
|
242
|
+
3. **Capability Checks**: Use WordPress capability checks for specific operations
|
|
243
|
+
|
|
244
|
+
### Example Secure Endpoint
|
|
245
|
+
|
|
246
|
+
```php
|
|
247
|
+
add_action('rest_api_init', function () {
|
|
248
|
+
register_rest_route('my-plugin/v1', '/analyze-seo', [
|
|
249
|
+
'methods' => 'POST',
|
|
250
|
+
'callback' => 'my_analyze_seo_callback',
|
|
251
|
+
'permission_callback' => function () {
|
|
252
|
+
return current_user_can('edit_posts');
|
|
253
|
+
},
|
|
254
|
+
'args' => array(
|
|
255
|
+
'url' => array(
|
|
256
|
+
'validate_callback' => function($param, $request, $key) {
|
|
257
|
+
return filter_var($param, FILTER_VALIDATE_URL);
|
|
258
|
+
},
|
|
259
|
+
'required' => true,
|
|
260
|
+
),
|
|
261
|
+
),
|
|
262
|
+
]);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
## Remote SSE and HTTP Streamable MCP servers
|
|
266
|
+
|
|
267
|
+
For remote servers, let your Angie users add them via Angie MCP Gateway settings.
|
|
268
|
+
|
|
269
|
+
### Supported Remote Server Types
|
|
270
|
+
- **SSE (Server-Sent Events)**: For real-time streaming responses
|
|
271
|
+
- **HTTP Streamable**: For HTTP-based streaming communication
|
|
272
|
+
|
|
273
|
+
### Configuration
|
|
274
|
+
Remote MCP servers can be configured through Angie's settings interface, allowing users to connect to external MCP services without requiring code changes.
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
## Error Handling
|
|
279
|
+
|
|
280
|
+
- Throw errors in handlers to return error responses to the client.
|
|
281
|
+
- Use custom error messages for user-facing errors.
|
|
282
|
+
- Log errors internally as needed.
|
|
283
|
+
|
|
284
|
+
**Example:**
|
|
285
|
+
```typescript
|
|
286
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
287
|
+
try {
|
|
288
|
+
// Your tool implementation
|
|
289
|
+
const result = await performToolAction(req.params);
|
|
290
|
+
return {
|
|
291
|
+
content: [{ type: 'text', text: result }],
|
|
292
|
+
};
|
|
293
|
+
} catch (err) {
|
|
294
|
+
console.error('Tool error:', err);
|
|
295
|
+
throw new Error('User-friendly error message');
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## Changelog
|
|
303
|
+
- **v1.0.0**: Initial release
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## Demo Plugin
|
|
308
|
+
|
|
309
|
+
**For more examples, see the demo plugin and MCP server in the example folder**
|
|
310
|
+
|
|
311
|
+
If you have questions or need help, open an issue or contact the Elementor team!
|
|
312
|
+
|
|
313
|
+
## Debugging & Testing
|
|
314
|
+
|
|
315
|
+
- Use browser console logs to verify server registration and tool calls.
|
|
316
|
+
- Test REST endpoints directly (e.g., with Postman) before wiring up the MCP server.
|
|
317
|
+
- Check Angie's UI for tool discovery and invocation.
|
|
318
|
+
|
|
319
|
+
### Common Debugging Steps
|
|
320
|
+
1. Check browser console for registration errors
|
|
321
|
+
2. Verify tool names match between registration and handler
|
|
322
|
+
3. Test REST API endpoints independently
|
|
323
|
+
4. Ensure proper nonce and permission setup
|
|
324
|
+
|
|
325
|
+
---
|
|
326
|
+
|
|
327
|
+
## License
|
|
328
|
+
|
|
329
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AngieDetectionResult } from './types';
|
|
2
|
+
export declare class AngieDetector {
|
|
3
|
+
private isAngieReady;
|
|
4
|
+
private readyPromise;
|
|
5
|
+
private readyResolve?;
|
|
6
|
+
constructor();
|
|
7
|
+
private handleAngieReady;
|
|
8
|
+
private handleDetectionTimeout;
|
|
9
|
+
isReady(): boolean;
|
|
10
|
+
waitForReady(): Promise<AngieDetectionResult>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { AngieServerConfig, ServerRegistration } from './types';
|
|
2
|
+
export declare class AngieMcpSdk {
|
|
3
|
+
private angieDetector;
|
|
4
|
+
private registrationQueue;
|
|
5
|
+
private clientManager;
|
|
6
|
+
private isInitialized;
|
|
7
|
+
constructor();
|
|
8
|
+
private setupAngieReadyHandler;
|
|
9
|
+
private handleAngieReady;
|
|
10
|
+
private processRegistration;
|
|
11
|
+
registerServer(config: AngieServerConfig): Promise<void>;
|
|
12
|
+
getRegistrations(): ServerRegistration[];
|
|
13
|
+
getPendingRegistrations(): ServerRegistration[];
|
|
14
|
+
isAngieReady(): boolean;
|
|
15
|
+
isReady(): boolean;
|
|
16
|
+
waitForReady(): Promise<void>;
|
|
17
|
+
destroy(): void;
|
|
18
|
+
private setupServerInitHandler;
|
|
19
|
+
private handleServerInitRequest;
|
|
20
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
|
|
2
|
+
import { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Transport implementation that uses the browser's MessageChannel API for communication
|
|
5
|
+
* between different browser contexts (iframes, workers, tabs, windows, etc.).
|
|
6
|
+
*/
|
|
7
|
+
export declare class BrowserContextTransport implements Transport {
|
|
8
|
+
sessionId: string;
|
|
9
|
+
onmessage?: (message: JSONRPCMessage) => void;
|
|
10
|
+
onerror?: (error: Error) => void;
|
|
11
|
+
onclose?: () => void;
|
|
12
|
+
private _port;
|
|
13
|
+
private _started;
|
|
14
|
+
private _closed;
|
|
15
|
+
/**
|
|
16
|
+
* Creates a new BrowserContextTransport using an existing MessagePort.
|
|
17
|
+
*
|
|
18
|
+
* @param { MessagePort } port The MessagePort to use for communication.
|
|
19
|
+
* @param { string } sessionId Optional session ID. If not provided, one will be generated.
|
|
20
|
+
*/
|
|
21
|
+
constructor(port: MessagePort, sessionId?: string);
|
|
22
|
+
/**
|
|
23
|
+
* Internal method to generate a session ID.
|
|
24
|
+
* This is separated so it can be used by static methods.
|
|
25
|
+
*/
|
|
26
|
+
private static generateSessionId;
|
|
27
|
+
/**
|
|
28
|
+
* Starts processing messages on the transport.
|
|
29
|
+
* This starts the underlying MessagePort if it hasn't been started yet.
|
|
30
|
+
*
|
|
31
|
+
* @throws Error if the transport is already started or has been closed.
|
|
32
|
+
*/
|
|
33
|
+
start(): Promise<void>;
|
|
34
|
+
/**
|
|
35
|
+
* Sends a JSON-RPC message over the MessagePort.
|
|
36
|
+
*
|
|
37
|
+
* @param { JSONRPCMessage } message The JSON-RPC message to send.
|
|
38
|
+
* @throws Error if the transport is closed or the message cannot be sent.
|
|
39
|
+
*/
|
|
40
|
+
send(message: JSONRPCMessage): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Closes the MessagePort and marks the transport as closed.
|
|
43
|
+
* This method will call onclose if it's defined.
|
|
44
|
+
*/
|
|
45
|
+
close(): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Generates a simple unique identifier using timestamp and random values.
|
|
48
|
+
* This is not a true UUID but is sufficient for session identification.
|
|
49
|
+
*/
|
|
50
|
+
private generateId;
|
|
51
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e,t,s,a;!function(e){e.POST_MESSAGE="postMessage"}(e||(e={})),function(e){e.SDK_ANGIE_READY_PING="sdk-angie-ready-ping",e.SDK_REQUEST_CLIENT_CREATION="sdk-request-client-creation",e.SDK_REQUEST_INIT_SERVER="sdk-request-init-server"}(t||(t={}));class r{isAngieReady=!1;readyPromise;readyResolve;constructor(){if(this.readyPromise=new Promise((e=>{this.readyResolve=e})),"undefined"==typeof window)return;let e=0;const s=()=>{if(this.isAngieReady||e>=500)return void(!this.isAngieReady&&e>=500&&this.handleDetectionTimeout());const a=new MessageChannel;a.port1.onmessage=e=>{this.handleAngieReady(e.data),a.port1.close(),a.port2.close()};const r={type:t.SDK_ANGIE_READY_PING,timestamp:Date.now()};window.postMessage(r,window.location.origin,[a.port2]),e++,setTimeout(s,500)};s()}handleAngieReady(e){this.isAngieReady=!0;const t={isReady:!0,version:e.version,capabilities:e.capabilities};this.readyResolve&&this.readyResolve(t)}handleDetectionTimeout(){this.readyResolve&&this.readyResolve({isReady:!1}),console.warn("AngieMcpSdk: AngieDetector: Detection timeout - Angie may not be available")}isReady(){return this.isAngieReady}async waitForReady(){return this.readyPromise}}class n{queue=[];isProcessing=!1;add(e){const t={id:this.generateId(e),config:e,timestamp:Date.now(),status:"pending"};return this.queue.push(t),console.log(`RegistrationQueue: Added server "${e.name}" to queue`),t}getAll(){return[...this.queue]}getPending(){return this.queue.filter((e=>"pending"===e.status))}updateStatus(e,t,s){const a=this.queue.find((t=>t.id===e));a&&(a.status=t,s&&(a.error=s),console.log(`RegistrationQueue: Updated server ${e} status to ${t}`))}async processQueue(e){if(this.isProcessing)return void console.log("RegistrationQueue: Already processing queue");this.isProcessing=!0;const t=this.getPending();console.log(`RegistrationQueue: Processing ${t.length} pending registrations`);try{for(const s of t)try{await e(s),this.updateStatus(s.id,"registered")}catch(e){const t=e instanceof Error?e.message:String(e);this.updateStatus(s.id,"failed",t),console.error(`RegistrationQueue: Failed to process registration ${s.id}:`,t)}}finally{this.isProcessing=!1}}clear(){this.queue=[],console.log("RegistrationQueue: Cleared all registrations")}remove(e){const t=this.queue.findIndex((t=>t.id===e));return-1!==t&&(this.queue.splice(t,1),console.log(`RegistrationQueue: Removed registration ${e}`),!0)}generateId(e){return`reg_${e.name}_${e.version}_${Date.now()}`}}class i{async requestClientCreation(s){const{config:a}=s,r={serverId:s.id,serverName:a.name,serverVersion:a.version,description:a.description,transport:e.POST_MESSAGE,capabilities:a.capabilities};return new Promise(((e,s)=>{const a=new MessageChannel,n=setTimeout((()=>{s(new Error("Client creation request timed out after 10000ms"))}),1e4);a.port1.onmessage=t=>{clearTimeout(n),e(t.data)};const i={type:t.SDK_REQUEST_CLIENT_CREATION,payload:r,timestamp:Date.now()};window.postMessage(i,window.location.origin,[a.port2])}))}}!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},e.getValidEnumValues=t=>{const s=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),a={};for(const e of s)a[e]=t[e];return e.objectValues(a)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(const s of e)if(t(s))return s},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(s||(s={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(a={}));const o=s.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),d=e=>{switch(typeof e){case"undefined":return o.undefined;case"string":return o.string;case"number":return Number.isNaN(e)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":return Array.isArray(e)?o.array:null===e?o.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?o.promise:"undefined"!=typeof Map&&e instanceof Map?o.map:"undefined"!=typeof Set&&e instanceof Set?o.set:"undefined"!=typeof Date&&e instanceof Date?o.date:o.object;default:return o.unknown}},c=s.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class u extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},s={_errors:[]},a=e=>{for(const r of e.issues)if("invalid_union"===r.code)r.unionErrors.map(a);else if("invalid_return_type"===r.code)a(r.returnTypeError);else if("invalid_arguments"===r.code)a(r.argumentsError);else if(0===r.path.length)s._errors.push(t(r));else{let e=s,a=0;for(;a<r.path.length;){const s=r.path[a];a===r.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(r))):e[s]=e[s]||{_errors:[]},e=e[s],a++}}};return a(this),s}static assert(e){if(!(e instanceof u))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,s.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const a of this.issues)a.path.length>0?(t[a.path[0]]=t[a.path[0]]||[],t[a.path[0]].push(e(a))):s.push(e(a));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}u.create=e=>new u(e);const l=(e,t)=>{let a;switch(e.code){case c.invalid_type:a=e.received===o.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case c.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,s.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:a=`Unrecognized key(s) in object: ${s.joinValues(e.keys,", ")}`;break;case c.invalid_union:a="Invalid input";break;case c.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${s.joinValues(e.options)}`;break;case c.invalid_enum_value:a=`Invalid enum value. Expected ${s.joinValues(e.options)}, received '${e.received}'`;break;case c.invalid_arguments:a="Invalid function arguments";break;case c.invalid_return_type:a="Invalid function return type";break;case c.invalid_date:a="Invalid date";break;case c.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:s.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case c.too_small:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case c.too_big:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case c.custom:a="Invalid input";break;case c.invalid_intersection_types:a="Intersection results could not be merged";break;case c.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case c.not_finite:a="Number must be finite";break;default:a=t.defaultError,s.assertNever(e)}return{message:a}};let h=l;function p(e,t){const s=h,a=(e=>{const{data:t,path:s,errorMaps:a,issueData:r}=e,n=[...s,...r.path||[]],i={...r,path:n};if(void 0!==r.message)return{...r,path:n,message:r.message};let o="";const d=a.filter((e=>!!e)).slice().reverse();for(const e of d)o=e(i,{data:t,defaultError:o}).message;return{...r,path:n,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===l?void 0:l].filter((e=>!!e))});e.common.issues.push(a)}class m{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const a of t){if("aborted"===a.status)return g;"dirty"===a.status&&e.dirty(),s.push(a.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const e of t){const t=await e.key,a=await e.value;s.push({key:t,value:a})}return m.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const a of t){const{key:t,value:r}=a;if("aborted"===t.status)return g;if("aborted"===r.status)return g;"dirty"===t.status&&e.dirty(),"dirty"===r.status&&e.dirty(),"__proto__"===t.value||void 0===r.value&&!a.alwaysSet||(s[t.value]=r.value)}return{status:e.value,value:s}}}const g=Object.freeze({status:"aborted"}),f=e=>({status:"dirty",value:e}),y=e=>({status:"valid",value:e}),_=e=>"aborted"===e.status,v=e=>"dirty"===e.status,x=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;var b;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(b||(b={}));class w{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const S=(e,t)=>{if(x(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new u(e.common.issues);return this._error=t,this._error}}};function T(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:a,description:r}=e;if(t&&(s||a))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:r}:{errorMap:(t,r)=>{const{message:n}=e;return"invalid_enum_value"===t.code?{message:n??r.defaultError}:void 0===r.data?{message:n??a??r.defaultError}:"invalid_type"!==t.code?{message:r.defaultError}:{message:n??s??r.defaultError}},description:r}}class A{get description(){return this._def.description}_getType(e){return d(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new m,ctx:{common:e.parent.common,data:e.data,parsedType:d(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},a=this._parseSync({data:e,path:s.path,parent:s});return S(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return x(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>x(e)?{value:e.value}:{issues:t.common.issues}))}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:d(e)},a=this._parse({data:e,path:s.path,parent:s}),r=await(k(a)?a:Promise.resolve(a));return S(s,r)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,a)=>{const r=e(t),n=()=>a.addIssue({code:c.custom,...s(t)});return"undefined"!=typeof Promise&&r instanceof Promise?r.then((e=>!!e||(n(),!1))):!!r||(n(),!1)}))}refinement(e,t){return this._refinement(((s,a)=>!!e(s)||(a.addIssue("function"==typeof t?t(s,a):t),!1)))}_refinement(e){return new Te({schema:this,typeName:je.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ae.create(this,this._def)}nullable(){return Ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this)}promise(){return Se.create(this,this._def)}or(e){return ue.create([this,e],this._def)}and(e){return me.create(this,e,this._def)}transform(e){return new Te({...T(this._def),schema:this,typeName:je.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Re({...T(this._def),innerType:this,defaultValue:t,typeName:je.ZodDefault})}brand(){return new Ie({typeName:je.ZodBranded,type:this,...T(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ze({...T(this._def),innerType:this,catchValue:t,typeName:je.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return Ne.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const C=/^c[^\s-]{8,}$/i,R=/^[0-9a-z]+$/,Z=/^[0-9A-HJKMNP-TV-Z]{26}$/i,O=/^[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,I=/^[a-z0-9_-]{21}$/i,E=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,N=/^[-+]?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)?)??$/,j=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let P;const $=/^(?:(?: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])$/,M=/^(?:(?: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])$/,D=/^(([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]))$/,F=/^(([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])$/,q=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,z=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,L="((\\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])))",V=new RegExp(`^${L}$`);function U(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function K(e){let t=`${L}T${U(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,new RegExp(`^${t}$`)}function Q(e,t){if(!E.test(e))return!1;try{const[s]=e.split("."),a=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),r=JSON.parse(atob(a));return!("object"!=typeof r||null===r||"typ"in r&&"JWT"!==r?.typ||!r.alg||t&&r.alg!==t)}catch{return!1}}function B(e,t){return!("v4"!==t&&t||!M.test(e))||!("v6"!==t&&t||!F.test(e))}class W extends A{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==o.string){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.string,received:t.parsedType}),g}const t=new m;let a;for(const i of this._def.checks)if("min"===i.kind)e.data.length<i.value&&(a=this._getOrReturnCtx(e,a),p(a,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("max"===i.kind)e.data.length>i.value&&(a=this._getOrReturnCtx(e,a),p(a,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),t.dirty());else if("length"===i.kind){const s=e.data.length>i.value,r=e.data.length<i.value;(s||r)&&(a=this._getOrReturnCtx(e,a),s?p(a,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):r&&p(a,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),t.dirty())}else if("email"===i.kind)j.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"email",code:c.invalid_string,message:i.message}),t.dirty());else if("emoji"===i.kind)P||(P=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),P.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"emoji",code:c.invalid_string,message:i.message}),t.dirty());else if("uuid"===i.kind)O.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"uuid",code:c.invalid_string,message:i.message}),t.dirty());else if("nanoid"===i.kind)I.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"nanoid",code:c.invalid_string,message:i.message}),t.dirty());else if("cuid"===i.kind)C.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"cuid",code:c.invalid_string,message:i.message}),t.dirty());else if("cuid2"===i.kind)R.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"cuid2",code:c.invalid_string,message:i.message}),t.dirty());else if("ulid"===i.kind)Z.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"ulid",code:c.invalid_string,message:i.message}),t.dirty());else if("url"===i.kind)try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),p(a,{validation:"url",code:c.invalid_string,message:i.message}),t.dirty()}else"regex"===i.kind?(i.regex.lastIndex=0,i.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"regex",code:c.invalid_string,message:i.message}),t.dirty())):"trim"===i.kind?e.data=e.data.trim():"includes"===i.kind?e.data.includes(i.value,i.position)||(a=this._getOrReturnCtx(e,a),p(a,{code:c.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),t.dirty()):"toLowerCase"===i.kind?e.data=e.data.toLowerCase():"toUpperCase"===i.kind?e.data=e.data.toUpperCase():"startsWith"===i.kind?e.data.startsWith(i.value)||(a=this._getOrReturnCtx(e,a),p(a,{code:c.invalid_string,validation:{startsWith:i.value},message:i.message}),t.dirty()):"endsWith"===i.kind?e.data.endsWith(i.value)||(a=this._getOrReturnCtx(e,a),p(a,{code:c.invalid_string,validation:{endsWith:i.value},message:i.message}),t.dirty()):"datetime"===i.kind?K(i).test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{code:c.invalid_string,validation:"datetime",message:i.message}),t.dirty()):"date"===i.kind?V.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{code:c.invalid_string,validation:"date",message:i.message}),t.dirty()):"time"===i.kind?new RegExp(`^${U(i)}$`).test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{code:c.invalid_string,validation:"time",message:i.message}),t.dirty()):"duration"===i.kind?N.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"duration",code:c.invalid_string,message:i.message}),t.dirty()):"ip"===i.kind?(r=e.data,("v4"!==(n=i.version)&&n||!$.test(r))&&("v6"!==n&&n||!D.test(r))&&(a=this._getOrReturnCtx(e,a),p(a,{validation:"ip",code:c.invalid_string,message:i.message}),t.dirty())):"jwt"===i.kind?Q(e.data,i.alg)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"jwt",code:c.invalid_string,message:i.message}),t.dirty()):"cidr"===i.kind?B(e.data,i.version)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"cidr",code:c.invalid_string,message:i.message}),t.dirty()):"base64"===i.kind?q.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"base64",code:c.invalid_string,message:i.message}),t.dirty()):"base64url"===i.kind?z.test(e.data)||(a=this._getOrReturnCtx(e,a),p(a,{validation:"base64url",code:c.invalid_string,message:i.message}),t.dirty()):s.assertNever(i);var r,n;return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement((t=>e.test(t)),{validation:t,code:c.invalid_string,...b.errToObj(s)})}_addCheck(e){return new W({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...b.errToObj(e)})}url(e){return this._addCheck({kind:"url",...b.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...b.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...b.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...b.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...b.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...b.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...b.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...b.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...b.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...b.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...b.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...b.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...b.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...b.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...b.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...b.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...b.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...b.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...b.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...b.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...b.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...b.errToObj(t)})}nonempty(e){return this.min(1,b.errToObj(e))}trim(){return new W({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new W({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new W({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function H(e,t){const s=(e.toString().split(".")[1]||"").length,a=(t.toString().split(".")[1]||"").length,r=s>a?s:a;return Number.parseInt(e.toFixed(r).replace(".",""))%Number.parseInt(t.toFixed(r).replace(".",""))/10**r}W.create=e=>new W({checks:[],typeName:je.ZodString,coerce:e?.coerce??!1,...T(e)});class G extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==o.number){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.number,received:t.parsedType}),g}let t;const a=new m;for(const r of this._def.checks)"int"===r.kind?s.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:c.invalid_type,expected:"integer",received:"float",message:r.message}),a.dirty()):"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),a.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),a.dirty()):"multipleOf"===r.kind?0!==H(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.not_multiple_of,multipleOf:r.value,message:r.message}),a.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),p(t,{code:c.not_finite,message:r.message}),a.dirty()):s.assertNever(r);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,s,a){return new G({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:b.toString(a)}]})}_addCheck(e){return new G({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:b.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:b.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&s.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}G.create=e=>new G({checks:[],typeName:je.ZodNumber,coerce:e?.coerce||!1,...T(e)});class J extends A{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==o.bigint)return this._getInvalidInput(e);let t;const a=new m;for(const r of this._def.checks)"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),a.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),a.dirty()):"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),p(t,{code:c.not_multiple_of,multipleOf:r.value,message:r.message}),a.dirty()):s.assertNever(r);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.bigint,received:t.parsedType}),g}gte(e,t){return this.setLimit("min",e,!0,b.toString(t))}gt(e,t){return this.setLimit("min",e,!1,b.toString(t))}lte(e,t){return this.setLimit("max",e,!0,b.toString(t))}lt(e,t){return this.setLimit("max",e,!1,b.toString(t))}setLimit(e,t,s,a){return new J({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:b.toString(a)}]})}_addCheck(e){return new J({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:b.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}J.create=e=>new J({checks:[],typeName:je.ZodBigInt,coerce:e?.coerce??!1,...T(e)});class Y extends A{_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==o.boolean){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.boolean,received:t.parsedType}),g}return y(e.data)}}Y.create=e=>new Y({typeName:je.ZodBoolean,coerce:e?.coerce||!1,...T(e)});class X extends A{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==o.date){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.date,received:t.parsedType}),g}if(Number.isNaN(e.data.getTime()))return p(this._getOrReturnCtx(e),{code:c.invalid_date}),g;const t=new m;let a;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(a=this._getOrReturnCtx(e,a),p(a,{code:c.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(a=this._getOrReturnCtx(e,a),p(a,{code:c.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):s.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new X({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:b.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:b.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}X.create=e=>new X({checks:[],coerce:e?.coerce||!1,typeName:je.ZodDate,...T(e)});class ee extends A{_parse(e){if(this._getType(e)!==o.symbol){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.symbol,received:t.parsedType}),g}return y(e.data)}}ee.create=e=>new ee({typeName:je.ZodSymbol,...T(e)});class te extends A{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.undefined,received:t.parsedType}),g}return y(e.data)}}te.create=e=>new te({typeName:je.ZodUndefined,...T(e)});class se extends A{_parse(e){if(this._getType(e)!==o.null){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.null,received:t.parsedType}),g}return y(e.data)}}se.create=e=>new se({typeName:je.ZodNull,...T(e)});class ae extends A{constructor(){super(...arguments),this._any=!0}_parse(e){return y(e.data)}}ae.create=e=>new ae({typeName:je.ZodAny,...T(e)});class re extends A{constructor(){super(...arguments),this._unknown=!0}_parse(e){return y(e.data)}}re.create=e=>new re({typeName:je.ZodUnknown,...T(e)});class ne extends A{_parse(e){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.never,received:t.parsedType}),g}}ne.create=e=>new ne({typeName:je.ZodNever,...T(e)});class ie extends A{_parse(e){if(this._getType(e)!==o.undefined){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.void,received:t.parsedType}),g}return y(e.data)}}ie.create=e=>new ie({typeName:je.ZodVoid,...T(e)});class oe extends A{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==o.array)return p(t,{code:c.invalid_type,expected:o.array,received:t.parsedType}),g;if(null!==a.exactLength){const e=t.data.length>a.exactLength.value,r=t.data.length<a.exactLength.value;(e||r)&&(p(t,{code:e?c.too_big:c.too_small,minimum:r?a.exactLength.value:void 0,maximum:e?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(null!==a.minLength&&t.data.length<a.minLength.value&&(p(t,{code:c.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),null!==a.maxLength&&t.data.length>a.maxLength.value&&(p(t,{code:c.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map(((e,s)=>a.type._parseAsync(new w(t,e,t.path,s))))).then((e=>m.mergeArray(s,e)));const r=[...t.data].map(((e,s)=>a.type._parseSync(new w(t,e,t.path,s))));return m.mergeArray(s,r)}get element(){return this._def.type}min(e,t){return new oe({...this._def,minLength:{value:e,message:b.toString(t)}})}max(e,t){return new oe({...this._def,maxLength:{value:e,message:b.toString(t)}})}length(e,t){return new oe({...this._def,exactLength:{value:e,message:b.toString(t)}})}nonempty(e){return this.min(1,e)}}function de(e){if(e instanceof ce){const t={};for(const s in e.shape){const a=e.shape[s];t[s]=Ae.create(de(a))}return new ce({...e._def,shape:()=>t})}return e instanceof oe?new oe({...e._def,type:de(e.element)}):e instanceof Ae?Ae.create(de(e.unwrap())):e instanceof Ce?Ce.create(de(e.unwrap())):e instanceof ge?ge.create(e.items.map((e=>de(e)))):e}oe.create=(e,t)=>new oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:je.ZodArray,...T(t)});class ce extends A{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=s.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==o.object){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.object,received:t.parsedType}),g}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:r}=this._getCached(),n=[];if(!(this._def.catchall instanceof ne&&"strip"===this._def.unknownKeys))for(const e in s.data)r.includes(e)||n.push(e);const i=[];for(const e of r){const t=a[e],r=s.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new w(s,r,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof ne){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of n)i.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)n.length>0&&(p(s,{code:c.unrecognized_keys,keys:n}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of n){const a=s.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new w(s,a,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of i){const s=await t.key,a=await t.value;e.push({key:s,value:a,alwaysSet:t.alwaysSet})}return e})).then((e=>m.mergeObjectSync(t,e))):m.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return b.errToObj,new ce({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,s)=>{const a=this._def.errorMap?.(t,s).message??s.defaultError;return"unrecognized_keys"===t.code?{message:b.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new ce({...this._def,unknownKeys:"strip"})}passthrough(){return new ce({...this._def,unknownKeys:"passthrough"})}extend(e){return new ce({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ce({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:je.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ce({...this._def,catchall:e})}pick(e){const t={};for(const a of s.objectKeys(e))e[a]&&this.shape[a]&&(t[a]=this.shape[a]);return new ce({...this._def,shape:()=>t})}omit(e){const t={};for(const a of s.objectKeys(this.shape))e[a]||(t[a]=this.shape[a]);return new ce({...this._def,shape:()=>t})}deepPartial(){return de(this)}partial(e){const t={};for(const a of s.objectKeys(this.shape)){const s=this.shape[a];e&&!e[a]?t[a]=s:t[a]=s.optional()}return new ce({...this._def,shape:()=>t})}required(e){const t={};for(const a of s.objectKeys(this.shape))if(e&&!e[a])t[a]=this.shape[a];else{let e=this.shape[a];for(;e instanceof Ae;)e=e._def.innerType;t[a]=e}return new ce({...this._def,shape:()=>t})}keyof(){return ke(s.objectKeys(this.shape))}}ce.create=(e,t)=>new ce({shape:()=>e,unknownKeys:"strip",catchall:ne.create(),typeName:je.ZodObject,...T(t)}),ce.strictCreate=(e,t)=>new ce({shape:()=>e,unknownKeys:"strict",catchall:ne.create(),typeName:je.ZodObject,...T(t)}),ce.lazycreate=(e,t)=>new ce({shape:e,unknownKeys:"strip",catchall:ne.create(),typeName:je.ZodObject,...T(t)});class ue extends A{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map((async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map((e=>new u(e.ctx.common.issues)));return p(t,{code:c.invalid_union,unionErrors:s}),g}));{let e;const a=[];for(const r of s){const s={...t,common:{...t.common,issues:[]},parent:null},n=r._parseSync({data:t.data,path:t.path,parent:s});if("valid"===n.status)return n;"dirty"!==n.status||e||(e={result:n,ctx:s}),s.common.issues.length&&a.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const r=a.map((e=>new u(e)));return p(t,{code:c.invalid_union,unionErrors:r}),g}}get options(){return this._def.options}}ue.create=(e,t)=>new ue({options:e,typeName:je.ZodUnion,...T(t)});const le=e=>e instanceof ve?le(e.schema):e instanceof Te?le(e.innerType()):e instanceof xe?[e.value]:e instanceof be?e.options:e instanceof we?s.objectValues(e.enum):e instanceof Re?le(e._def.innerType):e instanceof te?[void 0]:e instanceof se?[null]:e instanceof Ae?[void 0,...le(e.unwrap())]:e instanceof Ce?[null,...le(e.unwrap())]:e instanceof Ie||e instanceof Ne?le(e.unwrap()):e instanceof Ze?le(e._def.innerType):[];class he extends A{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.object)return p(t,{code:c.invalid_type,expected:o.object,received:t.parsedType}),g;const s=this.discriminator,a=t.data[s],r=this.optionsMap.get(a);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const a=new Map;for(const s of t){const t=le(s.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of t){if(a.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);a.set(r,s)}}return new he({typeName:je.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...T(s)})}}function pe(e,t){const a=d(e),r=d(t);if(e===t)return{valid:!0,data:e};if(a===o.object&&r===o.object){const a=s.objectKeys(t),r=s.objectKeys(e).filter((e=>-1!==a.indexOf(e))),n={...e,...t};for(const s of r){const a=pe(e[s],t[s]);if(!a.valid)return{valid:!1};n[s]=a.data}return{valid:!0,data:n}}if(a===o.array&&r===o.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let a=0;a<e.length;a++){const r=pe(e[a],t[a]);if(!r.valid)return{valid:!1};s.push(r.data)}return{valid:!0,data:s}}return a===o.date&&r===o.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class me extends A{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(e,a)=>{if(_(e)||_(a))return g;const r=pe(e.value,a.value);return r.valid?((v(e)||v(a))&&t.dirty(),{status:t.value,value:r.data}):(p(s,{code:c.invalid_intersection_types}),g)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then((([e,t])=>a(e,t))):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}me.create=(e,t,s)=>new me({left:e,right:t,typeName:je.ZodIntersection,...T(s)});class ge extends A{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==o.array)return p(s,{code:c.invalid_type,expected:o.array,received:s.parsedType}),g;if(s.data.length<this._def.items.length)return p(s,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&s.data.length>this._def.items.length&&(p(s,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map(((e,t)=>{const a=this._def.items[t]||this._def.rest;return a?a._parse(new w(s,e,s.path,t)):null})).filter((e=>!!e));return s.common.async?Promise.all(a).then((e=>m.mergeArray(t,e))):m.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new ge({...this._def,rest:e})}}ge.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ge({items:e,typeName:je.ZodTuple,rest:null,...T(t)})};class fe extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==o.object)return p(s,{code:c.invalid_type,expected:o.object,received:s.parsedType}),g;const a=[],r=this._def.keyType,n=this._def.valueType;for(const e in s.data)a.push({key:r._parse(new w(s,e,s.path,e)),value:n._parse(new w(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?m.mergeObjectAsync(t,a):m.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,s){return new fe(t instanceof A?{keyType:e,valueType:t,typeName:je.ZodRecord,...T(s)}:{keyType:W.create(),valueType:e,typeName:je.ZodRecord,...T(t)})}}class ye extends A{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==o.map)return p(s,{code:c.invalid_type,expected:o.map,received:s.parsedType}),g;const a=this._def.keyType,r=this._def.valueType,n=[...s.data.entries()].map((([e,t],n)=>({key:a._parse(new w(s,e,s.path,[n,"key"])),value:r._parse(new w(s,t,s.path,[n,"value"]))})));if(s.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const s of n){const a=await s.key,r=await s.value;if("aborted"===a.status||"aborted"===r.status)return g;"dirty"!==a.status&&"dirty"!==r.status||t.dirty(),e.set(a.value,r.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const s of n){const a=s.key,r=s.value;if("aborted"===a.status||"aborted"===r.status)return g;"dirty"!==a.status&&"dirty"!==r.status||t.dirty(),e.set(a.value,r.value)}return{status:t.value,value:e}}}}ye.create=(e,t,s)=>new ye({valueType:t,keyType:e,typeName:je.ZodMap,...T(s)});class _e extends A{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==o.set)return p(s,{code:c.invalid_type,expected:o.set,received:s.parsedType}),g;const a=this._def;null!==a.minSize&&s.data.size<a.minSize.value&&(p(s,{code:c.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),null!==a.maxSize&&s.data.size>a.maxSize.value&&(p(s,{code:c.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const r=this._def.valueType;function n(e){const s=new Set;for(const a of e){if("aborted"===a.status)return g;"dirty"===a.status&&t.dirty(),s.add(a.value)}return{status:t.value,value:s}}const i=[...s.data.values()].map(((e,t)=>r._parse(new w(s,e,s.path,t))));return s.common.async?Promise.all(i).then((e=>n(e))):n(i)}min(e,t){return new _e({...this._def,minSize:{value:e,message:b.toString(t)}})}max(e,t){return new _e({...this._def,maxSize:{value:e,message:b.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}_e.create=(e,t)=>new _e({valueType:e,minSize:null,maxSize:null,typeName:je.ZodSet,...T(t)});class ve extends A{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ve.create=(e,t)=>new ve({getter:e,typeName:je.ZodLazy,...T(t)});class xe extends A{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}}function ke(e,t){return new be({values:e,typeName:je.ZodEnum,...T(t)})}xe.create=(e,t)=>new xe({value:e,typeName:je.ZodLiteral,...T(t)});class be extends A{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),a=this._def.values;return p(t,{expected:s.joinValues(a),received:t.parsedType,code:c.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return p(t,{received:t.data,code:c.invalid_enum_value,options:s}),g}return y(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return be.create(e,{...this._def,...t})}exclude(e,t=this._def){return be.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}be.create=ke;class we extends A{_parse(e){const t=s.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==o.string&&a.parsedType!==o.number){const e=s.objectValues(t);return p(a,{expected:s.joinValues(e),received:a.parsedType,code:c.invalid_type}),g}if(this._cache||(this._cache=new Set(s.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=s.objectValues(t);return p(a,{received:a.data,code:c.invalid_enum_value,options:e}),g}return y(e.data)}get enum(){return this._def.values}}we.create=(e,t)=>new we({values:e,typeName:je.ZodNativeEnum,...T(t)});class Se extends A{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==o.promise&&!1===t.common.async)return p(t,{code:c.invalid_type,expected:o.promise,received:t.parsedType}),g;const s=t.parsedType===o.promise?t.data:Promise.resolve(t.data);return y(s.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}Se.create=(e,t)=>new Se({type:e,typeName:je.ZodPromise,...T(t)});class Te extends A{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===je.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:a}=this._processInputParams(e),r=this._def.effect||null,n={addIssue:e=>{p(a,e),e.fatal?t.abort():t.dirty()},get path(){return a.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===r.type){const e=r.transform(a.data,n);if(a.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return g;const s=await this._def.schema._parseAsync({data:e,path:a.path,parent:a});return"aborted"===s.status?g:"dirty"===s.status||"dirty"===t.value?f(s.value):s}));{if("aborted"===t.value)return g;const s=this._def.schema._parseSync({data:e,path:a.path,parent:a});return"aborted"===s.status?g:"dirty"===s.status||"dirty"===t.value?f(s.value):s}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,n);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===a.common.async){const s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===s.status?g:("dirty"===s.status&&t.dirty(),e(s.value),{status:t.value,value:s.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((s=>"aborted"===s.status?g:("dirty"===s.status&&t.dirty(),e(s.value).then((()=>({status:t.value,value:s.value}))))))}if("transform"===r.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!x(e))return g;const s=r.transform(e.value,n);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:s}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((e=>x(e)?Promise.resolve(r.transform(e.value,n)).then((e=>({status:t.value,value:e}))):g))}s.assertNever(r)}}Te.create=(e,t,s)=>new Te({schema:e,typeName:je.ZodEffects,effect:t,...T(s)}),Te.createWithPreprocess=(e,t,s)=>new Te({schema:t,effect:{type:"preprocess",transform:e},typeName:je.ZodEffects,...T(s)});class Ae extends A{_parse(e){return this._getType(e)===o.undefined?y(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ae.create=(e,t)=>new Ae({innerType:e,typeName:je.ZodOptional,...T(t)});class Ce extends A{_parse(e){return this._getType(e)===o.null?y(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:je.ZodNullable,...T(t)});class Re extends A{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===o.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:je.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...T(t)});class Ze extends A{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return k(a)?a.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new u(s.common.issues)},input:s.data})}))):{status:"valid",value:"valid"===a.status?a.value:this._def.catchValue({get error(){return new u(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ze.create=(e,t)=>new Ze({innerType:e,typeName:je.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...T(t)});class Oe extends A{_parse(e){if(this._getType(e)!==o.nan){const t=this._getOrReturnCtx(e);return p(t,{code:c.invalid_type,expected:o.nan,received:t.parsedType}),g}return{status:"valid",value:e.data}}}Oe.create=e=>new Oe({typeName:je.ZodNaN,...T(e)}),Symbol("zod_brand");class Ie extends A{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ee extends A{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),f(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?g:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(e,t){return new Ee({in:e,out:t,typeName:je.ZodPipeline})}}class Ne extends A{_parse(e){const t=this._def.innerType._parse(e),s=e=>(x(e)&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then((e=>s(e))):s(t)}unwrap(){return this._def.innerType}}var je;Ne.create=(e,t)=>new Ne({innerType:e,typeName:je.ZodReadonly,...T(t)}),ce.lazycreate,function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(je||(je={}));const Pe=W.create,$e=G.create,Me=(Oe.create,J.create,Y.create),De=(X.create,ee.create,te.create,se.create,ae.create,re.create),Fe=(ne.create,ie.create,oe.create),qe=ce.create,ze=(ce.strictCreate,ue.create),Le=he.create,Ve=(me.create,ge.create,fe.create),Ue=(ye.create,_e.create,ve.create,xe.create),Ke=be.create,Qe=(we.create,Se.create,Te.create,Ae.create),Be=(Ce.create,Te.createWithPreprocess,Ee.create,"2.0"),We=ze([Pe(),$e().int()]),He=Pe(),Ge=qe({progressToken:Qe(We)}).passthrough(),Je=qe({_meta:Qe(Ge)}).passthrough(),Ye=qe({method:Pe(),params:Qe(Je)}),Xe=qe({_meta:Qe(qe({}).passthrough())}).passthrough(),et=qe({method:Pe(),params:Qe(Xe)}),tt=qe({_meta:Qe(qe({}).passthrough())}).passthrough(),st=ze([Pe(),$e().int()]),at=qe({jsonrpc:Ue(Be),id:st}).merge(Ye).strict(),rt=qe({jsonrpc:Ue(Be)}).merge(et).strict(),nt=qe({jsonrpc:Ue(Be),id:st,result:tt}).strict();var it;!function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(it||(it={}));const ot=ze([at,rt,nt,qe({jsonrpc:Ue(Be),id:st,error:qe({code:$e().int(),message:Pe(),data:Qe(De())})}).strict()]),dt=tt.strict(),ct=et.extend({method:Ue("notifications/cancelled"),params:Xe.extend({requestId:st,reason:Pe().optional()})}),ut=qe({name:Pe(),title:Qe(Pe())}).passthrough(),lt=ut.extend({version:Pe()}),ht=qe({experimental:Qe(qe({}).passthrough()),sampling:Qe(qe({}).passthrough()),elicitation:Qe(qe({}).passthrough()),roots:Qe(qe({listChanged:Qe(Me())}).passthrough())}).passthrough(),pt=Ye.extend({method:Ue("initialize"),params:Je.extend({protocolVersion:Pe(),capabilities:ht,clientInfo:lt})}),mt=qe({experimental:Qe(qe({}).passthrough()),logging:Qe(qe({}).passthrough()),completions:Qe(qe({}).passthrough()),prompts:Qe(qe({listChanged:Qe(Me())}).passthrough()),resources:Qe(qe({subscribe:Qe(Me()),listChanged:Qe(Me())}).passthrough()),tools:Qe(qe({listChanged:Qe(Me())}).passthrough())}).passthrough(),gt=tt.extend({protocolVersion:Pe(),capabilities:mt,serverInfo:lt,instructions:Qe(Pe())}),ft=et.extend({method:Ue("notifications/initialized")}),yt=Ye.extend({method:Ue("ping")}),_t=qe({progress:$e(),total:Qe($e()),message:Qe(Pe())}).passthrough(),vt=et.extend({method:Ue("notifications/progress"),params:Xe.merge(_t).extend({progressToken:We})}),xt=Ye.extend({params:Je.extend({cursor:Qe(He)}).optional()}),kt=tt.extend({nextCursor:Qe(He)}),bt=qe({uri:Pe(),mimeType:Qe(Pe()),_meta:Qe(qe({}).passthrough())}).passthrough(),wt=bt.extend({text:Pe()}),St=bt.extend({blob:Pe().base64()}),Tt=ut.extend({uri:Pe(),description:Qe(Pe()),mimeType:Qe(Pe()),_meta:Qe(qe({}).passthrough())}),At=ut.extend({uriTemplate:Pe(),description:Qe(Pe()),mimeType:Qe(Pe()),_meta:Qe(qe({}).passthrough())}),Ct=xt.extend({method:Ue("resources/list")}),Rt=kt.extend({resources:Fe(Tt)}),Zt=xt.extend({method:Ue("resources/templates/list")}),Ot=kt.extend({resourceTemplates:Fe(At)}),It=Ye.extend({method:Ue("resources/read"),params:Je.extend({uri:Pe()})}),Et=tt.extend({contents:Fe(ze([wt,St]))}),Nt=et.extend({method:Ue("notifications/resources/list_changed")}),jt=Ye.extend({method:Ue("resources/subscribe"),params:Je.extend({uri:Pe()})}),Pt=Ye.extend({method:Ue("resources/unsubscribe"),params:Je.extend({uri:Pe()})}),$t=et.extend({method:Ue("notifications/resources/updated"),params:Xe.extend({uri:Pe()})}),Mt=qe({name:Pe(),description:Qe(Pe()),required:Qe(Me())}).passthrough(),Dt=ut.extend({description:Qe(Pe()),arguments:Qe(Fe(Mt)),_meta:Qe(qe({}).passthrough())}),Ft=xt.extend({method:Ue("prompts/list")}),qt=kt.extend({prompts:Fe(Dt)}),zt=Ye.extend({method:Ue("prompts/get"),params:Je.extend({name:Pe(),arguments:Qe(Ve(Pe()))})}),Lt=qe({type:Ue("text"),text:Pe(),_meta:Qe(qe({}).passthrough())}).passthrough(),Vt=qe({type:Ue("image"),data:Pe().base64(),mimeType:Pe(),_meta:Qe(qe({}).passthrough())}).passthrough(),Ut=qe({type:Ue("audio"),data:Pe().base64(),mimeType:Pe(),_meta:Qe(qe({}).passthrough())}).passthrough(),Kt=qe({type:Ue("resource"),resource:ze([wt,St]),_meta:Qe(qe({}).passthrough())}).passthrough(),Qt=ze([Lt,Vt,Ut,Tt.extend({type:Ue("resource_link")}),Kt]),Bt=qe({role:Ke(["user","assistant"]),content:Qt}).passthrough(),Wt=tt.extend({description:Qe(Pe()),messages:Fe(Bt)}),Ht=et.extend({method:Ue("notifications/prompts/list_changed")}),Gt=qe({title:Qe(Pe()),readOnlyHint:Qe(Me()),destructiveHint:Qe(Me()),idempotentHint:Qe(Me()),openWorldHint:Qe(Me())}).passthrough(),Jt=ut.extend({description:Qe(Pe()),inputSchema:qe({type:Ue("object"),properties:Qe(qe({}).passthrough()),required:Qe(Fe(Pe()))}).passthrough(),outputSchema:Qe(qe({type:Ue("object"),properties:Qe(qe({}).passthrough()),required:Qe(Fe(Pe()))}).passthrough()),annotations:Qe(Gt),_meta:Qe(qe({}).passthrough())}),Yt=xt.extend({method:Ue("tools/list")}),Xt=kt.extend({tools:Fe(Jt)}),es=tt.extend({content:Fe(Qt).default([]),structuredContent:qe({}).passthrough().optional(),isError:Qe(Me())}),ts=(es.or(tt.extend({toolResult:De()})),Ye.extend({method:Ue("tools/call"),params:Je.extend({name:Pe(),arguments:Qe(Ve(De()))})})),ss=et.extend({method:Ue("notifications/tools/list_changed")}),as=Ke(["debug","info","notice","warning","error","critical","alert","emergency"]),rs=Ye.extend({method:Ue("logging/setLevel"),params:Je.extend({level:as})}),ns=et.extend({method:Ue("notifications/message"),params:Xe.extend({level:as,logger:Qe(Pe()),data:De()})}),is=qe({name:Pe().optional()}).passthrough(),os=qe({hints:Qe(Fe(is)),costPriority:Qe($e().min(0).max(1)),speedPriority:Qe($e().min(0).max(1)),intelligencePriority:Qe($e().min(0).max(1))}).passthrough(),ds=qe({role:Ke(["user","assistant"]),content:ze([Lt,Vt,Ut])}).passthrough(),cs=Ye.extend({method:Ue("sampling/createMessage"),params:Je.extend({messages:Fe(ds),systemPrompt:Qe(Pe()),includeContext:Qe(Ke(["none","thisServer","allServers"])),temperature:Qe($e()),maxTokens:$e().int(),stopSequences:Qe(Fe(Pe())),metadata:Qe(qe({}).passthrough()),modelPreferences:Qe(os)})}),us=tt.extend({model:Pe(),stopReason:Qe(Ke(["endTurn","stopSequence","maxTokens"]).or(Pe())),role:Ke(["user","assistant"]),content:Le("type",[Lt,Vt,Ut])}),ls=ze([qe({type:Ue("boolean"),title:Qe(Pe()),description:Qe(Pe()),default:Qe(Me())}).passthrough(),qe({type:Ue("string"),title:Qe(Pe()),description:Qe(Pe()),minLength:Qe($e()),maxLength:Qe($e()),format:Qe(Ke(["email","uri","date","date-time"]))}).passthrough(),qe({type:Ke(["number","integer"]),title:Qe(Pe()),description:Qe(Pe()),minimum:Qe($e()),maximum:Qe($e())}).passthrough(),qe({type:Ue("string"),title:Qe(Pe()),description:Qe(Pe()),enum:Fe(Pe()),enumNames:Qe(Fe(Pe()))}).passthrough()]),hs=Ye.extend({method:Ue("elicitation/create"),params:Je.extend({message:Pe(),requestedSchema:qe({type:Ue("object"),properties:Ve(Pe(),ls),required:Qe(Fe(Pe()))}).passthrough()})}),ps=tt.extend({action:Ke(["accept","reject","cancel"]),content:Qe(Ve(Pe(),De()))}),ms=qe({type:Ue("ref/resource"),uri:Pe()}).passthrough(),gs=qe({type:Ue("ref/prompt"),name:Pe()}).passthrough(),fs=Ye.extend({method:Ue("completion/complete"),params:Je.extend({ref:ze([gs,ms]),argument:qe({name:Pe(),value:Pe()}).passthrough(),context:Qe(qe({arguments:Qe(Ve(Pe(),Pe()))}))})}),ys=tt.extend({completion:qe({values:Fe(Pe()).max(100),total:Qe($e().int()),hasMore:Qe(Me())}).passthrough()}),_s=qe({uri:Pe().startsWith("file://"),name:Qe(Pe()),_meta:Qe(qe({}).passthrough())}).passthrough(),vs=Ye.extend({method:Ue("roots/list")}),xs=tt.extend({roots:Fe(_s)}),ks=et.extend({method:Ue("notifications/roots/list_changed")});ze([yt,pt,fs,rs,zt,Ft,Ct,Zt,It,jt,Pt,ts,Yt]),ze([ct,vt,ft,ks]),ze([dt,us,ps,xs]),ze([yt,cs,hs,vs]),ze([ct,vt,ns,$t,Nt,ss,Ht]),ze([dt,gt,ys,Wt,qt,Rt,Ot,Et,es,Xt]),Error;class bs{sessionId;onmessage;onerror;onclose;_port;_started=!1;_closed=!1;constructor(e,t){if(!e)throw new Error("MessagePort is required");this._port=e,this.sessionId=t||this.generateId(),this._port.onmessage=e=>{try{const t=ot.parse(e.data);this.onmessage?.(t)}catch(e){const t=new Error(`Failed to parse message: ${e}`);this.onerror?.(t)}},this._port.onmessageerror=e=>{const t=new Error(`MessagePort error: ${JSON.stringify(e)}`);this.onerror?.(t)}}static generateSessionId(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).substring(2,10)}`}async start(){if(this._started)throw new Error("BrowserContextTransport already started! If using Client or Server class, note that connect() calls start() automatically.");if(this._closed)throw new Error("Cannot start a closed BrowserContextTransport");this._started=!0,this._port.start()}async send(e){if(this._closed)throw new Error("Cannot send on a closed BrowserContextTransport");return new Promise(((t,s)=>{try{this._port.postMessage(e),t()}catch(e){const t=e instanceof Error?e:new Error(String(e));this.onerror?.(t),s(t)}}))}async close(){this._closed||(this._closed=!0,this._port.close(),this.onclose?.())}generateId(){return bs.generateSessionId()}}class ws{angieDetector;registrationQueue;clientManager;isInitialized=!1;constructor(){this.angieDetector=new r,this.registrationQueue=new n,this.clientManager=new i,this.setupAngieReadyHandler(),this.setupServerInitHandler()}setupAngieReadyHandler(){this.angieDetector.waitForReady().then((e=>{e.isReady?this.handleAngieReady():console.warn("AngieMcpSdk: Angie not detected - servers will remain queued")})).catch((e=>{console.error("AngieMcpSdk: Error waiting for Angie:",e)}))}async handleAngieReady(){console.log("AngieMcpSdk: Angie is ready, processing queued registrations");try{await this.registrationQueue.processQueue((async e=>{await this.processRegistration(e)})),this.isInitialized=!0,console.log("AngieMcpSdk: Initialization complete")}catch(e){console.error("AngieMcpSdk: Error processing registration queue:",e)}}async processRegistration(e){console.log(`AngieMcpSdk: Processing registration for server "${e.config.name}"`);try{await this.clientManager.requestClientCreation(e),console.log(`AngieMcpSdk: Successfully registered server "${e.config.name}"`)}catch(t){throw console.error(`AngieMcpSdk: Failed to register server "${e.config.name}":`,t),t}}async registerServer(e){if(!e.server)throw new Error("Server instance is required");if(!e.name)throw new Error("Server name is required");if(!e.description)throw new Error("Server description is required");console.log(`AngieMcpSdk: Registering server "${e.name}"`);const t=this.registrationQueue.add(e);if(this.angieDetector.isReady())try{await this.processRegistration(t),this.registrationQueue.updateStatus(t.id,"registered"),console.log(`AngieMcpSdk: Server "${e.name}" registered successfully`)}catch(e){const s=e instanceof Error?e.message:String(e);throw this.registrationQueue.updateStatus(t.id,"failed",s),e}else console.log(`AngieMcpSdk: Server "${e.name}" queued until Angie is ready`)}getRegistrations(){return this.registrationQueue.getAll()}getPendingRegistrations(){return this.registrationQueue.getPending()}isAngieReady(){return this.angieDetector.isReady()}isReady(){return this.isInitialized}async waitForReady(){if(!(await this.angieDetector.waitForReady()).isReady)throw new Error("Angie is not available");for(;!this.isInitialized;)await new Promise((e=>setTimeout(e,100)))}destroy(){this.registrationQueue.clear(),console.log("AngieMcpSdk: SDK destroyed")}setupServerInitHandler(){window.addEventListener("message",(e=>{e.data?.type===t.SDK_REQUEST_INIT_SERVER&&this.handleServerInitRequest(e)}))}handleServerInitRequest(e){const{clientId:t,serverId:s}=e.data.payload||{};if(t&&s){console.log(`AngieMcpSdk: Handling server init request for clientId: ${t}, serverId: ${s}`);try{const t=this.registrationQueue.getAll().find((e=>e.id===s));if(!t)return void console.error(`AngieMcpSdk: No registration found for serverId: ${s}`);const a=e.ports[0];if(!a)return void console.error("AngieMcpSdk: No port provided in server init request");const r=t.config.server,n=new bs(a);r.connect(n),console.log(`AngieMcpSdk: Server "${t.config.name}" initialized successfully`)}catch(e){console.error(`AngieMcpSdk: Error initializing server for clientId ${t}:`,e)}}else console.error("AngieMcpSdk: Invalid server init request - missing clientId or serverId")}}export{r as AngieDetector,ws as AngieMcpSdk,i as ClientManager,n as RegistrationQueue};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ServerRegistration, AngieServerConfig } from './types';
|
|
2
|
+
export declare class RegistrationQueue {
|
|
3
|
+
private queue;
|
|
4
|
+
private isProcessing;
|
|
5
|
+
add(config: AngieServerConfig): ServerRegistration;
|
|
6
|
+
getAll(): ServerRegistration[];
|
|
7
|
+
getPending(): ServerRegistration[];
|
|
8
|
+
updateStatus(id: string, status: ServerRegistration['status'], error?: string): void;
|
|
9
|
+
processQueue(processor: (registration: ServerRegistration) => Promise<void>): Promise<void>;
|
|
10
|
+
clear(): void;
|
|
11
|
+
remove(id: string): boolean;
|
|
12
|
+
private generateId;
|
|
13
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
3
|
+
import { ServerCapabilities } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
export declare enum AngieMCPTransport {
|
|
5
|
+
POST_MESSAGE = "postMessage"
|
|
6
|
+
}
|
|
7
|
+
export interface AngieServerConfig {
|
|
8
|
+
name: string;
|
|
9
|
+
version: string;
|
|
10
|
+
description: string;
|
|
11
|
+
server: Server | McpServer;
|
|
12
|
+
capabilities?: ServerCapabilities;
|
|
13
|
+
}
|
|
14
|
+
export interface ServerRegistration {
|
|
15
|
+
id: string;
|
|
16
|
+
config: AngieServerConfig;
|
|
17
|
+
timestamp: number;
|
|
18
|
+
status: 'pending' | 'registered' | 'failed';
|
|
19
|
+
error?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface AngieDetectionResult {
|
|
22
|
+
isReady: boolean;
|
|
23
|
+
version?: string;
|
|
24
|
+
capabilities?: string[];
|
|
25
|
+
}
|
|
26
|
+
export interface AngieMessage {
|
|
27
|
+
type: string;
|
|
28
|
+
payload: any;
|
|
29
|
+
origin?: string;
|
|
30
|
+
timestamp: number;
|
|
31
|
+
}
|
|
32
|
+
export interface ClientCreationRequest {
|
|
33
|
+
serverId: string;
|
|
34
|
+
serverName: string;
|
|
35
|
+
description: string;
|
|
36
|
+
serverVersion: string;
|
|
37
|
+
transport: string;
|
|
38
|
+
capabilities?: ServerCapabilities;
|
|
39
|
+
}
|
|
40
|
+
export interface ClientCreationResponse {
|
|
41
|
+
success: boolean;
|
|
42
|
+
clientId?: string;
|
|
43
|
+
error?: string;
|
|
44
|
+
}
|
|
45
|
+
export declare enum MessageEventType {
|
|
46
|
+
SDK_ANGIE_READY_PING = "sdk-angie-ready-ping",
|
|
47
|
+
SDK_REQUEST_CLIENT_CREATION = "sdk-request-client-creation",
|
|
48
|
+
SDK_REQUEST_INIT_SERVER = "sdk-request-init-server"
|
|
49
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@elementor/angie-sdk",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "TypeScript SDK for Angie AI assistant",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "npm run build:types && npm run build:bundle",
|
|
10
|
+
"build:types": "tsc",
|
|
11
|
+
"build:bundle": "webpack --mode=production",
|
|
12
|
+
"dev": "tsc --watch",
|
|
13
|
+
"test": "jest",
|
|
14
|
+
"lint": "eslint src/**/*.ts",
|
|
15
|
+
"lint:fix": "eslint src/**/*.ts --fix"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"mcp",
|
|
19
|
+
"model-context-protocol",
|
|
20
|
+
"angie",
|
|
21
|
+
"elementor",
|
|
22
|
+
"ai",
|
|
23
|
+
"sdk"
|
|
24
|
+
],
|
|
25
|
+
"author": "Elementor",
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@modelcontextprotocol/sdk": "^1.13.0",
|
|
29
|
+
"zod": "^3.24.2"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/jest": "^29.5.12",
|
|
33
|
+
"@types/node": "^20.19.0",
|
|
34
|
+
"@typescript-eslint/eslint-plugin": "^6.19.1",
|
|
35
|
+
"@typescript-eslint/parser": "^6.19.1",
|
|
36
|
+
"eslint": "^8.56.0",
|
|
37
|
+
"jest": "^29.7.0",
|
|
38
|
+
"ts-jest": "^29.3.2",
|
|
39
|
+
"ts-loader": "^9.5.1",
|
|
40
|
+
"typescript": "^5.3.3",
|
|
41
|
+
"webpack": "^5.89.0",
|
|
42
|
+
"webpack-cli": "^5.1.4"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"dist",
|
|
46
|
+
"README.md"
|
|
47
|
+
],
|
|
48
|
+
"repository": {
|
|
49
|
+
"type": "git",
|
|
50
|
+
"url": "https://github.com/elementor/angie-sdk.git"
|
|
51
|
+
}
|
|
52
|
+
}
|