@mcp-b/global 2.3.2 → 3.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 +8 -60
- package/dist/index.d.ts.map +1 -1
- package/dist/index.iife.js +3 -3
- package/dist/index.js +48 -14
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
package/README.md
CHANGED
|
@@ -14,14 +14,14 @@
|
|
|
14
14
|
|
|
15
15
|
## Why Use @mcp-b/global?
|
|
16
16
|
|
|
17
|
-
| Feature | Benefit
|
|
18
|
-
| ---------------------------- |
|
|
19
|
-
| **W3C Standard** | Implements the emerging Web Model Context API specification
|
|
20
|
-
| **Drop-in IIFE** | Add AI capabilities with a single `<script>` tag - no build step
|
|
21
|
-
| **Native Chromium Support** | Auto-detects and uses native browser implementation when available
|
|
22
|
-
| **Dual Transport** | Works with both same-window clients AND parent pages (iframe support)
|
|
23
|
-
| **Spec-Aware Compatibility** | Tracks the
|
|
24
|
-
| **Works with Any AI** | Claude, ChatGPT, Gemini, Cursor, Copilot, and any MCP client
|
|
17
|
+
| Feature | Benefit |
|
|
18
|
+
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
19
|
+
| **W3C Standard** | Implements the emerging Web Model Context API specification |
|
|
20
|
+
| **Drop-in IIFE** | Add AI capabilities with a single `<script>` tag - no build step |
|
|
21
|
+
| **Native Chromium Support** | Auto-detects and uses native browser implementation when available |
|
|
22
|
+
| **Dual Transport** | Works with both same-window clients AND parent pages (iframe support) |
|
|
23
|
+
| **Spec-Aware Compatibility** | Tracks the current WebMCP draft (`document.modelContext`, `registerTool(tool, { signal })`, `getTools()`, and `executeTool(...)`). Deprecated `unregisterTool(name)` and the `{ unregister }` return handle remain for existing MCP-B integrations and will be removed in the next major version. |
|
|
24
|
+
| **Works with Any AI** | Claude, ChatGPT, Gemini, Cursor, Copilot, and any MCP client |
|
|
25
25
|
|
|
26
26
|
## Package Selection
|
|
27
27
|
|
|
@@ -134,47 +134,6 @@ initializeWebModelContext();
|
|
|
134
134
|
|
|
135
135
|
After initialization, `navigator.modelContext` exposes these methods:
|
|
136
136
|
|
|
137
|
-
#### `provideContext(options?)`
|
|
138
|
-
|
|
139
|
-
Deprecated compatibility API. The upstream WebMCP spec removed `provideContext()` on March 5, 2026. `@mcp-b/global` keeps it functional for now, but logs a deprecation warning and will remove it in the next major version.
|
|
140
|
-
|
|
141
|
-
Replaces all currently registered tools with a new set. This is an atomic replacement - all previous tools are removed first.
|
|
142
|
-
|
|
143
|
-
```typescript
|
|
144
|
-
navigator.modelContext.provideContext({
|
|
145
|
-
tools: [
|
|
146
|
-
{
|
|
147
|
-
name: 'search-products',
|
|
148
|
-
description: 'Search the product catalog by query',
|
|
149
|
-
inputSchema: {
|
|
150
|
-
type: 'object',
|
|
151
|
-
properties: {
|
|
152
|
-
query: { type: 'string', description: 'Search query' },
|
|
153
|
-
limit: { type: 'integer', description: 'Max results' },
|
|
154
|
-
},
|
|
155
|
-
required: ['query'],
|
|
156
|
-
},
|
|
157
|
-
async execute(args) {
|
|
158
|
-
const results = await searchProducts(args.query, args.limit ?? 10);
|
|
159
|
-
return {
|
|
160
|
-
content: [{ type: 'text', text: JSON.stringify(results) }],
|
|
161
|
-
};
|
|
162
|
-
},
|
|
163
|
-
},
|
|
164
|
-
{
|
|
165
|
-
name: 'get-cart',
|
|
166
|
-
description: 'Get the current shopping cart contents',
|
|
167
|
-
inputSchema: { type: 'object', properties: {} },
|
|
168
|
-
async execute() {
|
|
169
|
-
return {
|
|
170
|
-
content: [{ type: 'text', text: JSON.stringify(getCart()) }],
|
|
171
|
-
};
|
|
172
|
-
},
|
|
173
|
-
},
|
|
174
|
-
],
|
|
175
|
-
});
|
|
176
|
-
```
|
|
177
|
-
|
|
178
137
|
#### `registerTool(tool, options?)`
|
|
179
138
|
|
|
180
139
|
Registers a single tool. The tool name must be unique, otherwise throws if a tool with the same name already exists. The recommended unregistration path is `options.signal` (`AbortSignal`):
|
|
@@ -217,16 +176,6 @@ Removes a tool by name. The April 23, 2026 WebMCP draft removed `unregisterTool`
|
|
|
217
176
|
navigator.modelContext.unregisterTool('add-to-cart');
|
|
218
177
|
```
|
|
219
178
|
|
|
220
|
-
#### `clearContext()`
|
|
221
|
-
|
|
222
|
-
Deprecated compatibility API. The upstream WebMCP spec removed `clearContext()` on March 5, 2026. `@mcp-b/global` keeps it functional for now, but logs a deprecation warning and will remove it in the next major version.
|
|
223
|
-
|
|
224
|
-
Removes all registered tools.
|
|
225
|
-
|
|
226
|
-
```typescript
|
|
227
|
-
navigator.modelContext.clearContext();
|
|
228
|
-
```
|
|
229
|
-
|
|
230
179
|
#### `listTools()`
|
|
231
180
|
|
|
232
181
|
Returns metadata for all registered tools (without execute functions).
|
|
@@ -527,7 +476,6 @@ import type {
|
|
|
527
476
|
InputSchema,
|
|
528
477
|
ModelContext,
|
|
529
478
|
ModelContextCore,
|
|
530
|
-
ModelContextOptions,
|
|
531
479
|
NativeModelContextBehavior,
|
|
532
480
|
ToolAnnotations,
|
|
533
481
|
ToolDescriptor,
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/global.ts"],"mappings":";;;UAEiB,sBAAA;EACf,SAAA,GAAY,OAAA,CAAQ,yBAAA;EACpB,YAAA,GAAe,OAAA,CAAQ,2BAAA;AAAA;AAAA,KAGb,0BAAA;AAAA,UAEK,0BAAA;EACf,SAAA,GAAY,sBAAA;EACZ,cAAA;EAPe;;;;;;;EAef,0BAAA,GAA6B,0BAAA;EAfN;;;AAGzB;;;EAmBE,kBAAA;AAAA;AAAA,QAGM,MAAA;EAAA,UACI,MAAA;IACR,wBAAA,GAA2B,0BAAA;EAAA;AAAA;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/global.ts"],"mappings":";;;UAEiB,sBAAA;EACf,SAAA,GAAY,OAAA,CAAQ,yBAAA;EACpB,YAAA,GAAe,OAAA,CAAQ,2BAAA;AAAA;AAAA,KAGb,0BAAA;AAAA,UAEK,0BAAA;EACf,SAAA,GAAY,sBAAA;EACZ,cAAA;EAPe;;;;;;;EAef,0BAAA,GAA6B,0BAAA;EAfN;;;AAGzB;;;EAmBE,kBAAA;AAAA;AAAA,QAGM,MAAA;EAAA,UACI,MAAA;IACR,wBAAA,GAA2B,0BAAA;EAAA;AAAA;;;iBC2Mf,yBAAA,CAA0B,OAAA,GAAU,0BAAA;AAAA,iBA6DpC,sBAAA,CAAA"}
|
package/dist/index.iife.js
CHANGED
|
@@ -61,7 +61,7 @@ var WebMCP=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Modul
|
|
|
61
61
|
|
|
62
62
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Nt,s=!yt.jitless,c=s&&Pt.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?ni([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function ai(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Yt(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>$t(e,r,bt())))}),t)}let oi=x(`$ZodUnion`,(e,t)=>{T.init(e,t),S(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),S(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),S(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),S(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>Tt(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>ai(t,r,e,i)):ai(o,r,e,i)}}),si=x(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,oi.init(e,t);let n=e._zod.parse;S(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=Ct(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Nt(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),ci=x(`$ZodIntersection`,(e,t)=>{T.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>ui(e,t,n)):ui(e,i,a)}});function li(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ft(e)&&Ft(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=li(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=li(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ui(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Yt(e))return e;let o=li(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let di=x(`$ZodRecord`,(e,t)=>{T.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Ft(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>$t(e,r,bt())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Zt(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Zt(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Xn.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>$t(e,r,bt())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Zt(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Zt(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),fi=x(`$ZodEnum`,(e,t)=>{T.init(e,t);let n=xt(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Lt.has(typeof e)).map(e=>typeof e==`string`?Rt(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),pi=x(`$ZodLiteral`,(e,t)=>{if(T.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?Rt(e):e?Rt(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),mi=x(`$ZodTransform`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new vt(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new _t;return n.value=i,n.fallback=!0,n}});function hi(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let gi=x(`$ZodOptional`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),S(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Tt(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>hi(e,r)):hi(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),_i=x(`$ZodExactOptional`,(e,t)=>{gi.init(e,t),S(e._zod,`values`,()=>t.innerType._zod.values),S(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),vi=x(`$ZodNullable`,(e,t)=>{T.init(e,t),S(e._zod,`optin`,()=>t.innerType._zod.optin),S(e._zod,`optout`,()=>t.innerType._zod.optout),S(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${Tt(e.source)}|null)$`):void 0}),S(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),yi=x(`$ZodDefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>bi(e,t)):bi(r,t)}});function bi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let xi=x(`$ZodPrefault`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Si=x(`$ZodNonOptional`,(e,t)=>{T.init(e,t),S(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Ci(t,e)):Ci(i,e)}});function Ci(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}let wi=x(`$ZodCatch`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,S(e._zod,`optout`,()=>t.innerType._zod.optout),S(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>$t(e,n,bt()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>$t(e,n,bt()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Ti=x(`$ZodPipe`,(e,t)=>{T.init(e,t),S(e._zod,`values`,()=>t.in._zod.values),S(e._zod,`optin`,()=>t.in._zod.optin),S(e._zod,`optout`,()=>t.out._zod.optout),S(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ei(e,t.in,n)):Ei(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ei(e,t.out,n)):Ei(r,t.out,n)}});function Ei(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}let Di=x(`$ZodPreprocess`,(e,t)=>{Ti.init(e,t)}),Oi=x(`$ZodReadonly`,(e,t)=>{T.init(e,t),S(e._zod,`propValues`,()=>t.innerType._zod.propValues),S(e._zod,`values`,()=>t.innerType._zod.values),S(e._zod,`optin`,()=>t.innerType?._zod?.optin),S(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(ki):ki(r)}});function ki(e){return e.value=Object.freeze(e.value),e}let Ai=x(`$ZodCustom`,(e,t)=>{w.init(e,t),T.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>ji(t,n,r,e));ji(i,n,r,e)}});function ji(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(tn(e))}}var Mi,Ni=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Pi(){return new Ni}(Mi=globalThis).__zod_globalRegistry??(Mi.__zod_globalRegistry=Pi());let Fi=globalThis.__zod_globalRegistry;function Ii(e,t){return new e({type:`string`,...C(t)})}function Li(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...C(t)})}function Ri(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...C(t)})}function zi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...C(t)})}function Bi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...C(t)})}function Vi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...C(t)})}function Hi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...C(t)})}function Ui(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...C(t)})}function Wi(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...C(t)})}function Gi(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...C(t)})}function Ki(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...C(t)})}function qi(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...C(t)})}function Ji(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...C(t)})}function Yi(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...C(t)})}function Xi(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...C(t)})}function Zi(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...C(t)})}function Qi(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...C(t)})}function $i(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...C(t)})}function ea(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...C(t)})}function ta(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...C(t)})}function na(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...C(t)})}function ra(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...C(t)})}function ia(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...C(t)})}function aa(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...C(t)})}function oa(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...C(t)})}function sa(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...C(t)})}function ca(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...C(t)})}function la(e,t){return new e({type:`number`,checks:[],...C(t)})}function ua(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...C(t)})}function da(e,t){return new e({type:`boolean`,...C(t)})}function fa(e,t){return new e({type:`null`,...C(t)})}function pa(e){return new e({type:`unknown`})}function ma(e,t){return new e({type:`never`,...C(t)})}function ha(e,t){return new nr({check:`less_than`,...C(t),value:e,inclusive:!1})}function ga(e,t){return new nr({check:`less_than`,...C(t),value:e,inclusive:!0})}function _a(e,t){return new rr({check:`greater_than`,...C(t),value:e,inclusive:!1})}function va(e,t){return new rr({check:`greater_than`,...C(t),value:e,inclusive:!0})}function ya(e,t){return new ir({check:`multiple_of`,...C(t),value:e})}function ba(e,t){return new or({check:`max_length`,...C(t),maximum:e})}function xa(e,t){return new sr({check:`min_length`,...C(t),minimum:e})}function Sa(e,t){return new cr({check:`length_equals`,...C(t),length:e})}function Ca(e,t){return new ur({check:`string_format`,format:`regex`,...C(t),pattern:e})}function wa(e){return new dr({check:`string_format`,format:`lowercase`,...C(e)})}function Ta(e){return new fr({check:`string_format`,format:`uppercase`,...C(e)})}function Ea(e,t){return new pr({check:`string_format`,format:`includes`,...C(t),includes:e})}function Da(e,t){return new mr({check:`string_format`,format:`starts_with`,...C(t),prefix:e})}function Oa(e,t){return new hr({check:`string_format`,format:`ends_with`,...C(t),suffix:e})}function ka(e){return new gr({check:`overwrite`,tx:e})}function Aa(e){return ka(t=>t.normalize(e))}function ja(){return ka(e=>e.trim())}function Ma(){return ka(e=>e.toLowerCase())}function Na(){return ka(e=>e.toUpperCase())}function Pa(){return ka(e=>jt(e))}function Fa(e,t,n){return new e({type:`array`,element:t,...C(n)})}function Ia(e,t,n){let r=C(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function La(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...C(n)})}function Ra(e,t){let n=za(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(tn(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(tn(r))}},e(t.value,t)),t);return n}function za(e,t){let n=new w({check:`custom`,...C(t)});return n._zod.check=e,n}function Ba(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Fi,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function D(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,D(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&O(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Va(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
63
63
|
|
|
64
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Ha(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:Wa(t,`input`,e.processors),output:Wa(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function O(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return O(r.element,n);if(r.type===`set`)return O(r.valueType,n);if(r.type===`lazy`)return O(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return O(r.innerType,n);if(r.type===`intersection`)return O(r.left,n)||O(r.right,n);if(r.type===`record`||r.type===`map`)return O(r.keyType,n)||O(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:O(r.in,n)||O(r.out,n);if(r.type===`object`){for(let e in r.shape)if(O(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(O(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(O(e,n))return!0;return!!(r.rest&&O(r.rest,n))}return!1}let Ua=(e,t={})=>n=>{let r=Ba({...n,processors:t});return D(e,r),Va(r,e),Ha(r,e)},Wa=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ba({...i??{},target:a,io:t,processors:n});return D(e,o),Va(o,e),Ha(o,e)},Ga={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Ka=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Ga[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},qa=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Ja=(e,t,n,r)=>{n.type=`boolean`},Ya=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},Xa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},Za=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Qa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},$a=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},eo=(e,t,n,r)=>{n.not={}},to=(e,t,n,r)=>{},no=(e,t,n,r)=>{},ro=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},io=(e,t,n,r)=>{let i=e._zod.def,a=xt(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ao=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},oo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},so=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},co=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},lo=(e,t,n,r)=>{n.type=`boolean`},uo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},fo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},po=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},ho=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},go=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=D(a.element,t,{...r,path:[...r.path,`items`]})},_o=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=D(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=D(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},vo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>D(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},yo=(e,t,n,r)=>{let i=e._zod.def,a=D(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=D(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},bo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>D(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?D(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},xo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=D(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=D(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=D(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},So=(e,t,n,r)=>{let i=e._zod.def,a=D(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Co=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},wo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},To=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Eo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Do=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;D(o,t,r);let s=t.seen.get(e);s.ref=o},Oo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ko=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ao=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},jo={string:Ka,number:qa,boolean:Ja,bigint:Ya,symbol:Xa,null:Za,undefined:Qa,void:$a,never:eo,any:to,unknown:no,date:ro,enum:io,literal:ao,nan:oo,template_literal:so,file:co,success:lo,custom:uo,function:fo,transform:po,map:mo,set:ho,array:go,object:_o,union:vo,intersection:yo,tuple:bo,record:xo,nullable:So,nonoptional:Co,default:wo,prefault:To,catch:Eo,pipe:Do,readonly:Oo,promise:ko,optional:Ao,lazy:(e,t,n,r)=>{let i=e._zod.innerType;D(i,t,r);let a=t.seen.get(e);a.ref=i}};function Mo(e,t){if(`_idmap`in e){let n=e,r=Ba({...t,processors:jo}),i={};for(let e of n._idmap.entries()){let[t,n]=e;D(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Va(r,n),a[t]=Ha(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Ba({...t,processors:jo});return D(e,n),Va(n,e),Ha(n,e)}let No=x(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);T.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>ln(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>pn(e,t,n),e.parseAsync=async(t,n)=>dn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>hn(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>zt(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Po=x(`ZodMiniObject`,(e,t)=>{ri.init(e,t),No.init(e,t),S(e,`shape`,()=>t.shape)});function Fo(e,t){return new Po({type:`object`,shape:e??{},...C(t)})}let Io=x(`ZodISODateTime`,(e,t)=>{jr.init(e,t),j.init(e,t)});function Lo(e){return aa(Io,e)}let Ro=x(`ZodISODate`,(e,t)=>{Mr.init(e,t),j.init(e,t)});function zo(e){return oa(Ro,e)}let Bo=x(`ZodISOTime`,(e,t)=>{Nr.init(e,t),j.init(e,t)});function Vo(e){return sa(Bo,e)}let Ho=x(`ZodISODuration`,(e,t)=>{Pr.init(e,t),j.init(e,t)});function Uo(e){return ca(Ho,e)}let Wo=x(`ZodError`,(e,t)=>{rn.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>sn(e,t)},flatten:{value:t=>on(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,St,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,St,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Go=cn(Wo),Ko=un(Wo),qo=fn(Wo),Jo=mn(Wo),Yo=gn(Wo),Xo=_n(Wo),Zo=vn(Wo),Qo=yn(Wo),$o=bn(Wo),es=xn(Wo),ts=Sn(Wo),ns=Cn(Wo),rs=new WeakMap;function is(e,t,n){let r=Object.getPrototypeOf(e),i=rs.get(r);if(i||(i=new Set,rs.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let k=x(`ZodType`,(e,t)=>(T.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Wa(e,`input`),output:Wa(e,`output`)}}),e.toJSONSchema=Ua(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>Go(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>qo(e,t,n),e.parseAsync=async(t,n)=>Ko(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Jo(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Yo(e,t,n),e.decode=(t,n)=>Xo(e,t,n),e.encodeAsync=async(t,n)=>Zo(e,t,n),e.decodeAsync=async(t,n)=>Qo(e,t,n),e.safeEncode=(t,n)=>$o(e,t,n),e.safeDecode=(t,n)=>es(e,t,n),e.safeEncodeAsync=async(t,n)=>ts(e,t,n),e.safeDecodeAsync=async(t,n)=>ns(e,t,n),is(e,`ZodType`,{check(...e){let t=this.def;return this.clone(kt(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return zt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(pc(e,t))},superRefine(e,t){return this.check(mc(e,t))},overwrite(e){return this.check(ka(e))},optional(){return H(this)},exactOptional(){return Ys(this)},nullable(){return Zs(this)},nullish(){return H(Zs(this))},nonoptional(e){return rc(this,e)},array(){return F(this)},or(e){return R([this,e])},and(e){return Vs(this,e)},transform(e){return sc(this,Ks(e))},default(e){return $s(this,e)},prefault(e){return tc(this,e)},catch(e){return ac(this,e)},pipe(e){return sc(this,e)},readonly(){return uc(this)},describe(e){let t=this.clone();return Fi.add(t,{description:e}),t},meta(...e){if(e.length===0)return Fi.get(this);let t=this.clone();return Fi.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return Fi.get(e)?.description},configurable:!0}),e)),as=x(`_ZodString`,(e,t)=>{yr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ka(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,is(e,`_ZodString`,{regex(...e){return this.check(Ca(...e))},includes(...e){return this.check(Ea(...e))},startsWith(...e){return this.check(Da(...e))},endsWith(...e){return this.check(Oa(...e))},min(...e){return this.check(xa(...e))},max(...e){return this.check(ba(...e))},length(...e){return this.check(Sa(...e))},nonempty(...e){return this.check(xa(1,...e))},lowercase(e){return this.check(wa(e))},uppercase(e){return this.check(Ta(e))},trim(){return this.check(ja())},normalize(...e){return this.check(Aa(...e))},toLowerCase(){return this.check(Ma())},toUpperCase(){return this.check(Na())},slugify(){return this.check(Pa())}})}),os=x(`ZodString`,(e,t)=>{yr.init(e,t),as.init(e,t),e.email=t=>e.check(Li(ss,t)),e.url=t=>e.check(Ui(us,t)),e.jwt=t=>e.check(ia(Ts,t)),e.emoji=t=>e.check(Wi(ds,t)),e.guid=t=>e.check(Ri(cs,t)),e.uuid=t=>e.check(zi(ls,t)),e.uuidv4=t=>e.check(Bi(ls,t)),e.uuidv6=t=>e.check(Vi(ls,t)),e.uuidv7=t=>e.check(Hi(ls,t)),e.nanoid=t=>e.check(Gi(fs,t)),e.guid=t=>e.check(Ri(cs,t)),e.cuid=t=>e.check(Ki(ps,t)),e.cuid2=t=>e.check(qi(ms,t)),e.ulid=t=>e.check(Ji(hs,t)),e.base64=t=>e.check(ta(Ss,t)),e.base64url=t=>e.check(na(Cs,t)),e.xid=t=>e.check(Yi(gs,t)),e.ksuid=t=>e.check(Xi(_s,t)),e.ipv4=t=>e.check(Zi(vs,t)),e.ipv6=t=>e.check(Qi(ys,t)),e.cidrv4=t=>e.check($i(bs,t)),e.cidrv6=t=>e.check(ea(xs,t)),e.e164=t=>e.check(ra(ws,t)),e.datetime=t=>e.check(Lo(t)),e.date=t=>e.check(zo(t)),e.time=t=>e.check(Vo(t)),e.duration=t=>e.check(Uo(t))});function A(e){return Ii(os,e)}let j=x(`ZodStringFormat`,(e,t)=>{E.init(e,t),as.init(e,t)}),ss=x(`ZodEmail`,(e,t)=>{Sr.init(e,t),j.init(e,t)}),cs=x(`ZodGUID`,(e,t)=>{br.init(e,t),j.init(e,t)}),ls=x(`ZodUUID`,(e,t)=>{xr.init(e,t),j.init(e,t)}),us=x(`ZodURL`,(e,t)=>{Cr.init(e,t),j.init(e,t)}),ds=x(`ZodEmoji`,(e,t)=>{wr.init(e,t),j.init(e,t)}),fs=x(`ZodNanoID`,(e,t)=>{Tr.init(e,t),j.init(e,t)}),ps=x(`ZodCUID`,(e,t)=>{Er.init(e,t),j.init(e,t)}),ms=x(`ZodCUID2`,(e,t)=>{Dr.init(e,t),j.init(e,t)}),hs=x(`ZodULID`,(e,t)=>{Or.init(e,t),j.init(e,t)}),gs=x(`ZodXID`,(e,t)=>{kr.init(e,t),j.init(e,t)}),_s=x(`ZodKSUID`,(e,t)=>{Ar.init(e,t),j.init(e,t)}),vs=x(`ZodIPv4`,(e,t)=>{Fr.init(e,t),j.init(e,t)}),ys=x(`ZodIPv6`,(e,t)=>{Ir.init(e,t),j.init(e,t)}),bs=x(`ZodCIDRv4`,(e,t)=>{Lr.init(e,t),j.init(e,t)}),xs=x(`ZodCIDRv6`,(e,t)=>{Rr.init(e,t),j.init(e,t)}),Ss=x(`ZodBase64`,(e,t)=>{Br.init(e,t),j.init(e,t)}),Cs=x(`ZodBase64URL`,(e,t)=>{Hr.init(e,t),j.init(e,t)}),ws=x(`ZodE164`,(e,t)=>{Ur.init(e,t),j.init(e,t)}),Ts=x(`ZodJWT`,(e,t)=>{Gr.init(e,t),j.init(e,t)}),Es=x(`ZodNumber`,(e,t)=>{Kr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qa(e,t,n,r),is(e,`ZodNumber`,{gt(e,t){return this.check(_a(e,t))},gte(e,t){return this.check(va(e,t))},min(e,t){return this.check(va(e,t))},lt(e,t){return this.check(ha(e,t))},lte(e,t){return this.check(ga(e,t))},max(e,t){return this.check(ga(e,t))},int(e){return this.check(Os(e))},safe(e){return this.check(Os(e))},positive(e){return this.check(_a(0,e))},nonnegative(e){return this.check(va(0,e))},negative(e){return this.check(ha(0,e))},nonpositive(e){return this.check(ga(0,e))},multipleOf(e,t){return this.check(ya(e,t))},step(e,t){return this.check(ya(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function M(e){return la(Es,e)}let Ds=x(`ZodNumberFormat`,(e,t)=>{qr.init(e,t),Es.init(e,t)});function Os(e){return ua(Ds,e)}let ks=x(`ZodBoolean`,(e,t)=>{Jr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ja(e,t,n,r)});function N(e){return da(ks,e)}let As=x(`ZodNull`,(e,t)=>{Yr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Za(e,t,n,r)});function js(e){return fa(As,e)}let Ms=x(`ZodUnknown`,(e,t)=>{Xr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function P(){return pa(Ms)}let Ns=x(`ZodNever`,(e,t)=>{Zr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eo(e,t,n,r)});function Ps(e){return ma(Ns,e)}let Fs=x(`ZodArray`,(e,t)=>{$r.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>go(e,t,n,r),e.element=t.element,is(e,`ZodArray`,{min(e,t){return this.check(xa(e,t))},nonempty(e){return this.check(xa(1,e))},max(e,t){return this.check(ba(e,t))},length(e,t){return this.check(Sa(e,t))},unwrap(){return this.element}})});function F(e,t){return Fa(Fs,e,t)}let Is=x(`ZodObject`,(e,t)=>{ii.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_o(e,t,n,r),S(e,`shape`,()=>t.shape),is(e,`ZodObject`,{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:P()})},loose(){return this.clone({...this._zod.def,catchall:P()})},strict(){return this.clone({...this._zod.def,catchall:Ps()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Wt(this,e)},safeExtend(e){return Gt(this,e)},merge(e){return Kt(this,e)},pick(e){return Ht(this,e)},omit(e){return Ut(this,e)},partial(...e){return qt(qs,this,e[0])},required(...e){return Jt(nc,this,e[0])}})});function I(e,t){return new Is({type:`object`,shape:e??{},...C(t)})}function L(e,t){return new Is({type:`object`,shape:e,catchall:P(),...C(t)})}let Ls=x(`ZodUnion`,(e,t)=>{oi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vo(e,t,n,r),e.options=t.options});function R(e,t){return new Ls({type:`union`,options:e,...C(t)})}let Rs=x(`ZodDiscriminatedUnion`,(e,t)=>{Ls.init(e,t),si.init(e,t)});function zs(e,t,n){return new Rs({type:`union`,options:t,discriminator:e,...C(n)})}let Bs=x(`ZodIntersection`,(e,t)=>{ci.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yo(e,t,n,r)});function Vs(e,t){return new Bs({type:`intersection`,left:e,right:t})}let Hs=x(`ZodRecord`,(e,t)=>{di.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new Hs({type:`record`,keyType:A(),valueType:e,...C(t)}):new Hs({type:`record`,keyType:e,valueType:t,...C(n)})}let Us=x(`ZodEnum`,(e,t)=>{fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>io(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Us({...t,checks:[],...C(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Us({...t,checks:[],...C(r),entries:i})}});function B(e,t){return new Us({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...C(t)})}let Ws=x(`ZodLiteral`,(e,t)=>{pi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ao(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function V(e,t){return new Ws({type:`literal`,values:Array.isArray(e)?e:[e],...C(t)})}let Gs=x(`ZodTransform`,(e,t)=>{mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>po(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new vt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(tn(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(tn(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Ks(e){return new Gs({type:`transform`,transform:e})}let qs=x(`ZodOptional`,(e,t)=>{gi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function H(e){return new qs({type:`optional`,innerType:e})}let Js=x(`ZodExactOptional`,(e,t)=>{_i.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ys(e){return new Js({type:`optional`,innerType:e})}let Xs=x(`ZodNullable`,(e,t)=>{vi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>So(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Zs(e){return new Xs({type:`nullable`,innerType:e})}let Qs=x(`ZodDefault`,(e,t)=>{yi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function $s(e,t){return new Qs({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():It(t)}})}let ec=x(`ZodPrefault`,(e,t)=>{xi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>To(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function tc(e,t){return new ec({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():It(t)}})}let nc=x(`ZodNonOptional`,(e,t)=>{Si.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Co(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rc(e,t){return new nc({type:`nonoptional`,innerType:e,...C(t)})}let ic=x(`ZodCatch`,(e,t)=>{wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ac(e,t){return new ic({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let oc=x(`ZodPipe`,(e,t)=>{Ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Do(e,t,n,r),e.in=t.in,e.out=t.out});function sc(e,t){return new oc({type:`pipe`,in:e,out:t})}let cc=x(`ZodPreprocess`,(e,t)=>{oc.init(e,t),Di.init(e,t)}),lc=x(`ZodReadonly`,(e,t)=>{Oi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function uc(e){return new lc({type:`readonly`,innerType:e})}let dc=x(`ZodCustom`,(e,t)=>{Ai.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uo(e,t,n,r)});function fc(e,t){return Ia(dc,e??(()=>!0),t)}function pc(e,t={}){return La(dc,e,t)}function mc(e,t){return Ra(e,t)}function hc(e,t){return new cc({type:`pipe`,in:Ks(e),out:t})}let gc=Symbol(`Let zodToJsonSchema decide on which parser to use`),_c={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`,openAiAnyTypeName:`OpenAiAnyType`},vc=e=>typeof e==`string`?{..._c,name:e}:{..._c,...e},yc=e=>{let t=vc(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function bc(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function U(e,t,n,r,i){e[t]=n,bc(e,t,r,i)}let xc=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function W(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?xc(t,e.currentPath):t.join(`/`)}}function Sc(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==b.ZodAny&&(n.items=K(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&U(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&U(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(U(n,`minItems`,e.exactLength.value,e.exactLength.message,t),U(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Cc(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?U(n,`minimum`,r.value,r.message,t):U(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),U(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?U(n,`maximum`,r.value,r.message,t):U(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),U(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:U(n,`multipleOf`,r.value,r.message,t);break}return n}function wc(){return{type:`boolean`}}function Tc(e,t){return K(e.type._def,t)}let Ec=(e,t)=>K(e.innerType._def,t);function Dc(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Dc(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Oc(e,t)}}let Oc=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:U(n,`minimum`,r.value,r.message,t);break;case`max`:U(n,`maximum`,r.value,r.message,t);break}return n};function kc(e,t){return{...K(e.innerType._def,t),default:e.defaultValue()}}function Ac(e,t){return t.effectStrategy===`input`?K(e.schema._def,t):W(t)}function jc(e){return{type:`string`,enum:Array.from(e.values)}}let Mc=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Nc(e,t){let n=[K(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),K(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Mc(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Pc(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let Fc,Ic={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:()=>(Fc===void 0&&(Fc=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Fc),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 Lc(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Vc(n,`email`,r.message,t);break;case`format:idn-email`:Vc(n,`idn-email`,r.message,t);break;case`pattern:zod`:G(n,Ic.email,r.message,t);break}break;case`url`:Vc(n,`uri`,r.message,t);break;case`uuid`:Vc(n,`uuid`,r.message,t);break;case`regex`:G(n,r.regex,r.message,t);break;case`cuid`:G(n,Ic.cuid,r.message,t);break;case`cuid2`:G(n,Ic.cuid2,r.message,t);break;case`startsWith`:G(n,RegExp(`^${Rc(r.value,t)}`),r.message,t);break;case`endsWith`:G(n,RegExp(`${Rc(r.value,t)}$`),r.message,t);break;case`datetime`:Vc(n,`date-time`,r.message,t);break;case`date`:Vc(n,`date`,r.message,t);break;case`time`:Vc(n,`time`,r.message,t);break;case`duration`:Vc(n,`duration`,r.message,t);break;case`length`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:G(n,RegExp(Rc(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Vc(n,`ipv4`,r.message,t),r.version!==`v4`&&Vc(n,`ipv6`,r.message,t);break;case`base64url`:G(n,Ic.base64url,r.message,t);break;case`jwt`:G(n,Ic.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&G(n,Ic.ipv4Cidr,r.message,t),r.version!==`v4`&&G(n,Ic.ipv6Cidr,r.message,t);break;case`emoji`:G(n,Ic.emoji(),r.message,t);break;case`ulid`:G(n,Ic.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Vc(n,`binary`,r.message,t);break;case`contentEncoding:base64`:U(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:G(n,Ic.base64,r.message,t);break}break;case`nanoid`:G(n,Ic.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Rc(e,t){return t.patternStrategy===`escape`?Bc(e):e}let zc=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Bc(e){let t=``;for(let n=0;n<e.length;n++)zc.has(e[n])||(t+=`\\`),t+=e[n];return t}function Vc(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):U(e,`format`,t,n,r)}function G(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Hc(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):U(e,`pattern`,Hc(t,r),n,r)}function Hc(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
64
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Ha(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:Wa(t,`input`,e.processors),output:Wa(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function O(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return O(r.element,n);if(r.type===`set`)return O(r.valueType,n);if(r.type===`lazy`)return O(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return O(r.innerType,n);if(r.type===`intersection`)return O(r.left,n)||O(r.right,n);if(r.type===`record`||r.type===`map`)return O(r.keyType,n)||O(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:O(r.in,n)||O(r.out,n);if(r.type===`object`){for(let e in r.shape)if(O(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(O(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(O(e,n))return!0;return!!(r.rest&&O(r.rest,n))}return!1}let Ua=(e,t={})=>n=>{let r=Ba({...n,processors:t});return D(e,r),Va(r,e),Ha(r,e)},Wa=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ba({...i??{},target:a,io:t,processors:n});return D(e,o),Va(o,e),Ha(o,e)},Ga={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Ka=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Ga[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},qa=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Ja=(e,t,n,r)=>{n.type=`boolean`},Ya=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},Xa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},Za=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Qa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},$a=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},eo=(e,t,n,r)=>{n.not={}},to=(e,t,n,r)=>{},no=(e,t,n,r)=>{},ro=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},io=(e,t,n,r)=>{let i=e._zod.def,a=xt(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ao=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},oo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},so=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},co=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},lo=(e,t,n,r)=>{n.type=`boolean`},uo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},fo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},po=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},mo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},ho=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},go=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=D(a.element,t,{...r,path:[...r.path,`items`]})},_o=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=D(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=D(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},vo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>D(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},yo=(e,t,n,r)=>{let i=e._zod.def,a=D(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=D(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},bo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>D(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?D(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},xo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=D(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=D(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=D(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},So=(e,t,n,r)=>{let i=e._zod.def,a=D(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Co=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},wo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},To=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},Eo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Do=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;D(o,t,r);let s=t.seen.get(e);s.ref=o},Oo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ko=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ao=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},jo={string:Ka,number:qa,boolean:Ja,bigint:Ya,symbol:Xa,null:Za,undefined:Qa,void:$a,never:eo,any:to,unknown:no,date:ro,enum:io,literal:ao,nan:oo,template_literal:so,file:co,success:lo,custom:uo,function:fo,transform:po,map:mo,set:ho,array:go,object:_o,union:vo,intersection:yo,tuple:bo,record:xo,nullable:So,nonoptional:Co,default:wo,prefault:To,catch:Eo,pipe:Do,readonly:Oo,promise:ko,optional:Ao,lazy:(e,t,n,r)=>{let i=e._zod.innerType;D(i,t,r);let a=t.seen.get(e);a.ref=i}};function Mo(e,t){if(`_idmap`in e){let n=e,r=Ba({...t,processors:jo}),i={};for(let e of n._idmap.entries()){let[t,n]=e;D(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Va(r,n),a[t]=Ha(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Ba({...t,processors:jo});return D(e,n),Va(n,e),Ha(n,e)}let No=x(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);T.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>ln(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>pn(e,t,n),e.parseAsync=async(t,n)=>dn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>hn(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>zt(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Po=x(`ZodMiniObject`,(e,t)=>{ri.init(e,t),No.init(e,t),S(e,`shape`,()=>t.shape)});function Fo(e,t){return new Po({type:`object`,shape:e??{},...C(t)})}let Io=x(`ZodISODateTime`,(e,t)=>{jr.init(e,t),j.init(e,t)});function Lo(e){return aa(Io,e)}let Ro=x(`ZodISODate`,(e,t)=>{Mr.init(e,t),j.init(e,t)});function zo(e){return oa(Ro,e)}let Bo=x(`ZodISOTime`,(e,t)=>{Nr.init(e,t),j.init(e,t)});function Vo(e){return sa(Bo,e)}let Ho=x(`ZodISODuration`,(e,t)=>{Pr.init(e,t),j.init(e,t)});function Uo(e){return ca(Ho,e)}let Wo=x(`ZodError`,(e,t)=>{rn.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>sn(e,t)},flatten:{value:t=>on(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,St,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,St,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Go=cn(Wo),Ko=un(Wo),qo=fn(Wo),Jo=mn(Wo),Yo=gn(Wo),Xo=_n(Wo),Zo=vn(Wo),Qo=yn(Wo),$o=bn(Wo),es=xn(Wo),ts=Sn(Wo),ns=Cn(Wo),rs=new WeakMap;function is(e,t,n){let r=Object.getPrototypeOf(e),i=rs.get(r);if(i||(i=new Set,rs.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let k=x(`ZodType`,(e,t)=>(T.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Wa(e,`input`),output:Wa(e,`output`)}}),e.toJSONSchema=Ua(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>Go(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>qo(e,t,n),e.parseAsync=async(t,n)=>Ko(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Jo(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Yo(e,t,n),e.decode=(t,n)=>Xo(e,t,n),e.encodeAsync=async(t,n)=>Zo(e,t,n),e.decodeAsync=async(t,n)=>Qo(e,t,n),e.safeEncode=(t,n)=>$o(e,t,n),e.safeDecode=(t,n)=>es(e,t,n),e.safeEncodeAsync=async(t,n)=>ts(e,t,n),e.safeDecodeAsync=async(t,n)=>ns(e,t,n),is(e,`ZodType`,{check(...e){let t=this.def;return this.clone(kt(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return zt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(mc(e,t))},superRefine(e,t){return this.check(hc(e,t))},overwrite(e){return this.check(ka(e))},optional(){return V(this)},exactOptional(){return Xs(this)},nullable(){return Qs(this)},nullish(){return V(Qs(this))},nonoptional(e){return ic(this,e)},array(){return F(this)},or(e){return R([this,e])},and(e){return Vs(this,e)},transform(e){return cc(this,qs(e))},default(e){return ec(this,e)},prefault(e){return nc(this,e)},catch(e){return oc(this,e)},pipe(e){return cc(this,e)},readonly(){return dc(this)},describe(e){let t=this.clone();return Fi.add(t,{description:e}),t},meta(...e){if(e.length===0)return Fi.get(this);let t=this.clone();return Fi.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return Fi.get(e)?.description},configurable:!0}),e)),as=x(`_ZodString`,(e,t)=>{yr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ka(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,is(e,`_ZodString`,{regex(...e){return this.check(Ca(...e))},includes(...e){return this.check(Ea(...e))},startsWith(...e){return this.check(Da(...e))},endsWith(...e){return this.check(Oa(...e))},min(...e){return this.check(xa(...e))},max(...e){return this.check(ba(...e))},length(...e){return this.check(Sa(...e))},nonempty(...e){return this.check(xa(1,...e))},lowercase(e){return this.check(wa(e))},uppercase(e){return this.check(Ta(e))},trim(){return this.check(ja())},normalize(...e){return this.check(Aa(...e))},toLowerCase(){return this.check(Ma())},toUpperCase(){return this.check(Na())},slugify(){return this.check(Pa())}})}),os=x(`ZodString`,(e,t)=>{yr.init(e,t),as.init(e,t),e.email=t=>e.check(Li(ss,t)),e.url=t=>e.check(Ui(us,t)),e.jwt=t=>e.check(ia(Ts,t)),e.emoji=t=>e.check(Wi(ds,t)),e.guid=t=>e.check(Ri(cs,t)),e.uuid=t=>e.check(zi(ls,t)),e.uuidv4=t=>e.check(Bi(ls,t)),e.uuidv6=t=>e.check(Vi(ls,t)),e.uuidv7=t=>e.check(Hi(ls,t)),e.nanoid=t=>e.check(Gi(fs,t)),e.guid=t=>e.check(Ri(cs,t)),e.cuid=t=>e.check(Ki(ps,t)),e.cuid2=t=>e.check(qi(ms,t)),e.ulid=t=>e.check(Ji(hs,t)),e.base64=t=>e.check(ta(Ss,t)),e.base64url=t=>e.check(na(Cs,t)),e.xid=t=>e.check(Yi(gs,t)),e.ksuid=t=>e.check(Xi(_s,t)),e.ipv4=t=>e.check(Zi(vs,t)),e.ipv6=t=>e.check(Qi(ys,t)),e.cidrv4=t=>e.check($i(bs,t)),e.cidrv6=t=>e.check(ea(xs,t)),e.e164=t=>e.check(ra(ws,t)),e.datetime=t=>e.check(Lo(t)),e.date=t=>e.check(zo(t)),e.time=t=>e.check(Vo(t)),e.duration=t=>e.check(Uo(t))});function A(e){return Ii(os,e)}let j=x(`ZodStringFormat`,(e,t)=>{E.init(e,t),as.init(e,t)}),ss=x(`ZodEmail`,(e,t)=>{Sr.init(e,t),j.init(e,t)}),cs=x(`ZodGUID`,(e,t)=>{br.init(e,t),j.init(e,t)}),ls=x(`ZodUUID`,(e,t)=>{xr.init(e,t),j.init(e,t)}),us=x(`ZodURL`,(e,t)=>{Cr.init(e,t),j.init(e,t)}),ds=x(`ZodEmoji`,(e,t)=>{wr.init(e,t),j.init(e,t)}),fs=x(`ZodNanoID`,(e,t)=>{Tr.init(e,t),j.init(e,t)}),ps=x(`ZodCUID`,(e,t)=>{Er.init(e,t),j.init(e,t)}),ms=x(`ZodCUID2`,(e,t)=>{Dr.init(e,t),j.init(e,t)}),hs=x(`ZodULID`,(e,t)=>{Or.init(e,t),j.init(e,t)}),gs=x(`ZodXID`,(e,t)=>{kr.init(e,t),j.init(e,t)}),_s=x(`ZodKSUID`,(e,t)=>{Ar.init(e,t),j.init(e,t)}),vs=x(`ZodIPv4`,(e,t)=>{Fr.init(e,t),j.init(e,t)}),ys=x(`ZodIPv6`,(e,t)=>{Ir.init(e,t),j.init(e,t)}),bs=x(`ZodCIDRv4`,(e,t)=>{Lr.init(e,t),j.init(e,t)}),xs=x(`ZodCIDRv6`,(e,t)=>{Rr.init(e,t),j.init(e,t)}),Ss=x(`ZodBase64`,(e,t)=>{Br.init(e,t),j.init(e,t)}),Cs=x(`ZodBase64URL`,(e,t)=>{Hr.init(e,t),j.init(e,t)}),ws=x(`ZodE164`,(e,t)=>{Ur.init(e,t),j.init(e,t)}),Ts=x(`ZodJWT`,(e,t)=>{Gr.init(e,t),j.init(e,t)}),Es=x(`ZodNumber`,(e,t)=>{Kr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qa(e,t,n,r),is(e,`ZodNumber`,{gt(e,t){return this.check(_a(e,t))},gte(e,t){return this.check(va(e,t))},min(e,t){return this.check(va(e,t))},lt(e,t){return this.check(ha(e,t))},lte(e,t){return this.check(ga(e,t))},max(e,t){return this.check(ga(e,t))},int(e){return this.check(Os(e))},safe(e){return this.check(Os(e))},positive(e){return this.check(_a(0,e))},nonnegative(e){return this.check(va(0,e))},negative(e){return this.check(ha(0,e))},nonpositive(e){return this.check(ga(0,e))},multipleOf(e,t){return this.check(ya(e,t))},step(e,t){return this.check(ya(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function M(e){return la(Es,e)}let Ds=x(`ZodNumberFormat`,(e,t)=>{qr.init(e,t),Es.init(e,t)});function Os(e){return ua(Ds,e)}let ks=x(`ZodBoolean`,(e,t)=>{Jr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ja(e,t,n,r)});function N(e){return da(ks,e)}let As=x(`ZodNull`,(e,t)=>{Yr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Za(e,t,n,r)});function js(e){return fa(As,e)}let Ms=x(`ZodUnknown`,(e,t)=>{Xr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function P(){return pa(Ms)}let Ns=x(`ZodNever`,(e,t)=>{Zr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eo(e,t,n,r)});function Ps(e){return ma(Ns,e)}let Fs=x(`ZodArray`,(e,t)=>{$r.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>go(e,t,n,r),e.element=t.element,is(e,`ZodArray`,{min(e,t){return this.check(xa(e,t))},nonempty(e){return this.check(xa(1,e))},max(e,t){return this.check(ba(e,t))},length(e,t){return this.check(Sa(e,t))},unwrap(){return this.element}})});function F(e,t){return Fa(Fs,e,t)}let Is=x(`ZodObject`,(e,t)=>{ii.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_o(e,t,n,r),S(e,`shape`,()=>t.shape),is(e,`ZodObject`,{keyof(){return Ws(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:P()})},loose(){return this.clone({...this._zod.def,catchall:P()})},strict(){return this.clone({...this._zod.def,catchall:Ps()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Wt(this,e)},safeExtend(e){return Gt(this,e)},merge(e){return Kt(this,e)},pick(e){return Ht(this,e)},omit(e){return Ut(this,e)},partial(...e){return qt(Js,this,e[0])},required(...e){return Jt(rc,this,e[0])}})});function I(e,t){return new Is({type:`object`,shape:e??{},...C(t)})}function L(e,t){return new Is({type:`object`,shape:e,catchall:P(),...C(t)})}let Ls=x(`ZodUnion`,(e,t)=>{oi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vo(e,t,n,r),e.options=t.options});function R(e,t){return new Ls({type:`union`,options:e,...C(t)})}let Rs=x(`ZodDiscriminatedUnion`,(e,t)=>{Ls.init(e,t),si.init(e,t)});function zs(e,t,n){return new Rs({type:`union`,options:t,discriminator:e,...C(n)})}let Bs=x(`ZodIntersection`,(e,t)=>{ci.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yo(e,t,n,r)});function Vs(e,t){return new Bs({type:`intersection`,left:e,right:t})}let Hs=x(`ZodRecord`,(e,t)=>{di.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new Hs({type:`record`,keyType:A(),valueType:e,...C(t)}):new Hs({type:`record`,keyType:e,valueType:t,...C(n)})}let Us=x(`ZodEnum`,(e,t)=>{fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>io(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Us({...t,checks:[],...C(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Us({...t,checks:[],...C(r),entries:i})}});function Ws(e,t){return new Us({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...C(t)})}let Gs=x(`ZodLiteral`,(e,t)=>{pi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ao(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function B(e,t){return new Gs({type:`literal`,values:Array.isArray(e)?e:[e],...C(t)})}let Ks=x(`ZodTransform`,(e,t)=>{mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>po(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new vt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(tn(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(tn(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function qs(e){return new Ks({type:`transform`,transform:e})}let Js=x(`ZodOptional`,(e,t)=>{gi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function V(e){return new Js({type:`optional`,innerType:e})}let Ys=x(`ZodExactOptional`,(e,t)=>{_i.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xs(e){return new Ys({type:`optional`,innerType:e})}let Zs=x(`ZodNullable`,(e,t)=>{vi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>So(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qs(e){return new Zs({type:`nullable`,innerType:e})}let $s=x(`ZodDefault`,(e,t)=>{yi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ec(e,t){return new $s({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():It(t)}})}let tc=x(`ZodPrefault`,(e,t)=>{xi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>To(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nc(e,t){return new tc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():It(t)}})}let rc=x(`ZodNonOptional`,(e,t)=>{Si.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Co(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ic(e,t){return new rc({type:`nonoptional`,innerType:e,...C(t)})}let ac=x(`ZodCatch`,(e,t)=>{wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function oc(e,t){return new ac({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let sc=x(`ZodPipe`,(e,t)=>{Ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Do(e,t,n,r),e.in=t.in,e.out=t.out});function cc(e,t){return new sc({type:`pipe`,in:e,out:t})}let lc=x(`ZodPreprocess`,(e,t)=>{sc.init(e,t),Di.init(e,t)}),uc=x(`ZodReadonly`,(e,t)=>{Oi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function dc(e){return new uc({type:`readonly`,innerType:e})}let fc=x(`ZodCustom`,(e,t)=>{Ai.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uo(e,t,n,r)});function pc(e,t){return Ia(fc,e??(()=>!0),t)}function mc(e,t={}){return La(fc,e,t)}function hc(e,t){return Ra(e,t)}function gc(e,t){return new lc({type:`pipe`,in:qs(e),out:t})}let _c=Symbol(`Let zodToJsonSchema decide on which parser to use`),vc={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`,openAiAnyTypeName:`OpenAiAnyType`},yc=e=>typeof e==`string`?{...vc,name:e}:{...vc,...e},bc=e=>{let t=yc(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function xc(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function H(e,t,n,r,i){e[t]=n,xc(e,t,r,i)}let Sc=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function U(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Sc(t,e.currentPath):t.join(`/`)}}function Cc(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==b.ZodAny&&(n.items=G(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&H(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&H(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(H(n,`minItems`,e.exactLength.value,e.exactLength.message,t),H(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function wc(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function Tc(){return{type:`boolean`}}function Ec(e,t){return G(e.type._def,t)}let Dc=(e,t)=>G(e.innerType._def,t);function Oc(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Oc(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return kc(e,t)}}let kc=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:H(n,`minimum`,r.value,r.message,t);break;case`max`:H(n,`maximum`,r.value,r.message,t);break}return n};function Ac(e,t){return{...G(e.innerType._def,t),default:e.defaultValue()}}function jc(e,t){return t.effectStrategy===`input`?G(e.schema._def,t):U(t)}function Mc(e){return{type:`string`,enum:Array.from(e.values)}}let Nc=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Pc(e,t){let n=[G(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),G(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Nc(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Fc(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let Ic,Lc={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:()=>(Ic===void 0&&(Ic=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Ic),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 Rc(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Hc(n,`email`,r.message,t);break;case`format:idn-email`:Hc(n,`idn-email`,r.message,t);break;case`pattern:zod`:W(n,Lc.email,r.message,t);break}break;case`url`:Hc(n,`uri`,r.message,t);break;case`uuid`:Hc(n,`uuid`,r.message,t);break;case`regex`:W(n,r.regex,r.message,t);break;case`cuid`:W(n,Lc.cuid,r.message,t);break;case`cuid2`:W(n,Lc.cuid2,r.message,t);break;case`startsWith`:W(n,RegExp(`^${zc(r.value,t)}`),r.message,t);break;case`endsWith`:W(n,RegExp(`${zc(r.value,t)}$`),r.message,t);break;case`datetime`:Hc(n,`date-time`,r.message,t);break;case`date`:Hc(n,`date`,r.message,t);break;case`time`:Hc(n,`time`,r.message,t);break;case`duration`:Hc(n,`duration`,r.message,t);break;case`length`:H(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),H(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:W(n,RegExp(zc(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Hc(n,`ipv4`,r.message,t),r.version!==`v4`&&Hc(n,`ipv6`,r.message,t);break;case`base64url`:W(n,Lc.base64url,r.message,t);break;case`jwt`:W(n,Lc.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&W(n,Lc.ipv4Cidr,r.message,t),r.version!==`v4`&&W(n,Lc.ipv6Cidr,r.message,t);break;case`emoji`:W(n,Lc.emoji(),r.message,t);break;case`ulid`:W(n,Lc.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Hc(n,`binary`,r.message,t);break;case`contentEncoding:base64`:H(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:W(n,Lc.base64,r.message,t);break}break;case`nanoid`:W(n,Lc.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function zc(e,t){return t.patternStrategy===`escape`?Vc(e):e}let Bc=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Vc(e){let t=``;for(let n=0;n<e.length;n++)Bc.has(e[n])||(t+=`\\`),t+=e[n];return t}function Hc(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):H(e,`format`,t,n,r)}function W(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Uc(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):H(e,`pattern`,Uc(t,r),n,r)}function Uc(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
65
65
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
66
|
-
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Uc(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===b.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:K(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??W(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:K(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===b.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Lc(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===b.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===b.ZodBranded&&e.keyType._def.type._def.typeName===b.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Tc(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Wc(e,t){return t.mapStrategy===`record`?Uc(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[K(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||W(t),K(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||W(t)],minItems:2,maxItems:2}}}function Gc(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Kc(e){return e.target===`openAi`?void 0:{not:W({...e,currentPath:[...e.currentPath,`not`]})}}function qc(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}let Jc={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Yc(e,t){if(t.target===`openApi3`)return Xc(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Jc&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Jc[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Xc(e,t)}let Xc=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>K(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Zc(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Jc[e.innerType._def.typeName],nullable:!0}:{type:[Jc[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=K(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=K(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Qc(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,bc(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?U(n,`minimum`,r.value,r.message,t):U(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),U(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?U(n,`maximum`,r.value,r.message,t):U(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),U(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:U(n,`multipleOf`,r.value,r.message,t);break}return n}function $c(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=tl(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=K(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=el(e,t);return o!==void 0&&(r.additionalProperties=o),r}function el(e,t){if(e.catchall._def.typeName!==`ZodNever`)return K(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function tl(e){try{return e.isOptional()}catch{return!0}}let nl=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return K(e.innerType._def,t);let n=K(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:W(t)},n]}:W(t)},rl=(e,t)=>{if(t.pipeStrategy===`input`)return K(e.in._def,t);if(t.pipeStrategy===`output`)return K(e.out._def,t);let n=K(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,K(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function il(e,t){return K(e.type._def,t)}function al(e,t){let n={type:`array`,uniqueItems:!0,items:K(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&U(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&U(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function ol(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>K(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:K(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>K(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function sl(e){return{not:W(e)}}function cl(e){return W(e)}let ll=(e,t)=>K(e.innerType._def,t),ul=(e,t,n)=>{switch(t){case b.ZodString:return Lc(e,n);case b.ZodNumber:return Qc(e,n);case b.ZodObject:return $c(e,n);case b.ZodBigInt:return Cc(e,n);case b.ZodBoolean:return wc();case b.ZodDate:return Dc(e,n);case b.ZodUndefined:return sl(n);case b.ZodNull:return qc(n);case b.ZodArray:return Sc(e,n);case b.ZodUnion:case b.ZodDiscriminatedUnion:return Yc(e,n);case b.ZodIntersection:return Nc(e,n);case b.ZodTuple:return ol(e,n);case b.ZodRecord:return Uc(e,n);case b.ZodLiteral:return Pc(e,n);case b.ZodEnum:return jc(e);case b.ZodNativeEnum:return Gc(e);case b.ZodNullable:return Zc(e,n);case b.ZodOptional:return nl(e,n);case b.ZodMap:return Wc(e,n);case b.ZodSet:return al(e,n);case b.ZodLazy:return()=>e.getter()._def;case b.ZodPromise:return il(e,n);case b.ZodNaN:case b.ZodNever:return Kc(n);case b.ZodEffects:return Ac(e,n);case b.ZodAny:return W(n);case b.ZodUnknown:return cl(n);case b.ZodDefault:return kc(e,n);case b.ZodBranded:return Tc(e,n);case b.ZodReadonly:return ll(e,n);case b.ZodCatch:return Ec(e,n);case b.ZodPipeline:return rl(e,n);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return(e=>void 0)(t)}};function K(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==gc)return i}if(r&&!n){let e=dl(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=ul(e,e.typeName,t),o=typeof a==`function`?K(a(),t):a;if(o&&fl(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}let dl=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:xc(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),W(t)):t.$refStrategy===`seen`?W(t):void 0}},fl=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),pl=(e,t)=>{let n=yc(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:K(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??W(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=K(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??W(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function ml(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!ml(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!ml(e[r],t[r]))return!1;return!0}return e===t}function hl(e){return encodeURI(gl(e))}function gl(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let _l={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},vl={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},yl={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},bl=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function xl(e,t=Object.create(null),n=bl,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:xl(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(yl[i])continue;let a=`${r}/${hl(i)}`,o=e[i];if(Array.isArray(o)){if(_l[i]){let e=o.length;for(let r=0;r<e;r++)xl(o[r],t,n,`${a}/${r}`)}}else if(vl[i])for(let e in o)xl(o[e],t,n,`${a}/${hl(e)}`);else xl(o,t,n,a)}return t}let Sl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cl=[0,31,28,31,30,31,30,31,31,30,31,30,31],wl=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Tl=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,El=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Dl=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Ol=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,kl=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Al=/^(?:\/(?:[^~/]|~0|~1)*)*$/,jl=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Ml=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Nl=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Pl=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Fl=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Il=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Ll(e){return e.test.bind(e)}let Rl={date:Bl,time:Vl.bind(void 0,!1),"date-time":Ul,duration:Il,uri:Kl,"uri-reference":Ll(El),"uri-template":Ll(Dl),url:Ll(Ol),email:Nl,hostname:Ll(Tl),ipv4:Ll(Pl),ipv6:Ll(Fl),regex:Jl,uuid:Ll(kl),"json-pointer":Ll(Al),"json-pointer-uri-fragment":Ll(jl),"relative-json-pointer":Ll(Ml)};function zl(e){return e%4==0&&(e%100!=0||e%400==0)}function Bl(e){let t=e.match(Sl);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&zl(n)?29:Cl[r])}function Vl(e,t){let n=t.match(wl);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}let Hl=/t|\s/i;function Ul(e){let t=e.split(Hl);return t.length==2&&Bl(t[0])&&Vl(!0,t[1])}let Wl=/\/|:/,Gl=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Kl(e){return Wl.test(e)&&Gl.test(e)}let ql=/[^\\]\\Z/;function Jl(e){if(ql.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function Yl(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function q(e,t,n=`2019-09`,r=xl(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:ee,required:te,not:ne,anyOf:re,allOf:g,oneOf:ie,if:ae,then:_,else:v,format:oe,properties:se,patternProperties:ce,additionalProperties:le,unevaluatedProperties:ue,minProperties:de,maxProperties:fe,propertyNames:pe,dependentRequired:me,dependentSchemas:he,dependencies:ge,prefixItems:_e,items:ve,additionalItems:ye,unevaluatedItems:be,contains:xe,minContains:Se,maxContains:Ce,minItems:we,maxItems:Te,uniqueItems:Ee,minimum:De,maximum:Oe,exclusiveMinimum:ke,exclusiveMaximum:Ae,multipleOf:je,minLength:Me,maxLength:Ne,pattern:Pe,__absolute_ref__:Fe,__absolute_recursive_ref__:Ie}=t,y=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[Ie]:a,u=`${s}/$recursiveRef`,d=q(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||y.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Fe||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Fe&&Fe!==d&&(e+=` Absolute URI "${Fe}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
67
|
-
- `)}`,Error(e)}let l=`${s}/$ref`,u=q(e,t,n,r,i,a,o,l,c);if(u.valid||y.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:y.length===0,errors:y}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?ml(e,h)||y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),ee!==void 0&&(u===`object`||u===`array`?ee.some(t=>ml(e,t))||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`}):ee.some(t=>e===t)||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`})),ne!==void 0){let t=`${s}/not`;q(e,ne,n,r,i,a,o,t).valid&&y.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Le=[];if(re!==void 0){let t=`${s}/anyOf`,l=y.length,u=!1;for(let s=0;s<re.length;s++){let l=re[s],d=Object.create(c),f=q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u||=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(g!==void 0){let t=`${s}/allOf`,l=y.length,u=!0;for(let s=0;s<g.length;s++){let l=g[s],d=Object.create(c),f=q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u&&=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(ie!==void 0){let t=`${s}/oneOf`,l=y.length,u=ie.filter((s,l)=>{let u=Object.create(c),d=q(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return y.push(...d.errors),d.valid&&Le.push(u),d.valid}).length;u===1?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Le),ae!==void 0){let t=`${s}/if`;if(q(e,ae,n,r,i,a,o,t,c).valid){if(_!==void 0){let l=q(e,_,n,r,i,a,o,`${s}/then`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(v!==void 0){let l=q(e,v,n,r,i,a,o,`${s}/else`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(te!==void 0)for(let t of te)t in e||y.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(de!==void 0&&t.length<de&&y.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0&&t.length>fe&&y.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${fe} properties.`}),pe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${hl(s)}`,c=q(s,pe,n,r,i,a,e,t);c.valid||y.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(me!==void 0){let t=`${s}/dependantRequired`;for(let n in me)if(n in e){let r=me[n];for(let i of r)i in e||y.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(he!==void 0)for(let t in he){let l=`${s}/dependentSchemas`;if(t in e){let s=q(e,he[t],n,r,i,a,o,`${l}/${hl(t)}`,c);s.valid||y.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ge!==void 0){let t=`${s}/dependencies`;for(let s in ge)if(s in e){let c=ge[s];if(Array.isArray(c))for(let n of c)n in e||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=q(e,c,n,r,i,a,o,`${t}/${hl(s)}`);l.valid||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(se!==void 0){let t=`${s}/properties`;for(let s in se){if(!(s in e))continue;let d=`${o}/${hl(s)}`,f=q(e[s],se[s],n,r,i,a,d,`${t}/${hl(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,y.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ce!==void 0){let t=`${s}/patternProperties`;for(let s in ce){let d=new RegExp(s,`u`),f=ce[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${hl(p)}`,h=q(e[p],f,n,r,i,a,m,`${t}/${hl(s)}`);h.valid?c[p]=l[p]=!0:(u=i,y.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&le!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${hl(s)}`,f=q(e[s],le,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,y.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ue!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${hl(s)}`,u=q(e[s],ue,n,r,i,a,l,t);u.valid?c[s]=!0:y.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Te!==void 0&&e.length>Te&&y.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Te}).`}),we!==void 0&&e.length<we&&y.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${we}).`});let t=e.length,l=0,u=!1;if(_e!==void 0){let d=`${s}/prefixItems`,f=Math.min(_e.length,t);for(;l<f;l++){let t=q(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ve!==void 0){let d=`${s}/items`;if(Array.isArray(ve)){let s=Math.min(ve.length,t);for(;l<s;l++){let t=q(e[l],ve[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=q(e[l],ve,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ye!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=q(e[l],ye,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,y.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(xe!==void 0)if(t===0&&Se===void 0)y.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(Se!==void 0&&t<Se)y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${Se}).`});else{let l=`${s}/contains`,u=y.length,d=0;for(let s=0;s<t;s++){let t=q(e[s],xe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):y.push(...t.errors)}d>=(Se||0)&&(y.length=u),Se===void 0&&Ce===void 0&&d===0?y.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):Se!==void 0&&d<Se?y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${Se} items matching schema. Only ${d} items were found.`}):Ce!==void 0&&d>Ce&&y.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${d} items were found.`})}if(!u&&be!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=q(e[l],be,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||y.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(Ee)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&ml(r,t))&&(y.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(De!==void 0&&(ke===!0&&e<=De||e<De)&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ke?`or equal to `:``} ${De}.`}),Oe!==void 0&&(Ae===!0&&e>=Oe||e>Oe)&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ae?`or equal to `:``} ${Oe}.`})):(De!==void 0&&e<De&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${De}.`}),Oe!==void 0&&e>Oe&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Oe}.`}),ke!==void 0&&e<=ke&&y.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${ke}.`}),Ae!==void 0&&e>=Ae&&y.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ae}.`})),je!==void 0){let t=e%je;Math.abs(0-t)>=1.1920929e-7&&Math.abs(je-t)>=1.1920929e-7&&y.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${je}.`})}}else if(u===`string`){let t=Me===void 0&&Ne===void 0?0:Yl(e);Me!==void 0&&t<Me&&y.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Me}).`}),Ne!==void 0&&t>Ne&&y.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ne}).`}),Pe!==void 0&&!new RegExp(Pe,`u`).test(e)&&y.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),oe!==void 0&&Rl[oe]&&!Rl[oe](e)&&y.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${oe}".`})}return{valid:y.length===0,errors:y}}var Xl=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=xl(e)}validate(e){return q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),xl(e,this.lookup)}};let Zl=`Failed to parse input arguments`,Ql=`Tool was executed but the invocation failed. For example, the script function threw an error`,$l=`Tool was cancelled`,eu={type:`object`,properties:{}},tu=[`draft-2020-12`,`draft-07`],nu=Symbol(`standardValidator`),ru={installed:!1,previousModelContextDescriptor:void 0,previousModelContextTestingDescriptor:void 0};var iu=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;provideContextDeprecationWarned=!1;clearContextDeprecationWarned=!1;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}provideContext(e={}){this.warnProvideContextDeprecationOnce();let t=new Map;for(let n of e.tools??[]){let e=_u(n,t);t.set(e.name,e)}this.tools=t,this.notifyToolsChanged()}clearContext(){this.warnClearContextDeprecationOnce(),this.tools.clear(),this.notifyToolsChanged()}registerTool(e,t){let n=t?.signal;if(n?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${e?.name??`<unknown>`}") skipped: options.signal was already aborted.`);return}let r=_u(e,this.tools);this.tools.set(r.name,r),this.notifyToolsChanged(),n&&n.addEventListener(`abort`,()=>{this.tools.delete(r.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let t=cu(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTools(){return this.getToolInfos()}getTestingShim(){return this.testingShim||=new au(this),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{let t;try{t=JSON.stringify(e.inputSchema??{type:`object`})}catch{t=`{"type":"object"}`}return{name:e.name,description:e.description,inputSchema:t}})}async executeToolForTesting(e,t,n){if(n?.signal?.aborted)throw ou($l);let r=this.tools.get(e);if(!r)throw ou(`Tool not found: ${e}`);let i=su(t),a=await xu(i,r);if(a)throw ou(a);let o=!0,s={requestUserInteraction:async t=>{if(!o)throw Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof t!=`function`)throw TypeError(`requestUserInteraction(callback) requires a function callback`);return t()}};try{let e=r.execute(i,s);return ku(Du(await Au(Promise.resolve(e),n?.signal)))}catch(e){throw ou(e instanceof Error?`${Ql}: ${e.message}`:Ql)}finally{o=!1}}notifyToolsChanged(){queueMicrotask(()=>{let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.testingShim?.dispatchToolChange()})}warnProvideContextDeprecationOnce(){this.provideContextDeprecationWarned||(this.provideContextDeprecationWarned=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext.provideContext() is deprecated and will be removed in the next major version. Register tools individually with registerTool() instead.`))}warnClearContextDeprecationOnce(){this.clearContextDeprecationWarned||(this.clearContextDeprecationWarned=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead.`))}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister.`))}},au=class extends EventTarget{context;_ontoolchange=null;constructor(e){super(),this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,t,n){return this.context.executeToolForTesting(e,t,n)}getCrossDocumentScriptToolResult(){return Promise.resolve(`[]`)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!=`function`)throw TypeError(`Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.`);this.addEventListener(`toolchange`,e)}dispatchToolChange(){let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.dispatchEvent(new Event(`toolschanged`))}};function ou(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function su(e){let t;try{t=JSON.parse(e)}catch{throw ou(Zl)}if(!t||typeof t!=`object`||Array.isArray(t))throw ou(Zl);return t}function cu(e){if(typeof e==`string`)return e;if(J(e)&&typeof e.name==`string`)return e.name;throw TypeError(`Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.`)}function J(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function lu(e){if(!J(e))return null;let t=e[`~standard`];return J(t)?t:null}function uu(e){let t=lu(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function du(e){let t=lu(e);return!t||t.version!==1||!J(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function fu(e){return{"~standard":{version:1,vendor:`@mcp-b/webmcp-polyfill-json-schema`,validate(t){if(!J(t))return{issues:[{message:`expected object arguments`}]};let n=vu(t,e);return n?{issues:[n]}:{value:t}}}}}function pu(e){for(let t of tu)try{let n=e[`~standard`].jsonSchema.input({target:t});return hu(n),n}catch(e){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,e)}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function mu(e){if(e===void 0){let e=eu;return{inputSchema:e,standardValidator:fu(e)}}if(du(e)){let t=pu(e);return{inputSchema:t,standardValidator:fu(t)}}if(uu(e))return{inputSchema:eu,standardValidator:e};if(hu(e),Object.keys(e).length===0)return{inputSchema:eu,standardValidator:fu(eu)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:fu(t)}}function hu(e){if(!J(e))throw Error(`inputSchema must be a JSON Schema object`);gu(e,`$`)}function gu(e,t){let n=e.type;if(n!==void 0&&typeof n!=`string`&&!(Array.isArray(n)&&n.every(e=>typeof e==`string`&&e.length>0)))throw Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let r=e.required;if(r!==void 0&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`)))throw Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let i=e.properties;if(i!==void 0){if(!J(i))throw Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[e,n]of Object.entries(i)){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.properties.${e}: expected object schema`);gu(n,`${t}.properties.${e}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[e,n]of a.entries()){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.items[${e}]: expected object schema`);gu(n,`${t}.items[${e}]`)}else if(J(a))gu(a,`${t}.items`);else throw Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let n of[`allOf`,`anyOf`,`oneOf`]){let r=e[n];if(r!==void 0){if(!Array.isArray(r))throw Error(`Invalid JSON Schema at ${t}: "${n}" must be an array`);for(let[e,i]of r.entries()){if(!J(i))throw Error(`Invalid JSON Schema at ${t}.${n}[${e}]: expected object schema`);gu(i,`${t}.${n}[${e}]`)}}}let o=e.not;if(o!==void 0){if(!J(o))throw Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);gu(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function _u(e,t){if(!e||typeof e!=`object`)throw TypeError(`registerTool(tool) requires a tool object`);if(typeof e.name!=`string`||e.name.length===0)throw TypeError(`Tool "name" must be a non-empty string`);if(typeof e.description!=`string`||e.description.length===0)throw TypeError(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`);if(t.has(e.name))throw Error(`Tool already registered: ${e.name}`);let n=mu(e.inputSchema),r=e.annotations,i=r?{...r,...r.readOnlyHint===`true`?{readOnlyHint:!0}:r.readOnlyHint===`false`?{readOnlyHint:!1}:{},...r.destructiveHint===`true`?{destructiveHint:!0}:r.destructiveHint===`false`?{destructiveHint:!1}:{},...r.idempotentHint===`true`?{idempotentHint:!0}:r.idempotentHint===`false`?{idempotentHint:!1}:{},...r.openWorldHint===`true`?{openWorldHint:!0}:r.openWorldHint===`false`?{openWorldHint:!1}:{}}:void 0;return{...e,...i?{annotations:i}:{},inputSchema:n.inputSchema,[nu]:n.standardValidator}}function vu(e,t){let n=new Xl(t,`2020-12`,!0).validate(e);if(n.valid)return null;let r=n.errors[n.errors.length-1];return r?{message:r.error}:{message:`Input validation failed`}}function yu(e){if(!e||e.length===0)return null;let t=e.map(e=>J(e)&&`key`in e?e.key:e).map(e=>String(e)).filter(e=>e.length>0);return t.length===0?null:t.join(`.`)}async function bu(e,t){let n;try{n=await Promise.resolve(t[`~standard`].validate(e))}catch(e){let t=e instanceof Error?`: ${e.message}`:``;return console.error(`[WebMCPPolyfill] Standard Schema validation threw unexpectedly:`,e),`Input validation error: schema validation failed${t}`}if(!n.issues||n.issues.length===0)return null;let r=n.issues[0];if(!r)return`Input validation error`;let i=yu(r?.path);return i?`Input validation error: ${r.message} at ${i}`:`Input validation error: ${r.message}`}async function xu(e,t){return bu(e,t[nu])}function Su(e){return J(e)&&Array.isArray(e.content)}function Cu(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function wu(e){return Cu(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>wu(e)):J(e)?Object.values(e).every(e=>wu(e)):!1}function Tu(e){if(!(!J(e)||!wu(e)))return e}function Eu(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Du(e){if(Su(e))return e;let t=Tu(e);return{content:[{type:`text`,text:Eu(e)}],...t?{structuredContent:t}:{},isError:!1}}function Ou(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function ku(e){if(e.isError)throw ou(Ou(e)?.replace(/^Error:\s*/i,``).trim()||Ql);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw ou(Ql)}}function Au(e,t){return t?t.aborted?Promise.reject(ou($l)):new Promise((n,r)=>{let i=()=>{a(),r(ou($l))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function ju(){return typeof navigator<`u`?navigator:null}function Mu(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function Nu(e){let t=ju();if(!t||t.modelContext)return;ru.installed&&Pu();let n=new iu,r=n;r.__isWebMCPPolyfill=!0,ru.previousModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),ru.previousModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),Mu(t,`modelContext`,r);let i=e?.installTestingShim??`if-missing`,a=!!t.modelContextTesting;(i===`always`||(i===!0||i===`if-missing`)&&!a)&&Mu(t,`modelContextTesting`,n.getTestingShim()),ru.installed=!0}function Pu(){let e=ju();if(!e||!ru.installed)return;let t=(t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]};t(`modelContext`,ru.previousModelContextDescriptor),t(`modelContextTesting`,ru.previousModelContextTestingDescriptor),ru.installed=!1,ru.previousModelContextDescriptor=void 0,ru.previousModelContextTestingDescriptor=void 0}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Nu(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}function Fu(e){return!!e._zod}function Iu(e){let t=Object.values(e);if(t.length===0)return Fo({});let n=t.every(Fu),r=t.every(e=>!Fu(e));if(n)return Fo(e);if(r)return ht(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Lu(e,t){return Fu(e)?pn(e,t):e.safeParse(t)}async function Ru(e,t){return Fu(e)?await hn(e,t):await e.safeParseAsync(t)}function zu(e){if(!e)return;let t;if(t=Fu(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Bu(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return Iu(e)}}if(Fu(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Vu(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Hu(e){return e.description}function Uu(e){if(Fu(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Wu(e){if(Fu(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}let Gu=`2025-11-25`,Ku=[Gu,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],qu=`io.modelcontextprotocol/related-task`,Y=fc(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Ju=R([A(),M().int()]),Yu=A();L({ttl:R([M(),js()]).optional(),pollInterval:M().optional()});let Xu=I({ttl:M().optional()}),Zu=I({taskId:A()}),Qu=L({progressToken:Ju.optional(),[qu]:Zu.optional()}),$u=I({_meta:Qu.optional()}),ed=$u.extend({task:Xu.optional()}),td=e=>ed.safeParse(e).success,X=I({method:A(),params:$u.loose().optional()}),nd=I({_meta:Qu.optional()}),rd=I({method:A(),params:nd.loose().optional()}),Z=L({_meta:Qu.optional()}),id=R([A(),M().int()]),ad=I({jsonrpc:V(`2.0`),id,...X.shape}).strict(),od=e=>ad.safeParse(e).success,sd=I({jsonrpc:V(`2.0`),...rd.shape}).strict(),cd=e=>sd.safeParse(e).success,ld=I({jsonrpc:V(`2.0`),id,result:Z}).strict(),ud=e=>ld.safeParse(e).success;var Q;(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`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Q||={});let dd=I({jsonrpc:V(`2.0`),id:id.optional(),error:I({code:M().int(),message:A(),data:P().optional()})}).strict(),fd=e=>dd.safeParse(e).success,pd=R([ad,sd,ld,dd]);R([ld,dd]);let md=Z.strict(),hd=nd.extend({requestId:id.optional(),reason:A().optional()}),gd=rd.extend({method:V(`notifications/cancelled`),params:hd}),_d=I({icons:F(I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:B([`light`,`dark`]).optional()})).optional()}),vd=I({name:A(),title:A().optional()}),yd=vd.extend({...vd.shape,..._d.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),bd=hc(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Vs(I({form:Vs(I({applyDefaults:N().optional()}),z(A(),P())).optional(),url:Y.optional()}),z(A(),P()).optional())),xd=L({list:Y.optional(),cancel:Y.optional(),requests:L({sampling:L({createMessage:Y.optional()}).optional(),elicitation:L({create:Y.optional()}).optional()}).optional()}),Sd=L({list:Y.optional(),cancel:Y.optional(),requests:L({tools:L({call:Y.optional()}).optional()}).optional()}),Cd=I({experimental:z(A(),Y).optional(),sampling:I({context:Y.optional(),tools:Y.optional()}).optional(),elicitation:bd.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:xd.optional()}),wd=$u.extend({protocolVersion:A(),capabilities:Cd,clientInfo:yd}),Td=X.extend({method:V(`initialize`),params:wd}),Ed=I({experimental:z(A(),Y).optional(),logging:Y.optional(),completions:Y.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:Sd.optional()}),Dd=Z.extend({protocolVersion:A(),capabilities:Ed,serverInfo:yd,instructions:A().optional()}),Od=rd.extend({method:V(`notifications/initialized`),params:nd.optional()}),kd=X.extend({method:V(`ping`),params:$u.optional()}),Ad=I({progress:M(),total:H(M()),message:H(A())}),jd=I({...nd.shape,...Ad.shape,progressToken:Ju}),Md=rd.extend({method:V(`notifications/progress`),params:jd}),Nd=$u.extend({cursor:Yu.optional()}),Pd=X.extend({params:Nd.optional()}),Fd=Z.extend({nextCursor:Yu.optional()}),Id=B([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Ld=I({taskId:A(),status:Id,ttl:R([M(),js()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:H(M()),statusMessage:H(A())}),Rd=Z.extend({task:Ld}),zd=nd.merge(Ld),Bd=rd.extend({method:V(`notifications/tasks/status`),params:zd}),Vd=X.extend({method:V(`tasks/get`),params:$u.extend({taskId:A()})}),Hd=Z.merge(Ld),Ud=X.extend({method:V(`tasks/result`),params:$u.extend({taskId:A()})});Z.loose();let Wd=Pd.extend({method:V(`tasks/list`)}),Gd=Fd.extend({tasks:F(Ld)}),Kd=X.extend({method:V(`tasks/cancel`),params:$u.extend({taskId:A()})}),qd=Z.merge(Ld),Jd=I({uri:A(),mimeType:H(A()),_meta:z(A(),P()).optional()}),Yd=Jd.extend({text:A()}),Xd=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Zd=Jd.extend({blob:Xd}),Qd=B([`user`,`assistant`]),$d=I({audience:F(Qd).optional(),priority:M().min(0).max(1).optional(),lastModified:Lo({offset:!0}).optional()}),ef=I({...vd.shape,..._d.shape,uri:A(),description:H(A()),mimeType:H(A()),annotations:$d.optional(),_meta:H(L({}))}),tf=I({...vd.shape,..._d.shape,uriTemplate:A(),description:H(A()),mimeType:H(A()),annotations:$d.optional(),_meta:H(L({}))}),nf=Pd.extend({method:V(`resources/list`)}),rf=Fd.extend({resources:F(ef)}),af=Pd.extend({method:V(`resources/templates/list`)}),of=Fd.extend({resourceTemplates:F(tf)}),sf=$u.extend({uri:A()}),cf=sf,lf=X.extend({method:V(`resources/read`),params:cf}),uf=Z.extend({contents:F(R([Yd,Zd]))}),df=rd.extend({method:V(`notifications/resources/list_changed`),params:nd.optional()}),ff=sf,pf=X.extend({method:V(`resources/subscribe`),params:ff}),mf=sf,hf=X.extend({method:V(`resources/unsubscribe`),params:mf}),gf=nd.extend({uri:A()}),_f=rd.extend({method:V(`notifications/resources/updated`),params:gf}),vf=I({name:A(),description:H(A()),required:H(N())}),yf=I({...vd.shape,..._d.shape,description:H(A()),arguments:H(F(vf)),_meta:H(L({}))}),bf=Pd.extend({method:V(`prompts/list`)}),xf=Fd.extend({prompts:F(yf)}),Sf=$u.extend({name:A(),arguments:z(A(),A()).optional()}),Cf=X.extend({method:V(`prompts/get`),params:Sf}),wf=I({type:V(`text`),text:A(),annotations:$d.optional(),_meta:z(A(),P()).optional()}),Tf=I({type:V(`image`),data:Xd,mimeType:A(),annotations:$d.optional(),_meta:z(A(),P()).optional()}),Ef=I({type:V(`audio`),data:Xd,mimeType:A(),annotations:$d.optional(),_meta:z(A(),P()).optional()}),Df=I({type:V(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),Of=I({type:V(`resource`),resource:R([Yd,Zd]),annotations:$d.optional(),_meta:z(A(),P()).optional()}),kf=R([wf,Tf,Ef,ef.extend({type:V(`resource_link`)}),Of]),Af=I({role:Qd,content:kf}),jf=Z.extend({description:A().optional(),messages:F(Af)}),Mf=rd.extend({method:V(`notifications/prompts/list_changed`),params:nd.optional()}),Nf=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Pf=I({taskSupport:B([`required`,`optional`,`forbidden`]).optional()}),Ff=I({...vd.shape,..._d.shape,description:A().optional(),inputSchema:I({type:V(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()),outputSchema:I({type:V(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()).optional(),annotations:Nf.optional(),execution:Pf.optional(),_meta:z(A(),P()).optional()}),If=Pd.extend({method:V(`tools/list`)}),Lf=Fd.extend({tools:F(Ff)}),Rf=Z.extend({content:F(kf).default([]),structuredContent:z(A(),P()).optional(),isError:N().optional()});Rf.or(Z.extend({toolResult:P()}));let zf=ed.extend({name:A(),arguments:z(A(),P()).optional()}),Bf=X.extend({method:V(`tools/call`),params:zf}),Vf=rd.extend({method:V(`notifications/tools/list_changed`),params:nd.optional()});I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)});let Hf=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Uf=$u.extend({level:Hf}),Wf=X.extend({method:V(`logging/setLevel`),params:Uf}),Gf=nd.extend({level:Hf,logger:A().optional(),data:P()}),Kf=rd.extend({method:V(`notifications/message`),params:Gf}),qf=I({hints:F(I({name:A().optional()})).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),Jf=I({mode:B([`auto`,`required`,`none`]).optional()}),Yf=I({type:V(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:F(kf).default([]),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),Xf=zs(`type`,[wf,Tf,Ef]),Zf=zs(`type`,[wf,Tf,Ef,Df,Yf]),Qf=I({role:Qd,content:R([Zf,F(Zf)]),_meta:z(A(),P()).optional()}),$f=ed.extend({messages:F(Qf),modelPreferences:qf.optional(),systemPrompt:A().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:Y.optional(),tools:F(Ff).optional(),toolChoice:Jf.optional()}),ep=X.extend({method:V(`sampling/createMessage`),params:$f}),tp=Z.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:Qd,content:Xf}),np=Z.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:Qd,content:R([Zf,F(Zf)])}),rp=I({type:V(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),ip=I({type:V(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),ap=I({type:B([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),op=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),sp=I({type:V(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),cp=R([R([I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),R([op,sp]),R([I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(A())}),default:F(A()).optional()}),I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()})])]),rp,ip,ap]),lp=R([ed.extend({mode:V(`form`).optional(),message:A(),requestedSchema:I({type:V(`object`),properties:z(A(),cp),required:F(A()).optional()})}),ed.extend({mode:V(`url`),message:A(),elicitationId:A(),url:A().url()})]),up=X.extend({method:V(`elicitation/create`),params:lp}),dp=nd.extend({elicitationId:A()}),fp=rd.extend({method:V(`notifications/elicitation/complete`),params:dp}),pp=Z.extend({action:B([`accept`,`decline`,`cancel`]),content:hc(e=>e===null?void 0:e,z(A(),R([A(),M(),N(),F(A())])).optional())}),mp=I({type:V(`ref/resource`),uri:A()}),hp=I({type:V(`ref/prompt`),name:A()}),gp=$u.extend({ref:R([hp,mp]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()}),_p=X.extend({method:V(`completion/complete`),params:gp});function vp(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function yp(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let bp=Z.extend({completion:L({values:F(A()).max(100),total:H(M().int()),hasMore:H(N())})}),xp=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),Sp=X.extend({method:V(`roots/list`),params:$u.optional()}),Cp=Z.extend({roots:F(xp)}),wp=rd.extend({method:V(`notifications/roots/list_changed`),params:nd.optional()});R([kd,Td,_p,Wf,Cf,bf,nf,af,lf,pf,hf,Bf,If,Vd,Ud,Wd,Kd]),R([gd,Md,Od,wp,Bd]),R([md,tp,np,pp,Cp,Hd,Gd,Rd]),R([kd,ep,up,Sp,Vd,Ud,Wd,Kd]),R([gd,Md,Kf,_f,df,Vf,Mf,Bd,fp]),R([md,Dd,bp,jf,xf,rf,of,uf,Rf,Lf,Hd,Gd,Rd]);var $=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Q.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Tp(e.elicitations,n)}return new e(t,n,r)}},Tp=class extends ${constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Q.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Ep(e){return e===`completed`||e===`failed`||e===`cancelled`}function Dp(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Op(e,t){return Fu(e)?Mo(e,{target:Dp(t?.target),io:t?.pipeStrategy??`input`}):pl(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function kp(e){let t=zu(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Wu(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Ap(e,t){let n=Lu(e,t);if(!n.success)throw n.error;return n.data}var jp=class{constructor(e){this._options=e,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._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(gd,e=>{this._oncancel(e)}),this.setNotificationHandler(Md,e=>{this._onprogress(e)}),this.setRequestHandler(kd,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Vd,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Ud,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new $(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new $(Q.InvalidParams,`Task not found: ${r}`);if(!Ep(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Ep(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[qu]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Wd,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new $(Q.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Kd,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Task not found: ${e.params.taskId}`);if(Ep(n.status))throw new $(Q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new $(Q.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof $?e:new $(Q.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),$.fromError(Q.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),ud(e)||fd(e)?this._onresponse(e):od(e)?this._onrequest(e,t):cd(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=$.fromError(Q.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[qu]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Q.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=td(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new $(Q.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Q.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),ud(e)?n(e):n(new $(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(ud(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),ud(e)?r(e):r($.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Rd,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new $(Q.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Ep(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new $(Q.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new $(Q.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[qu]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof $?e:new $(Q.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Lu(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p($.fromError(Q.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Hd,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Gd,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},qd,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[qu]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[qu]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[qu]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=kp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Ap(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=kp(e);this._notificationHandlers.set(n,n=>{let r=Ap(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&od(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new $(Q.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new $(Q.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new $(Q.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Bd.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Ep(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new $(Q.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Ep(a.status))throw new $(Q.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Bd.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Ep(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Mp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Np(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];Mp(a)&&Mp(i)?n[r]={...a,...i}:n[r]=i}return n}var Pp=class{compile(e){throw Error(`[WebMCP] Ajv stub was invoked. This indicates the MCP SDK is bypassing PolyfillJsonSchemaValidator. Please report this as a bug.`)}getSchema(e){}errorsText(e){return``}};function Fp(){return new Pp({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0})}var Ip=class{constructor(e){this._ajv=e??Fp()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};function Lp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Rp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var zp=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}},Bp=class extends jp{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Hf.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Ip,this.setRequestHandler(Td,e=>this._oninitialize(e)),this.setNotificationHandler(Od,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Wf,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Hf.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new zp(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Np(this._capabilities,e)}setRequestHandler(e,t){let n=zu(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(Fu(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Lu(Bf,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new $(Q.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Lu(Rd,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new $(Q.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Lu(Rf,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new $(Q.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){Rp(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Lp(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ku.includes(t)?t:Gu,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`},md)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},np,t):this.request({method:`sampling/createMessage`,params:e},tp,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},pp,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},pp,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new $(Q.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof $?e:new $(Q.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},Cp,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};let Vp=Symbol.for(`mcp.completable`);function Hp(e){return!!e&&typeof e==`object`&&Vp in e}function Up(e){return e[Vp]?.complete}var Wp;(function(e){e.Completable=`McpCompletable`})(Wp||={});let Gp=/^[A-Za-z0-9._-]{1,128}$/;function Kp(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Gp.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function qp(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Jp(e){let t=Kp(e);return qp(e,t.warnings),t.isValid}var Yp=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Xp=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Bp(e,t)}get experimental(){return this._experimental||={tasks:new Yp(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(rm(If)),this.server.assertCanSetRequestHandler(rm(Bf)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(If,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=Bu(t.inputSchema);return e?Op(e,{strictUnions:!0,pipeStrategy:`input`}):Zp})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=Bu(t.outputSchema);e&&(n.outputSchema=Op(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Bf,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new $(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new $(Q.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new $(Q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof $&&e.code===Q.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Ru(Bu(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=Vu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new $(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Ru(Bu(e.outputSchema),t.structuredContent);if(!r.success){let e=Vu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new $(Q.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(rm(_p)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_p,async e=>{switch(e.params.ref.type){case`ref/prompt`:return vp(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return yp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new $(Q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return am;let r=zu(n.argsSchema)?.[e.params.argument.name];if(!Hp(r))return am;let i=Up(r);return i?im(await i(e.params.argument.value,e.params.context)):am}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return am;throw new $(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?im(await r(e.params.argument.value,e.params.context)):am}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(rm(nf)),this.server.assertCanSetRequestHandler(rm(af)),this.server.assertCanSetRequestHandler(rm(lf)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(nf,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(af,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(lf,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new $(Q.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new $(Q.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(rm(bf)),this.server.assertCanSetRequestHandler(rm(Cf)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(bf,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?nm(t.argsSchema):void 0}))})),this.server.setRequestHandler(Cf,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Ru(Bu(n.argsSchema),e.params.arguments);if(!r.success){let t=Vu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:Iu(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=Iu(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Hp(e instanceof qs?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Jp(e);let l={title:t,description:n,inputSchema:tm(r),outputSchema:tm(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Jp(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=Iu(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Iu(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let e=t[0];em(e)?(r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!em(t[0])&&(i=t.shift())):typeof e==`object`&&e&&(i=t.shift())}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};let Zp={type:`object`,properties:{}};function Qp(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function $p(e){return`_def`in e||`_zod`in e||Qp(e)}function em(e){return typeof e!=`object`||!e||$p(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Qp)}function tm(e){if(e)return em(e)?Iu(e):e}function nm(e){let t=zu(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Hu(t),required:!Uu(t)})):[]}function rm(e){let t=zu(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Wu(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function im(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let am={completion:{values:[],hasMore:!1}};var om=class{getValidator(e){return t=>{if(!J(t))return{valid:!1,data:void 0,errorMessage:`expected object arguments`};let n=vu(t,e);return n?{valid:!1,data:void 0,errorMessage:n.message}:{valid:!0,data:t,errorMessage:void 0}}}};let sm={type:`object`,properties:{}};function cm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function lm(e){return cm(e)&&Array.isArray(e.content)}function um(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function dm(e){if(!e||typeof e!=`object`)return!1;let{name:t,message:n}=e;return t===`SecurityError`&&typeof n==`string`&&/permissions policy|feature "tools" is disallowed/i.test(n)}function fm(e){return um(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>fm(e)):cm(e)?Object.values(e).every(e=>fm(e)):!1}function pm(e){if(!(!cm(e)||!fm(e)))return e}function mm(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function hm(e){if(lm(e))return e;let t=pm(e);return{content:[{type:`text`,text:mm(e)}],...t?{structuredContent:t}:{},isError:!1}}function gm(e){return e?.signal?e:{...e,signal:AbortSignal.timeout(1e4)}}var _m=class extends Xp{__isBrowserMcpServer=!0;native;_promptSchemas=new Map;_jsonValidator;_publicMethodsBound=!1;_provideContextDeprecationWarned=!1;_clearContextDeprecationWarned=!1;_unregisterToolDeprecationWarned=!1;_nativeToolCleanups=new Map;_producerEventTarget=new EventTarget;_ontoolchange=null;constructor(e,t){let n=new om,r={capabilities:Np(t?.capabilities||{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}}),jsonSchemaValidator:t?.jsonSchemaValidator??n};super(e,r),this._jsonValidator=n,this.native=t?.native,this.bindPublicApiMethods()}bindPublicApiMethods(){this._publicMethodsBound||=(this.registerTool=this.registerTool.bind(this),this.unregisterTool=this.unregisterTool.bind(this),this.provideContext=this.provideContext.bind(this),this.clearContext=this.clearContext.bind(this),this.listTools=this.listTools.bind(this),this.getTools=this.getTools.bind(this),this.callTool=this.callTool.bind(this),this.executeTool=this.executeTool.bind(this),this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.registerResource=this.registerResource.bind(this),this.listResources=this.listResources.bind(this),this.readResource=this.readResource.bind(this),this.registerPrompt=this.registerPrompt.bind(this),this.listPrompts=this.listPrompts.bind(this),this.getPrompt=this.getPrompt.bind(this),this.createMessage=this.createMessage.bind(this),this.elicitInput=this.elicitInput.bind(this),!0)}get _parentTools(){return this._registeredTools}get _parentResources(){return this._registeredResources}get _parentPrompts(){return this._registeredPrompts}toTransportSchema(e,t=!0){if(!e||typeof e!=`object`)return t?(console.warn(`[BrowserMcpServer] toTransportSchema received non-object schema (${typeof e}), using default`),sm):{};let n=Bu(e),r=n?Op(n,{strictUnions:!0,pipeStrategy:`input`}):e;return Object.keys(r).length===0?t?sm:r:t&&r.type===void 0?{type:`object`,...r}:r}isZodSchema(e){if(!e||typeof e!=`object`)return!1;let t=e;return`_zod`in t||`_def`in t}getNativeToolsApi(){if(!this.native)return;let e=this.native;if(!(typeof e.listTools!=`function`||typeof e.callTool!=`function`))return e}getNativeUnregisterTool(){if(!this.native)return;let e=this.native.unregisterTool;if(typeof e==`function`)return t=>e.call(this.native,t)}createNativeToolCleanup(e){let t=new AbortController,n;if(e){let r=()=>{t.abort()};e.aborted?r():(e.addEventListener(`abort`,r,{once:!0}),n=()=>e.removeEventListener(`abort`,r))}return{options:{signal:t.signal},abort:()=>{n?.(),t.signal.aborted||t.abort()}}}registerNativeToolMirror(e,t){if(!this.native)return;let n=this.native.registerTool,r=this.getNativeUnregisterTool(),i=t||!r?this.createNativeToolCleanup(t):void 0;try{i?n.call(this.native,e,i.options):n.call(this.native,e)}catch(e){if(i?.abort(),dm(e)){console.warn(`[BrowserMcpServer] Native WebMCP tool mirror is blocked by permissions policy; continuing with WebMCP transport registration only.`);return}throw e}if(!i)return;let a={abort:i.abort,nativeSignalAccepted:n.length>=2||!r};return this._nativeToolCleanups.set(e.name,a),a}unregisterNativeToolMirror(e,t){let n=this._nativeToolCleanups.get(e);this._nativeToolCleanups.delete(e);let r=this.getNativeUnregisterTool();if(t?.preferAbortSignal&&n?.nativeSignalAccepted===!0||!r){n?.abort();return}try{r(e)}finally{n?.abort()}}registerToolInServer(e){let t=this.toTransportSchema(e.inputSchema);return super.registerTool(e.name,{description:e.description,inputSchema:t,...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.annotations?{annotations:e.annotations}:{}},async t=>hm(await e.execute(t,{requestUserInteraction:async e=>e()}))),this.notifyProducerToolsChanged(),{unregister:()=>this.unregisterTool(e.name)}}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}addEventListener(e,t,n){this._producerEventTarget.addEventListener(e,t,n)}removeEventListener(e,t,n){this._producerEventTarget.removeEventListener(e,t,n)}dispatchEvent(e){return this._producerEventTarget.dispatchEvent(e)}notifyProducerToolsChanged(){queueMicrotask(()=>{let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[BrowserMcpServer] navigator.modelContext.ontoolchange handler threw:`,e)}this.dispatchEvent(e)})}backfillTools(e,t){let n=0;for(let r of e){if(!r?.name||this._parentTools[r.name])continue;let e={name:r.name,description:r.description??``,inputSchema:r.inputSchema??sm,execute:async e=>t(r.name,e)};r.outputSchema&&(e.outputSchema=r.outputSchema),r.annotations&&(e.annotations=r.annotations),this.registerToolInServer(e),n++}return n}registerTool(e,t){let n=t?.signal;if(n?.aborted)return console.warn(`[BrowserMcpServer] registerTool("${e?.name??`<unknown>`}") skipped: options.signal was already aborted.`),{unregister:()=>{}};this.registerNativeToolMirror(e,n);let r;try{r=this.registerToolInServer(e)}catch(t){if(this.native)try{this.unregisterNativeToolMirror(e.name)}catch(e){console.error(`[BrowserMcpServer] Rollback of native tool registration failed:`,e)}throw t}return n&&n.addEventListener(`abort`,()=>{this._parentTools[e.name]?.remove();try{this.unregisterNativeToolMirror(e.name,{preferAbortSignal:!0})}catch(e){console.warn(`[BrowserMcpServer] Native unregister via abort fallback failed:`,e)}this.notifyProducerToolsChanged()},{once:!0}),r}syncNativeTools(){let e=this.getNativeToolsApi();if(!e)return 0;let t=e.callTool.bind(e);return this.backfillTools(e.listTools(),async(e,n)=>t({name:e,arguments:n}))}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let t=this.resolveToolNameForUnregister(e),n=this._parentTools[t];n?.remove(),this.native&&this.unregisterNativeToolMirror(t),n&&this.notifyProducerToolsChanged()}clearRegisteredTools(){let e=!1;for(let t of Object.keys(this._parentTools))if(this._parentTools[t]?.remove(),e=!0,this.native)try{this.unregisterNativeToolMirror(t)}catch(e){console.warn(`[BrowserMcpServer] Native unregister during clear failed:`,e)}e&&this.notifyProducerToolsChanged()}registerResource(e){let t=super.registerResource(e.name,e.uri,{...e.description!==void 0&&{description:e.description},...e.mimeType!==void 0&&{mimeType:e.mimeType}},async t=>({contents:(await e.read(t)).contents}));return{unregister:()=>t.remove()}}registerPrompt(e){e.argsSchema&&this._promptSchemas.set(e.name,e.argsSchema);let t=super.registerPrompt(e.name,{...e.description!==void 0&&{description:e.description}},async t=>({messages:(await e.get(t)).messages}));return{unregister:()=>{this._promptSchemas.delete(e.name),t.remove()}}}provideContext(e){this.warnProvideContextDeprecationOnce(),this.clearRegisteredTools();for(let t of e?.tools??[])this.registerTool(t)}clearContext(){this.warnClearContextDeprecationOnce(),this.clearRegisteredTools()}resolveToolNameForUnregister(e){if(typeof e==`string`)return e;if(cm(e)&&typeof e.name==`string`)return e.name;throw TypeError(`Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.`)}warnProvideContextDeprecationOnce(){this._provideContextDeprecationWarned||(this._provideContextDeprecationWarned=!0,console.warn(`[BrowserMcpServer] navigator.modelContext.provideContext() is deprecated and will be removed in the next major version. Register tools individually with registerTool() instead.`))}warnClearContextDeprecationOnce(){this._clearContextDeprecationWarned||(this._clearContextDeprecationWarned=!0,console.warn(`[BrowserMcpServer] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead.`))}warnUnregisterToolDeprecationOnce(){this._unregisterToolDeprecationWarned||(this._unregisterToolDeprecationWarned=!0,console.warn(`[BrowserMcpServer] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister.`))}listResources(){return Object.entries(this._parentResources).filter(([,e])=>e.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata}))}async readResource(e){let t=this._parentResources[e];if(!t)throw Error(`Resource not found: ${e}`);return t.readCallback(new URL(e),{})}listPrompts(){return Object.entries(this._parentPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{let n=this._promptSchemas.get(e);return{name:e,...t.description!==void 0&&{description:t.description},...n?.properties?{arguments:Object.entries(n.properties).map(([e,t])=>({name:e,...typeof t==`object`&&t&&`description`in t?{description:t.description}:{},...n.required?.includes(e)?{required:!0}:{}}))}:{}}})}async getPrompt(e,t={}){let n=this._parentPrompts[e];if(!n)throw Error(`Prompt not found: ${e}`);let r=this._promptSchemas.get(e);if(r){let n=this._jsonValidator.getValidator(r)(t);if(!n.valid)throw Error(`Invalid arguments for prompt ${e}: ${n.errorMessage}`)}return n.callback(t,{})}listTools(){return Object.entries(this._parentTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,description:t.description??``,inputSchema:this.toTransportSchema(t.inputSchema??sm)};return t.outputSchema&&(n.outputSchema=this.toTransportSchema(t.outputSchema,!1)),t.annotations&&(n.annotations=t.annotations),n})}getTools(){return this.listTools().map(e=>{let t;try{t=JSON.stringify(e.inputSchema??sm)}catch{t=JSON.stringify(sm)}return{name:e.name,description:e.description??``,inputSchema:t}})}async validateToolInput(e,t,n){if(!e.inputSchema)return;if(this.isZodSchema(e.inputSchema)){let r=await Ru(e.inputSchema,t??{});if(!r.success)throw Error(`Invalid arguments for tool ${n}: ${Vu(r.error)}`);return r.data}let r=this._jsonValidator.getValidator(e.inputSchema)(t??{});if(!r.valid)throw Error(`Invalid arguments for tool ${n}: ${r.errorMessage}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;let r=t;if(!(`content`in r)||r.isError||!r.structuredContent)return;if(this.isZodSchema(e.outputSchema)){let t=await Ru(e.outputSchema,r.structuredContent);if(!t.success)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${Vu(t.error)}`);return}let i=this._jsonValidator.getValidator(e.outputSchema)(r.structuredContent);if(!i.valid)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${i.errorMessage}`)}async callTool(e){let t=this._parentTools[e.name];if(!t)throw Error(`Tool not found: ${e.name}`);return t.handler(e.arguments??{},{})}async executeTool(e,t={}){return this.callTool({name:e,arguments:t})}async connect(e){return this.setToolRequestHandlers(),this.setResourceRequestHandlers(),this.setPromptRequestHandlers(),this.server.setRequestHandler(If,()=>({tools:this.listTools()})),this.server.setRequestHandler(bf,()=>({prompts:this.listPrompts()})),this.server.setRequestHandler(Cf,async e=>{let t=this._parentPrompts[e.params.name];if(!t)throw Error(`Prompt ${e.params.name} not found`);if(!t.enabled)throw Error(`Prompt ${e.params.name} disabled`);let n=this._promptSchemas.get(e.params.name);if(n){let r=this._jsonValidator.getValidator(n)(e.params.arguments??{});if(!r.valid)throw Error(`Invalid arguments for prompt ${e.params.name}: ${r.errorMessage}`);return t.callback(e.params.arguments,{})}return t.callback({},{})}),super.connect(e)}async createMessage(e,t){return this.server.createMessage(e,gm(t))}async elicitInput(e,t){return this.server.elicitInput(e,gm(t))}};(function(e){return e.START=`start`,e.STARTED=`started`,e.STOP=`stop`,e.STOPPED=`stopped`,e.PING=`ping`,e.PONG=`pong`,e.ERROR=`error`,e.LIST_TOOLS=`list_tools`,e.CALL_TOOL=`call_tool`,e.TOOL_LIST_UPDATED=`tool_list_updated`,e.TOOL_LIST_UPDATED_ACK=`tool_list_updated_ack`,e.PROCESS_DATA=`process_data`,e.SERVER_STARTED=`server_started`,e.SERVER_STOPPED=`server_stopped`,e.ERROR_FROM_NATIVE_HOST=`error_from_native_host`,e.CONNECT_NATIVE=`connectNative`,e.PING_NATIVE=`ping_native`,e.DISCONNECT_NATIVE=`disconnect_native`,e})({}),{NAME:`com.chromemcp.nativehost`,DEFAULT_PORT:12306}.NAME;var vm=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;_serverReadyTimeout;_serverReadyRetryMs;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-iframe`,this._serverReadyRetryMs=e.serverReadyRetryMs??250}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;this._clientOrigin=e.origin;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){this.broadcastServerReady();return}try{let e=pd.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this.broadcastServerReady()}broadcastServerReady(){window.parent&&window.parent!==window?(window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},`*`),this.clearServerReadyRetry()):this.scheduleServerReadyRetry()}scheduleServerReadyRetry(){this._serverReadyTimeout||=setTimeout(()=>{this._serverReadyTimeout=void 0,this._started&&this.broadcastServerReady()},this._serverReadyRetryMs)}clearServerReadyRetry(){this._serverReadyTimeout&&=(clearTimeout(this._serverReadyTimeout),void 0)}async send(e){if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}window.parent&&window.parent!==window?window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this._clientOrigin):console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`)}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._started=!1,this._clientOrigin&&window.parent&&window.parent!==window&&window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},`*`),this.clearServerReadyRetry(),this.onclose?.()}},ym=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_beforeUnloadHandler;_cleanupInterval;_pendingRequests=new Map;SELF_TARGET_ORIGIN=`*`;REQUEST_TIMEOUT_MS=3e5;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-default`}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},this.SELF_TARGET_ORIGIN);return}try{let e=pd.parse(t);`method`in e&&`id`in e&&e.id!==void 0&&this._pendingRequests.set(e.id,{request:e,receivedAt:Date.now(),interruptedSent:!1}),this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._beforeUnloadHandler=()=>{this._handleBeforeUnload()},window.addEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval=setInterval(()=>{this._cleanupStaleRequests()},6e4),window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},this.SELF_TARGET_ORIGIN)}async send(e){if(!this._started)throw Error(`Transport not started`);if((`result`in e||`error`in e)&&e.id!==void 0){if(this._pendingRequests.get(e.id)?.interruptedSent){console.debug(`[TabServerTransport] Suppressing response for ${e.id} - interrupted response already sent`),this._pendingRequests.delete(e.id);return}this._pendingRequests.delete(e.id)}window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this.SELF_TARGET_ORIGIN)}_handleBeforeUnload(){let e=Array.from(this._pendingRequests.entries()).reverse();for(let[t,n]of e){n.interruptedSent=!0;let e={jsonrpc:`2.0`,id:t,result:{content:[{type:`text`,text:`Tool execution interrupted by page navigation`}],metadata:{navigationInterrupted:!0,originalMethod:`method`in n.request?n.request.method:`unknown`,timestamp:Date.now()}}};try{window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this.SELF_TARGET_ORIGIN)}catch(e){console.error(`[TabServerTransport] Failed to send beforeunload response:`,e)}}this._pendingRequests.clear()}_cleanupStaleRequests(){let e=Date.now(),t=[];for(let[n,r]of this._pendingRequests)e-r.receivedAt>this.REQUEST_TIMEOUT_MS&&t.push(n);if(t.length>0){console.warn(`[TabServerTransport] Cleaning up ${t.length} stale requests`);for(let e of t)this._pendingRequests.delete(e)}}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._beforeUnloadHandler&&window.removeEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval!==void 0&&clearInterval(this._cleanupInterval),this._pendingRequests.clear(),this._started=!1,window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},this.SELF_TARGET_ORIGIN),this.onclose?.()}};let bm=null;function xm(){return typeof window<`u`&&window.navigator!==void 0}function Sm(e){try{Object.defineProperty(navigator,`modelContext`,{configurable:!0,enumerable:!0,writable:!1,value:e})}catch{Object.defineProperty(Object.getPrototypeOf(navigator),`modelContext`,{configurable:!0,enumerable:!0,get(){return e}})}navigator.modelContext!==e&&console.error(`[WebModelContext] Failed to replace navigator.modelContext.`,`Descriptor:`,Object.getOwnPropertyDescriptor(navigator,`modelContext`))}function Cm(e){if(window.parent!==window&&e?.iframeServer!==!1){let{allowedOrigins:t,...n}=typeof e?.iframeServer==`object`?e.iframeServer:{};return new vm({allowedOrigins:t??[`*`],...n})}if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);let{allowedOrigins:t,...n}=typeof e?.tabServer==`object`?e.tabServer:{};return new ym({allowedOrigins:t??[`*`],...n})}function wm(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch(e){console.warn(`[WebMCP] Failed to parse testing inputSchema JSON:`,e);return}}function Tm(){let e=navigator.modelContextTesting;if(e){if(typeof e.getRegisteredTools==`function`)return{testingShim:e,tools:e.getRegisteredTools()};if(typeof e.listTools==`function`)return{testingShim:e,tools:e.listTools().map(e=>({name:e.name,description:e.description??``,inputSchema:wm(e.inputSchema)??{type:`object`,properties:{}}}))}}}function Em(e){let t=Tm();if(!t)return 0;let{testingShim:n,tools:r}=t;return e.backfillTools(r,async(e,t)=>{let r=await n.executeTool(e,JSON.stringify(t??{}));if(r===null)return{content:[{type:`text`,text:`Tool execution interrupted by navigation`}],isError:!0};let i;try{i=JSON.parse(r)}catch(t){throw Error(`Failed to parse serialized tool response for ${e}: ${t instanceof Error?t.message:String(t)}`)}if(!i||typeof i!=`object`||Array.isArray(i))throw Error(`Invalid serialized tool response for ${e}`);return i})}function Dm(e){if(!xm()||bm||navigator.modelContext?.__isBrowserMcpServer)return;Nu({installTestingShim:e?.installTestingShim??`if-missing`});let t=navigator.modelContext;if(!t)throw Error(`navigator.modelContext is not available`);let n=new _m({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:t});n.syncNativeTools(),Em(n),Sm(n);let r=Cm(e?.transport);bm={native:t,server:n,transport:r},n.connect(r).catch(e=>{console.error(`[WebModelContext] Failed to connect MCP transport:`,e)})}function Om(){if(!bm)return;let{native:e,server:t,transport:n}=bm;bm=null,t.close(),n.close(),Sm(e)}if(typeof window<`u`&&typeof document<`u`){let e=window.__webModelContextOptions;if(e?.autoInitialize!==!1)try{Dm(e)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}}return e.cleanupWebModelContext=Om,e.initializeWebModelContext=Dm,e})({});
|
|
66
|
+
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Wc(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===b.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:G(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??U(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:G(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===b.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Rc(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===b.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===b.ZodBranded&&e.keyType._def.type._def.typeName===b.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Ec(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Gc(e,t){return t.mapStrategy===`record`?Wc(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[G(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||U(t),G(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||U(t)],minItems:2,maxItems:2}}}function Kc(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function qc(e){return e.target===`openAi`?void 0:{not:U({...e,currentPath:[...e.currentPath,`not`]})}}function Jc(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}let Yc={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Xc(e,t){if(t.target===`openApi3`)return Zc(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Yc&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Yc[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Zc(e,t)}let Zc=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>G(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Qc(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Yc[e.innerType._def.typeName],nullable:!0}:{type:[Yc[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=G(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=G(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function $c(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,xc(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?H(n,`minimum`,r.value,r.message,t):H(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),H(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?H(n,`maximum`,r.value,r.message,t):H(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),H(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:H(n,`multipleOf`,r.value,r.message,t);break}return n}function el(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=nl(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=G(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=tl(e,t);return o!==void 0&&(r.additionalProperties=o),r}function tl(e,t){if(e.catchall._def.typeName!==`ZodNever`)return G(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function nl(e){try{return e.isOptional()}catch{return!0}}let rl=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return G(e.innerType._def,t);let n=G(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:U(t)},n]}:U(t)},il=(e,t)=>{if(t.pipeStrategy===`input`)return G(e.in._def,t);if(t.pipeStrategy===`output`)return G(e.out._def,t);let n=G(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,G(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function al(e,t){return G(e.type._def,t)}function ol(e,t){let n={type:`array`,uniqueItems:!0,items:G(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&H(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&H(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function sl(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>G(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:G(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>G(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function cl(e){return{not:U(e)}}function ll(e){return U(e)}let ul=(e,t)=>G(e.innerType._def,t),dl=(e,t,n)=>{switch(t){case b.ZodString:return Rc(e,n);case b.ZodNumber:return $c(e,n);case b.ZodObject:return el(e,n);case b.ZodBigInt:return wc(e,n);case b.ZodBoolean:return Tc();case b.ZodDate:return Oc(e,n);case b.ZodUndefined:return cl(n);case b.ZodNull:return Jc(n);case b.ZodArray:return Cc(e,n);case b.ZodUnion:case b.ZodDiscriminatedUnion:return Xc(e,n);case b.ZodIntersection:return Pc(e,n);case b.ZodTuple:return sl(e,n);case b.ZodRecord:return Wc(e,n);case b.ZodLiteral:return Fc(e,n);case b.ZodEnum:return Mc(e);case b.ZodNativeEnum:return Kc(e);case b.ZodNullable:return Qc(e,n);case b.ZodOptional:return rl(e,n);case b.ZodMap:return Gc(e,n);case b.ZodSet:return ol(e,n);case b.ZodLazy:return()=>e.getter()._def;case b.ZodPromise:return al(e,n);case b.ZodNaN:case b.ZodNever:return qc(n);case b.ZodEffects:return jc(e,n);case b.ZodAny:return U(n);case b.ZodUnknown:return ll(n);case b.ZodDefault:return Ac(e,n);case b.ZodBranded:return Ec(e,n);case b.ZodReadonly:return ul(e,n);case b.ZodCatch:return Dc(e,n);case b.ZodPipeline:return il(e,n);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return(e=>void 0)(t)}};function G(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==_c)return i}if(r&&!n){let e=fl(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=dl(e,e.typeName,t),o=typeof a==`function`?G(a(),t):a;if(o&&pl(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}let fl=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Sc(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),U(t)):t.$refStrategy===`seen`?U(t):void 0}},pl=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),ml=(e,t)=>{let n=bc(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:G(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??U(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=G(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??U(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function hl(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!hl(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!hl(e[r],t[r]))return!1;return!0}return e===t}function gl(e){return encodeURI(_l(e))}function _l(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let vl={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},yl={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},bl={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},xl=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function Sl(e,t=Object.create(null),n=xl,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Sl(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(bl[i])continue;let a=`${r}/${gl(i)}`,o=e[i];if(Array.isArray(o)){if(vl[i]){let e=o.length;for(let r=0;r<e;r++)Sl(o[r],t,n,`${a}/${r}`)}}else if(yl[i])for(let e in o)Sl(o[e],t,n,`${a}/${gl(e)}`);else Sl(o,t,n,a)}return t}let Cl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,wl=[0,31,28,31,30,31,30,31,31,30,31,30,31],Tl=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,El=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Dl=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Ol=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,kl=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Al=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,jl=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Ml=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Nl=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Pl=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Fl=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Il=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Ll=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Rl(e){return e.test.bind(e)}let zl={date:Vl,time:Hl.bind(void 0,!1),"date-time":Wl,duration:Ll,uri:ql,"uri-reference":Rl(Dl),"uri-template":Rl(Ol),url:Rl(kl),email:Pl,hostname:Rl(El),ipv4:Rl(Fl),ipv6:Rl(Il),regex:Yl,uuid:Rl(Al),"json-pointer":Rl(jl),"json-pointer-uri-fragment":Rl(Ml),"relative-json-pointer":Rl(Nl)};function Bl(e){return e%4==0&&(e%100!=0||e%400==0)}function Vl(e){let t=e.match(Cl);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Bl(n)?29:wl[r])}function Hl(e,t){let n=t.match(Tl);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}let Ul=/t|\s/i;function Wl(e){let t=e.split(Ul);return t.length==2&&Vl(t[0])&&Hl(!0,t[1])}let Gl=/\/|:/,Kl=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ql(e){return Gl.test(e)&&Kl.test(e)}let Jl=/[^\\]\\Z/;function Yl(e){if(Jl.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function Xl(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function K(e,t,n=`2019-09`,r=Sl(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:ee,required:te,not:ne,anyOf:re,allOf:g,oneOf:ie,if:ae,then:_,else:v,format:oe,properties:se,patternProperties:ce,additionalProperties:le,unevaluatedProperties:ue,minProperties:de,maxProperties:fe,propertyNames:pe,dependentRequired:me,dependentSchemas:he,dependencies:ge,prefixItems:_e,items:ve,additionalItems:ye,unevaluatedItems:be,contains:xe,minContains:Se,maxContains:Ce,minItems:we,maxItems:Te,uniqueItems:Ee,minimum:De,maximum:Oe,exclusiveMinimum:ke,exclusiveMaximum:Ae,multipleOf:je,minLength:Me,maxLength:Ne,pattern:Pe,__absolute_ref__:Fe,__absolute_recursive_ref__:Ie}=t,y=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[Ie]:a,u=`${s}/$recursiveRef`,d=K(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||y.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Fe||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Fe&&Fe!==d&&(e+=` Absolute URI "${Fe}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
67
|
+
- `)}`,Error(e)}let l=`${s}/$ref`,u=K(e,t,n,r,i,a,o,l,c);if(u.valid||y.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:y.length===0,errors:y}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?hl(e,h)||y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),ee!==void 0&&(u===`object`||u===`array`?ee.some(t=>hl(e,t))||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`}):ee.some(t=>e===t)||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`})),ne!==void 0){let t=`${s}/not`;K(e,ne,n,r,i,a,o,t).valid&&y.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Le=[];if(re!==void 0){let t=`${s}/anyOf`,l=y.length,u=!1;for(let s=0;s<re.length;s++){let l=re[s],d=Object.create(c),f=K(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u||=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(g!==void 0){let t=`${s}/allOf`,l=y.length,u=!0;for(let s=0;s<g.length;s++){let l=g[s],d=Object.create(c),f=K(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u&&=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(ie!==void 0){let t=`${s}/oneOf`,l=y.length,u=ie.filter((s,l)=>{let u=Object.create(c),d=K(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return y.push(...d.errors),d.valid&&Le.push(u),d.valid}).length;u===1?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Le),ae!==void 0){let t=`${s}/if`;if(K(e,ae,n,r,i,a,o,t,c).valid){if(_!==void 0){let l=K(e,_,n,r,i,a,o,`${s}/then`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(v!==void 0){let l=K(e,v,n,r,i,a,o,`${s}/else`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(te!==void 0)for(let t of te)t in e||y.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(de!==void 0&&t.length<de&&y.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0&&t.length>fe&&y.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${fe} properties.`}),pe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${gl(s)}`,c=K(s,pe,n,r,i,a,e,t);c.valid||y.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(me!==void 0){let t=`${s}/dependantRequired`;for(let n in me)if(n in e){let r=me[n];for(let i of r)i in e||y.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(he!==void 0)for(let t in he){let l=`${s}/dependentSchemas`;if(t in e){let s=K(e,he[t],n,r,i,a,o,`${l}/${gl(t)}`,c);s.valid||y.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ge!==void 0){let t=`${s}/dependencies`;for(let s in ge)if(s in e){let c=ge[s];if(Array.isArray(c))for(let n of c)n in e||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=K(e,c,n,r,i,a,o,`${t}/${gl(s)}`);l.valid||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(se!==void 0){let t=`${s}/properties`;for(let s in se){if(!(s in e))continue;let d=`${o}/${gl(s)}`,f=K(e[s],se[s],n,r,i,a,d,`${t}/${gl(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,y.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ce!==void 0){let t=`${s}/patternProperties`;for(let s in ce){let d=new RegExp(s,`u`),f=ce[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${gl(p)}`,h=K(e[p],f,n,r,i,a,m,`${t}/${gl(s)}`);h.valid?c[p]=l[p]=!0:(u=i,y.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&le!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${gl(s)}`,f=K(e[s],le,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,y.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ue!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${gl(s)}`,u=K(e[s],ue,n,r,i,a,l,t);u.valid?c[s]=!0:y.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Te!==void 0&&e.length>Te&&y.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Te}).`}),we!==void 0&&e.length<we&&y.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${we}).`});let t=e.length,l=0,u=!1;if(_e!==void 0){let d=`${s}/prefixItems`,f=Math.min(_e.length,t);for(;l<f;l++){let t=K(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ve!==void 0){let d=`${s}/items`;if(Array.isArray(ve)){let s=Math.min(ve.length,t);for(;l<s;l++){let t=K(e[l],ve[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=K(e[l],ve,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ye!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=K(e[l],ye,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,y.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(xe!==void 0)if(t===0&&Se===void 0)y.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(Se!==void 0&&t<Se)y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${Se}).`});else{let l=`${s}/contains`,u=y.length,d=0;for(let s=0;s<t;s++){let t=K(e[s],xe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):y.push(...t.errors)}d>=(Se||0)&&(y.length=u),Se===void 0&&Ce===void 0&&d===0?y.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):Se!==void 0&&d<Se?y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${Se} items matching schema. Only ${d} items were found.`}):Ce!==void 0&&d>Ce&&y.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${d} items were found.`})}if(!u&&be!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=K(e[l],be,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||y.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(Ee)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&hl(r,t))&&(y.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(De!==void 0&&(ke===!0&&e<=De||e<De)&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ke?`or equal to `:``} ${De}.`}),Oe!==void 0&&(Ae===!0&&e>=Oe||e>Oe)&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ae?`or equal to `:``} ${Oe}.`})):(De!==void 0&&e<De&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${De}.`}),Oe!==void 0&&e>Oe&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Oe}.`}),ke!==void 0&&e<=ke&&y.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${ke}.`}),Ae!==void 0&&e>=Ae&&y.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ae}.`})),je!==void 0){let t=e%je;Math.abs(0-t)>=1.1920929e-7&&Math.abs(je-t)>=1.1920929e-7&&y.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${je}.`})}}else if(u===`string`){let t=Me===void 0&&Ne===void 0?0:Xl(e);Me!==void 0&&t<Me&&y.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Me}).`}),Ne!==void 0&&t>Ne&&y.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ne}).`}),Pe!==void 0&&!new RegExp(Pe,`u`).test(e)&&y.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),oe!==void 0&&zl[oe]&&!zl[oe](e)&&y.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${oe}".`})}return{valid:y.length===0,errors:y}}var Zl=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Sl(e)}validate(e){return K(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Sl(e,this.lookup)}};let Ql=`Failed to parse input arguments`,$l=`Tool was executed but the invocation failed. For example, the script function threw an error`,eu=`Tool was cancelled`,tu={type:`object`,properties:{}},nu=[`draft-2020-12`,`draft-07`],ru=Symbol(`standardValidator`),q={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1};var iu=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,t){let n=t?.signal;if(n?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${e?.name??`<unknown>`}") skipped: options.signal was already aborted.`);return}let r=_u(e,this.tools);this.tools.set(r.name,r),this.notifyToolsChanged(),n&&n.addEventListener(`abort`,()=>{this.tools.delete(r.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let t=cu(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,t,n){return this.executeToolByName(e.name,t,n,!1)}getTestingShim(){return this.testingShim||=new au(this),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{let t;try{t=JSON.stringify(e.inputSchema??{type:`object`})}catch{t=`{"type":"object"}`}return{name:e.name,description:e.description,inputSchema:t}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{let t=this.tools.get(e.name);return{...e,title:t?.title??``,origin:globalThis.location?.origin??``,window:globalThis.window}})}async executeToolForTesting(e,t,n){return this.executeToolByName(e,t,n,!0)}async executeToolByName(e,t,n,r){if(n?.signal?.aborted)throw ou(eu);let i=this.tools.get(e);if(!i)throw ou(`Tool not found: ${e}`);let a=su(t),o=await xu(a,i);if(o)throw ou(o);let s=!0,c={requestUserInteraction:async t=>{if(!s)throw Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof t!=`function`)throw TypeError(`requestUserInteraction(callback) requires a function callback`);return t()}};try{let e=i.execute(a,c),t=await Au(Promise.resolve(e),n?.signal);if(r)return ku(Du(t));let o=JSON.stringify(t);return o===void 0?null:o}catch(e){throw ou(e instanceof Error?`${$l}: ${e.message}`:$l)}finally{s=!1}}notifyToolsChanged(){queueMicrotask(()=>{let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister.`))}},au=class extends EventTarget{context;_ontoolchange=null;constructor(e){super(),this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,t,n){return this.context.executeToolForTesting(e,t,n)}getCrossDocumentScriptToolResult(){return Promise.resolve(`[]`)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!=`function`)throw TypeError(`Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.`);this.addEventListener(`toolchange`,e)}dispatchToolChange(){let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.dispatchEvent(new Event(`toolschanged`))}};function ou(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function su(e){let t;try{t=JSON.parse(e)}catch{throw ou(Ql)}if(!t||typeof t!=`object`||Array.isArray(t))throw ou(Ql);return t}function cu(e){if(typeof e==`string`)return e;if(J(e)&&typeof e.name==`string`)return e.name;throw TypeError(`Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.`)}function J(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function lu(e){if(!J(e))return null;let t=e[`~standard`];return J(t)?t:null}function uu(e){let t=lu(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function du(e){let t=lu(e);return!t||t.version!==1||!J(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function fu(e){return{"~standard":{version:1,vendor:`@mcp-b/webmcp-polyfill-json-schema`,validate(t){if(!J(t))return{issues:[{message:`expected object arguments`}]};let n=vu(t,e);return n?{issues:[n]}:{value:t}}}}}function pu(e){for(let t of nu)try{let n=e[`~standard`].jsonSchema.input({target:t});return hu(n),n}catch(e){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,e)}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function mu(e){if(e===void 0){let e=tu;return{inputSchema:e,standardValidator:fu(e)}}if(du(e)){let t=pu(e);return{inputSchema:t,standardValidator:fu(t)}}if(uu(e))return{inputSchema:tu,standardValidator:e};if(hu(e),Object.keys(e).length===0)return{inputSchema:tu,standardValidator:fu(tu)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:fu(t)}}function hu(e){if(!J(e))throw Error(`inputSchema must be a JSON Schema object`);gu(e,`$`)}function gu(e,t){let n=e.type;if(n!==void 0&&typeof n!=`string`&&!(Array.isArray(n)&&n.every(e=>typeof e==`string`&&e.length>0)))throw Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let r=e.required;if(r!==void 0&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`)))throw Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let i=e.properties;if(i!==void 0){if(!J(i))throw Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[e,n]of Object.entries(i)){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.properties.${e}: expected object schema`);gu(n,`${t}.properties.${e}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[e,n]of a.entries()){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.items[${e}]: expected object schema`);gu(n,`${t}.items[${e}]`)}else if(J(a))gu(a,`${t}.items`);else throw Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let n of[`allOf`,`anyOf`,`oneOf`]){let r=e[n];if(r!==void 0){if(!Array.isArray(r))throw Error(`Invalid JSON Schema at ${t}: "${n}" must be an array`);for(let[e,i]of r.entries()){if(!J(i))throw Error(`Invalid JSON Schema at ${t}.${n}[${e}]: expected object schema`);gu(i,`${t}.${n}[${e}]`)}}}let o=e.not;if(o!==void 0){if(!J(o))throw Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);gu(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function _u(e,t){if(!e||typeof e!=`object`)throw TypeError(`registerTool(tool) requires a tool object`);if(typeof e.name!=`string`||e.name.length===0)throw TypeError(`Tool "name" must be a non-empty string`);if(typeof e.description!=`string`||e.description.length===0)throw TypeError(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`);if(t.has(e.name))throw Error(`Tool already registered: ${e.name}`);let n=mu(e.inputSchema),r=e.annotations,i=r?{...r,...r.readOnlyHint===`true`?{readOnlyHint:!0}:r.readOnlyHint===`false`?{readOnlyHint:!1}:{},...r.destructiveHint===`true`?{destructiveHint:!0}:r.destructiveHint===`false`?{destructiveHint:!1}:{},...r.idempotentHint===`true`?{idempotentHint:!0}:r.idempotentHint===`false`?{idempotentHint:!1}:{},...r.openWorldHint===`true`?{openWorldHint:!0}:r.openWorldHint===`false`?{openWorldHint:!1}:{}}:void 0;return{...e,...i?{annotations:i}:{},inputSchema:n.inputSchema,[ru]:n.standardValidator}}function vu(e,t){let n=new Zl(t,`2020-12`,!0).validate(e);if(n.valid)return null;let r=n.errors[n.errors.length-1];return r?{message:r.error}:{message:`Input validation failed`}}function yu(e){if(!e||e.length===0)return null;let t=e.map(e=>J(e)&&`key`in e?e.key:e).map(e=>String(e)).filter(e=>e.length>0);return t.length===0?null:t.join(`.`)}async function bu(e,t){let n;try{n=await Promise.resolve(t[`~standard`].validate(e))}catch(e){let t=e instanceof Error?`: ${e.message}`:``;return console.error(`[WebMCPPolyfill] Standard Schema validation threw unexpectedly:`,e),`Input validation error: schema validation failed${t}`}if(!n.issues||n.issues.length===0)return null;let r=n.issues[0];if(!r)return`Input validation error`;let i=yu(r?.path);return i?`Input validation error: ${r.message} at ${i}`:`Input validation error: ${r.message}`}async function xu(e,t){return bu(e,t[ru])}function Su(e){return J(e)&&Array.isArray(e.content)}function Cu(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function wu(e){return Cu(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>wu(e)):J(e)?Object.values(e).every(e=>wu(e)):!1}function Tu(e){if(!(!J(e)||!wu(e)))return e}function Eu(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Du(e){if(Su(e))return e;let t=Tu(e);return{content:[{type:`text`,text:Eu(e)}],...t?{structuredContent:t}:{},isError:!1}}function Ou(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function ku(e){if(e.isError)throw ou(Ou(e)?.replace(/^Error:\s*/i,``).trim()||$l);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw ou($l)}}function Au(e,t){return t?t.aborted?Promise.reject(ou(eu)):new Promise((n,r)=>{let i=()=>{a(),r(ou(eu))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function ju(){return typeof navigator<`u`?navigator:null}function Mu(){return typeof document<`u`?document:null}function Nu(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function Pu(e,t){Object.defineProperty(e,`modelContext`,{configurable:!0,enumerable:!0,writable:!1,value:t})}let Fu=!1;function Iu(e,t){Object.defineProperty(e,`modelContext`,{configurable:!0,enumerable:!0,get(){return Fu||(Fu=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.`)),t}})}function Lu(e){let t=ju(),n=Mu();if(!t&&!n||n?.modelContext)return;let r=t?.modelContext,i=!!r;if(q.installed&&Ru(),n&&r){q.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,`modelContext`),Pu(n,r),q.installedDocumentModelContext=!0,q.installed=!0;return}if(i)return;let a=new iu,o=a;if(o.__isWebMCPPolyfill=!0,n&&(q.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,`modelContext`),Pu(n,o),q.installedDocumentModelContext=!0),t){q.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),q.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),Fu=!1,Iu(t,o),q.installedNavigatorModelContext=!0;let n=e?.installTestingShim??`if-missing`,r=!!t.modelContextTesting;(n===`always`||(n===!0||n===`if-missing`)&&!r)&&(Nu(t,`modelContextTesting`,a.getTestingShim()),q.installedNavigatorModelContextTesting=!0)}q.installed=!0}function Ru(){if(!q.installed)return;let e=(e,t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]},t=ju(),n=Mu();n&&q.installedDocumentModelContext&&e(n,`modelContext`,q.previousDocumentModelContextDescriptor),t&&q.installedNavigatorModelContext&&e(t,`modelContext`,q.previousNavigatorModelContextDescriptor),t&&q.installedNavigatorModelContextTesting&&e(t,`modelContextTesting`,q.previousNavigatorModelContextTestingDescriptor),q.installed=!1,q.previousDocumentModelContextDescriptor=void 0,q.previousNavigatorModelContextDescriptor=void 0,q.previousNavigatorModelContextTestingDescriptor=void 0,q.installedDocumentModelContext=!1,q.installedNavigatorModelContext=!1,q.installedNavigatorModelContextTesting=!1,Fu=!1}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Lu(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}function zu(e){return!!e._zod}function Bu(e){let t=Object.values(e);if(t.length===0)return Fo({});let n=t.every(zu),r=t.every(e=>!zu(e));if(n)return Fo(e);if(r)return ht(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Vu(e,t){return zu(e)?pn(e,t):e.safeParse(t)}async function Hu(e,t){return zu(e)?await hn(e,t):await e.safeParseAsync(t)}function Uu(e){if(!e)return;let t;if(t=zu(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Wu(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return Bu(e)}}if(zu(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Gu(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Ku(e){return e.description}function qu(e){if(zu(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Ju(e){if(zu(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}let Yu=`2025-11-25`,Xu=[Yu,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Zu=`io.modelcontextprotocol/related-task`,Y=pc(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Qu=R([A(),M().int()]),$u=A();L({ttl:R([M(),js()]).optional(),pollInterval:M().optional()});let ed=I({ttl:M().optional()}),td=I({taskId:A()}),nd=L({progressToken:Qu.optional(),[Zu]:td.optional()}),rd=I({_meta:nd.optional()}),id=rd.extend({task:ed.optional()}),ad=e=>id.safeParse(e).success,X=I({method:A(),params:rd.loose().optional()}),od=I({_meta:nd.optional()}),sd=I({method:A(),params:od.loose().optional()}),Z=L({_meta:nd.optional()}),cd=R([A(),M().int()]),ld=I({jsonrpc:B(`2.0`),id:cd,...X.shape}).strict(),ud=e=>ld.safeParse(e).success,dd=I({jsonrpc:B(`2.0`),...sd.shape}).strict(),fd=e=>dd.safeParse(e).success,pd=I({jsonrpc:B(`2.0`),id:cd,result:Z}).strict(),md=e=>pd.safeParse(e).success;var Q;(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`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Q||={});let hd=I({jsonrpc:B(`2.0`),id:cd.optional(),error:I({code:M().int(),message:A(),data:P().optional()})}).strict(),gd=e=>hd.safeParse(e).success,_d=R([ld,dd,pd,hd]);R([pd,hd]);let vd=Z.strict(),yd=od.extend({requestId:cd.optional(),reason:A().optional()}),bd=sd.extend({method:B(`notifications/cancelled`),params:yd}),xd=I({icons:F(I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:Ws([`light`,`dark`]).optional()})).optional()}),Sd=I({name:A(),title:A().optional()}),Cd=Sd.extend({...Sd.shape,...xd.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),wd=gc(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Vs(I({form:Vs(I({applyDefaults:N().optional()}),z(A(),P())).optional(),url:Y.optional()}),z(A(),P()).optional())),Td=L({list:Y.optional(),cancel:Y.optional(),requests:L({sampling:L({createMessage:Y.optional()}).optional(),elicitation:L({create:Y.optional()}).optional()}).optional()}),Ed=L({list:Y.optional(),cancel:Y.optional(),requests:L({tools:L({call:Y.optional()}).optional()}).optional()}),Dd=I({experimental:z(A(),Y).optional(),sampling:I({context:Y.optional(),tools:Y.optional()}).optional(),elicitation:wd.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:Td.optional()}),Od=rd.extend({protocolVersion:A(),capabilities:Dd,clientInfo:Cd}),kd=X.extend({method:B(`initialize`),params:Od}),Ad=I({experimental:z(A(),Y).optional(),logging:Y.optional(),completions:Y.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:Ed.optional()}),jd=Z.extend({protocolVersion:A(),capabilities:Ad,serverInfo:Cd,instructions:A().optional()}),Md=sd.extend({method:B(`notifications/initialized`),params:od.optional()}),Nd=X.extend({method:B(`ping`),params:rd.optional()}),Pd=I({progress:M(),total:V(M()),message:V(A())}),Fd=I({...od.shape,...Pd.shape,progressToken:Qu}),Id=sd.extend({method:B(`notifications/progress`),params:Fd}),Ld=rd.extend({cursor:$u.optional()}),Rd=X.extend({params:Ld.optional()}),zd=Z.extend({nextCursor:$u.optional()}),Bd=Ws([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Vd=I({taskId:A(),status:Bd,ttl:R([M(),js()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:V(M()),statusMessage:V(A())}),Hd=Z.extend({task:Vd}),Ud=od.merge(Vd),Wd=sd.extend({method:B(`notifications/tasks/status`),params:Ud}),Gd=X.extend({method:B(`tasks/get`),params:rd.extend({taskId:A()})}),Kd=Z.merge(Vd),qd=X.extend({method:B(`tasks/result`),params:rd.extend({taskId:A()})});Z.loose();let Jd=Rd.extend({method:B(`tasks/list`)}),Yd=zd.extend({tasks:F(Vd)}),Xd=X.extend({method:B(`tasks/cancel`),params:rd.extend({taskId:A()})}),Zd=Z.merge(Vd),Qd=I({uri:A(),mimeType:V(A()),_meta:z(A(),P()).optional()}),$d=Qd.extend({text:A()}),ef=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),tf=Qd.extend({blob:ef}),nf=Ws([`user`,`assistant`]),rf=I({audience:F(nf).optional(),priority:M().min(0).max(1).optional(),lastModified:Lo({offset:!0}).optional()}),af=I({...Sd.shape,...xd.shape,uri:A(),description:V(A()),mimeType:V(A()),annotations:rf.optional(),_meta:V(L({}))}),of=I({...Sd.shape,...xd.shape,uriTemplate:A(),description:V(A()),mimeType:V(A()),annotations:rf.optional(),_meta:V(L({}))}),sf=Rd.extend({method:B(`resources/list`)}),cf=zd.extend({resources:F(af)}),lf=Rd.extend({method:B(`resources/templates/list`)}),uf=zd.extend({resourceTemplates:F(of)}),df=rd.extend({uri:A()}),ff=df,pf=X.extend({method:B(`resources/read`),params:ff}),mf=Z.extend({contents:F(R([$d,tf]))}),hf=sd.extend({method:B(`notifications/resources/list_changed`),params:od.optional()}),gf=df,_f=X.extend({method:B(`resources/subscribe`),params:gf}),vf=df,yf=X.extend({method:B(`resources/unsubscribe`),params:vf}),bf=od.extend({uri:A()}),xf=sd.extend({method:B(`notifications/resources/updated`),params:bf}),Sf=I({name:A(),description:V(A()),required:V(N())}),Cf=I({...Sd.shape,...xd.shape,description:V(A()),arguments:V(F(Sf)),_meta:V(L({}))}),wf=Rd.extend({method:B(`prompts/list`)}),Tf=zd.extend({prompts:F(Cf)}),Ef=rd.extend({name:A(),arguments:z(A(),A()).optional()}),Df=X.extend({method:B(`prompts/get`),params:Ef}),Of=I({type:B(`text`),text:A(),annotations:rf.optional(),_meta:z(A(),P()).optional()}),kf=I({type:B(`image`),data:ef,mimeType:A(),annotations:rf.optional(),_meta:z(A(),P()).optional()}),Af=I({type:B(`audio`),data:ef,mimeType:A(),annotations:rf.optional(),_meta:z(A(),P()).optional()}),jf=I({type:B(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),Mf=I({type:B(`resource`),resource:R([$d,tf]),annotations:rf.optional(),_meta:z(A(),P()).optional()}),Nf=R([Of,kf,Af,af.extend({type:B(`resource_link`)}),Mf]),Pf=I({role:nf,content:Nf}),Ff=Z.extend({description:A().optional(),messages:F(Pf)}),If=sd.extend({method:B(`notifications/prompts/list_changed`),params:od.optional()}),Lf=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Rf=I({taskSupport:Ws([`required`,`optional`,`forbidden`]).optional()}),zf=I({...Sd.shape,...xd.shape,description:A().optional(),inputSchema:I({type:B(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()),outputSchema:I({type:B(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()).optional(),annotations:Lf.optional(),execution:Rf.optional(),_meta:z(A(),P()).optional()}),Bf=Rd.extend({method:B(`tools/list`)}),Vf=zd.extend({tools:F(zf)}),Hf=Z.extend({content:F(Nf).default([]),structuredContent:z(A(),P()).optional(),isError:N().optional()});Hf.or(Z.extend({toolResult:P()}));let Uf=id.extend({name:A(),arguments:z(A(),P()).optional()}),Wf=X.extend({method:B(`tools/call`),params:Uf}),Gf=sd.extend({method:B(`notifications/tools/list_changed`),params:od.optional()});I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)});let Kf=Ws([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),qf=rd.extend({level:Kf}),Jf=X.extend({method:B(`logging/setLevel`),params:qf}),Yf=od.extend({level:Kf,logger:A().optional(),data:P()}),Xf=sd.extend({method:B(`notifications/message`),params:Yf}),Zf=I({hints:F(I({name:A().optional()})).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),Qf=I({mode:Ws([`auto`,`required`,`none`]).optional()}),$f=I({type:B(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:F(Nf).default([]),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),ep=zs(`type`,[Of,kf,Af]),tp=zs(`type`,[Of,kf,Af,jf,$f]),np=I({role:nf,content:R([tp,F(tp)]),_meta:z(A(),P()).optional()}),rp=id.extend({messages:F(np),modelPreferences:Zf.optional(),systemPrompt:A().optional(),includeContext:Ws([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:Y.optional(),tools:F(zf).optional(),toolChoice:Qf.optional()}),ip=X.extend({method:B(`sampling/createMessage`),params:rp}),ap=Z.extend({model:A(),stopReason:V(Ws([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:nf,content:ep}),op=Z.extend({model:A(),stopReason:V(Ws([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:nf,content:R([tp,F(tp)])}),sp=I({type:B(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),cp=I({type:B(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:Ws([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),lp=I({type:Ws([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),up=I({type:B(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),dp=I({type:B(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),fp=R([R([I({type:B(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),R([up,dp]),R([I({type:B(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:B(`string`),enum:F(A())}),default:F(A()).optional()}),I({type:B(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()})])]),sp,cp,lp]),pp=R([id.extend({mode:B(`form`).optional(),message:A(),requestedSchema:I({type:B(`object`),properties:z(A(),fp),required:F(A()).optional()})}),id.extend({mode:B(`url`),message:A(),elicitationId:A(),url:A().url()})]),mp=X.extend({method:B(`elicitation/create`),params:pp}),hp=od.extend({elicitationId:A()}),gp=sd.extend({method:B(`notifications/elicitation/complete`),params:hp}),_p=Z.extend({action:Ws([`accept`,`decline`,`cancel`]),content:gc(e=>e===null?void 0:e,z(A(),R([A(),M(),N(),F(A())])).optional())}),vp=I({type:B(`ref/resource`),uri:A()}),yp=I({type:B(`ref/prompt`),name:A()}),bp=rd.extend({ref:R([yp,vp]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()}),xp=X.extend({method:B(`completion/complete`),params:bp});function Sp(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Cp(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let wp=Z.extend({completion:L({values:F(A()).max(100),total:V(M().int()),hasMore:V(N())})}),Tp=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),Ep=X.extend({method:B(`roots/list`),params:rd.optional()}),Dp=Z.extend({roots:F(Tp)}),Op=sd.extend({method:B(`notifications/roots/list_changed`),params:od.optional()});R([Nd,kd,xp,Jf,Df,wf,sf,lf,pf,_f,yf,Wf,Bf,Gd,qd,Jd,Xd]),R([bd,Id,Md,Op,Wd]),R([vd,ap,op,_p,Dp,Kd,Yd,Hd]),R([Nd,ip,mp,Ep,Gd,qd,Jd,Xd]),R([bd,Id,Xf,xf,hf,Gf,If,Wd,gp]),R([vd,jd,wp,Ff,Tf,cf,uf,mf,Hf,Vf,Kd,Yd,Hd]);var $=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Q.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new kp(e.elicitations,n)}return new e(t,n,r)}},kp=class extends ${constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Q.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Ap(e){return e===`completed`||e===`failed`||e===`cancelled`}function jp(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Mp(e,t){return zu(e)?Mo(e,{target:jp(t?.target),io:t?.pipeStrategy??`input`}):ml(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Np(e){let t=Uu(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Ju(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Pp(e,t){let n=Vu(e,t);if(!n.success)throw n.error;return n.data}var Fp=class{constructor(e){this._options=e,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._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(bd,e=>{this._oncancel(e)}),this.setNotificationHandler(Id,e=>{this._onprogress(e)}),this.setRequestHandler(Nd,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Gd,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(qd,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new $(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new $(Q.InvalidParams,`Task not found: ${r}`);if(!Ap(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(Ap(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Zu]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Jd,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new $(Q.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Xd,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Task not found: ${e.params.taskId}`);if(Ap(n.status))throw new $(Q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new $(Q.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof $?e:new $(Q.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),$.fromError(Q.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),md(e)||gd(e)?this._onresponse(e):ud(e)?this._onrequest(e,t):fd(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=$.fromError(Q.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Zu]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Q.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=ad(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new $(Q.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Q.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),md(e)?n(e):n(new $(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(md(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),md(e)?r(e):r($.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Hd,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new $(Q.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},Ap(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new $(Q.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new $(Q.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Zu]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof $?e:new $(Q.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Vu(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p($.fromError(Q.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Kd,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Yd,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Zd,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Zu]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Zu]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Zu]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Np(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Pp(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Np(e);this._notificationHandlers.set(n,n=>{let r=Pp(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&ud(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new $(Q.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new $(Q.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new $(Q.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Wd.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),Ap(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new $(Q.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Ap(a.status))throw new $(Q.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Wd.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),Ap(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lp(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];Ip(a)&&Ip(i)?n[r]={...a,...i}:n[r]=i}return n}var Rp=class{compile(e){throw Error(`[WebMCP] Ajv stub was invoked. This indicates the MCP SDK is bypassing PolyfillJsonSchemaValidator. Please report this as a bug.`)}getSchema(e){}errorsText(e){return``}};function zp(){return new Rp({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0})}var Bp=class{constructor(e){this._ajv=e??zp()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};function Vp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Hp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Up=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}},Wp=class extends Fp{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Kf.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Bp,this.setRequestHandler(kd,e=>this._oninitialize(e)),this.setNotificationHandler(Md,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Jf,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Kf.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Up(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Lp(this._capabilities,e)}setRequestHandler(e,t){let n=Uu(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(zu(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Vu(Wf,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new $(Q.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Vu(Hd,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new $(Q.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Vu(Hf,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new $(Q.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){Hp(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Vp(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Xu.includes(t)?t:Yu,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`},vd)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},op,t):this.request({method:`sampling/createMessage`,params:e},ap,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},_p,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},_p,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new $(Q.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof $?e:new $(Q.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},Dp,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};let Gp=Symbol.for(`mcp.completable`);function Kp(e){return!!e&&typeof e==`object`&&Gp in e}function qp(e){return e[Gp]?.complete}var Jp;(function(e){e.Completable=`McpCompletable`})(Jp||={});let Yp=/^[A-Za-z0-9._-]{1,128}$/;function Xp(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Yp.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Zp(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Qp(e){let t=Xp(e);return Zp(e,t.warnings),t.isValid}var $p=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},em=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Wp(e,t)}get experimental(){return this._experimental||={tasks:new $p(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(sm(Bf)),this.server.assertCanSetRequestHandler(sm(Wf)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Bf,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=Wu(t.inputSchema);return e?Mp(e,{strictUnions:!0,pipeStrategy:`input`}):tm})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=Wu(t.outputSchema);e&&(n.outputSchema=Mp(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Wf,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new $(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new $(Q.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new $(Q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof $&&e.code===Q.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Hu(Wu(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=Gu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new $(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Hu(Wu(e.outputSchema),t.structuredContent);if(!r.success){let e=Gu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new $(Q.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(sm(xp)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(xp,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Sp(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Cp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new $(Q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return lm;let r=Uu(n.argsSchema)?.[e.params.argument.name];if(!Kp(r))return lm;let i=qp(r);return i?cm(await i(e.params.argument.value,e.params.context)):lm}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return lm;throw new $(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?cm(await r(e.params.argument.value,e.params.context)):lm}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(sm(sf)),this.server.assertCanSetRequestHandler(sm(lf)),this.server.assertCanSetRequestHandler(sm(pf)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(sf,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(lf,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(pf,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new $(Q.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new $(Q.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(sm(wf)),this.server.assertCanSetRequestHandler(sm(Df)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(wf,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?om(t.argsSchema):void 0}))})),this.server.setRequestHandler(Df,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Hu(Wu(n.argsSchema),e.params.arguments);if(!r.success){let t=Gu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:Bu(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=Bu(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Kp(e instanceof Js?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Qp(e);let l={title:t,description:n,inputSchema:am(r),outputSchema:am(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Qp(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=Bu(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Bu(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let e=t[0];im(e)?(r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!im(t[0])&&(i=t.shift())):typeof e==`object`&&e&&(i=t.shift())}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};let tm={type:`object`,properties:{}};function nm(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function rm(e){return`_def`in e||`_zod`in e||nm(e)}function im(e){return typeof e!=`object`||!e||rm(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(nm)}function am(e){if(e)return im(e)?Bu(e):e}function om(e){let t=Uu(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Ku(t),required:!qu(t)})):[]}function sm(e){let t=Uu(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Ju(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function cm(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let lm={completion:{values:[],hasMore:!1}};var um=class{getValidator(e){return t=>{if(!J(t))return{valid:!1,data:void 0,errorMessage:`expected object arguments`};let n=vu(t,e);return n?{valid:!1,data:void 0,errorMessage:n.message}:{valid:!0,data:t,errorMessage:void 0}}}};let dm={type:`object`,properties:{}};function fm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function pm(e){return fm(e)&&Array.isArray(e.content)}function mm(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function hm(e){if(!e||typeof e!=`object`)return!1;let{name:t,message:n}=e;return t===`SecurityError`&&typeof n==`string`&&/permissions policy|feature "tools" is disallowed/i.test(n)}function gm(e){return mm(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>gm(e)):fm(e)?Object.values(e).every(e=>gm(e)):!1}function _m(e){if(!(!fm(e)||!gm(e)))return e}function vm(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function ym(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function bm(e){if(pm(e))return e;let t=_m(e);return{content:[{type:`text`,text:ym(e)}],...t?{structuredContent:t}:{},isError:!1}}function xm(e){return e?.signal?e:{...e,signal:AbortSignal.timeout(1e4)}}var Sm=class extends em{__isBrowserMcpServer=!0;native;_promptSchemas=new Map;_jsonValidator;_publicMethodsBound=!1;_unregisterToolDeprecationWarned=!1;_nativeToolCleanups=new Map;_producerEventTarget=new EventTarget;_ontoolchange=null;constructor(e,t){let n=new um,r={capabilities:Lp(t?.capabilities||{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}}),jsonSchemaValidator:t?.jsonSchemaValidator??n};super(e,r),this._jsonValidator=n,this.native=t?.native,this.bindPublicApiMethods()}bindPublicApiMethods(){this._publicMethodsBound||=(this.registerTool=this.registerTool.bind(this),this.unregisterTool=this.unregisterTool.bind(this),this.listTools=this.listTools.bind(this),this.getTools=this.getTools.bind(this),this.callTool=this.callTool.bind(this),this.executeTool=this.executeTool.bind(this),this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.registerResource=this.registerResource.bind(this),this.listResources=this.listResources.bind(this),this.readResource=this.readResource.bind(this),this.registerPrompt=this.registerPrompt.bind(this),this.listPrompts=this.listPrompts.bind(this),this.getPrompt=this.getPrompt.bind(this),this.createMessage=this.createMessage.bind(this),this.elicitInput=this.elicitInput.bind(this),!0)}get _parentTools(){return this._registeredTools}get _parentResources(){return this._registeredResources}get _parentPrompts(){return this._registeredPrompts}toTransportSchema(e,t=!0){if(!e||typeof e!=`object`)return t?(console.warn(`[BrowserMcpServer] toTransportSchema received non-object schema (${typeof e}), using default`),dm):{};let n=Wu(e),r=n?Mp(n,{strictUnions:!0,pipeStrategy:`input`}):e;return Object.keys(r).length===0?t?dm:r:t&&r.type===void 0?{type:`object`,...r}:r}isZodSchema(e){if(!e||typeof e!=`object`)return!1;let t=e;return`_zod`in t||`_def`in t}getNativeToolsApi(){if(!this.native)return;let e=this.native;if(!(typeof e.listTools!=`function`||typeof e.callTool!=`function`))return e}getNativeUnregisterTool(){if(!this.native)return;let e=this.native.unregisterTool;if(typeof e==`function`)return t=>e.call(this.native,t)}createNativeToolCleanup(e){let t=new AbortController,n;if(e){let r=()=>{t.abort()};e.aborted?r():(e.addEventListener(`abort`,r,{once:!0}),n=()=>e.removeEventListener(`abort`,r))}return{options:{signal:t.signal},abort:()=>{n?.(),t.signal.aborted||t.abort()}}}registerNativeToolMirror(e,t){if(!this.native)return;let n=this.native.registerTool,r=this.getNativeUnregisterTool(),i=t||!r?this.createNativeToolCleanup(t):void 0,a;try{a=i?n.call(this.native,e,i.options):n.call(this.native,e)}catch(e){if(i?.abort(),hm(e)){console.warn(`[BrowserMcpServer] Native WebMCP tool mirror is blocked by permissions policy; continuing with WebMCP transport registration only.`);return}throw e}if(!i)return;let o={abort:i.abort,nativeSignalAccepted:n.length>=2||!r};return this._nativeToolCleanups.set(e.name,o),vm(a)&&a.then(void 0,t=>{if(i.abort(),this._nativeToolCleanups.get(e.name)===o&&this._nativeToolCleanups.delete(e.name),hm(t)){console.warn(`[BrowserMcpServer] Native WebMCP tool mirror is blocked by permissions policy; continuing with WebMCP transport registration only.`);return}console.warn(`[BrowserMcpServer] Native WebMCP tool mirror registration rejected; continuing with WebMCP transport registration only.`,t)}),o}unregisterNativeToolMirror(e,t){let n=this._nativeToolCleanups.get(e);this._nativeToolCleanups.delete(e);let r=this.getNativeUnregisterTool();if(t?.preferAbortSignal&&n?.nativeSignalAccepted===!0||!r){n?.abort();return}try{r(e)}finally{n?.abort()}}registerToolInServer(e){let t=this.toTransportSchema(e.inputSchema);return super.registerTool(e.name,{description:e.description,inputSchema:t,...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.annotations?{annotations:e.annotations}:{}},async t=>bm(await e.execute(t,{requestUserInteraction:async e=>e()}))),this.notifyProducerToolsChanged(),{unregister:()=>this.unregisterTool(e.name)}}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}addEventListener(e,t,n){this._producerEventTarget.addEventListener(e,t,n)}removeEventListener(e,t,n){this._producerEventTarget.removeEventListener(e,t,n)}dispatchEvent(e){return this._producerEventTarget.dispatchEvent(e)}notifyProducerToolsChanged(){queueMicrotask(()=>{let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[BrowserMcpServer] navigator.modelContext.ontoolchange handler threw:`,e)}this.dispatchEvent(e)})}backfillTools(e,t){let n=0;for(let r of e){if(!r?.name||this._parentTools[r.name])continue;let e={name:r.name,description:r.description??``,inputSchema:r.inputSchema??dm,execute:async e=>t(r.name,e)};r.outputSchema&&(e.outputSchema=r.outputSchema),r.annotations&&(e.annotations=r.annotations),this.registerToolInServer(e),n++}return n}registerTool(e,t){let n=t?.signal;if(n?.aborted)return console.warn(`[BrowserMcpServer] registerTool("${e?.name??`<unknown>`}") skipped: options.signal was already aborted.`),{unregister:()=>{}};this.registerNativeToolMirror(e,n);let r;try{r=this.registerToolInServer(e)}catch(t){if(this.native)try{this.unregisterNativeToolMirror(e.name)}catch(e){console.error(`[BrowserMcpServer] Rollback of native tool registration failed:`,e)}throw t}return n&&n.addEventListener(`abort`,()=>{this._parentTools[e.name]?.remove();try{this.unregisterNativeToolMirror(e.name,{preferAbortSignal:!0})}catch(e){console.warn(`[BrowserMcpServer] Native unregister via abort fallback failed:`,e)}this.notifyProducerToolsChanged()},{once:!0}),r}syncNativeTools(){let e=this.getNativeToolsApi();if(!e)return 0;let t=e.callTool.bind(e);return this.backfillTools(e.listTools(),async(e,n)=>t({name:e,arguments:n}))}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let t=this.resolveToolNameForUnregister(e),n=this._parentTools[t];n?.remove(),this.native&&this.unregisterNativeToolMirror(t),n&&this.notifyProducerToolsChanged()}registerResource(e){let t=super.registerResource(e.name,e.uri,{...e.description!==void 0&&{description:e.description},...e.mimeType!==void 0&&{mimeType:e.mimeType}},async t=>({contents:(await e.read(t)).contents}));return{unregister:()=>t.remove()}}registerPrompt(e){e.argsSchema&&this._promptSchemas.set(e.name,e.argsSchema);let t=super.registerPrompt(e.name,{...e.description!==void 0&&{description:e.description}},async t=>({messages:(await e.get(t)).messages}));return{unregister:()=>{this._promptSchemas.delete(e.name),t.remove()}}}resolveToolNameForUnregister(e){if(typeof e==`string`)return e;if(fm(e)&&typeof e.name==`string`)return e.name;throw TypeError(`Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.`)}warnUnregisterToolDeprecationOnce(){this._unregisterToolDeprecationWarned||(this._unregisterToolDeprecationWarned=!0,console.warn(`[BrowserMcpServer] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister.`))}listResources(){return Object.entries(this._parentResources).filter(([,e])=>e.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata}))}async readResource(e){let t=this._parentResources[e];if(!t)throw Error(`Resource not found: ${e}`);return t.readCallback(new URL(e),{})}listPrompts(){return Object.entries(this._parentPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{let n=this._promptSchemas.get(e);return{name:e,...t.description!==void 0&&{description:t.description},...n?.properties?{arguments:Object.entries(n.properties).map(([e,t])=>({name:e,...typeof t==`object`&&t&&`description`in t?{description:t.description}:{},...n.required?.includes(e)?{required:!0}:{}}))}:{}}})}async getPrompt(e,t={}){let n=this._parentPrompts[e];if(!n)throw Error(`Prompt not found: ${e}`);let r=this._promptSchemas.get(e);if(r){let n=this._jsonValidator.getValidator(r)(t);if(!n.valid)throw Error(`Invalid arguments for prompt ${e}: ${n.errorMessage}`)}return n.callback(t,{})}listTools(){return Object.entries(this._parentTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,description:t.description??``,inputSchema:this.toTransportSchema(t.inputSchema??dm)};return t.outputSchema&&(n.outputSchema=this.toTransportSchema(t.outputSchema,!1)),t.annotations&&(n.annotations=t.annotations),n})}async getTools(){let e=typeof globalThis.location==`object`&&typeof globalThis.location?.origin==`string`?globalThis.location.origin:``,t=typeof globalThis.window==`object`?globalThis.window:void 0;return this.listTools().map(n=>{let r;try{r=JSON.stringify(n.inputSchema??dm)}catch{r=JSON.stringify(dm)}return{name:n.name,title:typeof n.annotations?.title==`string`?n.annotations.title:n.description??``,description:n.description??``,inputSchema:r,origin:e,window:t}})}async validateToolInput(e,t,n){if(!e.inputSchema)return;if(this.isZodSchema(e.inputSchema)){let r=await Hu(e.inputSchema,t??{});if(!r.success)throw Error(`Invalid arguments for tool ${n}: ${Gu(r.error)}`);return r.data}let r=this._jsonValidator.getValidator(e.inputSchema)(t??{});if(!r.valid)throw Error(`Invalid arguments for tool ${n}: ${r.errorMessage}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;let r=t;if(!(`content`in r)||r.isError||!r.structuredContent)return;if(this.isZodSchema(e.outputSchema)){let t=await Hu(e.outputSchema,r.structuredContent);if(!t.success)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${Gu(t.error)}`);return}let i=this._jsonValidator.getValidator(e.outputSchema)(r.structuredContent);if(!i.valid)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${i.errorMessage}`)}async callTool(e){let t=this._parentTools[e.name];if(!t)throw Error(`Tool not found: ${e.name}`);return t.handler(e.arguments??{},{})}async executeTool(e,t={}){if(typeof e==`string`)return this.callTool({name:e,arguments:typeof t==`string`?JSON.parse(t):t});let n=await this.callTool({name:e.name,arguments:typeof t==`string`?JSON.parse(t):t}),r=JSON.stringify(n);return r===void 0?null:r}async connect(e){return this.setToolRequestHandlers(),this.setResourceRequestHandlers(),this.setPromptRequestHandlers(),this.server.setRequestHandler(Bf,()=>({tools:this.listTools()})),this.server.setRequestHandler(wf,()=>({prompts:this.listPrompts()})),this.server.setRequestHandler(Df,async e=>{let t=this._parentPrompts[e.params.name];if(!t)throw Error(`Prompt ${e.params.name} not found`);if(!t.enabled)throw Error(`Prompt ${e.params.name} disabled`);let n=this._promptSchemas.get(e.params.name);if(n){let r=this._jsonValidator.getValidator(n)(e.params.arguments??{});if(!r.valid)throw Error(`Invalid arguments for prompt ${e.params.name}: ${r.errorMessage}`);return t.callback(e.params.arguments,{})}return t.callback({},{})}),super.connect(e)}async createMessage(e,t){return this.server.createMessage(e,xm(t))}async elicitInput(e,t){return this.server.elicitInput(e,xm(t))}};(function(e){return e.START=`start`,e.STARTED=`started`,e.STOP=`stop`,e.STOPPED=`stopped`,e.PING=`ping`,e.PONG=`pong`,e.ERROR=`error`,e.LIST_TOOLS=`list_tools`,e.CALL_TOOL=`call_tool`,e.TOOL_LIST_UPDATED=`tool_list_updated`,e.TOOL_LIST_UPDATED_ACK=`tool_list_updated_ack`,e.PROCESS_DATA=`process_data`,e.SERVER_STARTED=`server_started`,e.SERVER_STOPPED=`server_stopped`,e.ERROR_FROM_NATIVE_HOST=`error_from_native_host`,e.CONNECT_NATIVE=`connectNative`,e.PING_NATIVE=`ping_native`,e.DISCONNECT_NATIVE=`disconnect_native`,e})({}),{NAME:`com.chromemcp.nativehost`,DEFAULT_PORT:12306}.NAME;var Cm=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;_serverReadyTimeout;_serverReadyRetryMs;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-iframe`,this._serverReadyRetryMs=e.serverReadyRetryMs??250}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;this._clientOrigin=e.origin;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){this.broadcastServerReady();return}try{let e=_d.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this.broadcastServerReady()}broadcastServerReady(){window.parent&&window.parent!==window?(window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},`*`),this.clearServerReadyRetry()):this.scheduleServerReadyRetry()}scheduleServerReadyRetry(){this._serverReadyTimeout||=setTimeout(()=>{this._serverReadyTimeout=void 0,this._started&&this.broadcastServerReady()},this._serverReadyRetryMs)}clearServerReadyRetry(){this._serverReadyTimeout&&=(clearTimeout(this._serverReadyTimeout),void 0)}async send(e){if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}window.parent&&window.parent!==window?window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this._clientOrigin):console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`)}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._started=!1,this._clientOrigin&&window.parent&&window.parent!==window&&window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},`*`),this.clearServerReadyRetry(),this.onclose?.()}},wm=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_beforeUnloadHandler;_cleanupInterval;_pendingRequests=new Map;SELF_TARGET_ORIGIN=`*`;REQUEST_TIMEOUT_MS=3e5;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-default`}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},this.SELF_TARGET_ORIGIN);return}try{let e=_d.parse(t);`method`in e&&`id`in e&&e.id!==void 0&&this._pendingRequests.set(e.id,{request:e,receivedAt:Date.now(),interruptedSent:!1}),this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._beforeUnloadHandler=()=>{this._handleBeforeUnload()},window.addEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval=setInterval(()=>{this._cleanupStaleRequests()},6e4),window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},this.SELF_TARGET_ORIGIN)}async send(e){if(!this._started)throw Error(`Transport not started`);if((`result`in e||`error`in e)&&e.id!==void 0){if(this._pendingRequests.get(e.id)?.interruptedSent){console.debug(`[TabServerTransport] Suppressing response for ${e.id} - interrupted response already sent`),this._pendingRequests.delete(e.id);return}this._pendingRequests.delete(e.id)}window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this.SELF_TARGET_ORIGIN)}_handleBeforeUnload(){let e=Array.from(this._pendingRequests.entries()).reverse();for(let[t,n]of e){n.interruptedSent=!0;let e={jsonrpc:`2.0`,id:t,result:{content:[{type:`text`,text:`Tool execution interrupted by page navigation`}],metadata:{navigationInterrupted:!0,originalMethod:`method`in n.request?n.request.method:`unknown`,timestamp:Date.now()}}};try{window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this.SELF_TARGET_ORIGIN)}catch(e){console.error(`[TabServerTransport] Failed to send beforeunload response:`,e)}}this._pendingRequests.clear()}_cleanupStaleRequests(){let e=Date.now(),t=[];for(let[n,r]of this._pendingRequests)e-r.receivedAt>this.REQUEST_TIMEOUT_MS&&t.push(n);if(t.length>0){console.warn(`[TabServerTransport] Cleaning up ${t.length} stale requests`);for(let e of t)this._pendingRequests.delete(e)}}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._beforeUnloadHandler&&window.removeEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval!==void 0&&clearInterval(this._cleanupInterval),this._pendingRequests.clear(),this._started=!1,window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},this.SELF_TARGET_ORIGIN),this.onclose?.()}};let Tm=null;function Em(){return typeof window<`u`&&window.navigator!==void 0}function Dm(){return Object.getOwnPropertyDescriptor(navigator,`modelContext`)?navigator.modelContext:document.modelContext??navigator.modelContext}function Om(e){try{Object.defineProperty(document,`modelContext`,{configurable:!0,enumerable:!0,writable:!1,value:e})}catch{Object.defineProperty(Object.getPrototypeOf(document),`modelContext`,{configurable:!0,enumerable:!0,get(){return e}})}document.modelContext!==e&&console.error(`[WebModelContext] Failed to replace document.modelContext.`,`Descriptor:`,Object.getOwnPropertyDescriptor(document,`modelContext`))}function km(e){try{Object.defineProperty(navigator,`modelContext`,{configurable:!0,enumerable:!0,writable:!1,value:e})}catch{Object.defineProperty(Object.getPrototypeOf(navigator),`modelContext`,{configurable:!0,enumerable:!0,get(){return e}})}navigator.modelContext!==e&&console.error(`[WebModelContext] Failed to replace navigator.modelContext.`,`Descriptor:`,Object.getOwnPropertyDescriptor(navigator,`modelContext`))}function Am(e){Om(e),km(e)}function jm(e){if(window.parent!==window&&e?.iframeServer!==!1){let{allowedOrigins:t,...n}=typeof e?.iframeServer==`object`?e.iframeServer:{};return new Cm({allowedOrigins:t??[`*`],...n})}if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);let{allowedOrigins:t,...n}=typeof e?.tabServer==`object`?e.tabServer:{};return new wm({allowedOrigins:t??[`*`],...n})}function Mm(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch(e){console.warn(`[WebMCP] Failed to parse testing inputSchema JSON:`,e);return}}function Nm(){let e=navigator.modelContextTesting;if(e){if(typeof e.getRegisteredTools==`function`)return{testingShim:e,tools:e.getRegisteredTools()};if(typeof e.listTools==`function`)return{testingShim:e,tools:e.listTools().map(e=>({name:e.name,description:e.description??``,inputSchema:Mm(e.inputSchema)??{type:`object`,properties:{}}}))}}}function Pm(e){let t=Nm();if(!t)return 0;let{testingShim:n,tools:r}=t;return e.backfillTools(r,async(e,t)=>{let r=await n.executeTool(e,JSON.stringify(t??{}));if(r===null)return{content:[{type:`text`,text:`Tool execution interrupted by navigation`}],isError:!0};let i;try{i=JSON.parse(r)}catch(t){throw Error(`Failed to parse serialized tool response for ${e}: ${t instanceof Error?t.message:String(t)}`)}if(!i||typeof i!=`object`||Array.isArray(i))throw Error(`Invalid serialized tool response for ${e}`);return i})}function Fm(e){if(!Em()||Tm||Dm()?.__isBrowserMcpServer)return;Lu({installTestingShim:e?.installTestingShim??`if-missing`});let t=Dm();if(!t)throw Error(`modelContext is not available`);let n=new Sm({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:t});n.syncNativeTools(),Pm(n);let r=Object.getOwnPropertyDescriptor(document,`modelContext`),i=Object.getOwnPropertyDescriptor(navigator,`modelContext`);Am(n);let a=jm(e?.transport);Tm={native:t,server:n,transport:a,previousDocumentModelContextDescriptor:r,previousNavigatorModelContextDescriptor:i},n.connect(a).catch(e=>{console.error(`[WebModelContext] Failed to connect MCP transport:`,e)})}function Im(){if(!Tm)return;let{server:e,transport:t,previousDocumentModelContextDescriptor:n,previousNavigatorModelContextDescriptor:r}=Tm;Tm=null,e.close(),t.close(),n?Object.defineProperty(document,`modelContext`,n):delete document.modelContext,r?Object.defineProperty(navigator,`modelContext`,r):delete navigator.modelContext}if(typeof window<`u`&&typeof document<`u`){let e=window.__webModelContextOptions;if(e?.autoInitialize!==!1)try{Fm(e)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}}return e.cleanupWebModelContext=Im,e.initializeWebModelContext=Fm,e})({});
|
package/dist/index.js
CHANGED
|
@@ -7,14 +7,30 @@ let runtime = null;
|
|
|
7
7
|
function isBrowserEnvironment() {
|
|
8
8
|
return typeof window !== "undefined" && typeof window.navigator !== "undefined";
|
|
9
9
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
10
|
+
function readCurrentModelContext() {
|
|
11
|
+
if (Object.getOwnPropertyDescriptor(navigator, "modelContext")) return navigator.modelContext;
|
|
12
|
+
return document.modelContext ?? navigator.modelContext;
|
|
13
|
+
}
|
|
14
|
+
function replaceDocumentModelContext(value) {
|
|
15
|
+
try {
|
|
16
|
+
Object.defineProperty(document, "modelContext", {
|
|
17
|
+
configurable: true,
|
|
18
|
+
enumerable: true,
|
|
19
|
+
writable: false,
|
|
20
|
+
value
|
|
21
|
+
});
|
|
22
|
+
} catch {
|
|
23
|
+
Object.defineProperty(Object.getPrototypeOf(document), "modelContext", {
|
|
24
|
+
configurable: true,
|
|
25
|
+
enumerable: true,
|
|
26
|
+
get() {
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (document.modelContext !== value) console.error("[WebModelContext] Failed to replace document.modelContext.", "Descriptor:", Object.getOwnPropertyDescriptor(document, "modelContext"));
|
|
32
|
+
}
|
|
33
|
+
function replaceNavigatorModelContext(value) {
|
|
18
34
|
try {
|
|
19
35
|
Object.defineProperty(navigator, "modelContext", {
|
|
20
36
|
configurable: true,
|
|
@@ -33,6 +49,17 @@ function replaceModelContext(value) {
|
|
|
33
49
|
}
|
|
34
50
|
if (navigator.modelContext !== value) console.error("[WebModelContext] Failed to replace navigator.modelContext.", "Descriptor:", Object.getOwnPropertyDescriptor(navigator, "modelContext"));
|
|
35
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Replace both modelContext surfaces with the given value.
|
|
54
|
+
*
|
|
55
|
+
* Chrome 150 makes document.modelContext canonical and keeps navigator.modelContext
|
|
56
|
+
* as a deprecated alias. @mcp-b/global still supports old navigator-first users, so
|
|
57
|
+
* the bridge exposes the BrowserMcpServer wrapper through both properties.
|
|
58
|
+
*/
|
|
59
|
+
function replaceModelContext(value) {
|
|
60
|
+
replaceDocumentModelContext(value);
|
|
61
|
+
replaceNavigatorModelContext(value);
|
|
62
|
+
}
|
|
36
63
|
function createTransport(config) {
|
|
37
64
|
if (window.parent !== window && config?.iframeServer !== false) {
|
|
38
65
|
const { allowedOrigins, ...rest } = typeof config?.iframeServer === "object" ? config.iframeServer : {};
|
|
@@ -105,22 +132,26 @@ function syncToolsFromTestingShim(server) {
|
|
|
105
132
|
function initializeWebModelContext(options) {
|
|
106
133
|
if (!isBrowserEnvironment()) return;
|
|
107
134
|
if (runtime) return;
|
|
108
|
-
if (
|
|
135
|
+
if (readCurrentModelContext()?.[SERVER_MARKER_PROPERTY]) return;
|
|
109
136
|
initializeWebMCPPolyfill({ installTestingShim: options?.installTestingShim ?? "if-missing" });
|
|
110
|
-
const native =
|
|
111
|
-
if (!native) throw new Error("
|
|
137
|
+
const native = readCurrentModelContext();
|
|
138
|
+
if (!native) throw new Error("modelContext is not available");
|
|
112
139
|
const server = new BrowserMcpServer({
|
|
113
140
|
name: `${window.location.hostname || "localhost"}-webmcp`,
|
|
114
141
|
version: "1.0.0"
|
|
115
142
|
}, { native });
|
|
116
143
|
server.syncNativeTools();
|
|
117
144
|
syncToolsFromTestingShim(server);
|
|
145
|
+
const previousDocumentModelContextDescriptor = Object.getOwnPropertyDescriptor(document, "modelContext");
|
|
146
|
+
const previousNavigatorModelContextDescriptor = Object.getOwnPropertyDescriptor(navigator, "modelContext");
|
|
118
147
|
replaceModelContext(server);
|
|
119
148
|
const transport = createTransport(options?.transport);
|
|
120
149
|
runtime = {
|
|
121
150
|
native,
|
|
122
151
|
server,
|
|
123
|
-
transport
|
|
152
|
+
transport,
|
|
153
|
+
previousDocumentModelContextDescriptor,
|
|
154
|
+
previousNavigatorModelContextDescriptor
|
|
124
155
|
};
|
|
125
156
|
server.connect(transport).catch((error) => {
|
|
126
157
|
console.error("[WebModelContext] Failed to connect MCP transport:", error);
|
|
@@ -128,11 +159,14 @@ function initializeWebModelContext(options) {
|
|
|
128
159
|
}
|
|
129
160
|
function cleanupWebModelContext() {
|
|
130
161
|
if (!runtime) return;
|
|
131
|
-
const {
|
|
162
|
+
const { server, transport, previousDocumentModelContextDescriptor, previousNavigatorModelContextDescriptor } = runtime;
|
|
132
163
|
runtime = null;
|
|
133
164
|
server.close();
|
|
134
165
|
transport.close();
|
|
135
|
-
|
|
166
|
+
if (previousDocumentModelContextDescriptor) Object.defineProperty(document, "modelContext", previousDocumentModelContextDescriptor);
|
|
167
|
+
else delete document.modelContext;
|
|
168
|
+
if (previousNavigatorModelContextDescriptor) Object.defineProperty(navigator, "modelContext", previousNavigatorModelContextDescriptor);
|
|
169
|
+
else delete navigator.modelContext;
|
|
136
170
|
}
|
|
137
171
|
|
|
138
172
|
//#endregion
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/global.ts","../src/index.ts"],"sourcesContent":["import {\n IframeChildTransport,\n type IframeChildTransportOptions,\n TabServerTransport,\n type TabServerTransportOptions,\n} from '@mcp-b/transports';\nimport { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill';\nimport { BrowserMcpServer, SERVER_MARKER_PROPERTY, type Transport } from '@mcp-b/webmcp-ts-sdk';\nimport type {\n InputSchema,\n ModelContextCore,\n ModelContextTesting,\n ModelContextTestingPolyfillExtensions,\n ToolListItem,\n ToolResponse,\n} from '@mcp-b/webmcp-types';\nimport type { WebModelContextInitOptions } from './types.js';\n\ninterface RuntimeState {\n native: ModelContextCore;\n server: BrowserMcpServer;\n transport: Transport;\n}\n\nlet runtime: RuntimeState | null = null;\n\nfunction isBrowserEnvironment(): boolean {\n return typeof window !== 'undefined' && typeof window.navigator !== 'undefined';\n}\n\n/**\n * Replace navigator.modelContext with the given value.\n * Tries an own-property on the navigator instance first. If the native browser\n * defines modelContext as a non-configurable property (common in Chromium), this\n * will throw — in that case we fall back to redefining the getter on\n * Navigator.prototype so that `navigator.modelContext` resolves to our value.\n */\nfunction replaceModelContext(value: unknown): void {\n try {\n Object.defineProperty(navigator, 'modelContext', {\n configurable: true,\n enumerable: true,\n writable: false,\n value,\n });\n } catch {\n // Native browser property is non-configurable on the instance.\n // Shadow it with a getter on the prototype instead.\n Object.defineProperty(Object.getPrototypeOf(navigator), 'modelContext', {\n configurable: true,\n enumerable: true,\n get() {\n return value;\n },\n });\n }\n\n // Verify the replacement actually worked — the prototype getter cannot\n // shadow a non-configurable own property on the navigator instance.\n if (navigator.modelContext !== value) {\n console.error(\n '[WebModelContext] Failed to replace navigator.modelContext.',\n 'Descriptor:',\n Object.getOwnPropertyDescriptor(navigator, 'modelContext')\n );\n }\n}\n\nfunction createTransport(config: WebModelContextInitOptions['transport']): Transport {\n const inIframe = window.parent !== window;\n\n if (inIframe && config?.iframeServer !== false) {\n const iframeOptions =\n typeof config?.iframeServer === 'object'\n ? config.iframeServer\n : ({} as Partial<IframeChildTransportOptions>);\n\n const { allowedOrigins, ...rest } = iframeOptions;\n\n return new IframeChildTransport({\n allowedOrigins: allowedOrigins ?? ['*'],\n ...rest,\n });\n }\n\n if (config?.tabServer === false) {\n throw new Error('tabServer transport is disabled and iframe transport was not selected');\n }\n\n const tabOptions =\n typeof config?.tabServer === 'object'\n ? config.tabServer\n : ({} as Partial<TabServerTransportOptions>);\n\n const { allowedOrigins, ...rest } = tabOptions;\n\n return new TabServerTransport({\n allowedOrigins: allowedOrigins ?? ['*'],\n ...rest,\n });\n}\n\nfunction parseTestingInputSchema(inputSchema: string | undefined): InputSchema | undefined {\n if (!inputSchema) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(inputSchema) as unknown;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return undefined;\n }\n return parsed as InputSchema;\n } catch (error) {\n console.warn('[WebMCP] Failed to parse testing inputSchema JSON:', error);\n return undefined;\n }\n}\n\nfunction getTestingShimTools():\n | {\n testingShim: ModelContextTesting;\n tools: ToolListItem[];\n }\n | undefined {\n const testingShim = navigator.modelContextTesting as\n | (ModelContextTesting & Partial<ModelContextTestingPolyfillExtensions>)\n | undefined;\n if (!testingShim) {\n return undefined;\n }\n\n if (typeof testingShim.getRegisteredTools === 'function') {\n return {\n testingShim,\n tools: testingShim.getRegisteredTools() as ToolListItem[],\n };\n }\n\n if (typeof testingShim.listTools !== 'function') {\n return undefined;\n }\n\n const tools = testingShim.listTools().map(\n (tool): ToolListItem => ({\n name: tool.name,\n description: tool.description ?? '',\n inputSchema: parseTestingInputSchema(tool.inputSchema) ?? {\n type: 'object',\n properties: {},\n },\n })\n );\n\n return {\n testingShim,\n tools,\n };\n}\n\nfunction syncToolsFromTestingShim(server: BrowserMcpServer): number {\n const shimState = getTestingShimTools();\n if (!shimState) {\n return 0;\n }\n\n const { testingShim, tools } = shimState;\n return server.backfillTools(tools, async (name: string, args: Record<string, unknown>) => {\n const serialized = await testingShim.executeTool(name, JSON.stringify(args ?? {}));\n if (serialized === null) {\n return {\n content: [{ type: 'text', text: 'Tool execution interrupted by navigation' }],\n isError: true,\n } satisfies ToolResponse;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(serialized);\n } catch (parseError) {\n throw new Error(\n `Failed to parse serialized tool response for ${name}: ${parseError instanceof Error ? parseError.message : String(parseError)}`\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`Invalid serialized tool response for ${name}`);\n }\n return parsed as ToolResponse;\n });\n}\n\nexport function initializeWebModelContext(options?: WebModelContextInitOptions): void {\n if (!isBrowserEnvironment()) {\n return;\n }\n\n if (runtime) {\n return;\n }\n\n // Cross-bundle guard: if navigator.modelContext is already a BrowserMcpServer\n // (set by another bundle in this window), skip initialization.\n const existingContext = navigator.modelContext as unknown as Record<string, unknown> | undefined;\n if (existingContext?.[SERVER_MARKER_PROPERTY]) {\n return;\n }\n\n // 1. Install polyfill (provides modelContext + modelContextTesting)\n initializeWebMCPPolyfill({\n installTestingShim: options?.installTestingShim ?? 'if-missing',\n });\n\n // 2. Save reference to the polyfill's (or native) context\n const native = navigator.modelContext as unknown as ModelContextCore;\n if (!native) {\n throw new Error('navigator.modelContext is not available');\n }\n\n // 3. Create server with native mirroring\n const hostname = window.location.hostname || 'localhost';\n const server = new BrowserMcpServer({ name: `${hostname}-webmcp`, version: '1.0.0' }, { native });\n server.syncNativeTools();\n syncToolsFromTestingShim(server);\n\n // 4. Replace navigator.modelContext with the server.\n // Try own-property on the navigator instance first (works for polyfill and most cases).\n // Fall back to a prototype getter if the native property is non-configurable.\n replaceModelContext(server);\n\n // 5. Create transport and connect\n const transport = createTransport(options?.transport);\n runtime = { native, server, transport };\n\n void server.connect(transport).catch((error: unknown) => {\n console.error('[WebModelContext] Failed to connect MCP transport:', error);\n });\n}\n\nexport function cleanupWebModelContext(): void {\n if (!runtime) {\n return;\n }\n\n const { native, server, transport } = runtime;\n runtime = null;\n\n void server.close();\n void transport.close();\n\n // Restore the context that existed before we wrapped it with BrowserMcpServer.\n // We intentionally do NOT call cleanupWebMCPPolyfill() here — the polyfill\n // manages its own lifecycle (auto-init, testing shim) independently.\n replaceModelContext(native);\n}\n","import { cleanupWebModelContext, initializeWebModelContext } from './global.js';\n\nexport { cleanupWebModelContext, initializeWebModelContext };\n\nexport type {\n NativeModelContextBehavior,\n TransportConfiguration,\n WebModelContextInitOptions,\n} from './types.js';\n\nif (typeof window !== 'undefined' && typeof document !== 'undefined') {\n const options = window.__webModelContextOptions;\n const shouldAutoInitialize = options?.autoInitialize !== false;\n\n if (shouldAutoInitialize) {\n try {\n initializeWebModelContext(options);\n } catch (error) {\n console.error('[WebModelContext] Auto-initialization failed:', error);\n }\n }\n}\n"],"mappings":";;;;;AAwBA,IAAI,UAA+B;AAEnC,SAAS,uBAAgC;AACvC,QAAO,OAAO,WAAW,eAAe,OAAO,OAAO,cAAc;;;;;;;;;AAUtE,SAAS,oBAAoB,OAAsB;AACjD,KAAI;AACF,SAAO,eAAe,WAAW,gBAAgB;GAC/C,cAAc;GACd,YAAY;GACZ,UAAU;GACV;GACD,CAAC;SACI;AAGN,SAAO,eAAe,OAAO,eAAe,UAAU,EAAE,gBAAgB;GACtE,cAAc;GACd,YAAY;GACZ,MAAM;AACJ,WAAO;;GAEV,CAAC;;AAKJ,KAAI,UAAU,iBAAiB,MAC7B,SAAQ,MACN,+DACA,eACA,OAAO,yBAAyB,WAAW,eAAe,CAC3D;;AAIL,SAAS,gBAAgB,QAA4D;AAGnF,KAFiB,OAAO,WAAW,UAEnB,QAAQ,iBAAiB,OAAO;EAM9C,MAAM,EAAE,gBAAgB,GAAG,SAJzB,OAAO,QAAQ,iBAAiB,WAC5B,OAAO,eACN,EAAE;AAIT,SAAO,IAAI,qBAAqB;GAC9B,gBAAgB,kBAAkB,CAAC,IAAI;GACvC,GAAG;GACJ,CAAC;;AAGJ,KAAI,QAAQ,cAAc,MACxB,OAAM,IAAI,MAAM,wEAAwE;CAQ1F,MAAM,EAAE,gBAAgB,GAAG,SAJzB,OAAO,QAAQ,cAAc,WACzB,OAAO,YACN,EAAE;AAIT,QAAO,IAAI,mBAAmB;EAC5B,gBAAgB,kBAAkB,CAAC,IAAI;EACvC,GAAG;EACJ,CAAC;;AAGJ,SAAS,wBAAwB,aAA0D;AACzF,KAAI,CAAC,YACH;AAGF,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,YAAY;AACtC,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,OAAO,CAChE;AAEF,SAAO;UACA,OAAO;AACd,UAAQ,KAAK,sDAAsD,MAAM;AACzE;;;AAIJ,SAAS,sBAKK;CACZ,MAAM,cAAc,UAAU;AAG9B,KAAI,CAAC,YACH;AAGF,KAAI,OAAO,YAAY,uBAAuB,WAC5C,QAAO;EACL;EACA,OAAO,YAAY,oBAAoB;EACxC;AAGH,KAAI,OAAO,YAAY,cAAc,WACnC;AAcF,QAAO;EACL;EACA,OAbY,YAAY,WAAW,CAAC,KACnC,UAAwB;GACvB,MAAM,KAAK;GACX,aAAa,KAAK,eAAe;GACjC,aAAa,wBAAwB,KAAK,YAAY,IAAI;IACxD,MAAM;IACN,YAAY,EAAE;IACf;GACF,EAKI;EACN;;AAGH,SAAS,yBAAyB,QAAkC;CAClE,MAAM,YAAY,qBAAqB;AACvC,KAAI,CAAC,UACH,QAAO;CAGT,MAAM,EAAE,aAAa,UAAU;AAC/B,QAAO,OAAO,cAAc,OAAO,OAAO,MAAc,SAAkC;EACxF,MAAM,aAAa,MAAM,YAAY,YAAY,MAAM,KAAK,UAAU,QAAQ,EAAE,CAAC,CAAC;AAClF,MAAI,eAAe,KACjB,QAAO;GACL,SAAS,CAAC;IAAE,MAAM;IAAQ,MAAM;IAA4C,CAAC;GAC7E,SAAS;GACV;EAGH,IAAI;AACJ,MAAI;AACF,YAAS,KAAK,MAAM,WAAW;WACxB,YAAY;AACnB,SAAM,IAAI,MACR,gDAAgD,KAAK,IAAI,sBAAsB,QAAQ,WAAW,UAAU,OAAO,WAAW,GAC/H;;AAEH,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,OAAO,CAChE,OAAM,IAAI,MAAM,wCAAwC,OAAO;AAEjE,SAAO;GACP;;AAGJ,SAAgB,0BAA0B,SAA4C;AACpF,KAAI,CAAC,sBAAsB,CACzB;AAGF,KAAI,QACF;AAMF,KADwB,UAAU,eACZ,wBACpB;AAIF,0BAAyB,EACvB,oBAAoB,SAAS,sBAAsB,cACpD,CAAC;CAGF,MAAM,SAAS,UAAU;AACzB,KAAI,CAAC,OACH,OAAM,IAAI,MAAM,0CAA0C;CAK5D,MAAM,SAAS,IAAI,iBAAiB;EAAE,MAAM,GAD3B,OAAO,SAAS,YAAY,YACW;EAAU,SAAS;EAAS,EAAE,EAAE,QAAQ,CAAC;AACjG,QAAO,iBAAiB;AACxB,0BAAyB,OAAO;AAKhC,qBAAoB,OAAO;CAG3B,MAAM,YAAY,gBAAgB,SAAS,UAAU;AACrD,WAAU;EAAE;EAAQ;EAAQ;EAAW;AAEvC,CAAK,OAAO,QAAQ,UAAU,CAAC,OAAO,UAAmB;AACvD,UAAQ,MAAM,sDAAsD,MAAM;GAC1E;;AAGJ,SAAgB,yBAA+B;AAC7C,KAAI,CAAC,QACH;CAGF,MAAM,EAAE,QAAQ,QAAQ,cAAc;AACtC,WAAU;AAEV,CAAK,OAAO,OAAO;AACnB,CAAK,UAAU,OAAO;AAKtB,qBAAoB,OAAO;;;;;AClP7B,IAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa;CACpE,MAAM,UAAU,OAAO;AAGvB,KAF6B,SAAS,mBAAmB,MAGvD,KAAI;AACF,4BAA0B,QAAQ;UAC3B,OAAO;AACd,UAAQ,MAAM,iDAAiD,MAAM"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/global.ts","../src/index.ts"],"sourcesContent":["import {\n IframeChildTransport,\n type IframeChildTransportOptions,\n TabServerTransport,\n type TabServerTransportOptions,\n} from '@mcp-b/transports';\nimport { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill';\nimport { BrowserMcpServer, SERVER_MARKER_PROPERTY, type Transport } from '@mcp-b/webmcp-ts-sdk';\nimport type {\n InputSchema,\n ModelContextCore,\n ModelContextTesting,\n ModelContextTestingPolyfillExtensions,\n ToolListItem,\n ToolResponse,\n} from '@mcp-b/webmcp-types';\nimport type { WebModelContextInitOptions } from './types.js';\n\ninterface RuntimeState {\n native: ModelContextCore;\n server: BrowserMcpServer;\n transport: Transport;\n previousDocumentModelContextDescriptor: PropertyDescriptor | undefined;\n previousNavigatorModelContextDescriptor: PropertyDescriptor | undefined;\n}\n\nlet runtime: RuntimeState | null = null;\n\nfunction isBrowserEnvironment(): boolean {\n return typeof window !== 'undefined' && typeof window.navigator !== 'undefined';\n}\n\nfunction readCurrentModelContext(): unknown {\n const navigatorDescriptor = Object.getOwnPropertyDescriptor(navigator, 'modelContext');\n if (navigatorDescriptor) {\n return navigator.modelContext;\n }\n\n return document.modelContext ?? navigator.modelContext;\n}\n\nfunction replaceDocumentModelContext(value: unknown): void {\n try {\n Object.defineProperty(document, 'modelContext', {\n configurable: true,\n enumerable: true,\n writable: false,\n value,\n });\n } catch {\n Object.defineProperty(Object.getPrototypeOf(document), 'modelContext', {\n configurable: true,\n enumerable: true,\n get() {\n return value;\n },\n });\n }\n\n if (document.modelContext !== value) {\n console.error(\n '[WebModelContext] Failed to replace document.modelContext.',\n 'Descriptor:',\n Object.getOwnPropertyDescriptor(document, 'modelContext')\n );\n }\n}\n\nfunction replaceNavigatorModelContext(value: unknown): void {\n try {\n Object.defineProperty(navigator, 'modelContext', {\n configurable: true,\n enumerable: true,\n writable: false,\n value,\n });\n } catch {\n // Native browser property is non-configurable on the instance.\n // Shadow it with a getter on the prototype instead.\n Object.defineProperty(Object.getPrototypeOf(navigator), 'modelContext', {\n configurable: true,\n enumerable: true,\n get() {\n return value;\n },\n });\n }\n\n // Verify the replacement actually worked — the prototype getter cannot\n // shadow a non-configurable own property on the navigator instance.\n if (navigator.modelContext !== value) {\n console.error(\n '[WebModelContext] Failed to replace navigator.modelContext.',\n 'Descriptor:',\n Object.getOwnPropertyDescriptor(navigator, 'modelContext')\n );\n }\n}\n\n/**\n * Replace both modelContext surfaces with the given value.\n *\n * Chrome 150 makes document.modelContext canonical and keeps navigator.modelContext\n * as a deprecated alias. @mcp-b/global still supports old navigator-first users, so\n * the bridge exposes the BrowserMcpServer wrapper through both properties.\n */\nfunction replaceModelContext(value: unknown): void {\n replaceDocumentModelContext(value);\n replaceNavigatorModelContext(value);\n}\n\nfunction createTransport(config: WebModelContextInitOptions['transport']): Transport {\n const inIframe = window.parent !== window;\n\n if (inIframe && config?.iframeServer !== false) {\n const iframeOptions =\n typeof config?.iframeServer === 'object'\n ? config.iframeServer\n : ({} as Partial<IframeChildTransportOptions>);\n\n const { allowedOrigins, ...rest } = iframeOptions;\n\n return new IframeChildTransport({\n allowedOrigins: allowedOrigins ?? ['*'],\n ...rest,\n });\n }\n\n if (config?.tabServer === false) {\n throw new Error('tabServer transport is disabled and iframe transport was not selected');\n }\n\n const tabOptions =\n typeof config?.tabServer === 'object'\n ? config.tabServer\n : ({} as Partial<TabServerTransportOptions>);\n\n const { allowedOrigins, ...rest } = tabOptions;\n\n return new TabServerTransport({\n allowedOrigins: allowedOrigins ?? ['*'],\n ...rest,\n });\n}\n\nfunction parseTestingInputSchema(inputSchema: string | undefined): InputSchema | undefined {\n if (!inputSchema) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(inputSchema) as unknown;\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return undefined;\n }\n return parsed as InputSchema;\n } catch (error) {\n console.warn('[WebMCP] Failed to parse testing inputSchema JSON:', error);\n return undefined;\n }\n}\n\nfunction getTestingShimTools():\n | {\n testingShim: ModelContextTesting;\n tools: ToolListItem[];\n }\n | undefined {\n const testingShim = navigator.modelContextTesting as\n | (ModelContextTesting & Partial<ModelContextTestingPolyfillExtensions>)\n | undefined;\n if (!testingShim) {\n return undefined;\n }\n\n if (typeof testingShim.getRegisteredTools === 'function') {\n return {\n testingShim,\n tools: testingShim.getRegisteredTools() as ToolListItem[],\n };\n }\n\n if (typeof testingShim.listTools !== 'function') {\n return undefined;\n }\n\n const tools = testingShim.listTools().map(\n (tool): ToolListItem => ({\n name: tool.name,\n description: tool.description ?? '',\n inputSchema: parseTestingInputSchema(tool.inputSchema) ?? {\n type: 'object',\n properties: {},\n },\n })\n );\n\n return {\n testingShim,\n tools,\n };\n}\n\nfunction syncToolsFromTestingShim(server: BrowserMcpServer): number {\n const shimState = getTestingShimTools();\n if (!shimState) {\n return 0;\n }\n\n const { testingShim, tools } = shimState;\n return server.backfillTools(tools, async (name: string, args: Record<string, unknown>) => {\n const serialized = await testingShim.executeTool(name, JSON.stringify(args ?? {}));\n if (serialized === null) {\n return {\n content: [{ type: 'text', text: 'Tool execution interrupted by navigation' }],\n isError: true,\n } satisfies ToolResponse;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(serialized);\n } catch (parseError) {\n throw new Error(\n `Failed to parse serialized tool response for ${name}: ${parseError instanceof Error ? parseError.message : String(parseError)}`\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`Invalid serialized tool response for ${name}`);\n }\n return parsed as ToolResponse;\n });\n}\n\nexport function initializeWebModelContext(options?: WebModelContextInitOptions): void {\n if (!isBrowserEnvironment()) {\n return;\n }\n\n if (runtime) {\n return;\n }\n\n // Cross-bundle guard: if modelContext is already a BrowserMcpServer\n // (set by another bundle in this window), skip initialization.\n const existingContext = readCurrentModelContext() as Record<string, unknown> | undefined;\n if (existingContext?.[SERVER_MARKER_PROPERTY]) {\n return;\n }\n\n // 1. Install polyfill (provides modelContext + modelContextTesting)\n initializeWebMCPPolyfill({\n installTestingShim: options?.installTestingShim ?? 'if-missing',\n });\n\n // 2. Save reference to the polyfill's (or native) context\n const native = readCurrentModelContext() as ModelContextCore | undefined;\n if (!native) {\n throw new Error('modelContext is not available');\n }\n\n // 3. Create server with native mirroring\n const hostname = window.location.hostname || 'localhost';\n const server = new BrowserMcpServer({ name: `${hostname}-webmcp`, version: '1.0.0' }, { native });\n server.syncNativeTools();\n syncToolsFromTestingShim(server);\n\n // 4. Replace navigator.modelContext with the server.\n // Try own-property on the navigator instance first (works for polyfill and most cases).\n // Fall back to a prototype getter if the native property is non-configurable.\n const previousDocumentModelContextDescriptor = Object.getOwnPropertyDescriptor(\n document,\n 'modelContext'\n );\n const previousNavigatorModelContextDescriptor = Object.getOwnPropertyDescriptor(\n navigator,\n 'modelContext'\n );\n replaceModelContext(server);\n\n // 5. Create transport and connect\n const transport = createTransport(options?.transport);\n runtime = {\n native,\n server,\n transport,\n previousDocumentModelContextDescriptor,\n previousNavigatorModelContextDescriptor,\n };\n\n void server.connect(transport).catch((error: unknown) => {\n console.error('[WebModelContext] Failed to connect MCP transport:', error);\n });\n}\n\nexport function cleanupWebModelContext(): void {\n if (!runtime) {\n return;\n }\n\n const {\n server,\n transport,\n previousDocumentModelContextDescriptor,\n previousNavigatorModelContextDescriptor,\n } = runtime;\n runtime = null;\n\n void server.close();\n void transport.close();\n\n // Restore the descriptors that existed before we wrapped with BrowserMcpServer.\n // We intentionally do NOT call cleanupWebMCPPolyfill() here — the polyfill\n // manages its own lifecycle (auto-init, testing shim) independently.\n if (previousDocumentModelContextDescriptor) {\n Object.defineProperty(document, 'modelContext', previousDocumentModelContextDescriptor);\n } else {\n delete (document as unknown as Record<string, unknown>).modelContext;\n }\n\n if (previousNavigatorModelContextDescriptor) {\n Object.defineProperty(navigator, 'modelContext', previousNavigatorModelContextDescriptor);\n } else {\n delete (navigator as unknown as Record<string, unknown>).modelContext;\n }\n}\n","import { cleanupWebModelContext, initializeWebModelContext } from './global.js';\n\nexport { cleanupWebModelContext, initializeWebModelContext };\n\nexport type {\n NativeModelContextBehavior,\n TransportConfiguration,\n WebModelContextInitOptions,\n} from './types.js';\n\nif (typeof window !== 'undefined' && typeof document !== 'undefined') {\n const options = window.__webModelContextOptions;\n const shouldAutoInitialize = options?.autoInitialize !== false;\n\n if (shouldAutoInitialize) {\n try {\n initializeWebModelContext(options);\n } catch (error) {\n console.error('[WebModelContext] Auto-initialization failed:', error);\n }\n }\n}\n"],"mappings":";;;;;AA0BA,IAAI,UAA+B;AAEnC,SAAS,uBAAgC;CACvC,OAAO,OAAO,WAAW,eAAe,OAAO,OAAO,cAAc;;AAGtE,SAAS,0BAAmC;CAE1C,IAD4B,OAAO,yBAAyB,WAAW,eAChD,EACrB,OAAO,UAAU;CAGnB,OAAO,SAAS,gBAAgB,UAAU;;AAG5C,SAAS,4BAA4B,OAAsB;CACzD,IAAI;EACF,OAAO,eAAe,UAAU,gBAAgB;GAC9C,cAAc;GACd,YAAY;GACZ,UAAU;GACV;GACD,CAAC;SACI;EACN,OAAO,eAAe,OAAO,eAAe,SAAS,EAAE,gBAAgB;GACrE,cAAc;GACd,YAAY;GACZ,MAAM;IACJ,OAAO;;GAEV,CAAC;;CAGJ,IAAI,SAAS,iBAAiB,OAC5B,QAAQ,MACN,8DACA,eACA,OAAO,yBAAyB,UAAU,eAAe,CAC1D;;AAIL,SAAS,6BAA6B,OAAsB;CAC1D,IAAI;EACF,OAAO,eAAe,WAAW,gBAAgB;GAC/C,cAAc;GACd,YAAY;GACZ,UAAU;GACV;GACD,CAAC;SACI;EAGN,OAAO,eAAe,OAAO,eAAe,UAAU,EAAE,gBAAgB;GACtE,cAAc;GACd,YAAY;GACZ,MAAM;IACJ,OAAO;;GAEV,CAAC;;CAKJ,IAAI,UAAU,iBAAiB,OAC7B,QAAQ,MACN,+DACA,eACA,OAAO,yBAAyB,WAAW,eAAe,CAC3D;;;;;;;;;AAWL,SAAS,oBAAoB,OAAsB;CACjD,4BAA4B,MAAM;CAClC,6BAA6B,MAAM;;AAGrC,SAAS,gBAAgB,QAA4D;CAGnF,IAFiB,OAAO,WAAW,UAEnB,QAAQ,iBAAiB,OAAO;EAM9C,MAAM,EAAE,gBAAgB,GAAG,SAJzB,OAAO,QAAQ,iBAAiB,WAC5B,OAAO,eACN,EAAE;EAIT,OAAO,IAAI,qBAAqB;GAC9B,gBAAgB,kBAAkB,CAAC,IAAI;GACvC,GAAG;GACJ,CAAC;;CAGJ,IAAI,QAAQ,cAAc,OACxB,MAAM,IAAI,MAAM,wEAAwE;CAQ1F,MAAM,EAAE,gBAAgB,GAAG,SAJzB,OAAO,QAAQ,cAAc,WACzB,OAAO,YACN,EAAE;CAIT,OAAO,IAAI,mBAAmB;EAC5B,gBAAgB,kBAAkB,CAAC,IAAI;EACvC,GAAG;EACJ,CAAC;;AAGJ,SAAS,wBAAwB,aAA0D;CACzF,IAAI,CAAC,aACH;CAGF,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,YAAY;EACtC,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,OAAO,EAChE;EAEF,OAAO;UACA,OAAO;EACd,QAAQ,KAAK,sDAAsD,MAAM;EACzE;;;AAIJ,SAAS,sBAKK;CACZ,MAAM,cAAc,UAAU;CAG9B,IAAI,CAAC,aACH;CAGF,IAAI,OAAO,YAAY,uBAAuB,YAC5C,OAAO;EACL;EACA,OAAO,YAAY,oBAAoB;EACxC;CAGH,IAAI,OAAO,YAAY,cAAc,YACnC;CAcF,OAAO;EACL;EACA,OAbY,YAAY,WAAW,CAAC,KACnC,UAAwB;GACvB,MAAM,KAAK;GACX,aAAa,KAAK,eAAe;GACjC,aAAa,wBAAwB,KAAK,YAAY,IAAI;IACxD,MAAM;IACN,YAAY,EAAE;IACf;GACF,EAKI;EACN;;AAGH,SAAS,yBAAyB,QAAkC;CAClE,MAAM,YAAY,qBAAqB;CACvC,IAAI,CAAC,WACH,OAAO;CAGT,MAAM,EAAE,aAAa,UAAU;CAC/B,OAAO,OAAO,cAAc,OAAO,OAAO,MAAc,SAAkC;EACxF,MAAM,aAAa,MAAM,YAAY,YAAY,MAAM,KAAK,UAAU,QAAQ,EAAE,CAAC,CAAC;EAClF,IAAI,eAAe,MACjB,OAAO;GACL,SAAS,CAAC;IAAE,MAAM;IAAQ,MAAM;IAA4C,CAAC;GAC7E,SAAS;GACV;EAGH,IAAI;EACJ,IAAI;GACF,SAAS,KAAK,MAAM,WAAW;WACxB,YAAY;GACnB,MAAM,IAAI,MACR,gDAAgD,KAAK,IAAI,sBAAsB,QAAQ,WAAW,UAAU,OAAO,WAAW,GAC/H;;EAEH,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,OAAO,EAChE,MAAM,IAAI,MAAM,wCAAwC,OAAO;EAEjE,OAAO;GACP;;AAGJ,SAAgB,0BAA0B,SAA4C;CACpF,IAAI,CAAC,sBAAsB,EACzB;CAGF,IAAI,SACF;CAMF,IADwB,yBACL,GAAG,yBACpB;CAIF,yBAAyB,EACvB,oBAAoB,SAAS,sBAAsB,cACpD,CAAC;CAGF,MAAM,SAAS,yBAAyB;CACxC,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,gCAAgC;CAKlD,MAAM,SAAS,IAAI,iBAAiB;EAAE,MAAM,GAD3B,OAAO,SAAS,YAAY,YACW;EAAU,SAAS;EAAS,EAAE,EAAE,QAAQ,CAAC;CACjG,OAAO,iBAAiB;CACxB,yBAAyB,OAAO;CAKhC,MAAM,yCAAyC,OAAO,yBACpD,UACA,eACD;CACD,MAAM,0CAA0C,OAAO,yBACrD,WACA,eACD;CACD,oBAAoB,OAAO;CAG3B,MAAM,YAAY,gBAAgB,SAAS,UAAU;CACrD,UAAU;EACR;EACA;EACA;EACA;EACA;EACD;CAED,AAAK,OAAO,QAAQ,UAAU,CAAC,OAAO,UAAmB;EACvD,QAAQ,MAAM,sDAAsD,MAAM;GAC1E;;AAGJ,SAAgB,yBAA+B;CAC7C,IAAI,CAAC,SACH;CAGF,MAAM,EACJ,QACA,WACA,wCACA,4CACE;CACJ,UAAU;CAEV,AAAK,OAAO,OAAO;CACnB,AAAK,UAAU,OAAO;CAKtB,IAAI,wCACF,OAAO,eAAe,UAAU,gBAAgB,uCAAuC;MAEvF,OAAQ,SAAgD;CAG1D,IAAI,yCACF,OAAO,eAAe,WAAW,gBAAgB,wCAAwC;MAEzF,OAAQ,UAAiD;;;;;ACzT7D,IAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa;CACpE,MAAM,UAAU,OAAO;CAGvB,IAF6B,SAAS,mBAAmB,OAGvD,IAAI;EACF,0BAA0B,QAAQ;UAC3B,OAAO;EACd,QAAQ,MAAM,iDAAiD,MAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-b/global",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "W3C Web Model Context API polyfill - Let AI agents like Claude, ChatGPT, and Gemini interact with your website via navigator.modelContext",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai-agents",
|
|
@@ -66,18 +66,18 @@
|
|
|
66
66
|
"registry": "https://registry.npmjs.org/"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@mcp-b/
|
|
70
|
-
"@mcp-b/
|
|
71
|
-
"@mcp-b/webmcp-types": "
|
|
72
|
-
"@mcp-b/webmcp-
|
|
69
|
+
"@mcp-b/transports": "3.0.0",
|
|
70
|
+
"@mcp-b/webmcp-ts-sdk": "3.0.0",
|
|
71
|
+
"@mcp-b/webmcp-types": "3.0.0",
|
|
72
|
+
"@mcp-b/webmcp-polyfill": "3.0.0"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
75
|
"@types/node": "22.17.2",
|
|
76
|
-
"@vitest/coverage-v8": "^4.1.
|
|
76
|
+
"@vitest/coverage-v8": "^4.1.7",
|
|
77
77
|
"fast-check": "^4.0.0",
|
|
78
|
-
"playwright": "^1.
|
|
78
|
+
"playwright": "^1.60.0",
|
|
79
79
|
"typescript": "^5.8.3",
|
|
80
|
-
"vite-plus": "
|
|
80
|
+
"vite-plus": "^0.1.22",
|
|
81
81
|
"vitest": "npm:@voidzero-dev/vite-plus-test@latest"
|
|
82
82
|
},
|
|
83
83
|
"engines": {
|