@babylonjs/mcp-servers 9.12.0 → 9.12.1
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/dist/flow-graph-mcp-server.js +1 -1
- package/dist/gui-mcp-server.js +1 -1
- package/dist/nge-mcp-server.js +1 -1
- package/dist/nme-mcp-server.js +1 -1
- package/dist/npe-mcp-server.js +1 -1
- package/dist/nrge-mcp-server.js +1 -1
- package/dist/smart-filters-mcp-server.js +1 -1
- package/package.json +1 -1
|
@@ -67,7 +67,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
67
67
|
]))`;continue}else if(i[c]==="$"){n+=`($|(?=[\r
|
|
68
68
|
]))`;continue}}if(r.s&&i[c]==="."){n+=a?`${i[c]}\r
|
|
69
69
|
`:`[${i[c]}\r
|
|
70
|
-
]`;continue}n+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(n)}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 n}function Mh(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===te.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,n)=>({...i,[n]:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Xe(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===te.ZodString&&e.keyType._def.checks?.length){const{type:i,...n}=Zh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===te.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===te.ZodBranded&&e.keyType._def.type._def.typeName===te.ZodString&&e.keyType._def.type._def.checks?.length){const{type:i,...n}=Ah(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function pw(e,t){if(t.mapStrategy==="record")return Mh(e,t);const r=ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Xe(t),i=ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Xe(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function mw(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function fw(e){return e.target==="openAi"?void 0:{not:Xe({...e,currentPath:[...e.currentPath,"not"]})}}function hw(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Bi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gw(e,t){if(t.target==="openApi3")return Lh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in Bi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=Bi[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=r.reduce((n,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(i.length===r.length){const n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return Lh(e,t)}const Lh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,n)=>ge(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function vw(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:Bi[e.innerType._def.typeName],nullable:!0}:{type:[Bi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const i=ge(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function yw(e,t){const r={type:"number"};if(!e.checks)return r;for(const i of e.checks)switch(i.kind){case"int":r.type="integer",Dh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?ve(r,"minimum",i.value,i.message,t):ve(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?ve(r,"maximum",i.value,i.message,t):ve(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",i.value,i.message,t));break;case"multipleOf":ve(r,"multipleOf",i.value,i.message,t);break}return r}function _w(e,t){const r=t.target==="openAi",i={type:"object",properties:{}},n=[],o=e.shape();for(const s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=$w(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=ge(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||n.push(s))}n.length&&(i.required=n);const a=bw(e,t);return a!==void 0&&(i.additionalProperties=a),i}function bw(e,t){if(e.catchall._def.typeName!=="ZodNever")return ge(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 $w(e){try{return e.isOptional()}catch{return!0}}const kw=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ge(e.innerType._def,t);const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Xe(t)},r]}:Xe(t)},ww=(e,t)=>{if(t.pipeStrategy==="input")return ge(e.in._def,t);if(t.pipeStrategy==="output")return ge(e.out._def,t);const r=ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function Sw(e,t){return ge(e.type._def,t)}function Iw(e,t){const i={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ve(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ve(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function Ow(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function Tw(e){return{not:Xe(e)}}function Pw(e){return Xe(e)}const Ew=(e,t)=>ge(e.innerType._def,t),zw=(e,t,r)=>{switch(t){case te.ZodString:return Zh(e,r);case te.ZodNumber:return yw(e,r);case te.ZodObject:return _w(e,r);case te.ZodBigInt:return ew(e,r);case te.ZodBoolean:return tw();case te.ZodDate:return Uh(e,r);case te.ZodUndefined:return Tw(r);case te.ZodNull:return hw(r);case te.ZodArray:return Qk(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return gw(e,r);case te.ZodIntersection:return cw(e,r);case te.ZodTuple:return Ow(e,r);case te.ZodRecord:return Mh(e,r);case te.ZodLiteral:return uw(e,r);case te.ZodEnum:return aw(e);case te.ZodNativeEnum:return mw(e);case te.ZodNullable:return vw(e,r);case te.ZodOptional:return kw(e,r);case te.ZodMap:return pw(e,r);case te.ZodSet:return Iw(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return Sw(e,r);case te.ZodNaN:case te.ZodNever:return fw(r);case te.ZodEffects:return ow(e,r);case te.ZodAny:return Xe(r);case te.ZodUnknown:return Pw(r);case te.ZodDefault:return iw(e,r);case te.ZodBranded:return Ah(e,r);case te.ZodReadonly:return Ew(e,r);case te.ZodCatch:return nw(e,r);case te.ZodPipeline:return ww(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(i=>{})()}};function ge(e,t,r=!1){const i=t.seen.get(e);if(t.override){const s=t.override?.(e,t,i,r);if(s!==Wk)return s}if(i&&!r){const s=Nw(i,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const o=zw(e,e.typeName,t),a=typeof o=="function"?ge(o(),t):o;if(a&&xw(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const Nw=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Rh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,i)=>t.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Xe(t)):t.$refStrategy==="seen"?Xe(t):void 0}},xw=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),jw=(e,t)=>{const r=Yk(t);let i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:ge(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Xe(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=ge(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Xe(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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 Cw(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Gh(e,t){return It(e)?Pa(e,{target:Cw(t?.target),io:t?.pipeStrategy??"input"}):jw(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Vh(e){const r=pr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=gh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Bh(e,t){const r=dr(e,t);if(!r.success)throw r.error;return r.data}const Dw=6e4;class Rw{constructor(t){this._options=t,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(Es,r=>{this._oncancel(r)}),this.setNotificationHandler(Ns,r=>{this._onprogress(r)}),this.setRequestHandler(zs,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xs,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new B(H.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Cs,async(r,i)=>{const n=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,m=new B(d.error.code,d.error.message,d.error.data);l(m)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}const a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new B(H.InvalidParams,`Task not found: ${o}`);if(!Wt(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Wt(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Ht]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Ds,async(r,i)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new B(H.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(As,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new B(H.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wt(n.status))throw new B(H.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new B(H.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof B?n:new B(H.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),B.fromError(H.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),Ui(o)||b$(o)?this._onresponse(o):$h(o)?this._onrequest(o,a):_$(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(const i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();const r=B.fromError(H.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const i of t.values())i(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){const i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,o=t.params?._meta?.[Ht]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:H.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=y$(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new B(H.ConnectionClosed,"Request was cancelled");const p={...m,relatedRequestId:t.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});const h=p.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:H.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...i}=t.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}o(i)}_onresponse(t){const r=Number(t.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),Ui(t))i(t);else{const a=new B(t.error.code,t.error.message,t.error.data);i(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Ui(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Ui(t))n(t);else{const a=B.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,i){const{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(t,r,i)}}catch(a){yield{type:"error",error:a instanceof B?a:new B(H.InternalError,String(a))}}return}let o;try{const a=await this.request(t,Zi,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new B(H.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Wt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new B(H.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new B(H.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof B?a:new B(H.InternalError,String(a))}}}request(t,r,i){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{const d=g=>{l(g)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(g){d(g);return}i?.signal?.throwIfAborted();const m=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Ht]:c}});const h=g=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(g)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(O=>this._onerror(new Error(`Failed to send cancellation: ${O}`)));const k=g instanceof B?g:new B(H.RequestTimeout,String(g));l(k)};this._responseHandlers.set(m,g=>{if(!i?.signal?.aborted){if(g instanceof Error)return l(g);try{const k=dr(r,g.result);k.success?u(k.data):l(k.error)}catch(k){l(k)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const $=i?.timeout??Dw,b=()=>h(B.fromError(H.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,i?.maxTotalTimeout,b,i?.resetTimeoutOnProgress??!1);const y=c?.taskId;if(y){const g=k=>{const O=this._responseHandlers.get(m);O?O(k):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,g),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(m),l(k)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(g=>{this._cleanupTimeout(m),l(g)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},js,r)}async getTaskResult(t,r,i){return this.request({method:"tasks/result",params:t},r,i)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Rs,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},A$,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const i=r?.relatedTask?.taskId;if(i){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Ht]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Ht]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ht]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const i=Vh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=Bh(t,n);return Promise.resolve(r(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const i=Vh(t);this._notificationHandlers.set(i,n=>{const o=Bh(t,n);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,i,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const i=await this._taskMessageQueue.dequeueAll(t,r);for(const n of i)if(n.type==="request"&&$h(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new B(H.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(i=n.pollInterval)}catch{}return new Promise((n,o)=>{if(r.aborted){o(new B(H.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new B(H.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await i.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const o=await i.getTask(n,r);if(!o)throw new B(H.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);const s=await i.getTask(n,r);if(s){const c=Fi.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Wt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{const s=await i.getTask(n,r);if(!s)throw new B(H.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Wt(s.status))throw new B(H.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);const c=await i.getTask(n,r);if(c){const u=Fi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function qh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Aw(e,t){const r={...e};for(const i in t){const n=i,o=t[n];if(o===void 0)continue;const a=r[n];qh(a)&&qh(o)?r[n]={...a,...o}:r[n]=o}return r}function Jh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tc={exports:{}},Kh={},zt={},Xt={},nc={},ce={},br={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(g){if(super(),!e.IDENTIFIER.test(g))throw new Error("CodeGen: name must be a valid identifier");this.str=g}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(g){super(),this._items=typeof g=="string"?[g]:g}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const g=this._items[0];return g===""||g==='""'}get str(){var g;return(g=this._str)!==null&&g!==void 0?g:this._str=this._items.reduce((k,O)=>`${k}${O}`,"")}get names(){var g;return(g=this._names)!==null&&g!==void 0?g:this._names=this._items.reduce((k,O)=>(O instanceof r&&(k[O.str]=(k[O.str]||0)+1),k),{})}}e._Code=i,e.nil=new i("");function n(y,...g){const k=[y[0]];let O=0;for(;O<g.length;)s(k,g[O]),k.push(y[++O]);return new i(k)}e._=n;const o=new i("+");function a(y,...g){const k=[p(y[0])];let O=0;for(;O<g.length;)k.push(o),s(k,g[O]),k.push(o,p(y[++O]));return c(k),new i(k)}e.str=a;function s(y,g){g instanceof i?y.push(...g._items):g instanceof r?y.push(g):y.push(d(g))}e.addCodeArg=s;function c(y){let g=1;for(;g<y.length-1;){if(y[g]===o){const k=u(y[g-1],y[g+1]);if(k!==void 0){y.splice(g-1,3,k);continue}y[g++]="+"}g++}}function u(y,g){if(g==='""')return y;if(y==='""')return g;if(typeof y=="string")return g instanceof r||y[y.length-1]!=='"'?void 0:typeof g!="string"?`${y.slice(0,-1)}${g}"`:g[0]==='"'?y.slice(0,-1)+g.slice(1):void 0;if(typeof g=="string"&&g[0]==='"'&&!(y instanceof r))return`"${y}${g.slice(1)}`}function l(y,g){return g.emptyStr()?y:y.emptyStr()?g:a`${y}${g}`}e.strConcat=l;function d(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:p(Array.isArray(y)?y.join(","):y)}function m(y){return new i(p(y))}e.stringify=m;function p(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=p;function h(y){return typeof y=="string"&&e.IDENTIFIER.test(y)?new i(`.${y}`):n`[${y}]`}e.getProperty=h;function $(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new i(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=$;function b(y){return new i(y.toString())}e.regexpCode=b})(br);var rc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=br;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var i;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(i||(e.UsedValueState=i={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class o extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=o;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new o(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const m=this.toName(u),{prefix:p}=m,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let $=this._values[p];if($){const g=$.get(h);if(g)return g}else $=this._values[p]=new Map;$.set(h,m);const b=this._scope[p]||(this._scope[p]=[]),y=b.length;return b[y]=l.ref,m.setValue(l,{property:p,itemIndex:y}),m}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,m=>{if(m.value===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return m.value.code},l,d)}_reduceValues(u,l,d={},m){let p=t.nil;for(const h in u){const $=u[h];if(!$)continue;const b=d[h]=d[h]||new Map;$.forEach(y=>{if(b.has(y))return;b.set(y,i.Started);let g=l(y);if(g){const k=this.opts.es5?e.varKinds.var:e.varKinds.const;p=(0,t._)`${p}${k} ${y} = ${g};${this.opts._n}`}else if(g=m?.(y))p=(0,t._)`${p}${g}${this.opts._n}`;else throw new r(y);b.set(y,i.Completed)})}return p}}e.ValueScope=s})(rc),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=br,r=rc;var i=br;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return i.Name}});var n=rc;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class o{optimizeNodes(){return this}optimizeNames(f,v){return this}}class a extends o{constructor(f,v,E){super(),this.varKind=f,this.name=v,this.rhs=E}render({es5:f,_n:v}){const E=f?r.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${M};`+v}optimizeNames(f,v){if(f[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,f,v)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(f,v,E){super(),this.lhs=f,this.rhs=v,this.sideEffects=E}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,v){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,f,v),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ne(f,this.rhs)}}class c extends s{constructor(f,v,E,M){super(f,E,M),this.op=v}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends o{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends o{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends o{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class m extends o{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,v){return this.code=K(this.code,f,v),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends o{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((v,E)=>v+E.render(f),"")}optimizeNodes(){const{nodes:f}=this;let v=f.length;for(;v--;){const E=f[v].optimizeNodes();Array.isArray(E)?f.splice(v,1,...E):E?f[v]=E:f.splice(v,1)}return f.length>0?this:void 0}optimizeNames(f,v){const{nodes:E}=this;let M=E.length;for(;M--;){const q=E[M];q.optimizeNames(f,v)||(Ee(f,q.names),E.splice(M,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((f,v)=>X(f,v.names),{})}}class h extends p{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends p{}class b extends h{}b.kind="else";class y extends h{constructor(f,v){super(v),this.condition=f}render(f){let v=`if(${this.condition})`+super.render(f);return this.else&&(v+="else "+this.else.render(f)),v}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let v=this.else;if(v){const E=v.optimizeNodes();v=this.else=Array.isArray(E)?new b(E):E}if(v)return f===!1?v instanceof y?v:v.nodes:this.nodes.length?this:new y(ot(f),v instanceof y?[v]:v.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,v){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames(f,v),!!(super.optimizeNames(f,v)||this.else))return this.condition=K(this.condition,f,v),this}get names(){const f=super.names;return ne(f,this.condition),this.else&&X(f,this.else.names),f}}y.kind="if";class g extends h{}g.kind="for";class k extends g{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,v){if(super.optimizeNames(f,v))return this.iteration=K(this.iteration,f,v),this}get names(){return X(super.names,this.iteration.names)}}class O extends g{constructor(f,v,E,M){super(),this.varKind=f,this.name=v,this.from=E,this.to=M}render(f){const v=f.es5?r.varKinds.var:this.varKind,{name:E,from:M,to:q}=this;return`for(${v} ${E}=${M}; ${E}<${q}; ${E}++)`+super.render(f)}get names(){const f=ne(super.names,this.from);return ne(f,this.to)}}class N extends g{constructor(f,v,E,M){super(),this.loop=f,this.varKind=v,this.name=E,this.iterable=M}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,v){if(super.optimizeNames(f,v))return this.iterable=K(this.iterable,f,v),this}get names(){return X(super.names,this.iterable.names)}}class G extends h{constructor(f,v,E){super(),this.name=f,this.args=v,this.async=E}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}G.kind="func";class Y extends p{render(f){return"return "+super.render(f)}}Y.kind="return";class pe extends h{render(f){let v="try"+super.render(f);return this.catch&&(v+=this.catch.render(f)),this.finally&&(v+=this.finally.render(f)),v}optimizeNodes(){var f,v;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(v=this.finally)===null||v===void 0||v.optimizeNodes(),this}optimizeNames(f,v){var E,M;return super.optimizeNames(f,v),(E=this.catch)===null||E===void 0||E.optimizeNames(f,v),(M=this.finally)===null||M===void 0||M.optimizeNames(f,v),this}get names(){const f=super.names;return this.catch&&X(f,this.catch.names),this.finally&&X(f,this.finally.names),f}}class Ie extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}Ie.kind="catch";class Pe extends h{render(f){return"finally"+super.render(f)}}Pe.kind="finally";class F{constructor(f,v={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...v,_n:v.lines?`
|
|
70
|
+
]`;continue}n+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(n)}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 n}function Mh(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===te.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,n)=>({...i,[n]:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Xe(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===te.ZodString&&e.keyType._def.checks?.length){const{type:i,...n}=Zh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===te.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===te.ZodBranded&&e.keyType._def.type._def.typeName===te.ZodString&&e.keyType._def.type._def.checks?.length){const{type:i,...n}=Ah(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function pw(e,t){if(t.mapStrategy==="record")return Mh(e,t);const r=ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Xe(t),i=ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Xe(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function mw(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function fw(e){return e.target==="openAi"?void 0:{not:Xe({...e,currentPath:[...e.currentPath,"not"]})}}function hw(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Bi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function gw(e,t){if(t.target==="openApi3")return Lh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in Bi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=Bi[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=r.reduce((n,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(i.length===r.length){const n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return Lh(e,t)}const Lh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,n)=>ge(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function vw(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:Bi[e.innerType._def.typeName],nullable:!0}:{type:[Bi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const i=ge(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function yw(e,t){const r={type:"number"};if(!e.checks)return r;for(const i of e.checks)switch(i.kind){case"int":r.type="integer",Dh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?ve(r,"minimum",i.value,i.message,t):ve(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?ve(r,"maximum",i.value,i.message,t):ve(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",i.value,i.message,t));break;case"multipleOf":ve(r,"multipleOf",i.value,i.message,t);break}return r}function _w(e,t){const r=t.target==="openAi",i={type:"object",properties:{}},n=[],o=e.shape();for(const s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=$w(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=ge(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||n.push(s))}n.length&&(i.required=n);const a=bw(e,t);return a!==void 0&&(i.additionalProperties=a),i}function bw(e,t){if(e.catchall._def.typeName!=="ZodNever")return ge(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 $w(e){try{return e.isOptional()}catch{return!0}}const kw=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ge(e.innerType._def,t);const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Xe(t)},r]}:Xe(t)},ww=(e,t)=>{if(t.pipeStrategy==="input")return ge(e.in._def,t);if(t.pipeStrategy==="output")return ge(e.out._def,t);const r=ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function Sw(e,t){return ge(e.type._def,t)}function Iw(e,t){const i={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ve(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ve(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function Ow(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function Tw(e){return{not:Xe(e)}}function Pw(e){return Xe(e)}const Ew=(e,t)=>ge(e.innerType._def,t),zw=(e,t,r)=>{switch(t){case te.ZodString:return Zh(e,r);case te.ZodNumber:return yw(e,r);case te.ZodObject:return _w(e,r);case te.ZodBigInt:return ew(e,r);case te.ZodBoolean:return tw();case te.ZodDate:return Uh(e,r);case te.ZodUndefined:return Tw(r);case te.ZodNull:return hw(r);case te.ZodArray:return Qk(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return gw(e,r);case te.ZodIntersection:return cw(e,r);case te.ZodTuple:return Ow(e,r);case te.ZodRecord:return Mh(e,r);case te.ZodLiteral:return uw(e,r);case te.ZodEnum:return aw(e);case te.ZodNativeEnum:return mw(e);case te.ZodNullable:return vw(e,r);case te.ZodOptional:return kw(e,r);case te.ZodMap:return pw(e,r);case te.ZodSet:return Iw(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return Sw(e,r);case te.ZodNaN:case te.ZodNever:return fw(r);case te.ZodEffects:return ow(e,r);case te.ZodAny:return Xe(r);case te.ZodUnknown:return Pw(r);case te.ZodDefault:return iw(e,r);case te.ZodBranded:return Ah(e,r);case te.ZodReadonly:return Ew(e,r);case te.ZodCatch:return nw(e,r);case te.ZodPipeline:return ww(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(i=>{})()}};function ge(e,t,r=!1){const i=t.seen.get(e);if(t.override){const s=t.override?.(e,t,i,r);if(s!==Wk)return s}if(i&&!r){const s=Nw(i,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const o=zw(e,e.typeName,t),a=typeof o=="function"?ge(o(),t):o;if(a&&xw(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const Nw=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Rh(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,i)=>t.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Xe(t)):t.$refStrategy==="seen"?Xe(t):void 0}},xw=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),jw=(e,t)=>{const r=Yk(t);let i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:ge(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Xe(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=ge(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Xe(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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 Cw(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Gh(e,t){return It(e)?Pa(e,{target:Cw(t?.target),io:t?.pipeStrategy??"input"}):jw(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Vh(e){const r=pr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=gh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Bh(e,t){const r=dr(e,t);if(!r.success)throw r.error;return r.data}const Dw=6e4;class Rw{constructor(t){this._options=t,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(Es,r=>{this._oncancel(r)}),this.setNotificationHandler(Ns,r=>{this._onprogress(r)}),this.setRequestHandler(zs,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xs,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new B(H.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Cs,async(r,i)=>{const n=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,m=new B(d.error.code,d.error.message,d.error.data);l(m)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}const a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new B(H.InvalidParams,`Task not found: ${o}`);if(!Wt(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Wt(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Ht]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Ds,async(r,i)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new B(H.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(As,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new B(H.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wt(n.status))throw new B(H.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new B(H.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof B?n:new B(H.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),B.fromError(H.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),Ui(o)||b$(o)?this._onresponse(o):$h(o)?this._onrequest(o,a):_$(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(const i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();const r=B.fromError(H.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const i of t.values())i(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){const i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,o=t.params?._meta?.[Ht]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:H.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=y$(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new B(H.ConnectionClosed,"Request was cancelled");const p={...m,relatedRequestId:t.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});const h=p.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:H.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...i}=t.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}o(i)}_onresponse(t){const r=Number(t.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),Ui(t))i(t);else{const a=new B(t.error.code,t.error.message,t.error.data);i(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Ui(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Ui(t))n(t);else{const a=B.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,i){const{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(t,r,i)}}catch(a){yield{type:"error",error:a instanceof B?a:new B(H.InternalError,String(a))}}return}let o;try{const a=await this.request(t,Zi,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new B(H.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Wt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new B(H.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new B(H.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof B?a:new B(H.InternalError,String(a))}}}request(t,r,i){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{const d=g=>{l(g)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(g){d(g);return}i?.signal?.throwIfAborted();const m=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(p.params={...p.params,task:s}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Ht]:c}});const h=g=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(g)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(O=>this._onerror(new Error(`Failed to send cancellation: ${O}`)));const k=g instanceof B?g:new B(H.RequestTimeout,String(g));l(k)};this._responseHandlers.set(m,g=>{if(!i?.signal?.aborted){if(g instanceof Error)return l(g);try{const k=dr(r,g.result);k.success?u(k.data):l(k.error)}catch(k){l(k)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const $=i?.timeout??Dw,b=()=>h(B.fromError(H.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,i?.maxTotalTimeout,b,i?.resetTimeoutOnProgress??!1);const y=c?.taskId;if(y){const g=k=>{const O=this._responseHandlers.get(m);O?O(k):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,g),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(m),l(k)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(g=>{this._cleanupTimeout(m),l(g)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},js,r)}async getTaskResult(t,r,i){return this.request({method:"tasks/result",params:t},r,i)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Rs,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},A$,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const i=r?.relatedTask?.taskId;if(i){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Ht]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Ht]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ht]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const i=Vh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=Bh(t,n);return Promise.resolve(r(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const i=Vh(t);this._notificationHandlers.set(i,n=>{const o=Bh(t,n);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,i,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const i=await this._taskMessageQueue.dequeueAll(t,r);for(const n of i)if(n.type==="request"&&$h(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new B(H.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(i=n.pollInterval)}catch{}return new Promise((n,o)=>{if(r.aborted){o(new B(H.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new B(H.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await i.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const o=await i.getTask(n,r);if(!o)throw new B(H.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);const s=await i.getTask(n,r);if(s){const c=Fi.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Wt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{const s=await i.getTask(n,r);if(!s)throw new B(H.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Wt(s.status))throw new B(H.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);const c=await i.getTask(n,r);if(c){const u=Fi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function qh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Aw(e,t){const r={...e};for(const i in t){const n=i,o=t[n];if(o===void 0)continue;const a=r[n];qh(a)&&qh(o)?r[n]={...a,...o}:r[n]=o}return r}function Jh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tc={exports:{}},Kh={},zt={},Xt={},nc={},ce={},br={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(g){if(super(),!e.IDENTIFIER.test(g))throw new Error("CodeGen: name must be a valid identifier");this.str=g}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(g){super(),this._items=typeof g=="string"?[g]:g}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const g=this._items[0];return g===""||g==='""'}get str(){var g;return(g=this._str)!==null&&g!==void 0?g:this._str=this._items.reduce((k,O)=>`${k}${O}`,"")}get names(){var g;return(g=this._names)!==null&&g!==void 0?g:this._names=this._items.reduce((k,O)=>(O instanceof r&&(k[O.str]=(k[O.str]||0)+1),k),{})}}e._Code=i,e.nil=new i("");function n(y,...g){const k=[y[0]];let O=0;for(;O<g.length;)s(k,g[O]),k.push(y[++O]);return new i(k)}e._=n;const o=new i("+");function a(y,...g){const k=[p(y[0])];let O=0;for(;O<g.length;)k.push(o),s(k,g[O]),k.push(o,p(y[++O]));return c(k),new i(k)}e.str=a;function s(y,g){g instanceof i?y.push(...g._items):g instanceof r?y.push(g):y.push(d(g))}e.addCodeArg=s;function c(y){let g=1;for(;g<y.length-1;){if(y[g]===o){const k=u(y[g-1],y[g+1]);if(k!==void 0){y.splice(g-1,3,k);continue}y[g++]="+"}g++}}function u(y,g){if(g==='""')return y;if(y==='""')return g;if(typeof y=="string")return g instanceof r||y[y.length-1]!=='"'?void 0:typeof g!="string"?`${y.slice(0,-1)}${g}"`:g[0]==='"'?y.slice(0,-1)+g.slice(1):void 0;if(typeof g=="string"&&g[0]==='"'&&!(y instanceof r))return`"${y}${g.slice(1)}`}function l(y,g){return g.emptyStr()?y:y.emptyStr()?g:a`${y}${g}`}e.strConcat=l;function d(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:p(Array.isArray(y)?y.join(","):y)}function m(y){return new i(p(y))}e.stringify=m;function p(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=p;function h(y){return typeof y=="string"&&e.IDENTIFIER.test(y)?new i(`.${y}`):n`[${y}]`}e.getProperty=h;function $(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new i(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=$;function b(y){return new i(y.toString())}e.regexpCode=b})(br);var rc={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=br;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var i;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(i||(e.UsedValueState=i={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class o extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=o;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new o(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const m=this.toName(u),{prefix:p}=m,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let $=this._values[p];if($){const g=$.get(h);if(g)return g}else $=this._values[p]=new Map;$.set(h,m);const b=this._scope[p]||(this._scope[p]=[]),y=b.length;return b[y]=l.ref,m.setValue(l,{property:p,itemIndex:y}),m}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,m=>{if(m.value===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return m.value.code},l,d)}_reduceValues(u,l,d={},m){let p=t.nil;for(const h in u){const $=u[h];if(!$)continue;const b=d[h]=d[h]||new Map;$.forEach(y=>{if(b.has(y))return;b.set(y,i.Started);let g=l(y);if(g){const k=this.opts.es5?e.varKinds.var:e.varKinds.const;p=(0,t._)`${p}${k} ${y} = ${g};${this.opts._n}`}else if(g=m?.(y))p=(0,t._)`${p}${g}${this.opts._n}`;else throw new r(y);b.set(y,i.Completed)})}return p}}e.ValueScope=s})(rc),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=br,r=rc;var i=br;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return i.Name}});var n=rc;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class o{optimizeNodes(){return this}optimizeNames(f,v){return this}}class a extends o{constructor(f,v,E){super(),this.varKind=f,this.name=v,this.rhs=E}render({es5:f,_n:v}){const E=f?r.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${E} ${this.name}${M};`+v}optimizeNames(f,v){if(f[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,f,v)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(f,v,E){super(),this.lhs=f,this.rhs=v,this.sideEffects=E}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,v){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,f,v),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return ne(f,this.rhs)}}class c extends s{constructor(f,v,E,M){super(f,E,M),this.op=v}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends o{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends o{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends o{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class m extends o{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,v){return this.code=K(this.code,f,v),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends o{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((v,E)=>v+E.render(f),"")}optimizeNodes(){const{nodes:f}=this;let v=f.length;for(;v--;){const E=f[v].optimizeNodes();Array.isArray(E)?f.splice(v,1,...E):E?f[v]=E:f.splice(v,1)}return f.length>0?this:void 0}optimizeNames(f,v){const{nodes:E}=this;let M=E.length;for(;M--;){const q=E[M];q.optimizeNames(f,v)||(Ee(f,q.names),E.splice(M,1))}return E.length>0?this:void 0}get names(){return this.nodes.reduce((f,v)=>X(f,v.names),{})}}class h extends p{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends p{}class b extends h{}b.kind="else";class y extends h{constructor(f,v){super(v),this.condition=f}render(f){let v=`if(${this.condition})`+super.render(f);return this.else&&(v+="else "+this.else.render(f)),v}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let v=this.else;if(v){const E=v.optimizeNodes();v=this.else=Array.isArray(E)?new b(E):E}if(v)return f===!1?v instanceof y?v:v.nodes:this.nodes.length?this:new y(ot(f),v instanceof y?[v]:v.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,v){var E;if(this.else=(E=this.else)===null||E===void 0?void 0:E.optimizeNames(f,v),!!(super.optimizeNames(f,v)||this.else))return this.condition=K(this.condition,f,v),this}get names(){const f=super.names;return ne(f,this.condition),this.else&&X(f,this.else.names),f}}y.kind="if";class g extends h{}g.kind="for";class k extends g{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,v){if(super.optimizeNames(f,v))return this.iteration=K(this.iteration,f,v),this}get names(){return X(super.names,this.iteration.names)}}class O extends g{constructor(f,v,E,M){super(),this.varKind=f,this.name=v,this.from=E,this.to=M}render(f){const v=f.es5?r.varKinds.var:this.varKind,{name:E,from:M,to:q}=this;return`for(${v} ${E}=${M}; ${E}<${q}; ${E}++)`+super.render(f)}get names(){const f=ne(super.names,this.from);return ne(f,this.to)}}class N extends g{constructor(f,v,E,M){super(),this.loop=f,this.varKind=v,this.name=E,this.iterable=M}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,v){if(super.optimizeNames(f,v))return this.iterable=K(this.iterable,f,v),this}get names(){return X(super.names,this.iterable.names)}}class G extends h{constructor(f,v,E){super(),this.name=f,this.args=v,this.async=E}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}G.kind="func";class Y extends p{render(f){return"return "+super.render(f)}}Y.kind="return";class pe extends h{render(f){let v="try"+super.render(f);return this.catch&&(v+=this.catch.render(f)),this.finally&&(v+=this.finally.render(f)),v}optimizeNodes(){var f,v;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(v=this.finally)===null||v===void 0||v.optimizeNodes(),this}optimizeNames(f,v){var E,M;return super.optimizeNames(f,v),(E=this.catch)===null||E===void 0||E.optimizeNames(f,v),(M=this.finally)===null||M===void 0||M.optimizeNames(f,v),this}get names(){const f=super.names;return this.catch&&X(f,this.catch.names),this.finally&&X(f,this.finally.names),f}}class Ie extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}Ie.kind="catch";class Pe extends h{render(f){return"finally"+super.render(f)}}Pe.kind="finally";class F{constructor(f,v={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...v,_n:v.lines?`
|
|
71
71
|
`:""},this._extScope=f,this._scope=new r.Scope({parent:f}),this._nodes=[new $]}toString(){return this._root.render(this.opts)}name(f){return this._scope.name(f)}scopeName(f){return this._extScope.name(f)}scopeValue(f,v){const E=this._extScope.value(f,v);return(this._values[E.prefix]||(this._values[E.prefix]=new Set)).add(E),E}getScopeValue(f,v){return this._extScope.getValue(f,v)}scopeRefs(f){return this._extScope.scopeRefs(f,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(f,v,E,M){const q=this._scope.toName(v);return E!==void 0&&M&&(this._constants[q.str]=E),this._leafNode(new a(f,q,E)),q}const(f,v,E){return this._def(r.varKinds.const,f,v,E)}let(f,v,E){return this._def(r.varKinds.let,f,v,E)}var(f,v,E){return this._def(r.varKinds.var,f,v,E)}assign(f,v,E){return this._leafNode(new s(f,v,E))}add(f,v){return this._leafNode(new c(f,e.operators.ADD,v))}code(f){return typeof f=="function"?f():f!==t.nil&&this._leafNode(new m(f)),this}object(...f){const v=["{"];for(const[E,M]of f)v.length>1&&v.push(","),v.push(E),(E!==M||this.opts.es5)&&(v.push(":"),(0,t.addCodeArg)(v,M));return v.push("}"),new t._Code(v)}if(f,v,E){if(this._blockNode(new y(f)),v&&E)this.code(v).else().code(E).endIf();else if(v)this.code(v).endIf();else if(E)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(f){return this._elseNode(new y(f))}else(){return this._elseNode(new b)}endIf(){return this._endBlockNode(y,b)}_for(f,v){return this._blockNode(f),v&&this.code(v).endFor(),this}for(f,v){return this._for(new k(f),v)}forRange(f,v,E,M,q=this.opts.es5?r.varKinds.var:r.varKinds.let){const me=this._scope.toName(f);return this._for(new O(q,me,v,E),()=>M(me))}forOf(f,v,E,M=r.varKinds.const){const q=this._scope.toName(f);if(this.opts.es5){const me=v instanceof t.Name?v:this.var("_arr",v);return this.forRange("_i",0,(0,t._)`${me}.length`,de=>{this.var(q,(0,t._)`${me}[${de}]`),E(q)})}return this._for(new N("of",M,q,v),()=>E(q))}forIn(f,v,E,M=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(f,(0,t._)`Object.keys(${v})`,E);const q=this._scope.toName(f);return this._for(new N("in",M,q,v),()=>E(q))}endFor(){return this._endBlockNode(g)}label(f){return this._leafNode(new u(f))}break(f){return this._leafNode(new l(f))}return(f){const v=new Y;if(this._blockNode(v),this.code(f),v.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Y)}try(f,v,E){if(!v&&!E)throw new Error('CodeGen: "try" without "catch" and "finally"');const M=new pe;if(this._blockNode(M),this.code(f),v){const q=this.name("e");this._currNode=M.catch=new Ie(q),v(q)}return E&&(this._currNode=M.finally=new Pe,this.code(E)),this._endBlockNode(Ie,Pe)}throw(f){return this._leafNode(new d(f))}block(f,v){return this._blockStarts.push(this._nodes.length),f&&this.code(f).endBlock(v),this}endBlock(f){const v=this._blockStarts.pop();if(v===void 0)throw new Error("CodeGen: not in self-balancing block");const E=this._nodes.length-v;if(E<0||f!==void 0&&E!==f)throw new Error(`CodeGen: wrong number of nodes: ${E} vs ${f} expected`);return this._nodes.length=v,this}func(f,v=t.nil,E,M){return this._blockNode(new G(f,v,E)),M&&this.code(M).endFunc(),this}endFunc(){return this._endBlockNode(G)}optimize(f=1){for(;f-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(f){return this._currNode.nodes.push(f),this}_blockNode(f){this._currNode.nodes.push(f),this._nodes.push(f)}_endBlockNode(f,v){const E=this._currNode;if(E instanceof f||v&&E instanceof v)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${v?`${f.kind}/${v.kind}`:f.kind}"`)}_elseNode(f){const v=this._currNode;if(!(v instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=v.else=f,this}get _root(){return this._nodes[0]}get _currNode(){const f=this._nodes;return f[f.length-1]}set _currNode(f){const v=this._nodes;v[v.length-1]=f}}e.CodeGen=F;function X(P,f){for(const v in f)P[v]=(P[v]||0)+(f[v]||0);return P}function ne(P,f){return f instanceof t._CodeOrName?X(P,f.names):P}function K(P,f,v){if(P instanceof t.Name)return E(P);if(!M(P))return P;return new t._Code(P._items.reduce((q,me)=>(me instanceof t.Name&&(me=E(me)),me instanceof t._Code?q.push(...me._items):q.push(me),q),[]));function E(q){const me=v[q.str];return me===void 0||f[q.str]!==1?q:(delete f[q.str],me)}function M(q){return q instanceof t._Code&&q._items.some(me=>me instanceof t.Name&&f[me.str]===1&&v[me.str]!==void 0)}}function Ee(P,f){for(const v in f)P[v]=(P[v]||0)-(f[v]||0)}function ot(P){return typeof P=="boolean"||typeof P=="number"||P===null?!P:(0,t._)`!${j(P)}`}e.not=ot;const at=I(e.operators.AND);function Lt(...P){return P.reduce(at)}e.and=Lt;const Tt=I(e.operators.OR);function R(...P){return P.reduce(Tt)}e.or=R;function I(P){return(f,v)=>f===t.nil?v:v===t.nil?f:(0,t._)`${j(f)} ${P} ${j(v)}`}function j(P){return P instanceof t.Name?P:(0,t._)`(${P})`}})(ce);var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;const Se=ce,Uw=br;function Zw(e){const t={};for(const r of e)t[r]=!0;return t}Z.toHash=Zw;function Fw(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Hh(e,t),!Wh(t,e.self.RULES.all))}Z.alwaysValidSchema=Fw;function Hh(e,t=e.schema){const{opts:r,self:i}=e;if(!r.strictSchema||typeof t=="boolean")return;const n=i.RULES.keywords;for(const o in t)n[o]||tg(e,`unknown keyword: "${o}"`)}Z.checkUnknownRules=Hh;function Wh(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(t[r])return!0;return!1}Z.schemaHasRules=Wh;function Mw(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Z.schemaHasRulesButRef=Mw;function Lw({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Se._)`${r}`}return(0,Se._)`${e}${t}${(0,Se.getProperty)(i)}`}Z.schemaRefOrVal=Lw;function Gw(e){return Xh(decodeURIComponent(e))}Z.unescapeFragment=Gw;function Vw(e){return encodeURIComponent(ic(e))}Z.escapeFragment=Vw;function ic(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=ic;function Xh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=Xh;function Bw(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}Z.eachItem=Bw;function Yh({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,o,a,s)=>{const c=a===void 0?o:a instanceof Se.Name?(o instanceof Se.Name?e(n,o,a):t(n,o,a),a):o instanceof Se.Name?(t(n,a,o),o):r(o,a);return s===Se.Name&&!(c instanceof Se.Name)?i(n,c):c}}Z.mergeEvaluated={props:Yh({mergeNames:(e,t,r)=>e.if((0,Se._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,Se._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,Se._)`${r} || {}`).code((0,Se._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,Se._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,Se._)`${r} || {}`),oc(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Qh}),items:Yh({mergeNames:(e,t,r)=>e.if((0,Se._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,Se._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,Se._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,Se._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Qh(e,t){if(t===!0)return e.var("props",!0);const r=e.var("props",(0,Se._)`{}`);return t!==void 0&&oc(e,r,t),r}Z.evaluatedPropsToName=Qh;function oc(e,t,r){Object.keys(r).forEach(i=>e.assign((0,Se._)`${t}${(0,Se.getProperty)(i)}`,!0))}Z.setEvaluated=oc;const eg={};function qw(e,t){return e.scopeValue("func",{ref:t,code:eg[t.code]||(eg[t.code]=new Uw._Code(t.code))})}Z.useFunc=qw;var ac;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ac||(Z.Type=ac={}));function Jw(e,t,r){if(e instanceof Se.Name){const i=t===ac.Num;return r?i?(0,Se._)`"[" + ${e} + "]"`:(0,Se._)`"['" + ${e} + "']"`:i?(0,Se._)`"/" + ${e}`:(0,Se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Se.getProperty)(e).toString():"/"+ic(e)}Z.getErrorPath=Jw;function tg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Z.checkStrictMode=tg;var qi={},ng;function At(){if(ng)return qi;ng=1,Object.defineProperty(qi,"__esModule",{value:!0});const e=ce,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return qi.default=t,qi}var rg;function Ji(){return rg||(rg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=ce,r=Z,i=At();e.keywordError={message:({keyword:b})=>(0,t.str)`must pass "${b}" keyword validation`},e.keyword$DataError={message:({keyword:b,schemaType:y})=>y?(0,t.str)`"${b}" keyword must be ${y} ($data)`:(0,t.str)`"${b}" keyword is invalid ($data)`};function n(b,y=e.keywordError,g,k){const{it:O}=b,{gen:N,compositeRule:G,allErrors:Y}=O,pe=d(b,y,g);k??(G||Y)?c(N,pe):u(O,(0,t._)`[${pe}]`)}e.reportError=n;function o(b,y=e.keywordError,g){const{it:k}=b,{gen:O,compositeRule:N,allErrors:G}=k,Y=d(b,y,g);c(O,Y),N||G||u(k,i.default.vErrors)}e.reportExtraError=o;function a(b,y){b.assign(i.default.errors,y),b.if((0,t._)`${i.default.vErrors} !== null`,()=>b.if(y,()=>b.assign((0,t._)`${i.default.vErrors}.length`,y),()=>b.assign(i.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:b,keyword:y,schemaValue:g,data:k,errsCount:O,it:N}){if(O===void 0)throw new Error("ajv implementation error");const G=b.name("err");b.forRange("i",O,i.default.errors,Y=>{b.const(G,(0,t._)`${i.default.vErrors}[${Y}]`),b.if((0,t._)`${G}.instancePath === undefined`,()=>b.assign((0,t._)`${G}.instancePath`,(0,t.strConcat)(i.default.instancePath,N.errorPath))),b.assign((0,t._)`${G}.schemaPath`,(0,t.str)`${N.errSchemaPath}/${y}`),N.opts.verbose&&(b.assign((0,t._)`${G}.schema`,g),b.assign((0,t._)`${G}.data`,k))})}e.extendErrors=s;function c(b,y){const g=b.const("err",y);b.if((0,t._)`${i.default.vErrors} === null`,()=>b.assign(i.default.vErrors,(0,t._)`[${g}]`),(0,t._)`${i.default.vErrors}.push(${g})`),b.code((0,t._)`${i.default.errors}++`)}function u(b,y){const{gen:g,validateName:k,schemaEnv:O}=b;O.$async?g.throw((0,t._)`new ${b.ValidationError}(${y})`):(g.assign((0,t._)`${k}.errors`,y),g.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function d(b,y,g){const{createErrors:k}=b.it;return k===!1?(0,t._)`{}`:m(b,y,g)}function m(b,y,g={}){const{gen:k,it:O}=b,N=[p(O,g),h(b,g)];return $(b,y,N),k.object(...N)}function p({errorPath:b},{instancePath:y}){const g=y?(0,t.str)`${b}${(0,r.getErrorPath)(y,r.Type.Str)}`:b;return[i.default.instancePath,(0,t.strConcat)(i.default.instancePath,g)]}function h({keyword:b,it:{errSchemaPath:y}},{schemaPath:g,parentSchema:k}){let O=k?y:(0,t.str)`${y}/${b}`;return g&&(O=(0,t.str)`${O}${(0,r.getErrorPath)(g,r.Type.Str)}`),[l.schemaPath,O]}function $(b,{params:y,message:g},k){const{keyword:O,data:N,schemaValue:G,it:Y}=b,{opts:pe,propertyName:Ie,topSchemaRef:Pe,schemaPath:F}=Y;k.push([l.keyword,O],[l.params,typeof y=="function"?y(b):y||(0,t._)`{}`]),pe.messages&&k.push([l.message,typeof g=="function"?g(b):g]),pe.verbose&&k.push([l.schema,G],[l.parentSchema,(0,t._)`${Pe}${F}`],[i.default.data,N]),Ie&&k.push([l.propertyName,Ie])}})(nc)),nc}var ig;function Kw(){if(ig)return Xt;ig=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.boolOrEmptySchema=Xt.topBoolOrEmptySchema=void 0;const e=Ji(),t=ce,r=At(),i={message:"boolean schema is false"};function n(s){const{gen:c,schema:u,validateName:l}=s;u===!1?a(s,!1):typeof u=="object"&&u.$async===!0?c.return(r.default.data):(c.assign((0,t._)`${l}.errors`,null),c.return(!0))}Xt.topBoolOrEmptySchema=n;function o(s,c){const{gen:u,schema:l}=s;l===!1?(u.var(c,!1),a(s)):u.var(c,!0)}Xt.boolOrEmptySchema=o;function a(s,c){const{gen:u,data:l}=s,d={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:s};(0,e.reportError)(d,i,void 0,c)}return Xt}var je={},Yt={};Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.getRules=Yt.isJSONType=void 0;const Hw=["string","number","integer","boolean","null","object","array"],Ww=new Set(Hw);function Xw(e){return typeof e=="string"&&Ww.has(e)}Yt.isJSONType=Xw;function Yw(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Yt.getRules=Yw;var Nt={},og;function ag(){if(og)return Nt;og=1,Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.shouldUseRule=Nt.shouldUseGroup=Nt.schemaHasRulesForType=void 0;function e({schema:i,self:n},o){const a=n.RULES.types[o];return a&&a!==!0&&t(i,a)}Nt.schemaHasRulesForType=e;function t(i,n){return n.rules.some(o=>r(i,o))}Nt.shouldUseGroup=t;function r(i,n){var o;return i[n.keyword]!==void 0||((o=n.definition.implements)===null||o===void 0?void 0:o.some(a=>i[a]!==void 0))}return Nt.shouldUseRule=r,Nt}Object.defineProperty(je,"__esModule",{value:!0}),je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;const Qw=Yt,eS=ag(),tS=Ji(),oe=ce,sg=Z;var kn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(kn||(je.DataType=kn={}));function nS(e){const t=cg(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}je.getSchemaTypes=nS;function cg(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Qw.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}je.getJSONTypes=cg;function rS(e,t){const{gen:r,data:i,opts:n}=e,o=iS(t,n.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,eS.schemaHasRulesForType)(e,t[0]));if(a){const s=cc(t,i,n.strictNumbers,kn.Wrong);r.if(s,()=>{o.length?oS(e,t,o):uc(e)})}return a}je.coerceAndCheckDataType=rS;const ug=new Set(["string","number","integer","boolean","null"]);function iS(e,t){return t?e.filter(r=>ug.has(r)||t==="array"&&r==="array"):[]}function oS(e,t,r){const{gen:i,data:n,opts:o}=e,a=i.let("dataType",(0,oe._)`typeof ${n}`),s=i.let("coerced",(0,oe._)`undefined`);o.coerceTypes==="array"&&i.if((0,oe._)`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,(0,oe._)`${n}[0]`).assign(a,(0,oe._)`typeof ${n}`).if(cc(t,n,o.strictNumbers),()=>i.assign(s,n))),i.if((0,oe._)`${s} !== undefined`);for(const u of r)(ug.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);i.else(),uc(e),i.endIf(),i.if((0,oe._)`${s} !== undefined`,()=>{i.assign(n,s),aS(e,s)});function c(u){switch(u){case"string":i.elseIf((0,oe._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,oe._)`"" + ${n}`).elseIf((0,oe._)`${n} === null`).assign(s,(0,oe._)`""`);return;case"number":i.elseIf((0,oe._)`${a} == "boolean" || ${n} === null
|
|
72
72
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(s,(0,oe._)`+${n}`);return;case"integer":i.elseIf((0,oe._)`${a} === "boolean" || ${n} === null
|
|
73
73
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(s,(0,oe._)`+${n}`);return;case"boolean":i.elseIf((0,oe._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(s,!1).elseIf((0,oe._)`${n} === "true" || ${n} === 1`).assign(s,!0);return;case"null":i.elseIf((0,oe._)`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(s,null);return;case"array":i.elseIf((0,oe._)`${a} === "string" || ${a} === "number"
|
package/dist/gui-mcp-server.js
CHANGED
|
@@ -67,7 +67,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
67
67
|
]))`;continue}else if(i[c]==="$"){n+=`($|(?=[\r
|
|
68
68
|
]))`;continue}}if(r.s&&i[c]==="."){n+=a?`${i[c]}\r
|
|
69
69
|
`:`[${i[c]}\r
|
|
70
|
-
]`;continue}n+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(n)}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 n}function Lh(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===ne.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,n)=>({...i,[n]:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ke(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ne.ZodString&&e.keyType._def.checks?.length){const{type:i,...n}=Zh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===ne.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ne.ZodBranded&&e.keyType._def.type._def.typeName===ne.ZodString&&e.keyType._def.type._def.checks?.length){const{type:i,...n}=Dh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function yw(e,t){if(t.mapStrategy==="record")return Lh(e,t);const r=ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(t),i=ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function _w(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function $w(e){return e.target==="openAi"?void 0:{not:Ke({...e,currentPath:[...e.currentPath,"not"]})}}function bw(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Vi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Sw(e,t){if(t.target==="openApi3")return Fh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in Vi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=Vi[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=r.reduce((n,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(i.length===r.length){const n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return Fh(e,t)}const Fh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,n)=>ge(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function ww(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:Vi[e.innerType._def.typeName],nullable:!0}:{type:[Vi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const i=ge(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function kw(e,t){const r={type:"number"};if(!e.checks)return r;for(const i of e.checks)switch(i.kind){case"int":r.type="integer",Uh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?be(r,"minimum",i.value,i.message,t):be(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),be(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?be(r,"maximum",i.value,i.message,t):be(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),be(r,"maximum",i.value,i.message,t));break;case"multipleOf":be(r,"multipleOf",i.value,i.message,t);break}return r}function Iw(e,t){const r=t.target==="openAi",i={type:"object",properties:{}},n=[],o=e.shape();for(const s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=Tw(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=ge(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||n.push(s))}n.length&&(i.required=n);const a=xw(e,t);return a!==void 0&&(i.additionalProperties=a),i}function xw(e,t){if(e.catchall._def.typeName!=="ZodNever")return ge(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 Tw(e){try{return e.isOptional()}catch{return!0}}const Pw=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ge(e.innerType._def,t);const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(t)},r]}:Ke(t)},zw=(e,t)=>{if(t.pipeStrategy==="input")return ge(e.in._def,t);if(t.pipeStrategy==="output")return ge(e.out._def,t);const r=ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function Ew(e,t){return ge(e.type._def,t)}function Ow(e,t){const i={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&be(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&be(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function jw(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function Nw(e){return{not:Ke(e)}}function Rw(e){return Ke(e)}const Uw=(e,t)=>ge(e.innerType._def,t),Cw=(e,t,r)=>{switch(t){case ne.ZodString:return Zh(e,r);case ne.ZodNumber:return kw(e,r);case ne.ZodObject:return Iw(e,r);case ne.ZodBigInt:return aw(e,r);case ne.ZodBoolean:return sw();case ne.ZodDate:return Ah(e,r);case ne.ZodUndefined:return Nw(r);case ne.ZodNull:return bw(r);case ne.ZodArray:return ow(e,r);case ne.ZodUnion:case ne.ZodDiscriminatedUnion:return Sw(e,r);case ne.ZodIntersection:return pw(e,r);case ne.ZodTuple:return jw(e,r);case ne.ZodRecord:return Lh(e,r);case ne.ZodLiteral:return hw(e,r);case ne.ZodEnum:return fw(e);case ne.ZodNativeEnum:return _w(e);case ne.ZodNullable:return ww(e,r);case ne.ZodOptional:return Pw(e,r);case ne.ZodMap:return yw(e,r);case ne.ZodSet:return Ow(e,r);case ne.ZodLazy:return()=>e.getter()._def;case ne.ZodPromise:return Ew(e,r);case ne.ZodNaN:case ne.ZodNever:return $w(r);case ne.ZodEffects:return dw(e,r);case ne.ZodAny:return Ke(r);case ne.ZodUnknown:return Rw(r);case ne.ZodDefault:return lw(e,r);case ne.ZodBranded:return Dh(e,r);case ne.ZodReadonly:return Uw(e,r);case ne.ZodCatch:return cw(e,r);case ne.ZodPipeline:return zw(e,r);case ne.ZodFunction:case ne.ZodVoid:case ne.ZodSymbol:return;default:return(i=>{})()}};function ge(e,t,r=!1){const i=t.seen.get(e);if(t.override){const s=t.override?.(e,t,i,r);if(s!==nw)return s}if(i&&!r){const s=Dw(i,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const o=Cw(e,e.typeName,t),a=typeof o=="function"?ge(o(),t):o;if(a&&Aw(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const Dw=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ch(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,i)=>t.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ke(t)):t.$refStrategy==="seen"?Ke(t):void 0}},Aw=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Zw=(e,t)=>{const r=iw(t);let i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:ge(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ke(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=ge(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ke(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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 Mw(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Vh(e,t){return wt(e)?xa(e,{target:Mw(t?.target),io:t?.pipeStrategy??"input"}):Zw(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Gh(e){const r=ur(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=gh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function qh(e,t){const r=cr(e,t);if(!r.success)throw r.error;return r.data}const Lw=6e4;class Fw{constructor(t){this._options=t,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(xs,r=>{this._oncancel(r)}),this.setNotificationHandler(Ps,r=>{this._onprogress(r)}),this.setRequestHandler(Ts,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zs,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new H(Q.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Os,async(r,i)=>{const n=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,m=new H(d.error.code,d.error.message,d.error.data);l(m)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}const a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new H(Q.InvalidParams,`Task not found: ${o}`);if(!Kt(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Kt(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Ht]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(js,async(r,i)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new H(Q.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Rs,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new H(Q.InvalidParams,`Task not found: ${r.params.taskId}`);if(Kt(n.status))throw new H(Q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new H(Q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof H?n:new H(Q.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),H.fromError(Q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),Ci(o)||xb(o)?this._onresponse(o):bh(o)?this._onrequest(o,a):Ib(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(const i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();const r=H.fromError(Q.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const i of t.values())i(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){const i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,o=t.params?._meta?.[Ht]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:Q.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=kb(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new H(Q.ConnectionClosed,"Request was cancelled");const f={...m,relatedRequestId:t.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});const h=f.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:Q.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...i}=t.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}o(i)}_onresponse(t){const r=Number(t.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),Ci(t))i(t);else{const a=new H(t.error.code,t.error.message,t.error.data);i(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Ci(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Ci(t))n(t);else{const a=H.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,i){const{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(t,r,i)}}catch(a){yield{type:"error",error:a instanceof H?a:new H(Q.InternalError,String(a))}}return}let o;try{const a=await this.request(t,Di,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new H(Q.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Kt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new H(Q.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new H(Q.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof H?a:new H(Q.InternalError,String(a))}}}request(t,r,i){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{const d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(v){d(v);return}i?.signal?.throwIfAborted();const m=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Ht]:c}});const h=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));const w=v instanceof H?v:new H(Q.RequestTimeout,String(v));l(w)};this._responseHandlers.set(m,v=>{if(!i?.signal?.aborted){if(v instanceof Error)return l(v);try{const w=cr(r,v.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const b=i?.timeout??Lw,g=()=>h(H.fromError(Q.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(m,b,i?.maxTotalTimeout,g,i?.resetTimeoutOnProgress??!1);const y=c?.taskId;if(y){const v=w=>{const x=this._responseHandlers.get(m);x?x(w):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(m),l(w)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Es,r)}async getTaskResult(t,r,i){return this.request({method:"tasks/result",params:t},r,i)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Ns,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Vb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const i=r?.relatedTask?.taskId;if(i){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Ht]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Ht]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ht]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const i=Gh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=qh(t,n);return Promise.resolve(r(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const i=Gh(t);this._notificationHandlers.set(i,n=>{const o=qh(t,n);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,i,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const i=await this._taskMessageQueue.dequeueAll(t,r);for(const n of i)if(n.type==="request"&&bh(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new H(Q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(i=n.pollInterval)}catch{}return new Promise((n,o)=>{if(r.aborted){o(new H(Q.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new H(Q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await i.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const o=await i.getTask(n,r);if(!o)throw new H(Q.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);const s=await i.getTask(n,r);if(s){const c=Ai.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Kt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{const s=await i.getTask(n,r);if(!s)throw new H(Q.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Kt(s.status))throw new H(Q.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);const c=await i.getTask(n,r);if(c){const u=Ai.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Kt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function Bh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vw(e,t){const r={...e};for(const i in t){const n=i,o=t[n];if(o===void 0)continue;const a=r[n];Bh(a)&&Bh(o)?r[n]={...a,...o}:r[n]=o}return r}function Jh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ys={exports:{}},Hh={},Pt={},Wt={},Qs={},se={},vr={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((w,x)=>`${w}${x}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((w,x)=>(x instanceof r&&(w[x.str]=(w[x.str]||0)+1),w),{})}}e._Code=i,e.nil=new i("");function n(y,...v){const w=[y[0]];let x=0;for(;x<v.length;)s(w,v[x]),w.push(y[++x]);return new i(w)}e._=n;const o=new i("+");function a(y,...v){const w=[f(y[0])];let x=0;for(;x<v.length;)w.push(o),s(w,v[x]),w.push(o,f(y[++x]));return c(w),new i(w)}e.str=a;function s(y,v){v instanceof i?y.push(...v._items):v instanceof r?y.push(v):y.push(d(v))}e.addCodeArg=s;function c(y){let v=1;for(;v<y.length-1;){if(y[v]===o){const w=u(y[v-1],y[v+1]);if(w!==void 0){y.splice(v-1,3,w);continue}y[v++]="+"}v++}}function u(y,v){if(v==='""')return y;if(y==='""')return v;if(typeof y=="string")return v instanceof r||y[y.length-1]!=='"'?void 0:typeof v!="string"?`${y.slice(0,-1)}${v}"`:v[0]==='"'?y.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(y instanceof r))return`"${y}${v.slice(1)}`}function l(y,v){return v.emptyStr()?y:y.emptyStr()?v:a`${y}${v}`}e.strConcat=l;function d(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:f(Array.isArray(y)?y.join(","):y)}function m(y){return new i(f(y))}e.stringify=m;function f(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function h(y){return typeof y=="string"&&e.IDENTIFIER.test(y)?new i(`.${y}`):n`[${y}]`}e.getProperty=h;function b(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new i(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=b;function g(y){return new i(y.toString())}e.regexpCode=g})(vr);var ec={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=vr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var i;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(i||(e.UsedValueState=i={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class o extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=o;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new o(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const m=this.toName(u),{prefix:f}=m,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let b=this._values[f];if(b){const v=b.get(h);if(v)return v}else b=this._values[f]=new Map;b.set(h,m);const g=this._scope[f]||(this._scope[f]=[]),y=g.length;return g[y]=l.ref,m.setValue(l,{property:f,itemIndex:y}),m}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,m=>{if(m.value===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return m.value.code},l,d)}_reduceValues(u,l,d={},m){let f=t.nil;for(const h in u){const b=u[h];if(!b)continue;const g=d[h]=d[h]||new Map;b.forEach(y=>{if(g.has(y))return;g.set(y,i.Started);let v=l(y);if(v){const w=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${w} ${y} = ${v};${this.opts._n}`}else if(v=m?.(y))f=(0,t._)`${f}${v}${this.opts._n}`;else throw new r(y);g.set(y,i.Completed)})}return f}}e.ValueScope=s})(ec),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=vr,r=ec;var i=vr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return i.Name}});var n=ec;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class o{optimizeNodes(){return this}optimizeNames(p,$){return this}}class a extends o{constructor(p,$,z){super(),this.varKind=p,this.name=$,this.rhs=z}render({es5:p,_n:$}){const z=p?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${z} ${this.name}${G};`+$}optimizeNames(p,$){if(p[this.name.str])return this.rhs&&(this.rhs=B(this.rhs,p,$)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(p,$,z){super(),this.lhs=p,this.rhs=$,this.sideEffects=z}render({_n:p}){return`${this.lhs} = ${this.rhs};`+p}optimizeNames(p,$){if(!(this.lhs instanceof t.Name&&!p[this.lhs.str]&&!this.sideEffects))return this.rhs=B(this.rhs,p,$),this}get names(){const p=this.lhs instanceof t.Name?{}:{...this.lhs.names};return W(p,this.rhs)}}class c extends s{constructor(p,$,z,G){super(p,z,G),this.op=$}render({_n:p}){return`${this.lhs} ${this.op}= ${this.rhs};`+p}}class u extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`${this.label}:`+p}}class l extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`break${this.label?` ${this.label}`:""};`+p}}class d extends o{constructor(p){super(),this.error=p}render({_n:p}){return`throw ${this.error};`+p}get names(){return this.error.names}}class m extends o{constructor(p){super(),this.code=p}render({_n:p}){return`${this.code};`+p}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(p,$){return this.code=B(this.code,p,$),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends o{constructor(p=[]){super(),this.nodes=p}render(p){return this.nodes.reduce(($,z)=>$+z.render(p),"")}optimizeNodes(){const{nodes:p}=this;let $=p.length;for(;$--;){const z=p[$].optimizeNodes();Array.isArray(z)?p.splice($,1,...z):z?p[$]=z:p.splice($,1)}return p.length>0?this:void 0}optimizeNames(p,$){const{nodes:z}=this;let G=z.length;for(;G--;){const K=z[G];K.optimizeNames(p,$)||(ze(p,K.names),z.splice(G,1))}return z.length>0?this:void 0}get names(){return this.nodes.reduce((p,$)=>X(p,$.names),{})}}class h extends f{render(p){return"{"+p._n+super.render(p)+"}"+p._n}}class b extends f{}class g extends h{}g.kind="else";class y extends h{constructor(p,$){super($),this.condition=p}render(p){let $=`if(${this.condition})`+super.render(p);return this.else&&($+="else "+this.else.render(p)),$}optimizeNodes(){super.optimizeNodes();const p=this.condition;if(p===!0)return this.nodes;let $=this.else;if($){const z=$.optimizeNodes();$=this.else=Array.isArray(z)?new g(z):z}if($)return p===!1?$ instanceof y?$:$.nodes:this.nodes.length?this:new y(it(p),$ instanceof y?[$]:$.nodes);if(!(p===!1||!this.nodes.length))return this}optimizeNames(p,$){var z;if(this.else=(z=this.else)===null||z===void 0?void 0:z.optimizeNames(p,$),!!(super.optimizeNames(p,$)||this.else))return this.condition=B(this.condition,p,$),this}get names(){const p=super.names;return W(p,this.condition),this.else&&X(p,this.else.names),p}}y.kind="if";class v extends h{}v.kind="for";class w extends v{constructor(p){super(),this.iteration=p}render(p){return`for(${this.iteration})`+super.render(p)}optimizeNames(p,$){if(super.optimizeNames(p,$))return this.iteration=B(this.iteration,p,$),this}get names(){return X(super.names,this.iteration.names)}}class x extends v{constructor(p,$,z,G){super(),this.varKind=p,this.name=$,this.from=z,this.to=G}render(p){const $=p.es5?r.varKinds.var:this.varKind,{name:z,from:G,to:K}=this;return`for(${$} ${z}=${G}; ${z}<${K}; ${z}++)`+super.render(p)}get names(){const p=W(super.names,this.from);return W(p,this.to)}}class E extends v{constructor(p,$,z,G){super(),this.loop=p,this.varKind=$,this.name=z,this.iterable=G}render(p){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(p)}optimizeNames(p,$){if(super.optimizeNames(p,$))return this.iterable=B(this.iterable,p,$),this}get names(){return X(super.names,this.iterable.names)}}class F extends h{constructor(p,$,z){super(),this.name=p,this.args=$,this.async=z}render(p){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(p)}}F.kind="func";class V extends f{render(p){return"return "+super.render(p)}}V.kind="return";class ue extends h{render(p){let $="try"+super.render(p);return this.catch&&($+=this.catch.render(p)),this.finally&&($+=this.finally.render(p)),$}optimizeNodes(){var p,$;return super.optimizeNodes(),(p=this.catch)===null||p===void 0||p.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(p,$){var z,G;return super.optimizeNames(p,$),(z=this.catch)===null||z===void 0||z.optimizeNames(p,$),(G=this.finally)===null||G===void 0||G.optimizeNames(p,$),this}get names(){const p=super.names;return this.catch&&X(p,this.catch.names),this.finally&&X(p,this.finally.names),p}}class me extends h{constructor(p){super(),this.error=p}render(p){return`catch(${this.error})`+super.render(p)}}me.kind="catch";class _e extends h{render(p){return"finally"+super.render(p)}}_e.kind="finally";class L{constructor(p,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
70
|
+
]`;continue}n+=i[c],i[c]==="\\"?o=!0:a&&i[c]==="]"?a=!1:!a&&i[c]==="["&&(a=!0)}try{new RegExp(n)}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 n}function Lh(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===ne.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((i,n)=>({...i,[n]:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ke(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===ne.ZodString&&e.keyType._def.checks?.length){const{type:i,...n}=Zh(e.keyType._def,t);return{...r,propertyNames:n}}else{if(e.keyType?._def.typeName===ne.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===ne.ZodBranded&&e.keyType._def.type._def.typeName===ne.ZodString&&e.keyType._def.type._def.checks?.length){const{type:i,...n}=Dh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function yw(e,t){if(t.mapStrategy==="record")return Lh(e,t);const r=ge(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(t),i=ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,i],minItems:2,maxItems:2}}}function _w(e){const t=e.values,i=Object.keys(e.values).filter(o=>typeof t[t[o]]!="number").map(o=>t[o]),n=Array.from(new Set(i.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:i}}function $w(e){return e.target==="openAi"?void 0:{not:Ke({...e,currentPath:[...e.currentPath,"not"]})}}function bw(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Vi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Sw(e,t){if(t.target==="openApi3")return Fh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in Vi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=Vi[o._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:i.length>1?i:i[0]}}else if(r.every(i=>i._def.typeName==="ZodLiteral"&&!i.description)){const i=r.reduce((n,o)=>{const a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(i.length===r.length){const n=i.filter((o,a,s)=>s.indexOf(o)===a);return{type:n.length>1?n:n[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(i=>i._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((i,n)=>[...i,...n._def.values.filter(o=>!i.includes(o))],[])};return Fh(e,t)}const Fh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((i,n)=>ge(i._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(i=>!!i&&(!t.strictUnions||typeof i=="object"&&Object.keys(i).length>0));return r.length?{anyOf:r}:void 0};function ww(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:Vi[e.innerType._def.typeName],nullable:!0}:{type:[Vi[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const i=ge(e.innerType._def,{...t,currentPath:[...t.currentPath]});return i&&"$ref"in i?{allOf:[i],nullable:!0}:i&&{...i,nullable:!0}}const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function kw(e,t){const r={type:"number"};if(!e.checks)return r;for(const i of e.checks)switch(i.kind){case"int":r.type="integer",Uh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?be(r,"minimum",i.value,i.message,t):be(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),be(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?be(r,"maximum",i.value,i.message,t):be(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),be(r,"maximum",i.value,i.message,t));break;case"multipleOf":be(r,"multipleOf",i.value,i.message,t);break}return r}function Iw(e,t){const r=t.target==="openAi",i={type:"object",properties:{}},n=[],o=e.shape();for(const s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let u=Tw(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=ge(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(i.properties[s]=l,u||n.push(s))}n.length&&(i.required=n);const a=xw(e,t);return a!==void 0&&(i.additionalProperties=a),i}function xw(e,t){if(e.catchall._def.typeName!=="ZodNever")return ge(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 Tw(e){try{return e.isOptional()}catch{return!0}}const Pw=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return ge(e.innerType._def,t);const r=ge(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(t)},r]}:Ke(t)},zw=(e,t)=>{if(t.pipeStrategy==="input")return ge(e.in._def,t);if(t.pipeStrategy==="output")return ge(e.out._def,t);const r=ge(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),i=ge(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,i].filter(n=>n!==void 0)}};function Ew(e,t){return ge(e.type._def,t)}function Ow(e,t){const i={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&be(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&be(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function jw(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[]),additionalItems:ge(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,i)=>ge(r._def,{...t,currentPath:[...t.currentPath,"items",`${i}`]})).reduce((r,i)=>i===void 0?r:[...r,i],[])}}function Nw(e){return{not:Ke(e)}}function Rw(e){return Ke(e)}const Uw=(e,t)=>ge(e.innerType._def,t),Cw=(e,t,r)=>{switch(t){case ne.ZodString:return Zh(e,r);case ne.ZodNumber:return kw(e,r);case ne.ZodObject:return Iw(e,r);case ne.ZodBigInt:return aw(e,r);case ne.ZodBoolean:return sw();case ne.ZodDate:return Ah(e,r);case ne.ZodUndefined:return Nw(r);case ne.ZodNull:return bw(r);case ne.ZodArray:return ow(e,r);case ne.ZodUnion:case ne.ZodDiscriminatedUnion:return Sw(e,r);case ne.ZodIntersection:return pw(e,r);case ne.ZodTuple:return jw(e,r);case ne.ZodRecord:return Lh(e,r);case ne.ZodLiteral:return hw(e,r);case ne.ZodEnum:return fw(e);case ne.ZodNativeEnum:return _w(e);case ne.ZodNullable:return ww(e,r);case ne.ZodOptional:return Pw(e,r);case ne.ZodMap:return yw(e,r);case ne.ZodSet:return Ow(e,r);case ne.ZodLazy:return()=>e.getter()._def;case ne.ZodPromise:return Ew(e,r);case ne.ZodNaN:case ne.ZodNever:return $w(r);case ne.ZodEffects:return dw(e,r);case ne.ZodAny:return Ke(r);case ne.ZodUnknown:return Rw(r);case ne.ZodDefault:return lw(e,r);case ne.ZodBranded:return Dh(e,r);case ne.ZodReadonly:return Uw(e,r);case ne.ZodCatch:return cw(e,r);case ne.ZodPipeline:return zw(e,r);case ne.ZodFunction:case ne.ZodVoid:case ne.ZodSymbol:return;default:return(i=>{})()}};function ge(e,t,r=!1){const i=t.seen.get(e);if(t.override){const s=t.override?.(e,t,i,r);if(s!==nw)return s}if(i&&!r){const s=Dw(i,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const o=Cw(e,e.typeName,t),a=typeof o=="function"?ge(o(),t):o;if(a&&Aw(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const Dw=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ch(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,i)=>t.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ke(t)):t.$refStrategy==="seen"?Ke(t):void 0}},Aw=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Zw=(e,t)=>{const r=iw(t);let i=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:ge(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ke(r)}),{}):void 0;const n=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,o=ge(e._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Ke(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(i||(i={}),i[r.openAiAnyTypeName]||(i[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const s=n===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...i,[n]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.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 Mw(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Vh(e,t){return wt(e)?xa(e,{target:Mw(t?.target),io:t?.pipeStrategy??"input"}):Zw(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Gh(e){const r=ur(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=gh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function qh(e,t){const r=cr(e,t);if(!r.success)throw r.error;return r.data}const Lw=6e4;class Fw{constructor(t){this._options=t,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(xs,r=>{this._oncancel(r)}),this.setNotificationHandler(Ps,r=>{this._onprogress(r)}),this.setRequestHandler(Ts,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zs,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new H(Q.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Os,async(r,i)=>{const n=async()=>{const o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,i.sessionId);){if(s.type==="response"||s.type==="error"){const c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{const d=c,m=new H(d.error.code,d.error.message,d.error.data);l(m)}else{const d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:i.requestId})}}const a=await this._taskStore.getTask(o,i.sessionId);if(!a)throw new H(Q.InvalidParams,`Task not found: ${o}`);if(!Kt(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Kt(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Ht]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(js,async(r,i)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,i.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new H(Q.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Rs,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new H(Q.InvalidParams,`Task not found: ${r.params.taskId}`);if(Kt(n.status))throw new H(Q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",i.sessionId),this._clearTaskQueue(r.params.taskId);const o=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!o)throw new H(Q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof H?n:new H(Q.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,i,n,o=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:i,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const i=Date.now()-r.startTime;if(r.maxTotalTimeout&&i>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),H.fromError(Q.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:i});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const i=this.transport?.onerror;this._transport.onerror=o=>{i?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{n?.(o,a),Ci(o)||xb(o)?this._onresponse(o):bh(o)?this._onrequest(o,a):Ib(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const i of this._timeoutInfo.values())clearTimeout(i.timeoutId);this._timeoutInfo.clear();for(const i of this._requestHandlerAbortControllers.values())i.abort();this._requestHandlerAbortControllers.clear();const r=H.fromError(Q.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const i of t.values())i(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){const i=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,o=t.params?._meta?.[Ht]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:Q.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):n?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const s=kb(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,n?.sessionId):void 0,u={signal:a.signal,sessionId:n?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;const d={relatedRequestId:t.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new H(Q.ConnectionClosed,"Request was cancelled");const f={...m,relatedRequestId:t.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});const h=f.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>i(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)},async l=>{if(a.signal.aborted)return;const d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:Q.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},n?.sessionId):await n?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===a&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...i}=t.params,n=Number(r),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(c){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),a(c);return}o(i)}_onresponse(t){const r=Number(t.id),i=this._requestResolvers.get(r);if(i){if(this._requestResolvers.delete(r),Ci(t))i(t);else{const a=new H(t.error.code,t.error.message,t.error.data);i(a)}return}const n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Ci(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Ci(t))n(t);else{const a=H.fromError(t.error.code,t.error.message,t.error.data);n(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,i){const{task:n}=i??{};if(!n){try{yield{type:"result",result:await this.request(t,r,i)}}catch(a){yield{type:"error",error:a instanceof H?a:new H(Q.InternalError,String(a))}}return}let o;try{const a=await this.request(t,Di,i);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new H(Q.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Kt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new H(Q.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new H(Q.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),i?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof H?a:new H(Q.InternalError,String(a))}}}request(t,r,i){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=i??{};return new Promise((u,l)=>{const d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(v){d(v);return}i?.signal?.throwIfAborted();const m=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:m};i?.onprogress&&(this._progressHandlers.set(m,i.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:m}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Ht]:c}});const h=v=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));const w=v instanceof H?v:new H(Q.RequestTimeout,String(v));l(w)};this._responseHandlers.set(m,v=>{if(!i?.signal?.aborted){if(v instanceof Error)return l(v);try{const w=cr(r,v.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const b=i?.timeout??Lw,g=()=>h(H.fromError(Q.RequestTimeout,"Request timed out",{timeout:b}));this._setupTimeout(m,b,i?.maxTotalTimeout,g,i?.resetTimeoutOnProgress??!1);const y=c?.taskId;if(y){const v=w=>{const x=this._responseHandlers.get(m);x?x(w):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(m),l(w)})}else this._transport.send(f,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Es,r)}async getTaskResult(t,r,i){return this.request({method:"tasks/result",params:t},r,i)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Ns,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Vb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const i=r?.relatedTask?.taskId;if(i){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Ht]:r.relatedTask}}};await this._enqueueTaskMessage(i,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Ht]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Ht]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const i=Gh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=qh(t,n);return Promise.resolve(r(a,o))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const i=Gh(t);this._notificationHandlers.set(i,n=>{const o=qh(t,n);return Promise.resolve(r(o))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,i){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,i,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const i=await this._taskMessageQueue.dequeueAll(t,r);for(const n of i)if(n.type==="request"&&bh(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new H(Q.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let i=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(i=n.pollInterval)}catch{}return new Promise((n,o)=>{if(r.aborted){o(new H(Q.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new H(Q.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const i=this._taskStore;if(!i)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await i.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const o=await i.getTask(n,r);if(!o)throw new H(Q.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,a)=>{await i.storeTaskResult(n,o,a,r);const s=await i.getTask(n,r);if(s){const c=Ai.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Kt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>i.getTaskResult(n,r),updateTaskStatus:async(n,o,a)=>{const s=await i.getTask(n,r);if(!s)throw new H(Q.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Kt(s.status))throw new H(Q.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await i.updateTaskStatus(n,o,a,r);const c=await i.getTask(n,r);if(c){const u=Ai.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Kt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function Bh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vw(e,t){const r={...e};for(const i in t){const n=i,o=t[n];if(o===void 0)continue;const a=r[n];Bh(a)&&Bh(o)?r[n]={...a,...o}:r[n]=o}return r}function Jh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ys={exports:{}},Hh={},Pt={},Wt={},Qs={},se={},vr={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((w,x)=>`${w}${x}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((w,x)=>(x instanceof r&&(w[x.str]=(w[x.str]||0)+1),w),{})}}e._Code=i,e.nil=new i("");function n(y,...v){const w=[y[0]];let x=0;for(;x<v.length;)s(w,v[x]),w.push(y[++x]);return new i(w)}e._=n;const o=new i("+");function a(y,...v){const w=[f(y[0])];let x=0;for(;x<v.length;)w.push(o),s(w,v[x]),w.push(o,f(y[++x]));return c(w),new i(w)}e.str=a;function s(y,v){v instanceof i?y.push(...v._items):v instanceof r?y.push(v):y.push(d(v))}e.addCodeArg=s;function c(y){let v=1;for(;v<y.length-1;){if(y[v]===o){const w=u(y[v-1],y[v+1]);if(w!==void 0){y.splice(v-1,3,w);continue}y[v++]="+"}v++}}function u(y,v){if(v==='""')return y;if(y==='""')return v;if(typeof y=="string")return v instanceof r||y[y.length-1]!=='"'?void 0:typeof v!="string"?`${y.slice(0,-1)}${v}"`:v[0]==='"'?y.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(y instanceof r))return`"${y}${v.slice(1)}`}function l(y,v){return v.emptyStr()?y:y.emptyStr()?v:a`${y}${v}`}e.strConcat=l;function d(y){return typeof y=="number"||typeof y=="boolean"||y===null?y:f(Array.isArray(y)?y.join(","):y)}function m(y){return new i(f(y))}e.stringify=m;function f(y){return JSON.stringify(y).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=f;function h(y){return typeof y=="string"&&e.IDENTIFIER.test(y)?new i(`.${y}`):n`[${y}]`}e.getProperty=h;function b(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new i(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=b;function g(y){return new i(y.toString())}e.regexpCode=g})(vr);var ec={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=vr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var i;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(i||(e.UsedValueState=i={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class n{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}e.Scope=n;class o extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${d}]`}}e.ValueScopeName=o;const a=(0,t._)`\n`;class s extends n{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?a:t.nil}}get(){return this._scope}name(u){return new o(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const m=this.toName(u),{prefix:f}=m,h=(d=l.key)!==null&&d!==void 0?d:l.ref;let b=this._values[f];if(b){const v=b.get(h);if(v)return v}else b=this._values[f]=new Map;b.set(h,m);const g=this._scope[f]||(this._scope[f]=[]),y=g.length;return g[y]=l.ref,m.setValue(l,{property:f,itemIndex:y}),m}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,t._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,m=>{if(m.value===void 0)throw new Error(`CodeGen: name "${m}" has no value`);return m.value.code},l,d)}_reduceValues(u,l,d={},m){let f=t.nil;for(const h in u){const b=u[h];if(!b)continue;const g=d[h]=d[h]||new Map;b.forEach(y=>{if(g.has(y))return;g.set(y,i.Started);let v=l(y);if(v){const w=this.opts.es5?e.varKinds.var:e.varKinds.const;f=(0,t._)`${f}${w} ${y} = ${v};${this.opts._n}`}else if(v=m?.(y))f=(0,t._)`${f}${v}${this.opts._n}`;else throw new r(y);g.set(y,i.Completed)})}return f}}e.ValueScope=s})(ec),(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=vr,r=ec;var i=vr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return i._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return i.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return i.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return i.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return i.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return i.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return i.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return i.Name}});var n=ec;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class o{optimizeNodes(){return this}optimizeNames(p,$){return this}}class a extends o{constructor(p,$,z){super(),this.varKind=p,this.name=$,this.rhs=z}render({es5:p,_n:$}){const z=p?r.varKinds.var:this.varKind,G=this.rhs===void 0?"":` = ${this.rhs}`;return`${z} ${this.name}${G};`+$}optimizeNames(p,$){if(p[this.name.str])return this.rhs&&(this.rhs=B(this.rhs,p,$)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(p,$,z){super(),this.lhs=p,this.rhs=$,this.sideEffects=z}render({_n:p}){return`${this.lhs} = ${this.rhs};`+p}optimizeNames(p,$){if(!(this.lhs instanceof t.Name&&!p[this.lhs.str]&&!this.sideEffects))return this.rhs=B(this.rhs,p,$),this}get names(){const p=this.lhs instanceof t.Name?{}:{...this.lhs.names};return W(p,this.rhs)}}class c extends s{constructor(p,$,z,G){super(p,z,G),this.op=$}render({_n:p}){return`${this.lhs} ${this.op}= ${this.rhs};`+p}}class u extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`${this.label}:`+p}}class l extends o{constructor(p){super(),this.label=p,this.names={}}render({_n:p}){return`break${this.label?` ${this.label}`:""};`+p}}class d extends o{constructor(p){super(),this.error=p}render({_n:p}){return`throw ${this.error};`+p}get names(){return this.error.names}}class m extends o{constructor(p){super(),this.code=p}render({_n:p}){return`${this.code};`+p}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(p,$){return this.code=B(this.code,p,$),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class f extends o{constructor(p=[]){super(),this.nodes=p}render(p){return this.nodes.reduce(($,z)=>$+z.render(p),"")}optimizeNodes(){const{nodes:p}=this;let $=p.length;for(;$--;){const z=p[$].optimizeNodes();Array.isArray(z)?p.splice($,1,...z):z?p[$]=z:p.splice($,1)}return p.length>0?this:void 0}optimizeNames(p,$){const{nodes:z}=this;let G=z.length;for(;G--;){const K=z[G];K.optimizeNames(p,$)||(ze(p,K.names),z.splice(G,1))}return z.length>0?this:void 0}get names(){return this.nodes.reduce((p,$)=>X(p,$.names),{})}}class h extends f{render(p){return"{"+p._n+super.render(p)+"}"+p._n}}class b extends f{}class g extends h{}g.kind="else";class y extends h{constructor(p,$){super($),this.condition=p}render(p){let $=`if(${this.condition})`+super.render(p);return this.else&&($+="else "+this.else.render(p)),$}optimizeNodes(){super.optimizeNodes();const p=this.condition;if(p===!0)return this.nodes;let $=this.else;if($){const z=$.optimizeNodes();$=this.else=Array.isArray(z)?new g(z):z}if($)return p===!1?$ instanceof y?$:$.nodes:this.nodes.length?this:new y(it(p),$ instanceof y?[$]:$.nodes);if(!(p===!1||!this.nodes.length))return this}optimizeNames(p,$){var z;if(this.else=(z=this.else)===null||z===void 0?void 0:z.optimizeNames(p,$),!!(super.optimizeNames(p,$)||this.else))return this.condition=B(this.condition,p,$),this}get names(){const p=super.names;return W(p,this.condition),this.else&&X(p,this.else.names),p}}y.kind="if";class v extends h{}v.kind="for";class w extends v{constructor(p){super(),this.iteration=p}render(p){return`for(${this.iteration})`+super.render(p)}optimizeNames(p,$){if(super.optimizeNames(p,$))return this.iteration=B(this.iteration,p,$),this}get names(){return X(super.names,this.iteration.names)}}class x extends v{constructor(p,$,z,G){super(),this.varKind=p,this.name=$,this.from=z,this.to=G}render(p){const $=p.es5?r.varKinds.var:this.varKind,{name:z,from:G,to:K}=this;return`for(${$} ${z}=${G}; ${z}<${K}; ${z}++)`+super.render(p)}get names(){const p=W(super.names,this.from);return W(p,this.to)}}class E extends v{constructor(p,$,z,G){super(),this.loop=p,this.varKind=$,this.name=z,this.iterable=G}render(p){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(p)}optimizeNames(p,$){if(super.optimizeNames(p,$))return this.iterable=B(this.iterable,p,$),this}get names(){return X(super.names,this.iterable.names)}}class F extends h{constructor(p,$,z){super(),this.name=p,this.args=$,this.async=z}render(p){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(p)}}F.kind="func";class V extends f{render(p){return"return "+super.render(p)}}V.kind="return";class ue extends h{render(p){let $="try"+super.render(p);return this.catch&&($+=this.catch.render(p)),this.finally&&($+=this.finally.render(p)),$}optimizeNodes(){var p,$;return super.optimizeNodes(),(p=this.catch)===null||p===void 0||p.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(p,$){var z,G;return super.optimizeNames(p,$),(z=this.catch)===null||z===void 0||z.optimizeNames(p,$),(G=this.finally)===null||G===void 0||G.optimizeNames(p,$),this}get names(){const p=super.names;return this.catch&&X(p,this.catch.names),this.finally&&X(p,this.finally.names),p}}class me extends h{constructor(p){super(),this.error=p}render(p){return`catch(${this.error})`+super.render(p)}}me.kind="catch";class _e extends h{render(p){return"finally"+super.render(p)}}_e.kind="finally";class L{constructor(p,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
|
|
71
71
|
`:""},this._extScope=p,this._scope=new r.Scope({parent:p}),this._nodes=[new b]}toString(){return this._root.render(this.opts)}name(p){return this._scope.name(p)}scopeName(p){return this._extScope.name(p)}scopeValue(p,$){const z=this._extScope.value(p,$);return(this._values[z.prefix]||(this._values[z.prefix]=new Set)).add(z),z}getScopeValue(p,$){return this._extScope.getValue(p,$)}scopeRefs(p){return this._extScope.scopeRefs(p,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(p,$,z,G){const K=this._scope.toName($);return z!==void 0&&G&&(this._constants[K.str]=z),this._leafNode(new a(p,K,z)),K}const(p,$,z){return this._def(r.varKinds.const,p,$,z)}let(p,$,z){return this._def(r.varKinds.let,p,$,z)}var(p,$,z){return this._def(r.varKinds.var,p,$,z)}assign(p,$,z){return this._leafNode(new s(p,$,z))}add(p,$){return this._leafNode(new c(p,e.operators.ADD,$))}code(p){return typeof p=="function"?p():p!==t.nil&&this._leafNode(new m(p)),this}object(...p){const $=["{"];for(const[z,G]of p)$.length>1&&$.push(","),$.push(z),(z!==G||this.opts.es5)&&($.push(":"),(0,t.addCodeArg)($,G));return $.push("}"),new t._Code($)}if(p,$,z){if(this._blockNode(new y(p)),$&&z)this.code($).else().code(z).endIf();else if($)this.code($).endIf();else if(z)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(p){return this._elseNode(new y(p))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(p,$){return this._blockNode(p),$&&this.code($).endFor(),this}for(p,$){return this._for(new w(p),$)}forRange(p,$,z,G,K=this.opts.es5?r.varKinds.var:r.varKinds.let){const pe=this._scope.toName(p);return this._for(new x(K,pe,$,z),()=>G(pe))}forOf(p,$,z,G=r.varKinds.const){const K=this._scope.toName(p);if(this.opts.es5){const pe=$ instanceof t.Name?$:this.var("_arr",$);return this.forRange("_i",0,(0,t._)`${pe}.length`,fe=>{this.var(K,(0,t._)`${pe}[${fe}]`),z(K)})}return this._for(new E("of",G,K,$),()=>z(K))}forIn(p,$,z,G=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(p,(0,t._)`Object.keys(${$})`,z);const K=this._scope.toName(p);return this._for(new E("in",G,K,$),()=>z(K))}endFor(){return this._endBlockNode(v)}label(p){return this._leafNode(new u(p))}break(p){return this._leafNode(new l(p))}return(p){const $=new V;if(this._blockNode($),this.code(p),$.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(V)}try(p,$,z){if(!$&&!z)throw new Error('CodeGen: "try" without "catch" and "finally"');const G=new ue;if(this._blockNode(G),this.code(p),$){const K=this.name("e");this._currNode=G.catch=new me(K),$(K)}return z&&(this._currNode=G.finally=new _e,this.code(z)),this._endBlockNode(me,_e)}throw(p){return this._leafNode(new d(p))}block(p,$){return this._blockStarts.push(this._nodes.length),p&&this.code(p).endBlock($),this}endBlock(p){const $=this._blockStarts.pop();if($===void 0)throw new Error("CodeGen: not in self-balancing block");const z=this._nodes.length-$;if(z<0||p!==void 0&&z!==p)throw new Error(`CodeGen: wrong number of nodes: ${z} vs ${p} expected`);return this._nodes.length=$,this}func(p,$=t.nil,z,G){return this._blockNode(new F(p,$,z)),G&&this.code(G).endFunc(),this}endFunc(){return this._endBlockNode(F)}optimize(p=1){for(;p-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(p){return this._currNode.nodes.push(p),this}_blockNode(p){this._currNode.nodes.push(p),this._nodes.push(p)}_endBlockNode(p,$){const z=this._currNode;if(z instanceof p||$&&z instanceof $)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${$?`${p.kind}/${$.kind}`:p.kind}"`)}_elseNode(p){const $=this._currNode;if(!($ instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=$.else=p,this}get _root(){return this._nodes[0]}get _currNode(){const p=this._nodes;return p[p.length-1]}set _currNode(p){const $=this._nodes;$[$.length-1]=p}}e.CodeGen=L;function X(P,p){for(const $ in p)P[$]=(P[$]||0)+(p[$]||0);return P}function W(P,p){return p instanceof t._CodeOrName?X(P,p.names):P}function B(P,p,$){if(P instanceof t.Name)return z(P);if(!G(P))return P;return new t._Code(P._items.reduce((K,pe)=>(pe instanceof t.Name&&(pe=z(pe)),pe instanceof t._Code?K.push(...pe._items):K.push(pe),K),[]));function z(K){const pe=$[K.str];return pe===void 0||p[K.str]!==1?K:(delete p[K.str],pe)}function G(K){return K instanceof t._Code&&K._items.some(pe=>pe instanceof t.Name&&p[pe.str]===1&&$[pe.str]!==void 0)}}function ze(P,p){for(const $ in p)P[$]=(P[$]||0)-(p[$]||0)}function it(P){return typeof P=="boolean"||typeof P=="number"||P===null?!P:(0,t._)`!${N(P)}`}e.not=it;const ot=I(e.operators.AND);function Lt(...P){return P.reduce(ot)}e.and=Lt;const It=I(e.operators.OR);function C(...P){return P.reduce(It)}e.or=C;function I(P){return(p,$)=>p===t.nil?$:$===t.nil?p:(0,t._)`${N(p)} ${P} ${N($)}`}function N(P){return P instanceof t.Name?P:(0,t._)`(${P})`}})(se);var M={};Object.defineProperty(M,"__esModule",{value:!0}),M.checkStrictMode=M.getErrorPath=M.Type=M.useFunc=M.setEvaluated=M.evaluatedPropsToName=M.mergeEvaluated=M.eachItem=M.unescapeJsonPointer=M.escapeJsonPointer=M.escapeFragment=M.unescapeFragment=M.schemaRefOrVal=M.schemaHasRulesButRef=M.schemaHasRules=M.checkUnknownRules=M.alwaysValidSchema=M.toHash=void 0;const xe=se,Gw=vr;function qw(e){const t={};for(const r of e)t[r]=!0;return t}M.toHash=qw;function Bw(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Kh(e,t),!Wh(t,e.self.RULES.all))}M.alwaysValidSchema=Bw;function Kh(e,t=e.schema){const{opts:r,self:i}=e;if(!r.strictSchema||typeof t=="boolean")return;const n=i.RULES.keywords;for(const o in t)n[o]||tg(e,`unknown keyword: "${o}"`)}M.checkUnknownRules=Kh;function Wh(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(t[r])return!0;return!1}M.schemaHasRules=Wh;function Jw(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}M.schemaHasRulesButRef=Jw;function Hw({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,xe._)`${r}`}return(0,xe._)`${e}${t}${(0,xe.getProperty)(i)}`}M.schemaRefOrVal=Hw;function Kw(e){return Xh(decodeURIComponent(e))}M.unescapeFragment=Kw;function Ww(e){return encodeURIComponent(tc(e))}M.escapeFragment=Ww;function tc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}M.escapeJsonPointer=tc;function Xh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}M.unescapeJsonPointer=Xh;function Xw(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}M.eachItem=Xw;function Yh({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,o,a,s)=>{const c=a===void 0?o:a instanceof xe.Name?(o instanceof xe.Name?e(n,o,a):t(n,o,a),a):o instanceof xe.Name?(t(n,a,o),o):r(o,a);return s===xe.Name&&!(c instanceof xe.Name)?i(n,c):c}}M.mergeEvaluated={props:Yh({mergeNames:(e,t,r)=>e.if((0,xe._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,xe._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,xe._)`${r} || {}`).code((0,xe._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,xe._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,xe._)`${r} || {}`),nc(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Qh}),items:Yh({mergeNames:(e,t,r)=>e.if((0,xe._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,xe._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,xe._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,xe._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Qh(e,t){if(t===!0)return e.var("props",!0);const r=e.var("props",(0,xe._)`{}`);return t!==void 0&&nc(e,r,t),r}M.evaluatedPropsToName=Qh;function nc(e,t,r){Object.keys(r).forEach(i=>e.assign((0,xe._)`${t}${(0,xe.getProperty)(i)}`,!0))}M.setEvaluated=nc;const eg={};function Yw(e,t){return e.scopeValue("func",{ref:t,code:eg[t.code]||(eg[t.code]=new Gw._Code(t.code))})}M.useFunc=Yw;var rc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(rc||(M.Type=rc={}));function Qw(e,t,r){if(e instanceof xe.Name){const i=t===rc.Num;return r?i?(0,xe._)`"[" + ${e} + "]"`:(0,xe._)`"['" + ${e} + "']"`:i?(0,xe._)`"/" + ${e}`:(0,xe._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,xe.getProperty)(e).toString():"/"+tc(e)}M.getErrorPath=Qw;function tg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}M.checkStrictMode=tg;var Gi={},ng;function Ut(){if(ng)return Gi;ng=1,Object.defineProperty(Gi,"__esModule",{value:!0});const e=se,t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Gi.default=t,Gi}var rg;function qi(){return rg||(rg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=se,r=M,i=Ut();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:y})=>y?(0,t.str)`"${g}" keyword must be ${y} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function n(g,y=e.keywordError,v,w){const{it:x}=g,{gen:E,compositeRule:F,allErrors:V}=x,ue=d(g,y,v);w??(F||V)?c(E,ue):u(x,(0,t._)`[${ue}]`)}e.reportError=n;function o(g,y=e.keywordError,v){const{it:w}=g,{gen:x,compositeRule:E,allErrors:F}=w,V=d(g,y,v);c(x,V),E||F||u(w,i.default.vErrors)}e.reportExtraError=o;function a(g,y){g.assign(i.default.errors,y),g.if((0,t._)`${i.default.vErrors} !== null`,()=>g.if(y,()=>g.assign((0,t._)`${i.default.vErrors}.length`,y),()=>g.assign(i.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:g,keyword:y,schemaValue:v,data:w,errsCount:x,it:E}){if(x===void 0)throw new Error("ajv implementation error");const F=g.name("err");g.forRange("i",x,i.default.errors,V=>{g.const(F,(0,t._)`${i.default.vErrors}[${V}]`),g.if((0,t._)`${F}.instancePath === undefined`,()=>g.assign((0,t._)`${F}.instancePath`,(0,t.strConcat)(i.default.instancePath,E.errorPath))),g.assign((0,t._)`${F}.schemaPath`,(0,t.str)`${E.errSchemaPath}/${y}`),E.opts.verbose&&(g.assign((0,t._)`${F}.schema`,v),g.assign((0,t._)`${F}.data`,w))})}e.extendErrors=s;function c(g,y){const v=g.const("err",y);g.if((0,t._)`${i.default.vErrors} === null`,()=>g.assign(i.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${i.default.vErrors}.push(${v})`),g.code((0,t._)`${i.default.errors}++`)}function u(g,y){const{gen:v,validateName:w,schemaEnv:x}=g;x.$async?v.throw((0,t._)`new ${g.ValidationError}(${y})`):(v.assign((0,t._)`${w}.errors`,y),v.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function d(g,y,v){const{createErrors:w}=g.it;return w===!1?(0,t._)`{}`:m(g,y,v)}function m(g,y,v={}){const{gen:w,it:x}=g,E=[f(x,v),h(g,v)];return b(g,y,E),w.object(...E)}function f({errorPath:g},{instancePath:y}){const v=y?(0,t.str)`${g}${(0,r.getErrorPath)(y,r.Type.Str)}`:g;return[i.default.instancePath,(0,t.strConcat)(i.default.instancePath,v)]}function h({keyword:g,it:{errSchemaPath:y}},{schemaPath:v,parentSchema:w}){let x=w?y:(0,t.str)`${y}/${g}`;return v&&(x=(0,t.str)`${x}${(0,r.getErrorPath)(v,r.Type.Str)}`),[l.schemaPath,x]}function b(g,{params:y,message:v},w){const{keyword:x,data:E,schemaValue:F,it:V}=g,{opts:ue,propertyName:me,topSchemaRef:_e,schemaPath:L}=V;w.push([l.keyword,x],[l.params,typeof y=="function"?y(g):y||(0,t._)`{}`]),ue.messages&&w.push([l.message,typeof v=="function"?v(g):v]),ue.verbose&&w.push([l.schema,F],[l.parentSchema,(0,t._)`${_e}${L}`],[i.default.data,E]),me&&w.push([l.propertyName,me])}})(Qs)),Qs}var ig;function ek(){if(ig)return Wt;ig=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.boolOrEmptySchema=Wt.topBoolOrEmptySchema=void 0;const e=qi(),t=se,r=Ut(),i={message:"boolean schema is false"};function n(s){const{gen:c,schema:u,validateName:l}=s;u===!1?a(s,!1):typeof u=="object"&&u.$async===!0?c.return(r.default.data):(c.assign((0,t._)`${l}.errors`,null),c.return(!0))}Wt.topBoolOrEmptySchema=n;function o(s,c){const{gen:u,schema:l}=s;l===!1?(u.var(c,!1),a(s)):u.var(c,!0)}Wt.boolOrEmptySchema=o;function a(s,c){const{gen:u,data:l}=s,d={gen:u,keyword:"false schema",data:l,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:s};(0,e.reportError)(d,i,void 0,c)}return Wt}var je={},Xt={};Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.getRules=Xt.isJSONType=void 0;const tk=["string","number","integer","boolean","null","object","array"],nk=new Set(tk);function rk(e){return typeof e=="string"&&nk.has(e)}Xt.isJSONType=rk;function ik(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Xt.getRules=ik;var zt={},og;function ag(){if(og)return zt;og=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.shouldUseRule=zt.shouldUseGroup=zt.schemaHasRulesForType=void 0;function e({schema:i,self:n},o){const a=n.RULES.types[o];return a&&a!==!0&&t(i,a)}zt.schemaHasRulesForType=e;function t(i,n){return n.rules.some(o=>r(i,o))}zt.shouldUseGroup=t;function r(i,n){var o;return i[n.keyword]!==void 0||((o=n.definition.implements)===null||o===void 0?void 0:o.some(a=>i[a]!==void 0))}return zt.shouldUseRule=r,zt}Object.defineProperty(je,"__esModule",{value:!0}),je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;const ok=Xt,ak=ag(),sk=qi(),oe=se,sg=M;var $n;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})($n||(je.DataType=$n={}));function ck(e){const t=cg(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}je.getSchemaTypes=ck;function cg(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(ok.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}je.getJSONTypes=cg;function uk(e,t){const{gen:r,data:i,opts:n}=e,o=lk(t,n.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,ak.schemaHasRulesForType)(e,t[0]));if(a){const s=oc(t,i,n.strictNumbers,$n.Wrong);r.if(s,()=>{o.length?dk(e,t,o):ac(e)})}return a}je.coerceAndCheckDataType=uk;const ug=new Set(["string","number","integer","boolean","null"]);function lk(e,t){return t?e.filter(r=>ug.has(r)||t==="array"&&r==="array"):[]}function dk(e,t,r){const{gen:i,data:n,opts:o}=e,a=i.let("dataType",(0,oe._)`typeof ${n}`),s=i.let("coerced",(0,oe._)`undefined`);o.coerceTypes==="array"&&i.if((0,oe._)`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,(0,oe._)`${n}[0]`).assign(a,(0,oe._)`typeof ${n}`).if(oc(t,n,o.strictNumbers),()=>i.assign(s,n))),i.if((0,oe._)`${s} !== undefined`);for(const u of r)(ug.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);i.else(),ac(e),i.endIf(),i.if((0,oe._)`${s} !== undefined`,()=>{i.assign(n,s),fk(e,s)});function c(u){switch(u){case"string":i.elseIf((0,oe._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,oe._)`"" + ${n}`).elseIf((0,oe._)`${n} === null`).assign(s,(0,oe._)`""`);return;case"number":i.elseIf((0,oe._)`${a} == "boolean" || ${n} === null
|
|
72
72
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(s,(0,oe._)`+${n}`);return;case"integer":i.elseIf((0,oe._)`${a} === "boolean" || ${n} === null
|
|
73
73
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(s,(0,oe._)`+${n}`);return;case"boolean":i.elseIf((0,oe._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(s,!1).elseIf((0,oe._)`${n} === "true" || ${n} === 1`).assign(s,!0);return;case"null":i.elseIf((0,oe._)`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(s,null);return;case"array":i.elseIf((0,oe._)`${a} === "string" || ${a} === "number"
|