@babylonjs/mcp-servers 9.12.0 → 9.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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
package/dist/npe-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 Hh(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}=qh(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}=Fh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function Sk(e,t){if(t.mapStrategy==="record")return Hh(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 kk(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 wk(e){return e.target==="openAi"?void 0:{not:Xe({...e,currentPath:[...e.currentPath,"not"]})}}function Ik(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const qi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Pk(e,t){if(t.target==="openApi3")return Kh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in qi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=qi[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 Kh(e,t)}const Kh=(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 xk(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:qi[e.innerType._def.typeName],nullable:!0}:{type:[qi[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 Tk(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",Bh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?_e(r,"minimum",i.value,i.message,t):_e(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),_e(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?_e(r,"maximum",i.value,i.message,t):_e(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),_e(r,"maximum",i.value,i.message,t));break;case"multipleOf":_e(r,"multipleOf",i.value,i.message,t);break}return r}function Ok(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=Ek(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=zk(e,t);return a!==void 0&&(i.additionalProperties=a),i}function zk(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 Ek(e){try{return e.isOptional()}catch{return!0}}const Nk=(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)},jk=(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 Dk(e,t){return ge(e.type._def,t)}function Ck(e,t){const i={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&_e(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&_e(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function Ak(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 Uk(e){return{not:Xe(e)}}function Rk(e){return Xe(e)}const Zk=(e,t)=>ge(e.innerType._def,t),Mk=(e,t,r)=>{switch(t){case te.ZodString:return qh(e,r);case te.ZodNumber:return Tk(e,r);case te.ZodObject:return Ok(e,r);case te.ZodBigInt:return lk(e,r);case te.ZodBoolean:return dk();case te.ZodDate:return Vh(e,r);case te.ZodUndefined:return Uk(r);case te.ZodNull:return Ik(r);case te.ZodArray:return uk(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return Pk(e,r);case te.ZodIntersection:return yk(e,r);case te.ZodTuple:return Ak(e,r);case te.ZodRecord:return Hh(e,r);case te.ZodLiteral:return _k(e,r);case te.ZodEnum:return gk(e);case te.ZodNativeEnum:return kk(e);case te.ZodNullable:return xk(e,r);case te.ZodOptional:return Nk(e,r);case te.ZodMap:return Sk(e,r);case te.ZodSet:return Ck(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return Dk(e,r);case te.ZodNaN:case te.ZodNever:return wk(r);case te.ZodEffects:return hk(e,r);case te.ZodAny:return Xe(r);case te.ZodUnknown:return Rk(r);case te.ZodDefault:return fk(e,r);case te.ZodBranded:return Fh(e,r);case te.ZodReadonly:return Zk(e,r);case te.ZodCatch:return pk(e,r);case te.ZodPipeline:return jk(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!==ak)return s}if(i&&!r){const s=Bk(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=Mk(e,e.typeName,t),a=typeof o=="function"?ge(o(),t):o;if(a&&Lk(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const Bk=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Lh(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}},Lk=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Fk=(e,t)=>{const r=ck(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 Vk(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)?Na(e,{target:Vk(t?.target),io:t?.pipeStrategy??"input"}):Fk(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Wh(e){const r=dr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=Sh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Yh(e,t){const r=lr(e,t);if(!r.success)throw r.error;return r.data}const qk=6e4;class Jk{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(Ns,r=>{this._oncancel(r)}),this.setNotificationHandler(Ds,r=>{this._onprogress(r)}),this.setRequestHandler(js,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Cs,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new J(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Us,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 J(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 J(W.InvalidParams,`Task not found: ${o}`);if(!Gt(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Gt(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Kt]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Rs,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 J(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Ms,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new J(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Gt(n.status))throw new J(W.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 J(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof J?n:new J(W.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),J.fromError(W.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),Ri(o)||zb(o)?this._onresponse(o):xh(o)?this._onrequest(o,a):Ob(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=J.fromError(W.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?.[Kt]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.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=Tb(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 J(W.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:W.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),Ri(t))i(t);else{const a=new J(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(Ri(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),Ri(t))n(t);else{const a=J.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 J?a:new J(W.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 J(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Gt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new J(W.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new J(W.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 J?a:new J(W.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=y=>{l(y)};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(y){d(y);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||{},[Kt]:c}});const h=y=>{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(y)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const b=y instanceof J?y:new J(W.RequestTimeout,String(y));l(b)};this._responseHandlers.set(m,y=>{if(!i?.signal?.aborted){if(y instanceof Error)return l(y);try{const b=lr(r,y.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const $=i?.timeout??qk,g=()=>h(J.fromError(W.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,i?.maxTotalTimeout,g,i?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const y=b=>{const I=this._responseHandlers.get(m);I?I(b):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,y),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(m),l(b)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(y=>{this._cleanupTimeout(m),l(y)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},As,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},Zs,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Hb,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||{},[Kt]: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||{},[Kt]: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||{},[Kt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const i=Wh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=Yh(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=Wh(t);this._notificationHandlers.set(i,n=>{const o=Yh(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"&&xh(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new J(W.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 J(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new J(W.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 J(W.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=Mi.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Gt(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 J(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Gt(s.status))throw new J(W.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=Mi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Gt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function Xh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Hk(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];Xh(a)&&Xh(o)?r[n]={...a,...o}:r[n]=o}return r}function Qh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ic={exports:{}},eg={},Ot={},Wt={},oc={},se={},_r={};(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(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,I)=>`${b}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,I)=>(I instanceof r&&(b[I.str]=(b[I.str]||0)+1),b),{})}}e._Code=i,e.nil=new i("");function n(v,...y){const b=[v[0]];let I=0;for(;I<y.length;)s(b,y[I]),b.push(v[++I]);return new i(b)}e._=n;const o=new i("+");function a(v,...y){const b=[p(v[0])];let I=0;for(;I<y.length;)b.push(o),s(b,y[I]),b.push(o,p(v[++I]));return c(b),new i(b)}e.str=a;function s(v,y){y instanceof i?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}e.addCodeArg=s;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===o){const b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:a`${v}${y}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:p(Array.isArray(v)?v.join(","):v)}function m(v){return new i(p(v))}e.stringify=m;function p(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=p;function h(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new i(`.${v}`):n`[${v}]`}e.getProperty=h;function $(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new i(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=$;function g(v){return new i(v.toString())}e.regexpCode=g})(_r);var ac={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=_r;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 y=$.get(h);if(y)return y}else $=this._values[p]=new Map;$.set(h,m);const g=this._scope[p]||(this._scope[p]=[]),v=g.length;return g[v]=l.ref,m.setValue(l,{property:p,itemIndex:v}),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 g=d[h]=d[h]||new Map;$.forEach(v=>{if(g.has(v))return;g.set(v,i.Started);let y=l(v);if(y){const b=this.opts.es5?e.varKinds.var:e.varKinds.const;p=(0,t._)`${p}${b} ${v} = ${y};${this.opts._n}`}else if(y=m?.(v))p=(0,t._)`${p}${y}${this.opts._n}`;else throw new r(v);g.set(v,i.Completed)})}return p}}e.ValueScope=s})(ac),(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=_r,r=ac;var i=_r;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=ac;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,_){return this}}class a extends o{constructor(f,_,z){super(),this.varKind=f,this.name=_,this.rhs=z}render({es5:f,_n:_}){const z=f?r.varKinds.var:this.varKind,L=this.rhs===void 0?"":` = ${this.rhs}`;return`${z} ${this.name}${L};`+_}optimizeNames(f,_){if(f[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,f,_)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(f,_,z){super(),this.lhs=f,this.rhs=_,this.sideEffects=z}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,_){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,f,_),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return Y(f,this.rhs)}}class c extends s{constructor(f,_,z,L){super(f,z,L),this.op=_}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,_){return this.code=K(this.code,f,_),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((_,z)=>_+z.render(f),"")}optimizeNodes(){const{nodes:f}=this;let _=f.length;for(;_--;){const z=f[_].optimizeNodes();Array.isArray(z)?f.splice(_,1,...z):z?f[_]=z:f.splice(_,1)}return f.length>0?this:void 0}optimizeNames(f,_){const{nodes:z}=this;let L=z.length;for(;L--;){const H=z[L];H.optimizeNames(f,_)||(ze(f,H.names),z.splice(L,1))}return z.length>0?this:void 0}get names(){return this.nodes.reduce((f,_)=>Q(f,_.names),{})}}class h extends p{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends p{}class g extends h{}g.kind="else";class v extends h{constructor(f,_){super(_),this.condition=f}render(f){let _=`if(${this.condition})`+super.render(f);return this.else&&(_+="else "+this.else.render(f)),_}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let _=this.else;if(_){const z=_.optimizeNodes();_=this.else=Array.isArray(z)?new g(z):z}if(_)return f===!1?_ instanceof v?_:_.nodes:this.nodes.length?this:new v(at(f),_ instanceof v?[_]:_.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,_){var z;if(this.else=(z=this.else)===null||z===void 0?void 0:z.optimizeNames(f,_),!!(super.optimizeNames(f,_)||this.else))return this.condition=K(this.condition,f,_),this}get names(){const f=super.names;return Y(f,this.condition),this.else&&Q(f,this.else.names),f}}v.kind="if";class y extends h{}y.kind="for";class b extends y{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iteration=K(this.iteration,f,_),this}get names(){return Q(super.names,this.iteration.names)}}class I extends y{constructor(f,_,z,L){super(),this.varKind=f,this.name=_,this.from=z,this.to=L}render(f){const _=f.es5?r.varKinds.var:this.varKind,{name:z,from:L,to:H}=this;return`for(${_} ${z}=${L}; ${z}<${H}; ${z}++)`+super.render(f)}get names(){const f=Y(super.names,this.from);return Y(f,this.to)}}class O extends y{constructor(f,_,z,L){super(),this.loop=f,this.varKind=_,this.name=z,this.iterable=L}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iterable=K(this.iterable,f,_),this}get names(){return Q(super.names,this.iterable.names)}}class M extends h{constructor(f,_,z){super(),this.name=f,this.args=_,this.async=z}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}M.kind="func";class V extends p{render(f){return"return "+super.render(f)}}V.kind="return";class le extends h{render(f){let _="try"+super.render(f);return this.catch&&(_+=this.catch.render(f)),this.finally&&(_+=this.finally.render(f)),_}optimizeNodes(){var f,_;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(_=this.finally)===null||_===void 0||_.optimizeNodes(),this}optimizeNames(f,_){var z,L;return super.optimizeNames(f,_),(z=this.catch)===null||z===void 0||z.optimizeNames(f,_),(L=this.finally)===null||L===void 0||L.optimizeNames(f,_),this}get names(){const f=super.names;return this.catch&&Q(f,this.catch.names),this.finally&&Q(f,this.finally.names),f}}class me extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}me.kind="catch";class Oe extends h{render(f){return"finally"+super.render(f)}}Oe.kind="finally";class B{constructor(f,_={}){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 Hh(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}=qh(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}=Fh(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function Sk(e,t){if(t.mapStrategy==="record")return Hh(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 kk(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 wk(e){return e.target==="openAi"?void 0:{not:Xe({...e,currentPath:[...e.currentPath,"not"]})}}function Ik(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const qi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Pk(e,t){if(t.target==="openApi3")return Kh(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(i=>i._def.typeName in qi&&(!i._def.checks||!i._def.checks.length))){const i=r.reduce((n,o)=>{const a=qi[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 Kh(e,t)}const Kh=(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 xk(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:qi[e.innerType._def.typeName],nullable:!0}:{type:[qi[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 Tk(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",Bh(r,"type",i.message,t);break;case"min":t.target==="jsonSchema7"?i.inclusive?_e(r,"minimum",i.value,i.message,t):_e(r,"exclusiveMinimum",i.value,i.message,t):(i.inclusive||(r.exclusiveMinimum=!0),_e(r,"minimum",i.value,i.message,t));break;case"max":t.target==="jsonSchema7"?i.inclusive?_e(r,"maximum",i.value,i.message,t):_e(r,"exclusiveMaximum",i.value,i.message,t):(i.inclusive||(r.exclusiveMaximum=!0),_e(r,"maximum",i.value,i.message,t));break;case"multipleOf":_e(r,"multipleOf",i.value,i.message,t);break}return r}function Ok(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=Ek(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=zk(e,t);return a!==void 0&&(i.additionalProperties=a),i}function zk(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 Ek(e){try{return e.isOptional()}catch{return!0}}const Nk=(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)},jk=(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 Dk(e,t){return ge(e.type._def,t)}function Ck(e,t){const i={type:"array",uniqueItems:!0,items:ge(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&_e(i,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&_e(i,"maxItems",e.maxSize.value,e.maxSize.message,t),i}function Ak(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 Uk(e){return{not:Xe(e)}}function Rk(e){return Xe(e)}const Zk=(e,t)=>ge(e.innerType._def,t),Mk=(e,t,r)=>{switch(t){case te.ZodString:return qh(e,r);case te.ZodNumber:return Tk(e,r);case te.ZodObject:return Ok(e,r);case te.ZodBigInt:return lk(e,r);case te.ZodBoolean:return dk();case te.ZodDate:return Vh(e,r);case te.ZodUndefined:return Uk(r);case te.ZodNull:return Ik(r);case te.ZodArray:return uk(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return Pk(e,r);case te.ZodIntersection:return yk(e,r);case te.ZodTuple:return Ak(e,r);case te.ZodRecord:return Hh(e,r);case te.ZodLiteral:return _k(e,r);case te.ZodEnum:return gk(e);case te.ZodNativeEnum:return kk(e);case te.ZodNullable:return xk(e,r);case te.ZodOptional:return Nk(e,r);case te.ZodMap:return Sk(e,r);case te.ZodSet:return Ck(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return Dk(e,r);case te.ZodNaN:case te.ZodNever:return wk(r);case te.ZodEffects:return hk(e,r);case te.ZodAny:return Xe(r);case te.ZodUnknown:return Rk(r);case te.ZodDefault:return fk(e,r);case te.ZodBranded:return Fh(e,r);case te.ZodReadonly:return Zk(e,r);case te.ZodCatch:return pk(e,r);case te.ZodPipeline:return jk(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!==ak)return s}if(i&&!r){const s=Bk(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=Mk(e,e.typeName,t),a=typeof o=="function"?ge(o(),t):o;if(a&&Lk(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const Bk=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Lh(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}},Lk=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),Fk=(e,t)=>{const r=ck(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 Vk(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)?Na(e,{target:Vk(t?.target),io:t?.pipeStrategy??"input"}):Fk(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Wh(e){const r=dr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const i=Sh(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");return i}function Yh(e,t){const r=lr(e,t);if(!r.success)throw r.error;return r.data}const qk=6e4;class Jk{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(Ns,r=>{this._oncancel(r)}),this.setNotificationHandler(Ds,r=>{this._onprogress(r)}),this.setRequestHandler(js,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Cs,async(r,i)=>{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new J(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Us,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 J(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 J(W.InvalidParams,`Task not found: ${o}`);if(!Gt(a.status))return await this._waitForTaskUpdate(o,i.signal),await n();if(Gt(a.status)){const s=await this._taskStore.getTaskResult(o,i.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[Kt]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Rs,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 J(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Ms,async(r,i)=>{try{const n=await this._taskStore.getTask(r.params.taskId,i.sessionId);if(!n)throw new J(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Gt(n.status))throw new J(W.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 J(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof J?n:new J(W.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),J.fromError(W.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),Ri(o)||zb(o)?this._onresponse(o):xh(o)?this._onrequest(o,a):Ob(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=J.fromError(W.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?.[Kt]?.taskId;if(i===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.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=Tb(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 J(W.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:W.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),Ri(t))i(t);else{const a=new J(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(Ri(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),Ri(t))n(t);else{const a=J.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 J?a:new J(W.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 J(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:o},i);if(yield{type:"taskStatus",task:s},Gt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,i)}:s.status==="failed"?yield{type:"error",error:new J(W.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new J(W.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 J?a:new J(W.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=y=>{l(y)};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(y){d(y);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||{},[Kt]:c}});const h=y=>{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(y)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`)));const b=y instanceof J?y:new J(W.RequestTimeout,String(y));l(b)};this._responseHandlers.set(m,y=>{if(!i?.signal?.aborted){if(y instanceof Error)return l(y);try{const b=lr(r,y.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),i?.signal?.addEventListener("abort",()=>{h(i?.signal?.reason)});const $=i?.timeout??qk,g=()=>h(J.fromError(W.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,i?.maxTotalTimeout,g,i?.resetTimeoutOnProgress??!1);const v=c?.taskId;if(v){const y=b=>{const I=this._responseHandlers.get(m);I?I(b):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,y),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(m),l(b)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:a}).catch(y=>{this._cleanupTimeout(m),l(y)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},As,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},Zs,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Hb,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||{},[Kt]: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||{},[Kt]: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||{},[Kt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const i=Wh(t);this.assertRequestHandlerCapability(i),this._requestHandlers.set(i,(n,o)=>{const a=Yh(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=Wh(t);this._notificationHandlers.set(i,n=>{const o=Yh(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"&&xh(n.message)){const o=n.message.id,a=this._requestResolvers.get(o);a?(a(new J(W.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 J(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,i);r.addEventListener("abort",()=>{clearTimeout(a),o(new J(W.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 J(W.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=Mi.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Gt(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 J(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Gt(s.status))throw new J(W.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=Mi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Gt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>i.listTasks(n,r)}}}function Xh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Hk(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];Xh(a)&&Xh(o)?r[n]={...a,...o}:r[n]=o}return r}function Qh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ic={exports:{}},eg={},Ot={},Wt={},oc={},se={},_r={};(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(y){if(super(),!e.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class i extends t{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((b,I)=>`${b}${I}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((b,I)=>(I instanceof r&&(b[I.str]=(b[I.str]||0)+1),b),{})}}e._Code=i,e.nil=new i("");function n(v,...y){const b=[v[0]];let I=0;for(;I<y.length;)s(b,y[I]),b.push(v[++I]);return new i(b)}e._=n;const o=new i("+");function a(v,...y){const b=[p(v[0])];let I=0;for(;I<y.length;)b.push(o),s(b,y[I]),b.push(o,p(v[++I]));return c(b),new i(b)}e.str=a;function s(v,y){y instanceof i?v.push(...y._items):y instanceof r?v.push(y):v.push(d(y))}e.addCodeArg=s;function c(v){let y=1;for(;y<v.length-1;){if(v[y]===o){const b=u(v[y-1],v[y+1]);if(b!==void 0){v.splice(y-1,3,b);continue}v[y++]="+"}y++}}function u(v,y){if(y==='""')return v;if(v==='""')return y;if(typeof v=="string")return y instanceof r||v[v.length-1]!=='"'?void 0:typeof y!="string"?`${v.slice(0,-1)}${y}"`:y[0]==='"'?v.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(v instanceof r))return`"${v}${y.slice(1)}`}function l(v,y){return y.emptyStr()?v:v.emptyStr()?y:a`${v}${y}`}e.strConcat=l;function d(v){return typeof v=="number"||typeof v=="boolean"||v===null?v:p(Array.isArray(v)?v.join(","):v)}function m(v){return new i(p(v))}e.stringify=m;function p(v){return JSON.stringify(v).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=p;function h(v){return typeof v=="string"&&e.IDENTIFIER.test(v)?new i(`.${v}`):n`[${v}]`}e.getProperty=h;function $(v){if(typeof v=="string"&&e.IDENTIFIER.test(v))return new i(`${v}`);throw new Error(`CodeGen: invalid export name: ${v}, use explicit $id name mapping`)}e.getEsmExportName=$;function g(v){return new i(v.toString())}e.regexpCode=g})(_r);var ac={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=_r;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 y=$.get(h);if(y)return y}else $=this._values[p]=new Map;$.set(h,m);const g=this._scope[p]||(this._scope[p]=[]),v=g.length;return g[v]=l.ref,m.setValue(l,{property:p,itemIndex:v}),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 g=d[h]=d[h]||new Map;$.forEach(v=>{if(g.has(v))return;g.set(v,i.Started);let y=l(v);if(y){const b=this.opts.es5?e.varKinds.var:e.varKinds.const;p=(0,t._)`${p}${b} ${v} = ${y};${this.opts._n}`}else if(y=m?.(v))p=(0,t._)`${p}${y}${this.opts._n}`;else throw new r(v);g.set(v,i.Completed)})}return p}}e.ValueScope=s})(ac),(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=_r,r=ac;var i=_r;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=ac;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,_){return this}}class a extends o{constructor(f,_,z){super(),this.varKind=f,this.name=_,this.rhs=z}render({es5:f,_n:_}){const z=f?r.varKinds.var:this.varKind,L=this.rhs===void 0?"":` = ${this.rhs}`;return`${z} ${this.name}${L};`+_}optimizeNames(f,_){if(f[this.name.str])return this.rhs&&(this.rhs=K(this.rhs,f,_)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends o{constructor(f,_,z){super(),this.lhs=f,this.rhs=_,this.sideEffects=z}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,_){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=K(this.rhs,f,_),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return Y(f,this.rhs)}}class c extends s{constructor(f,_,z,L){super(f,z,L),this.op=_}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,_){return this.code=K(this.code,f,_),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((_,z)=>_+z.render(f),"")}optimizeNodes(){const{nodes:f}=this;let _=f.length;for(;_--;){const z=f[_].optimizeNodes();Array.isArray(z)?f.splice(_,1,...z):z?f[_]=z:f.splice(_,1)}return f.length>0?this:void 0}optimizeNames(f,_){const{nodes:z}=this;let L=z.length;for(;L--;){const H=z[L];H.optimizeNames(f,_)||(ze(f,H.names),z.splice(L,1))}return z.length>0?this:void 0}get names(){return this.nodes.reduce((f,_)=>Q(f,_.names),{})}}class h extends p{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends p{}class g extends h{}g.kind="else";class v extends h{constructor(f,_){super(_),this.condition=f}render(f){let _=`if(${this.condition})`+super.render(f);return this.else&&(_+="else "+this.else.render(f)),_}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let _=this.else;if(_){const z=_.optimizeNodes();_=this.else=Array.isArray(z)?new g(z):z}if(_)return f===!1?_ instanceof v?_:_.nodes:this.nodes.length?this:new v(at(f),_ instanceof v?[_]:_.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,_){var z;if(this.else=(z=this.else)===null||z===void 0?void 0:z.optimizeNames(f,_),!!(super.optimizeNames(f,_)||this.else))return this.condition=K(this.condition,f,_),this}get names(){const f=super.names;return Y(f,this.condition),this.else&&Q(f,this.else.names),f}}v.kind="if";class y extends h{}y.kind="for";class b extends y{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iteration=K(this.iteration,f,_),this}get names(){return Q(super.names,this.iteration.names)}}class I extends y{constructor(f,_,z,L){super(),this.varKind=f,this.name=_,this.from=z,this.to=L}render(f){const _=f.es5?r.varKinds.var:this.varKind,{name:z,from:L,to:H}=this;return`for(${_} ${z}=${L}; ${z}<${H}; ${z}++)`+super.render(f)}get names(){const f=Y(super.names,this.from);return Y(f,this.to)}}class O extends y{constructor(f,_,z,L){super(),this.loop=f,this.varKind=_,this.name=z,this.iterable=L}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iterable=K(this.iterable,f,_),this}get names(){return Q(super.names,this.iterable.names)}}class M extends h{constructor(f,_,z){super(),this.name=f,this.args=_,this.async=z}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}M.kind="func";class V extends p{render(f){return"return "+super.render(f)}}V.kind="return";class le extends h{render(f){let _="try"+super.render(f);return this.catch&&(_+=this.catch.render(f)),this.finally&&(_+=this.finally.render(f)),_}optimizeNodes(){var f,_;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(_=this.finally)===null||_===void 0||_.optimizeNodes(),this}optimizeNames(f,_){var z,L;return super.optimizeNames(f,_),(z=this.catch)===null||z===void 0||z.optimizeNames(f,_),(L=this.finally)===null||L===void 0||L.optimizeNames(f,_),this}get names(){const f=super.names;return this.catch&&Q(f,this.catch.names),this.finally&&Q(f,this.finally.names),f}}class me extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}me.kind="catch";class Oe extends h{render(f){return"finally"+super.render(f)}}Oe.kind="finally";class B{constructor(f,_={}){this._values={},this._blockStarts=[],this._constants={},this.opts={..._,_n:_.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,_){const z=this._extScope.value(f,_);return(this._values[z.prefix]||(this._values[z.prefix]=new Set)).add(z),z}getScopeValue(f,_){return this._extScope.getValue(f,_)}scopeRefs(f){return this._extScope.scopeRefs(f,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(f,_,z,L){const H=this._scope.toName(_);return z!==void 0&&L&&(this._constants[H.str]=z),this._leafNode(new a(f,H,z)),H}const(f,_,z){return this._def(r.varKinds.const,f,_,z)}let(f,_,z){return this._def(r.varKinds.let,f,_,z)}var(f,_,z){return this._def(r.varKinds.var,f,_,z)}assign(f,_,z){return this._leafNode(new s(f,_,z))}add(f,_){return this._leafNode(new c(f,e.operators.ADD,_))}code(f){return typeof f=="function"?f():f!==t.nil&&this._leafNode(new m(f)),this}object(...f){const _=["{"];for(const[z,L]of f)_.length>1&&_.push(","),_.push(z),(z!==L||this.opts.es5)&&(_.push(":"),(0,t.addCodeArg)(_,L));return _.push("}"),new t._Code(_)}if(f,_,z){if(this._blockNode(new v(f)),_&&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(f){return this._elseNode(new v(f))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(v,g)}_for(f,_){return this._blockNode(f),_&&this.code(_).endFor(),this}for(f,_){return this._for(new b(f),_)}forRange(f,_,z,L,H=this.opts.es5?r.varKinds.var:r.varKinds.let){const fe=this._scope.toName(f);return this._for(new I(H,fe,_,z),()=>L(fe))}forOf(f,_,z,L=r.varKinds.const){const H=this._scope.toName(f);if(this.opts.es5){const fe=_ instanceof t.Name?_:this.var("_arr",_);return this.forRange("_i",0,(0,t._)`${fe}.length`,de=>{this.var(H,(0,t._)`${fe}[${de}]`),z(H)})}return this._for(new O("of",L,H,_),()=>z(H))}forIn(f,_,z,L=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(f,(0,t._)`Object.keys(${_})`,z);const H=this._scope.toName(f);return this._for(new O("in",L,H,_),()=>z(H))}endFor(){return this._endBlockNode(y)}label(f){return this._leafNode(new u(f))}break(f){return this._leafNode(new l(f))}return(f){const _=new V;if(this._blockNode(_),this.code(f),_.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(V)}try(f,_,z){if(!_&&!z)throw new Error('CodeGen: "try" without "catch" and "finally"');const L=new le;if(this._blockNode(L),this.code(f),_){const H=this.name("e");this._currNode=L.catch=new me(H),_(H)}return z&&(this._currNode=L.finally=new Oe,this.code(z)),this._endBlockNode(me,Oe)}throw(f){return this._leafNode(new d(f))}block(f,_){return this._blockStarts.push(this._nodes.length),f&&this.code(f).endBlock(_),this}endBlock(f){const _=this._blockStarts.pop();if(_===void 0)throw new Error("CodeGen: not in self-balancing block");const z=this._nodes.length-_;if(z<0||f!==void 0&&z!==f)throw new Error(`CodeGen: wrong number of nodes: ${z} vs ${f} expected`);return this._nodes.length=_,this}func(f,_=t.nil,z,L){return this._blockNode(new M(f,_,z)),L&&this.code(L).endFunc(),this}endFunc(){return this._endBlockNode(M)}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,_){const z=this._currNode;if(z instanceof f||_&&z instanceof _)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${_?`${f.kind}/${_.kind}`:f.kind}"`)}_elseNode(f){const _=this._currNode;if(!(_ instanceof v))throw new Error('CodeGen: "else" without "if"');return this._currNode=_.else=f,this}get _root(){return this._nodes[0]}get _currNode(){const f=this._nodes;return f[f.length-1]}set _currNode(f){const _=this._nodes;_[_.length-1]=f}}e.CodeGen=B;function Q(T,f){for(const _ in f)T[_]=(T[_]||0)+(f[_]||0);return T}function Y(T,f){return f instanceof t._CodeOrName?Q(T,f.names):T}function K(T,f,_){if(T instanceof t.Name)return z(T);if(!L(T))return T;return new t._Code(T._items.reduce((H,fe)=>(fe instanceof t.Name&&(fe=z(fe)),fe instanceof t._Code?H.push(...fe._items):H.push(fe),H),[]));function z(H){const fe=_[H.str];return fe===void 0||f[H.str]!==1?H:(delete f[H.str],fe)}function L(H){return H instanceof t._Code&&H._items.some(fe=>fe instanceof t.Name&&f[fe.str]===1&&_[fe.str]!==void 0)}}function ze(T,f){for(const _ in f)T[_]=(T[_]||0)-(f[_]||0)}function at(T){return typeof T=="boolean"||typeof T=="number"||T===null?!T:(0,t._)`!${j(T)}`}e.not=at;const st=P(e.operators.AND);function Bt(...T){return T.reduce(st)}e.and=Bt;const Pt=P(e.operators.OR);function A(...T){return T.reduce(Pt)}e.or=A;function P(T){return(f,_)=>f===t.nil?_:_===t.nil?f:(0,t._)`${j(f)} ${T} ${j(_)}`}function j(T){return T instanceof t.Name?T:(0,t._)`(${T})`}})(se);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 Ie=se,Kk=_r;function Gk(e){const t={};for(const r of e)t[r]=!0;return t}Z.toHash=Gk;function Wk(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(tg(e,t),!ng(t,e.self.RULES.all))}Z.alwaysValidSchema=Wk;function tg(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]||sg(e,`unknown keyword: "${o}"`)}Z.checkUnknownRules=tg;function ng(e,t){if(typeof e=="boolean")return!e;for(const r in e)if(t[r])return!0;return!1}Z.schemaHasRules=ng;function Yk(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=Yk;function Xk({topSchemaRef:e,schemaPath:t},r,i,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ie._)`${r}`}return(0,Ie._)`${e}${t}${(0,Ie.getProperty)(i)}`}Z.schemaRefOrVal=Xk;function Qk(e){return rg(decodeURIComponent(e))}Z.unescapeFragment=Qk;function ew(e){return encodeURIComponent(sc(e))}Z.escapeFragment=ew;function sc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=sc;function rg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=rg;function tw(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}Z.eachItem=tw;function ig({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:i}){return(n,o,a,s)=>{const c=a===void 0?o:a instanceof Ie.Name?(o instanceof Ie.Name?e(n,o,a):t(n,o,a),a):o instanceof Ie.Name?(t(n,a,o),o):r(o,a);return s===Ie.Name&&!(c instanceof Ie.Name)?i(n,c):c}}Z.mergeEvaluated={props:ig({mergeNames:(e,t,r)=>e.if((0,Ie._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,Ie._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,Ie._)`${r} || {}`).code((0,Ie._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,Ie._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,Ie._)`${r} || {}`),cc(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:og}),items:ig({mergeNames:(e,t,r)=>e.if((0,Ie._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,Ie._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,Ie._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,Ie._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function og(e,t){if(t===!0)return e.var("props",!0);const r=e.var("props",(0,Ie._)`{}`);return t!==void 0&&cc(e,r,t),r}Z.evaluatedPropsToName=og;function cc(e,t,r){Object.keys(r).forEach(i=>e.assign((0,Ie._)`${t}${(0,Ie.getProperty)(i)}`,!0))}Z.setEvaluated=cc;const ag={};function nw(e,t){return e.scopeValue("func",{ref:t,code:ag[t.code]||(ag[t.code]=new Kk._Code(t.code))})}Z.useFunc=nw;var uc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(uc||(Z.Type=uc={}));function rw(e,t,r){if(e instanceof Ie.Name){const i=t===uc.Num;return r?i?(0,Ie._)`"[" + ${e} + "]"`:(0,Ie._)`"['" + ${e} + "']"`:i?(0,Ie._)`"/" + ${e}`:(0,Ie._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ie.getProperty)(e).toString():"/"+sc(e)}Z.getErrorPath=rw;function sg(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=sg;var Ji={},cg;function At(){if(cg)return Ji;cg=1,Object.defineProperty(Ji,"__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 Ji.default=t,Ji}var ug;function Hi(){return ug||(ug=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=Z,i=At();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:v})=>v?(0,t.str)`"${g}" keyword must be ${v} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function n(g,v=e.keywordError,y,b){const{it:I}=g,{gen:O,compositeRule:M,allErrors:V}=I,le=d(g,v,y);b??(M||V)?c(O,le):u(I,(0,t._)`[${le}]`)}e.reportError=n;function o(g,v=e.keywordError,y){const{it:b}=g,{gen:I,compositeRule:O,allErrors:M}=b,V=d(g,v,y);c(I,V),O||M||u(b,i.default.vErrors)}e.reportExtraError=o;function a(g,v){g.assign(i.default.errors,v),g.if((0,t._)`${i.default.vErrors} !== null`,()=>g.if(v,()=>g.assign((0,t._)`${i.default.vErrors}.length`,v),()=>g.assign(i.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:g,keyword:v,schemaValue:y,data:b,errsCount:I,it:O}){if(I===void 0)throw new Error("ajv implementation error");const M=g.name("err");g.forRange("i",I,i.default.errors,V=>{g.const(M,(0,t._)`${i.default.vErrors}[${V}]`),g.if((0,t._)`${M}.instancePath === undefined`,()=>g.assign((0,t._)`${M}.instancePath`,(0,t.strConcat)(i.default.instancePath,O.errorPath))),g.assign((0,t._)`${M}.schemaPath`,(0,t.str)`${O.errSchemaPath}/${v}`),O.opts.verbose&&(g.assign((0,t._)`${M}.schema`,y),g.assign((0,t._)`${M}.data`,b))})}e.extendErrors=s;function c(g,v){const y=g.const("err",v);g.if((0,t._)`${i.default.vErrors} === null`,()=>g.assign(i.default.vErrors,(0,t._)`[${y}]`),(0,t._)`${i.default.vErrors}.push(${y})`),g.code((0,t._)`${i.default.errors}++`)}function u(g,v){const{gen:y,validateName:b,schemaEnv:I}=g;I.$async?y.throw((0,t._)`new ${g.ValidationError}(${v})`):(y.assign((0,t._)`${b}.errors`,v),y.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,v,y){const{createErrors:b}=g.it;return b===!1?(0,t._)`{}`:m(g,v,y)}function m(g,v,y={}){const{gen:b,it:I}=g,O=[p(I,y),h(g,y)];return $(g,v,O),b.object(...O)}function p({errorPath:g},{instancePath:v}){const y=v?(0,t.str)`${g}${(0,r.getErrorPath)(v,r.Type.Str)}`:g;return[i.default.instancePath,(0,t.strConcat)(i.default.instancePath,y)]}function h({keyword:g,it:{errSchemaPath:v}},{schemaPath:y,parentSchema:b}){let I=b?v:(0,t.str)`${v}/${g}`;return y&&(I=(0,t.str)`${I}${(0,r.getErrorPath)(y,r.Type.Str)}`),[l.schemaPath,I]}function $(g,{params:v,message:y},b){const{keyword:I,data:O,schemaValue:M,it:V}=g,{opts:le,propertyName:me,topSchemaRef:Oe,schemaPath:B}=V;b.push([l.keyword,I],[l.params,typeof v=="function"?v(g):v||(0,t._)`{}`]),le.messages&&b.push([l.message,typeof y=="function"?y(g):y]),le.verbose&&b.push([l.schema,M],[l.parentSchema,(0,t._)`${Oe}${B}`],[i.default.data,O]),me&&b.push([l.propertyName,me])}})(oc)),oc}var lg;function iw(){if(lg)return Wt;lg=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.boolOrEmptySchema=Wt.topBoolOrEmptySchema=void 0;const e=Hi(),t=se,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))}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 De={},Yt={};Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.getRules=Yt.isJSONType=void 0;const ow=["string","number","integer","boolean","null","object","array"],aw=new Set(ow);function sw(e){return typeof e=="string"&&aw.has(e)}Yt.isJSONType=sw;function cw(){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=cw;var zt={},dg;function pg(){if(dg)return zt;dg=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(De,"__esModule",{value:!0}),De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;const uw=Yt,lw=pg(),dw=Hi(),re=se,mg=Z;var $n;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})($n||(De.DataType=$n={}));function pw(e){const t=fg(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}De.getSchemaTypes=pw;function fg(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(uw.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}De.getJSONTypes=fg;function mw(e,t){const{gen:r,data:i,opts:n}=e,o=fw(t,n.coerceTypes),a=t.length>0&&!(o.length===0&&t.length===1&&(0,lw.schemaHasRulesForType)(e,t[0]));if(a){const s=dc(t,i,n.strictNumbers,$n.Wrong);r.if(s,()=>{o.length?hw(e,t,o):pc(e)})}return a}De.coerceAndCheckDataType=mw;const hg=new Set(["string","number","integer","boolean","null"]);function fw(e,t){return t?e.filter(r=>hg.has(r)||t==="array"&&r==="array"):[]}function hw(e,t,r){const{gen:i,data:n,opts:o}=e,a=i.let("dataType",(0,re._)`typeof ${n}`),s=i.let("coerced",(0,re._)`undefined`);o.coerceTypes==="array"&&i.if((0,re._)`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>i.assign(n,(0,re._)`${n}[0]`).assign(a,(0,re._)`typeof ${n}`).if(dc(t,n,o.strictNumbers),()=>i.assign(s,n))),i.if((0,re._)`${s} !== undefined`);for(const u of r)(hg.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);i.else(),pc(e),i.endIf(),i.if((0,re._)`${s} !== undefined`,()=>{i.assign(n,s),gw(e,s)});function c(u){switch(u){case"string":i.elseIf((0,re._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,re._)`"" + ${n}`).elseIf((0,re._)`${n} === null`).assign(s,(0,re._)`""`);return;case"number":i.elseIf((0,re._)`${a} == "boolean" || ${n} === null
|
|
72
72
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(s,(0,re._)`+${n}`);return;case"integer":i.elseIf((0,re._)`${a} === "boolean" || ${n} === null
|
|
73
73
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(s,(0,re._)`+${n}`);return;case"boolean":i.elseIf((0,re._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(s,!1).elseIf((0,re._)`${n} === "true" || ${n} === 1`).assign(s,!0);return;case"null":i.elseIf((0,re._)`${n} === "" || ${n} === 0 || ${n} === false`),i.assign(s,null);return;case"array":i.elseIf((0,re._)`${a} === "string" || ${a} === "number"
|
package/dist/nrge-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(o[c]==="$"){n+=`($|(?=[\r
|
|
68
68
|
]))`;continue}}if(r.s&&o[c]==="."){n+=a?`${o[c]}\r
|
|
69
69
|
`:`[${o[c]}\r
|
|
70
|
-
]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[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 Bh(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((o,n)=>({...o,[n]:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ke(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:me(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:o,...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:o,...n}=Ch(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function vS(e,t){if(t.mapStrategy==="record")return Bh(e,t);const r=me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(t),o=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function yS(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function _S(e){return e.target==="openAi"?void 0:{not:Ke({...e,currentPath:[...e.currentPath,"not"]})}}function $S(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Fo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bS(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(o=>o._def.typeName in Fo&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=Fo[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return Lh(e,t)}const Lh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>me(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function kS(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:Fo[e.innerType._def.typeName],nullable:!0}:{type:[Fo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const o=me(e.innerType._def,{...t,currentPath:[...t.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}const r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function SS(e,t){const r={type:"number"};if(!e.checks)return r;for(const o of e.checks)switch(o.kind){case"int":r.type="integer",Dh(r,"type",o.message,t);break;case"min":t.target==="jsonSchema7"?o.inclusive?ve(r,"minimum",o.value,o.message,t):ve(r,"exclusiveMinimum",o.value,o.message,t):(o.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",o.value,o.message,t));break;case"max":t.target==="jsonSchema7"?o.inclusive?ve(r,"maximum",o.value,o.message,t):ve(r,"exclusiveMaximum",o.value,o.message,t):(o.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",o.value,o.message,t));break;case"multipleOf":ve(r,"multipleOf",o.value,o.message,t);break}return r}function wS(e,t){const r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(const s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=PS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=me(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);const a=IS(e,t);return a!==void 0&&(o.additionalProperties=a),o}function IS(e,t){if(e.catchall._def.typeName!=="ZodNever")return me(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 PS(e){try{return e.isOptional()}catch{return!0}}const xS=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return me(e.innerType._def,t);const r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(t)},r]}:Ke(t)},OS=(e,t)=>{if(t.pipeStrategy==="input")return me(e.in._def,t);if(t.pipeStrategy==="output")return me(e.out._def,t);const r=me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function TS(e,t){return me(e.type._def,t)}function NS(e,t){const o={type:"array",uniqueItems:!0,items:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ve(o,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ve(o,"maxItems",e.maxSize.value,e.maxSize.message,t),o}function zS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function jS(e){return{not:Ke(e)}}function ES(e){return Ke(e)}const RS=(e,t)=>me(e.innerType._def,t),DS=(e,t,r)=>{switch(t){case te.ZodString:return Zh(e,r);case te.ZodNumber:return SS(e,r);case te.ZodObject:return wS(e,r);case te.ZodBigInt:return iS(e,r);case te.ZodBoolean:return aS();case te.ZodDate:return Uh(e,r);case te.ZodUndefined:return jS(r);case te.ZodNull:return $S(r);case te.ZodArray:return oS(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return bS(e,r);case te.ZodIntersection:return mS(e,r);case te.ZodTuple:return zS(e,r);case te.ZodRecord:return Bh(e,r);case te.ZodLiteral:return fS(e,r);case te.ZodEnum:return dS(e);case te.ZodNativeEnum:return yS(e);case te.ZodNullable:return kS(e,r);case te.ZodOptional:return xS(e,r);case te.ZodMap:return vS(e,r);case te.ZodSet:return NS(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return TS(e,r);case te.ZodNaN:case te.ZodNever:return _S(r);case te.ZodEffects:return lS(e,r);case te.ZodAny:return Ke(r);case te.ZodUnknown:return ES(r);case te.ZodDefault:return uS(e,r);case te.ZodBranded:return Ch(e,r);case te.ZodReadonly:return RS(e,r);case te.ZodCatch:return sS(e,r);case te.ZodPipeline:return OS(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(o=>{})()}};function me(e,t,r=!1){const o=t.seen.get(e);if(t.override){const s=t.override?.(e,t,o,r);if(s!==tS)return s}if(o&&!r){const s=AS(o,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=DS(e,e.typeName,t),a=typeof i=="function"?me(i(),t):i;if(a&&CS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const AS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ah(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ke(t)):t.$refStrategy==="seen"?Ke(t):void 0}},CS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),US=(e,t)=>{const r=rS(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:me(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,i=me(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&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[r.openAiAnyTypeName]||(o[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?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};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 ZS(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Fh(e,t){return kt(e)?Pa(e,{target:ZS(t?.target),io:t?.pipeStrategy??"input"}):US(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Gh(e){const r=lr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const o=gh(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function qh(e,t){const r=ur(e,t);if(!r.success)throw r.error;return r.data}const MS=6e4;class BS{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(Ps,r=>{this._oncancel(r)}),this.setNotificationHandler(Os,r=>{this._onprogress(r)}),this.setRequestHandler(xs,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ts,async(r,o)=>{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(zs,async(r,o)=>{const n=async()=>{const i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.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 q(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:o.requestId})}}const a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new q(W.InvalidParams,`Task not found: ${i}`);if(!Vt(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(Vt(a.status)){const s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Jt]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(js,async(r,o)=>{try{const{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new q(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Rs,async(r,o)=>{try{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Vt(n.status))throw new q(W.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);const i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new q(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof q?n:new q(W.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,o,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),q.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});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 o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};const n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Ao(i)||Ib(i)?this._onresponse(i):bh(i)?this._onrequest(i,a):wb(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(const o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();const r=q.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const o of t.values())o(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(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){const o=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,i=t.params?._meta?.[Jt]?.taskId;if(o===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{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=Sb(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};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new q(W.ConnectionClosed,"Request was cancelled");const p={...m,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});const h=p.relatedTask?.taskId??i;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:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>o(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{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:W.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{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,...o}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){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}i(o)}_onresponse(t){const r=Number(t.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Ao(t))o(t);else{const a=new q(t.error.code,t.error.message,t.error.data);o(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 i=!1;if(Ao(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"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Ao(t))n(t);else{const a=q.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,o){const{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(t,r,o)}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}return}let i;try{const a=await this.request(t,Co,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new q(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},Vt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new q(W.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new q(W.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}}request(t,r,o){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};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}o?.signal?.throwIfAborted();const m=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:m};o?.onprogress&&(this._progressHandlers.set(m,o.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||{},[Jt]: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:i,onresumptiontoken:a}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));const S=v instanceof q?v:new q(W.RequestTimeout,String(v));l(S)};this._responseHandlers.set(m,v=>{if(!o?.signal?.aborted){if(v instanceof Error)return l(v);try{const S=ur(r,v.result);S.success?u(S.data):l(S.error)}catch(S){l(S)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});const $=o?.timeout??MS,g=()=>h(q.fromError(W.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,o?.maxTotalTimeout,g,o?.resetTimeoutOnProgress??!1);const y=c?.taskId;if(y){const v=S=>{const P=this._responseHandlers.get(m);P?P(S):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(m),l(S)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ns,r)}async getTaskResult(t,r,o){return this.request({method:"tasks/result",params:t},r,o)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Es,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Lb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const o=r?.relatedTask?.taskId;if(o){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Jt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{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||{},[Jt]: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||{},[Jt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const o=Gh(t);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{const a=qh(t,n);return Promise.resolve(r(a,i))})}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 o=Gh(t);this._notificationHandlers.set(o,n=>{const i=qh(t,n);return Promise.resolve(r(i))})}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,o){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,o,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const o=await this._taskMessageQueue.dequeueAll(t,r);for(const n of o)if(n.type==="request"&&bh(n.message)){const i=n.message.id,a=this._requestResolvers.get(i);a?(a(new q(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let o=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new q(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new q(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await o.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const i=await o.getTask(n,r);if(!i)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);const s=await o.getTask(n,r);if(s){const c=Uo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Vt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{const s=await o.getTask(n,r);if(!s)throw new q(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Vt(s.status))throw new q(W.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);const c=await o.getTask(n,r);if(c){const u=Uo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Vt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}}function Jh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function LS(e,t){const r={...e};for(const o in t){const n=o,i=t[n];if(i===void 0)continue;const a=r[n];Jh(a)&&Jh(i)?r[n]={...a,...i}:r[n]=i}return r}function Vh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ys={exports:{}},Hh={},Pt={},Ht={},Qs={},se={},yr={};(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 o 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((S,P)=>`${S}${P}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((S,P)=>(P instanceof r&&(S[P.str]=(S[P.str]||0)+1),S),{})}}e._Code=o,e.nil=new o("");function n(y,...v){const S=[y[0]];let P=0;for(;P<v.length;)s(S,v[P]),S.push(y[++P]);return new o(S)}e._=n;const i=new o("+");function a(y,...v){const S=[p(y[0])];let P=0;for(;P<v.length;)S.push(i),s(S,v[P]),S.push(i,p(y[++P]));return c(S),new o(S)}e.str=a;function s(y,v){v instanceof o?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]===i){const S=u(y[v-1],y[v+1]);if(S!==void 0){y.splice(v-1,3,S);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:p(Array.isArray(y)?y.join(","):y)}function m(y){return new o(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 o(`.${y}`):n`[${y}]`}e.getProperty=h;function $(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new o(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=$;function g(y){return new o(y.toString())}e.regexpCode=g})(yr);var ec={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=yr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var o;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),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 i 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=i;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 i(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 v=$.get(h);if(v)return v}else $=this._values[p]=new Map;$.set(h,m);const g=this._scope[p]||(this._scope[p]=[]),y=g.length;return g[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 g=d[h]=d[h]||new Map;$.forEach(y=>{if(g.has(y))return;g.set(y,o.Started);let v=l(y);if(v){const S=this.opts.es5?e.varKinds.var:e.varKinds.const;p=(0,t._)`${p}${S} ${y} = ${v};${this.opts._n}`}else if(v=m?.(y))p=(0,t._)`${p}${v}${this.opts._n}`;else throw new r(y);g.set(y,o.Completed)})}return p}}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=yr,r=ec;var o=yr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.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 i{optimizeNodes(){return this}optimizeNames(f,_){return this}}class a extends i{constructor(f,_,T){super(),this.varKind=f,this.name=_,this.rhs=T}render({es5:f,_n:_}){const T=f?r.varKinds.var:this.varKind,L=this.rhs===void 0?"":` = ${this.rhs}`;return`${T} ${this.name}${L};`+_}optimizeNames(f,_){if(f[this.name.str])return this.rhs&&(this.rhs=V(this.rhs,f,_)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends i{constructor(f,_,T){super(),this.lhs=f,this.rhs=_,this.sideEffects=T}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,_){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=V(this.rhs,f,_),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return X(f,this.rhs)}}class c extends s{constructor(f,_,T,L){super(f,T,L),this.op=_}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends i{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class m extends i{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,_){return this.code=V(this.code,f,_),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends i{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((_,T)=>_+T.render(f),"")}optimizeNodes(){const{nodes:f}=this;let _=f.length;for(;_--;){const T=f[_].optimizeNodes();Array.isArray(T)?f.splice(_,1,...T):T?f[_]=T:f.splice(_,1)}return f.length>0?this:void 0}optimizeNames(f,_){const{nodes:T}=this;let L=T.length;for(;L--;){const J=T[L];J.optimizeNames(f,_)||(Oe(f,J.names),T.splice(L,1))}return T.length>0?this:void 0}get names(){return this.nodes.reduce((f,_)=>Q(f,_.names),{})}}class h extends p{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends p{}class g extends h{}g.kind="else";class y extends h{constructor(f,_){super(_),this.condition=f}render(f){let _=`if(${this.condition})`+super.render(f);return this.else&&(_+="else "+this.else.render(f)),_}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let _=this.else;if(_){const T=_.optimizeNodes();_=this.else=Array.isArray(T)?new g(T):T}if(_)return f===!1?_ instanceof y?_:_.nodes:this.nodes.length?this:new y(rt(f),_ instanceof y?[_]:_.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,_){var T;if(this.else=(T=this.else)===null||T===void 0?void 0:T.optimizeNames(f,_),!!(super.optimizeNames(f,_)||this.else))return this.condition=V(this.condition,f,_),this}get names(){const f=super.names;return X(f,this.condition),this.else&&Q(f,this.else.names),f}}y.kind="if";class v extends h{}v.kind="for";class S extends v{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iteration=V(this.iteration,f,_),this}get names(){return Q(super.names,this.iteration.names)}}class P extends v{constructor(f,_,T,L){super(),this.varKind=f,this.name=_,this.from=T,this.to=L}render(f){const _=f.es5?r.varKinds.var:this.varKind,{name:T,from:L,to:J}=this;return`for(${_} ${T}=${L}; ${T}<${J}; ${T}++)`+super.render(f)}get names(){const f=X(super.names,this.from);return X(f,this.to)}}class N extends v{constructor(f,_,T,L){super(),this.loop=f,this.varKind=_,this.name=T,this.iterable=L}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iterable=V(this.iterable,f,_),this}get names(){return Q(super.names,this.iterable.names)}}class B extends h{constructor(f,_,T){super(),this.name=f,this.args=_,this.async=T}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}B.kind="func";class K extends p{render(f){return"return "+super.render(f)}}K.kind="return";class ue extends h{render(f){let _="try"+super.render(f);return this.catch&&(_+=this.catch.render(f)),this.finally&&(_+=this.finally.render(f)),_}optimizeNodes(){var f,_;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(_=this.finally)===null||_===void 0||_.optimizeNodes(),this}optimizeNames(f,_){var T,L;return super.optimizeNames(f,_),(T=this.catch)===null||T===void 0||T.optimizeNames(f,_),(L=this.finally)===null||L===void 0||L.optimizeNames(f,_),this}get names(){const f=super.names;return this.catch&&Q(f,this.catch.names),this.finally&&Q(f,this.finally.names),f}}class de extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}de.kind="catch";class xe extends h{render(f){return"finally"+super.render(f)}}xe.kind="finally";class M{constructor(f,_={}){this._values={},this._blockStarts=[],this._constants={},this.opts={..._,_n:_.lines?`
|
|
70
|
+
]`;continue}n+=o[c],o[c]==="\\"?i=!0:a&&o[c]==="]"?a=!1:!a&&o[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 Bh(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((o,n)=>({...o,[n]:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",n]})??Ke(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:me(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:o,...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:o,...n}=Ch(e.keyType._def,t);return{...r,propertyNames:n}}}return r}function vS(e,t){if(t.mapStrategy==="record")return Bh(e,t);const r=me(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Ke(t),o=me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Ke(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function yS(e){const t=e.values,o=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),n=Array.from(new Set(o.map(i=>typeof i)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:o}}function _S(e){return e.target==="openAi"?void 0:{not:Ke({...e,currentPath:[...e.currentPath,"not"]})}}function $S(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Fo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bS(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(o=>o._def.typeName in Fo&&(!o._def.checks||!o._def.checks.length))){const o=r.reduce((n,i)=>{const a=Fo[i._def.typeName];return a&&!n.includes(a)?[...n,a]:n},[]);return{type:o.length>1?o:o[0]}}else if(r.every(o=>o._def.typeName==="ZodLiteral"&&!o.description)){const o=r.reduce((n,i)=>{const a=typeof i._def.value;switch(a){case"string":case"number":case"boolean":return[...n,a];case"bigint":return[...n,"integer"];case"object":if(i._def.value===null)return[...n,"null"];default:return n}},[]);if(o.length===r.length){const n=o.filter((i,a,s)=>s.indexOf(i)===a);return{type:n.length>1?n:n[0],enum:r.reduce((i,a)=>i.includes(a._def.value)?i:[...i,a._def.value],[])}}}else if(r.every(o=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,n)=>[...o,...n._def.values.filter(i=>!o.includes(i))],[])};return Lh(e,t)}const Lh=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((o,n)=>me(o._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(o=>!!o&&(!t.strictUnions||typeof o=="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function kS(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:Fo[e.innerType._def.typeName],nullable:!0}:{type:[Fo[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const o=me(e.innerType._def,{...t,currentPath:[...t.currentPath]});return o&&"$ref"in o?{allOf:[o],nullable:!0}:o&&{...o,nullable:!0}}const r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function SS(e,t){const r={type:"number"};if(!e.checks)return r;for(const o of e.checks)switch(o.kind){case"int":r.type="integer",Dh(r,"type",o.message,t);break;case"min":t.target==="jsonSchema7"?o.inclusive?ve(r,"minimum",o.value,o.message,t):ve(r,"exclusiveMinimum",o.value,o.message,t):(o.inclusive||(r.exclusiveMinimum=!0),ve(r,"minimum",o.value,o.message,t));break;case"max":t.target==="jsonSchema7"?o.inclusive?ve(r,"maximum",o.value,o.message,t):ve(r,"exclusiveMaximum",o.value,o.message,t):(o.inclusive||(r.exclusiveMaximum=!0),ve(r,"maximum",o.value,o.message,t));break;case"multipleOf":ve(r,"multipleOf",o.value,o.message,t);break}return r}function wS(e,t){const r=t.target==="openAi",o={type:"object",properties:{}},n=[],i=e.shape();for(const s in i){let c=i[s];if(c===void 0||c._def===void 0)continue;let u=PS(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=me(c._def,{...t,currentPath:[...t.currentPath,"properties",s],propertyPath:[...t.currentPath,"properties",s]});l!==void 0&&(o.properties[s]=l,u||n.push(s))}n.length&&(o.required=n);const a=IS(e,t);return a!==void 0&&(o.additionalProperties=a),o}function IS(e,t){if(e.catchall._def.typeName!=="ZodNever")return me(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 PS(e){try{return e.isOptional()}catch{return!0}}const xS=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return me(e.innerType._def,t);const r=me(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(t)},r]}:Ke(t)},OS=(e,t)=>{if(t.pipeStrategy==="input")return me(e.in._def,t);if(t.pipeStrategy==="output")return me(e.out._def,t);const r=me(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),o=me(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter(n=>n!==void 0)}};function TS(e,t){return me(e.type._def,t)}function NS(e,t){const o={type:"array",uniqueItems:!0,items:me(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ve(o,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ve(o,"maxItems",e.maxSize.value,e.maxSize.message,t),o}function zS(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,o)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:me(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,o)=>me(r._def,{...t,currentPath:[...t.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function jS(e){return{not:Ke(e)}}function ES(e){return Ke(e)}const RS=(e,t)=>me(e.innerType._def,t),DS=(e,t,r)=>{switch(t){case te.ZodString:return Zh(e,r);case te.ZodNumber:return SS(e,r);case te.ZodObject:return wS(e,r);case te.ZodBigInt:return iS(e,r);case te.ZodBoolean:return aS();case te.ZodDate:return Uh(e,r);case te.ZodUndefined:return jS(r);case te.ZodNull:return $S(r);case te.ZodArray:return oS(e,r);case te.ZodUnion:case te.ZodDiscriminatedUnion:return bS(e,r);case te.ZodIntersection:return mS(e,r);case te.ZodTuple:return zS(e,r);case te.ZodRecord:return Bh(e,r);case te.ZodLiteral:return fS(e,r);case te.ZodEnum:return dS(e);case te.ZodNativeEnum:return yS(e);case te.ZodNullable:return kS(e,r);case te.ZodOptional:return xS(e,r);case te.ZodMap:return vS(e,r);case te.ZodSet:return NS(e,r);case te.ZodLazy:return()=>e.getter()._def;case te.ZodPromise:return TS(e,r);case te.ZodNaN:case te.ZodNever:return _S(r);case te.ZodEffects:return lS(e,r);case te.ZodAny:return Ke(r);case te.ZodUnknown:return ES(r);case te.ZodDefault:return uS(e,r);case te.ZodBranded:return Ch(e,r);case te.ZodReadonly:return RS(e,r);case te.ZodCatch:return sS(e,r);case te.ZodPipeline:return OS(e,r);case te.ZodFunction:case te.ZodVoid:case te.ZodSymbol:return;default:return(o=>{})()}};function me(e,t,r=!1){const o=t.seen.get(e);if(t.override){const s=t.override?.(e,t,o,r);if(s!==tS)return s}if(o&&!r){const s=AS(o,t);if(s!==void 0)return s}const n={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,n);const i=DS(e,e.typeName,t),a=typeof i=="function"?me(i(),t):i;if(a&&CS(e,t,a),t.postProcess){const s=t.postProcess(a,e,t);return n.jsonSchema=a,s}return n.jsonSchema=a,a}const AS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Ah(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,o)=>t.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Ke(t)):t.$refStrategy==="seen"?Ke(t):void 0}},CS=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),US=(e,t)=>{const r=rS(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:me(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,i=me(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&&(i.title=a),r.flags.hasReferencedOpenAiAnyType&&(o||(o={}),o[r.openAiAnyTypeName]||(o[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?o?{...i,[r.definitionPath]:o}:i:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...o,[n]:i}};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 ZS(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function Fh(e,t){return kt(e)?Pa(e,{target:ZS(t?.target),io:t?.pipeStrategy??"input"}):US(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function Gh(e){const r=lr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const o=gh(r);if(typeof o!="string")throw new Error("Schema method literal must be a string");return o}function qh(e,t){const r=ur(e,t);if(!r.success)throw r.error;return r.data}const MS=6e4;class BS{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(Ps,r=>{this._oncancel(r)}),this.setNotificationHandler(Os,r=>{this._onprogress(r)}),this.setRequestHandler(xs,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ts,async(r,o)=>{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(zs,async(r,o)=>{const n=async()=>{const i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,o.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 q(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:o.requestId})}}const a=await this._taskStore.getTask(i,o.sessionId);if(!a)throw new q(W.InvalidParams,`Task not found: ${i}`);if(!Vt(a.status))return await this._waitForTaskUpdate(i,o.signal),await n();if(Vt(a.status)){const s=await this._taskStore.getTaskResult(i,o.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Jt]:{taskId:i}}}}return await n()};return await n()}),this.setRequestHandler(js,async(r,o)=>{try{const{tasks:n,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,o.sessionId);return{tasks:n,nextCursor:i,_meta:{}}}catch(n){throw new q(W.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Rs,async(r,o)=>{try{const n=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!n)throw new q(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Vt(n.status))throw new q(W.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",o.sessionId),this._clearTaskQueue(r.params.taskId);const i=await this._taskStore.getTask(r.params.taskId,o.sessionId);if(!i)throw new q(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(n){throw n instanceof q?n:new q(W.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,o,n,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:o,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const o=Date.now()-r.startTime;if(r.maxTotalTimeout&&o>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),q.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:o});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 o=this.transport?.onerror;this._transport.onerror=i=>{o?.(i),this._onerror(i)};const n=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{n?.(i,a),Ao(i)||Ib(i)?this._onresponse(i):bh(i)?this._onrequest(i,a):wb(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();for(const o of this._requestHandlerAbortControllers.values())o.abort();this._requestHandlerAbortControllers.clear();const r=q.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const o of t.values())o(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(o=>this._onerror(new Error(`Uncaught error in notification handler: ${o}`)))}_onrequest(t,r){const o=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,n=this._transport,i=t.params?._meta?.[Jt]?.taskId;if(o===void 0){const l={jsonrpc:"2.0",id:t.id,error:{code:W.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{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=Sb(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};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new q(W.ConnectionClosed,"Request was cancelled");const p={...m,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});const h=p.relatedTask?.taskId??i;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:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>o(t,u)).then(async l=>{if(a.signal.aborted)return;const d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{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:W.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{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,...o}=t.params,n=Number(r),i=this._progressHandlers.get(n);if(!i){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}i(o)}_onresponse(t){const r=Number(t.id),o=this._requestResolvers.get(r);if(o){if(this._requestResolvers.delete(r),Ao(t))o(t);else{const a=new q(t.error.code,t.error.message,t.error.data);o(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 i=!1;if(Ao(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"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),Ao(t))n(t);else{const a=q.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,o){const{task:n}=o??{};if(!n){try{yield{type:"result",result:await this.request(t,r,o)}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}return}let i;try{const a=await this.request(t,Co,o);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new q(W.InternalError,"Task creation did not return a task");for(;;){const s=await this.getTask({taskId:i},o);if(yield{type:"taskStatus",task:s},Vt(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)}:s.status==="failed"?yield{type:"error",error:new q(W.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new q(W.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,o)};return}const c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),o?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof q?a:new q(W.InternalError,String(a))}}}request(t,r,o){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=o??{};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}o?.signal?.throwIfAborted();const m=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:m};o?.onprogress&&(this._progressHandlers.set(m,o.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||{},[Jt]: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:i,onresumptiontoken:a}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));const S=v instanceof q?v:new q(W.RequestTimeout,String(v));l(S)};this._responseHandlers.set(m,v=>{if(!o?.signal?.aborted){if(v instanceof Error)return l(v);try{const S=ur(r,v.result);S.success?u(S.data):l(S.error)}catch(S){l(S)}}}),o?.signal?.addEventListener("abort",()=>{h(o?.signal?.reason)});const $=o?.timeout??MS,g=()=>h(q.fromError(W.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(m,$,o?.maxTotalTimeout,g,o?.resetTimeoutOnProgress??!1);const y=c?.taskId;if(y){const v=S=>{const P=this._responseHandlers.get(m);P?P(S):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(m),l(S)})}else this._transport.send(p,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(m),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ns,r)}async getTaskResult(t,r,o){return this.request({method:"tasks/result",params:t},r,o)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Es,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Lb,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const o=r?.relatedTask?.taskId;if(o){const s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Jt]:r.relatedTask}}};await this._enqueueTaskMessage(o,{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||{},[Jt]: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||{},[Jt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const o=Gh(t);this.assertRequestHandlerCapability(o),this._requestHandlers.set(o,(n,i)=>{const a=qh(t,n);return Promise.resolve(r(a,i))})}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 o=Gh(t);this._notificationHandlers.set(o,n=>{const i=qh(t,n);return Promise.resolve(r(i))})}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,o){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,o,n)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const o=await this._taskMessageQueue.dequeueAll(t,r);for(const n of o)if(n.type==="request"&&bh(n.message)){const i=n.message.id,a=this._requestResolvers.get(i);a?(a(new q(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let o=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(t);n?.pollInterval&&(o=n.pollInterval)}catch{}return new Promise((n,i)=>{if(r.aborted){i(new q(W.InvalidRequest,"Request cancelled"));return}const a=setTimeout(n,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new q(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const o=this._taskStore;if(!o)throw new Error("No task store configured");return{createTask:async n=>{if(!t)throw new Error("No request provided");return await o.createTask(n,t.id,{method:t.method,params:t.params},r)},getTask:async n=>{const i=await o.getTask(n,r);if(!i)throw new q(W.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(n,i,a)=>{await o.storeTaskResult(n,i,a,r);const s=await o.getTask(n,r);if(s){const c=Uo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Vt(s.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>o.getTaskResult(n,r),updateTaskStatus:async(n,i,a)=>{const s=await o.getTask(n,r);if(!s)throw new q(W.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Vt(s.status))throw new q(W.InvalidParams,`Cannot update task "${n}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await o.updateTaskStatus(n,i,a,r);const c=await o.getTask(n,r);if(c){const u=Uo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Vt(c.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>o.listTasks(n,r)}}}function Jh(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function LS(e,t){const r={...e};for(const o in t){const n=o,i=t[n];if(i===void 0)continue;const a=r[n];Jh(a)&&Jh(i)?r[n]={...a,...i}:r[n]=i}return r}function Vh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ys={exports:{}},Hh={},Pt={},Ht={},Qs={},se={},yr={};(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 o 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((S,P)=>`${S}${P}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((S,P)=>(P instanceof r&&(S[P.str]=(S[P.str]||0)+1),S),{})}}e._Code=o,e.nil=new o("");function n(y,...v){const S=[y[0]];let P=0;for(;P<v.length;)s(S,v[P]),S.push(y[++P]);return new o(S)}e._=n;const i=new o("+");function a(y,...v){const S=[p(y[0])];let P=0;for(;P<v.length;)S.push(i),s(S,v[P]),S.push(i,p(y[++P]));return c(S),new o(S)}e.str=a;function s(y,v){v instanceof o?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]===i){const S=u(y[v-1],y[v+1]);if(S!==void 0){y.splice(v-1,3,S);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:p(Array.isArray(y)?y.join(","):y)}function m(y){return new o(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 o(`.${y}`):n`[${y}]`}e.getProperty=h;function $(y){if(typeof y=="string"&&e.IDENTIFIER.test(y))return new o(`${y}`);throw new Error(`CodeGen: invalid export name: ${y}, use explicit $id name mapping`)}e.getEsmExportName=$;function g(y){return new o(y.toString())}e.regexpCode=g})(yr);var ec={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=yr;class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var o;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),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 i 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=i;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 i(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 v=$.get(h);if(v)return v}else $=this._values[p]=new Map;$.set(h,m);const g=this._scope[p]||(this._scope[p]=[]),y=g.length;return g[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 g=d[h]=d[h]||new Map;$.forEach(y=>{if(g.has(y))return;g.set(y,o.Started);let v=l(y);if(v){const S=this.opts.es5?e.varKinds.var:e.varKinds.const;p=(0,t._)`${p}${S} ${y} = ${v};${this.opts._n}`}else if(v=m?.(y))p=(0,t._)`${p}${v}${this.opts._n}`;else throw new r(y);g.set(y,o.Completed)})}return p}}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=yr,r=ec;var o=yr;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return o._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return o.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return o.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return o.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return o.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return o.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return o.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return o.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 i{optimizeNodes(){return this}optimizeNames(f,_){return this}}class a extends i{constructor(f,_,T){super(),this.varKind=f,this.name=_,this.rhs=T}render({es5:f,_n:_}){const T=f?r.varKinds.var:this.varKind,L=this.rhs===void 0?"":` = ${this.rhs}`;return`${T} ${this.name}${L};`+_}optimizeNames(f,_){if(f[this.name.str])return this.rhs&&(this.rhs=V(this.rhs,f,_)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class s extends i{constructor(f,_,T){super(),this.lhs=f,this.rhs=_,this.sideEffects=T}render({_n:f}){return`${this.lhs} = ${this.rhs};`+f}optimizeNames(f,_){if(!(this.lhs instanceof t.Name&&!f[this.lhs.str]&&!this.sideEffects))return this.rhs=V(this.rhs,f,_),this}get names(){const f=this.lhs instanceof t.Name?{}:{...this.lhs.names};return X(f,this.rhs)}}class c extends s{constructor(f,_,T,L){super(f,T,L),this.op=_}render({_n:f}){return`${this.lhs} ${this.op}= ${this.rhs};`+f}}class u extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`${this.label}:`+f}}class l extends i{constructor(f){super(),this.label=f,this.names={}}render({_n:f}){return`break${this.label?` ${this.label}`:""};`+f}}class d extends i{constructor(f){super(),this.error=f}render({_n:f}){return`throw ${this.error};`+f}get names(){return this.error.names}}class m extends i{constructor(f){super(),this.code=f}render({_n:f}){return`${this.code};`+f}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(f,_){return this.code=V(this.code,f,_),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class p extends i{constructor(f=[]){super(),this.nodes=f}render(f){return this.nodes.reduce((_,T)=>_+T.render(f),"")}optimizeNodes(){const{nodes:f}=this;let _=f.length;for(;_--;){const T=f[_].optimizeNodes();Array.isArray(T)?f.splice(_,1,...T):T?f[_]=T:f.splice(_,1)}return f.length>0?this:void 0}optimizeNames(f,_){const{nodes:T}=this;let L=T.length;for(;L--;){const J=T[L];J.optimizeNames(f,_)||(Oe(f,J.names),T.splice(L,1))}return T.length>0?this:void 0}get names(){return this.nodes.reduce((f,_)=>Q(f,_.names),{})}}class h extends p{render(f){return"{"+f._n+super.render(f)+"}"+f._n}}class $ extends p{}class g extends h{}g.kind="else";class y extends h{constructor(f,_){super(_),this.condition=f}render(f){let _=`if(${this.condition})`+super.render(f);return this.else&&(_+="else "+this.else.render(f)),_}optimizeNodes(){super.optimizeNodes();const f=this.condition;if(f===!0)return this.nodes;let _=this.else;if(_){const T=_.optimizeNodes();_=this.else=Array.isArray(T)?new g(T):T}if(_)return f===!1?_ instanceof y?_:_.nodes:this.nodes.length?this:new y(rt(f),_ instanceof y?[_]:_.nodes);if(!(f===!1||!this.nodes.length))return this}optimizeNames(f,_){var T;if(this.else=(T=this.else)===null||T===void 0?void 0:T.optimizeNames(f,_),!!(super.optimizeNames(f,_)||this.else))return this.condition=V(this.condition,f,_),this}get names(){const f=super.names;return X(f,this.condition),this.else&&Q(f,this.else.names),f}}y.kind="if";class v extends h{}v.kind="for";class S extends v{constructor(f){super(),this.iteration=f}render(f){return`for(${this.iteration})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iteration=V(this.iteration,f,_),this}get names(){return Q(super.names,this.iteration.names)}}class P extends v{constructor(f,_,T,L){super(),this.varKind=f,this.name=_,this.from=T,this.to=L}render(f){const _=f.es5?r.varKinds.var:this.varKind,{name:T,from:L,to:J}=this;return`for(${_} ${T}=${L}; ${T}<${J}; ${T}++)`+super.render(f)}get names(){const f=X(super.names,this.from);return X(f,this.to)}}class N extends v{constructor(f,_,T,L){super(),this.loop=f,this.varKind=_,this.name=T,this.iterable=L}render(f){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(f)}optimizeNames(f,_){if(super.optimizeNames(f,_))return this.iterable=V(this.iterable,f,_),this}get names(){return Q(super.names,this.iterable.names)}}class B extends h{constructor(f,_,T){super(),this.name=f,this.args=_,this.async=T}render(f){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(f)}}B.kind="func";class K extends p{render(f){return"return "+super.render(f)}}K.kind="return";class ue extends h{render(f){let _="try"+super.render(f);return this.catch&&(_+=this.catch.render(f)),this.finally&&(_+=this.finally.render(f)),_}optimizeNodes(){var f,_;return super.optimizeNodes(),(f=this.catch)===null||f===void 0||f.optimizeNodes(),(_=this.finally)===null||_===void 0||_.optimizeNodes(),this}optimizeNames(f,_){var T,L;return super.optimizeNames(f,_),(T=this.catch)===null||T===void 0||T.optimizeNames(f,_),(L=this.finally)===null||L===void 0||L.optimizeNames(f,_),this}get names(){const f=super.names;return this.catch&&Q(f,this.catch.names),this.finally&&Q(f,this.finally.names),f}}class de extends h{constructor(f){super(),this.error=f}render(f){return`catch(${this.error})`+super.render(f)}}de.kind="catch";class xe extends h{render(f){return"finally"+super.render(f)}}xe.kind="finally";class M{constructor(f,_={}){this._values={},this._blockStarts=[],this._constants={},this.opts={..._,_n:_.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,_){const T=this._extScope.value(f,_);return(this._values[T.prefix]||(this._values[T.prefix]=new Set)).add(T),T}getScopeValue(f,_){return this._extScope.getValue(f,_)}scopeRefs(f){return this._extScope.scopeRefs(f,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(f,_,T,L){const J=this._scope.toName(_);return T!==void 0&&L&&(this._constants[J.str]=T),this._leafNode(new a(f,J,T)),J}const(f,_,T){return this._def(r.varKinds.const,f,_,T)}let(f,_,T){return this._def(r.varKinds.let,f,_,T)}var(f,_,T){return this._def(r.varKinds.var,f,_,T)}assign(f,_,T){return this._leafNode(new s(f,_,T))}add(f,_){return this._leafNode(new c(f,e.operators.ADD,_))}code(f){return typeof f=="function"?f():f!==t.nil&&this._leafNode(new m(f)),this}object(...f){const _=["{"];for(const[T,L]of f)_.length>1&&_.push(","),_.push(T),(T!==L||this.opts.es5)&&(_.push(":"),(0,t.addCodeArg)(_,L));return _.push("}"),new t._Code(_)}if(f,_,T){if(this._blockNode(new y(f)),_&&T)this.code(_).else().code(T).endIf();else if(_)this.code(_).endIf();else if(T)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(f){return this._elseNode(new y(f))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(y,g)}_for(f,_){return this._blockNode(f),_&&this.code(_).endFor(),this}for(f,_){return this._for(new S(f),_)}forRange(f,_,T,L,J=this.opts.es5?r.varKinds.var:r.varKinds.let){const pe=this._scope.toName(f);return this._for(new P(J,pe,_,T),()=>L(pe))}forOf(f,_,T,L=r.varKinds.const){const J=this._scope.toName(f);if(this.opts.es5){const pe=_ instanceof t.Name?_:this.var("_arr",_);return this.forRange("_i",0,(0,t._)`${pe}.length`,le=>{this.var(J,(0,t._)`${pe}[${le}]`),T(J)})}return this._for(new N("of",L,J,_),()=>T(J))}forIn(f,_,T,L=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(f,(0,t._)`Object.keys(${_})`,T);const J=this._scope.toName(f);return this._for(new N("in",L,J,_),()=>T(J))}endFor(){return this._endBlockNode(v)}label(f){return this._leafNode(new u(f))}break(f){return this._leafNode(new l(f))}return(f){const _=new K;if(this._blockNode(_),this.code(f),_.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(K)}try(f,_,T){if(!_&&!T)throw new Error('CodeGen: "try" without "catch" and "finally"');const L=new ue;if(this._blockNode(L),this.code(f),_){const J=this.name("e");this._currNode=L.catch=new de(J),_(J)}return T&&(this._currNode=L.finally=new xe,this.code(T)),this._endBlockNode(de,xe)}throw(f){return this._leafNode(new d(f))}block(f,_){return this._blockStarts.push(this._nodes.length),f&&this.code(f).endBlock(_),this}endBlock(f){const _=this._blockStarts.pop();if(_===void 0)throw new Error("CodeGen: not in self-balancing block");const T=this._nodes.length-_;if(T<0||f!==void 0&&T!==f)throw new Error(`CodeGen: wrong number of nodes: ${T} vs ${f} expected`);return this._nodes.length=_,this}func(f,_=t.nil,T,L){return this._blockNode(new B(f,_,T)),L&&this.code(L).endFunc(),this}endFunc(){return this._endBlockNode(B)}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,_){const T=this._currNode;if(T instanceof f||_&&T instanceof _)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${_?`${f.kind}/${_.kind}`:f.kind}"`)}_elseNode(f){const _=this._currNode;if(!(_ instanceof y))throw new Error('CodeGen: "else" without "if"');return this._currNode=_.else=f,this}get _root(){return this._nodes[0]}get _currNode(){const f=this._nodes;return f[f.length-1]}set _currNode(f){const _=this._nodes;_[_.length-1]=f}}e.CodeGen=M;function Q(O,f){for(const _ in f)O[_]=(O[_]||0)+(f[_]||0);return O}function X(O,f){return f instanceof t._CodeOrName?Q(O,f.names):O}function V(O,f,_){if(O instanceof t.Name)return T(O);if(!L(O))return O;return new t._Code(O._items.reduce((J,pe)=>(pe instanceof t.Name&&(pe=T(pe)),pe instanceof t._Code?J.push(...pe._items):J.push(pe),J),[]));function T(J){const pe=_[J.str];return pe===void 0||f[J.str]!==1?J:(delete f[J.str],pe)}function L(J){return J instanceof t._Code&&J._items.some(pe=>pe instanceof t.Name&&f[pe.str]===1&&_[pe.str]!==void 0)}}function Oe(O,f){for(const _ in f)O[_]=(O[_]||0)-(f[_]||0)}function rt(O){return typeof O=="boolean"||typeof O=="number"||O===null?!O:(0,t._)`!${E(O)}`}e.not=rt;const ot=I(e.operators.AND);function Zt(...O){return O.reduce(ot)}e.and=Zt;const St=I(e.operators.OR);function A(...O){return O.reduce(St)}e.or=A;function I(O){return(f,_)=>f===t.nil?_:_===t.nil?f:(0,t._)`${E(f)} ${O} ${E(_)}`}function E(O){return O instanceof t.Name?O:(0,t._)`(${O})`}})(se);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=se,FS=yr;function GS(e){const t={};for(const r of e)t[r]=!0;return t}Z.toHash=GS;function qS(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Kh(e,t),!Wh(t,e.self.RULES.all))}Z.alwaysValidSchema=qS;function Kh(e,t=e.schema){const{opts:r,self:o}=e;if(!r.strictSchema||typeof t=="boolean")return;const n=o.RULES.keywords;for(const i in t)n[i]||tg(e,`unknown keyword: "${i}"`)}Z.checkUnknownRules=Kh;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 JS(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=JS;function VS({topSchemaRef:e,schemaPath:t},r,o,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)(o)}`}Z.schemaRefOrVal=VS;function HS(e){return Xh(decodeURIComponent(e))}Z.unescapeFragment=HS;function KS(e){return encodeURIComponent(tc(e))}Z.escapeFragment=KS;function tc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=tc;function Xh(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=Xh;function WS(e,t){if(Array.isArray(e))for(const r of e)t(r);else t(e)}Z.eachItem=WS;function Yh({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:o}){return(n,i,a,s)=>{const c=a===void 0?i:a instanceof Se.Name?(i instanceof Se.Name?e(n,i,a):t(n,i,a),a):i instanceof Se.Name?(t(n,a,i),i):r(i,a);return s===Se.Name&&!(c instanceof Se.Name)?o(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} || {}`),nc(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&&nc(e,r,t),r}Z.evaluatedPropsToName=Qh;function nc(e,t,r){Object.keys(r).forEach(o=>e.assign((0,Se._)`${t}${(0,Se.getProperty)(o)}`,!0))}Z.setEvaluated=nc;const eg={};function XS(e,t){return e.scopeValue("func",{ref:t,code:eg[t.code]||(eg[t.code]=new FS._Code(t.code))})}Z.useFunc=XS;var rc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(rc||(Z.Type=rc={}));function YS(e,t,r){if(e instanceof Se.Name){const o=t===rc.Num;return r?o?(0,Se._)`"[" + ${e} + "]"`:(0,Se._)`"['" + ${e} + "']"`:o?(0,Se._)`"/" + ${e}`:(0,Se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Se.getProperty)(e).toString():"/"+tc(e)}Z.getErrorPath=YS;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 Go={},ng;function Et(){if(ng)return Go;ng=1,Object.defineProperty(Go,"__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 Go.default=t,Go}var rg;function qo(){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=Z,o=Et();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,S){const{it:P}=g,{gen:N,compositeRule:B,allErrors:K}=P,ue=d(g,y,v);S??(B||K)?c(N,ue):u(P,(0,t._)`[${ue}]`)}e.reportError=n;function i(g,y=e.keywordError,v){const{it:S}=g,{gen:P,compositeRule:N,allErrors:B}=S,K=d(g,y,v);c(P,K),N||B||u(S,o.default.vErrors)}e.reportExtraError=i;function a(g,y){g.assign(o.default.errors,y),g.if((0,t._)`${o.default.vErrors} !== null`,()=>g.if(y,()=>g.assign((0,t._)`${o.default.vErrors}.length`,y),()=>g.assign(o.default.vErrors,null)))}e.resetErrorsCount=a;function s({gen:g,keyword:y,schemaValue:v,data:S,errsCount:P,it:N}){if(P===void 0)throw new Error("ajv implementation error");const B=g.name("err");g.forRange("i",P,o.default.errors,K=>{g.const(B,(0,t._)`${o.default.vErrors}[${K}]`),g.if((0,t._)`${B}.instancePath === undefined`,()=>g.assign((0,t._)`${B}.instancePath`,(0,t.strConcat)(o.default.instancePath,N.errorPath))),g.assign((0,t._)`${B}.schemaPath`,(0,t.str)`${N.errSchemaPath}/${y}`),N.opts.verbose&&(g.assign((0,t._)`${B}.schema`,v),g.assign((0,t._)`${B}.data`,S))})}e.extendErrors=s;function c(g,y){const v=g.const("err",y);g.if((0,t._)`${o.default.vErrors} === null`,()=>g.assign(o.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${o.default.vErrors}.push(${v})`),g.code((0,t._)`${o.default.errors}++`)}function u(g,y){const{gen:v,validateName:S,schemaEnv:P}=g;P.$async?v.throw((0,t._)`new ${g.ValidationError}(${y})`):(v.assign((0,t._)`${S}.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:S}=g.it;return S===!1?(0,t._)`{}`:m(g,y,v)}function m(g,y,v={}){const{gen:S,it:P}=g,N=[p(P,v),h(g,v)];return $(g,y,N),S.object(...N)}function p({errorPath:g},{instancePath:y}){const v=y?(0,t.str)`${g}${(0,r.getErrorPath)(y,r.Type.Str)}`:g;return[o.default.instancePath,(0,t.strConcat)(o.default.instancePath,v)]}function h({keyword:g,it:{errSchemaPath:y}},{schemaPath:v,parentSchema:S}){let P=S?y:(0,t.str)`${y}/${g}`;return v&&(P=(0,t.str)`${P}${(0,r.getErrorPath)(v,r.Type.Str)}`),[l.schemaPath,P]}function $(g,{params:y,message:v},S){const{keyword:P,data:N,schemaValue:B,it:K}=g,{opts:ue,propertyName:de,topSchemaRef:xe,schemaPath:M}=K;S.push([l.keyword,P],[l.params,typeof y=="function"?y(g):y||(0,t._)`{}`]),ue.messages&&S.push([l.message,typeof v=="function"?v(g):v]),ue.verbose&&S.push([l.schema,B],[l.parentSchema,(0,t._)`${xe}${M}`],[o.default.data,N]),de&&S.push([l.propertyName,de])}})(Qs)),Qs}var og;function QS(){if(og)return Ht;og=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.boolOrEmptySchema=Ht.topBoolOrEmptySchema=void 0;const e=qo(),t=se,r=Et(),o={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))}Ht.topBoolOrEmptySchema=n;function i(s,c){const{gen:u,schema:l}=s;l===!1?(u.var(c,!1),a(s)):u.var(c,!0)}Ht.boolOrEmptySchema=i;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,o,void 0,c)}return Ht}var je={},Kt={};Object.defineProperty(Kt,"__esModule",{value:!0}),Kt.getRules=Kt.isJSONType=void 0;const ew=["string","number","integer","boolean","null","object","array"],tw=new Set(ew);function nw(e){return typeof e=="string"&&tw.has(e)}Kt.isJSONType=nw;function rw(){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:{}}}Kt.getRules=rw;var xt={},ig;function ag(){if(ig)return xt;ig=1,Object.defineProperty(xt,"__esModule",{value:!0}),xt.shouldUseRule=xt.shouldUseGroup=xt.schemaHasRulesForType=void 0;function e({schema:o,self:n},i){const a=n.RULES.types[i];return a&&a!==!0&&t(o,a)}xt.schemaHasRulesForType=e;function t(o,n){return n.rules.some(i=>r(o,i))}xt.shouldUseGroup=t;function r(o,n){var i;return o[n.keyword]!==void 0||((i=n.definition.implements)===null||i===void 0?void 0:i.some(a=>o[a]!==void 0))}return xt.shouldUseRule=r,xt}Object.defineProperty(je,"__esModule",{value:!0}),je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;const ow=Kt,iw=ag(),aw=qo(),oe=se,sg=Z;var $n;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})($n||(je.DataType=$n={}));function sw(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=sw;function cg(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(ow.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}je.getJSONTypes=cg;function cw(e,t){const{gen:r,data:o,opts:n}=e,i=uw(t,n.coerceTypes),a=t.length>0&&!(i.length===0&&t.length===1&&(0,iw.schemaHasRulesForType)(e,t[0]));if(a){const s=ic(t,o,n.strictNumbers,$n.Wrong);r.if(s,()=>{i.length?lw(e,t,i):ac(e)})}return a}je.coerceAndCheckDataType=cw;const ug=new Set(["string","number","integer","boolean","null"]);function uw(e,t){return t?e.filter(r=>ug.has(r)||t==="array"&&r==="array"):[]}function lw(e,t,r){const{gen:o,data:n,opts:i}=e,a=o.let("dataType",(0,oe._)`typeof ${n}`),s=o.let("coerced",(0,oe._)`undefined`);i.coerceTypes==="array"&&o.if((0,oe._)`${a} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>o.assign(n,(0,oe._)`${n}[0]`).assign(a,(0,oe._)`typeof ${n}`).if(ic(t,n,i.strictNumbers),()=>o.assign(s,n))),o.if((0,oe._)`${s} !== undefined`);for(const u of r)(ug.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);o.else(),ac(e),o.endIf(),o.if((0,oe._)`${s} !== undefined`,()=>{o.assign(n,s),dw(e,s)});function c(u){switch(u){case"string":o.elseIf((0,oe._)`${a} == "number" || ${a} == "boolean"`).assign(s,(0,oe._)`"" + ${n}`).elseIf((0,oe._)`${n} === null`).assign(s,(0,oe._)`""`);return;case"number":o.elseIf((0,oe._)`${a} == "boolean" || ${n} === null
|
|
72
72
|
|| (${a} == "string" && ${n} && ${n} == +${n})`).assign(s,(0,oe._)`+${n}`);return;case"integer":o.elseIf((0,oe._)`${a} === "boolean" || ${n} === null
|
|
73
73
|
|| (${a} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(s,(0,oe._)`+${n}`);return;case"boolean":o.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":o.elseIf((0,oe._)`${n} === "" || ${n} === 0 || ${n} === false`),o.assign(s,null);return;case"array":o.elseIf((0,oe._)`${a} === "string" || ${a} === "number"
|