@orochibraru/ui 1.0.3 → 1.0.4-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -69,7 +69,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
69
69
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
70
70
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
71
71
  `:`[${n[c]}\r
72
- ]`;continue}if(o+=n[c],n[c]==="\\")s=!0;else if(i&&n[c]==="]")i=!1;else if(!i&&n[c]==="[")i=!0}try{new RegExp(o)}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 o}function ei(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:F(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??he(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:F(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===w.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Qs(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===w.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===w.ZodBranded&&e.keyType._def.type._def.typeName===w.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Ys(e.keyType._def,t);return{...r,propertyNames:o}}return r}function wh(e,t){if(t.mapStrategy==="record")return ei(e,t);let r=F(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||he(t),n=F(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||he(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function kh(e){let t=e.values,n=Object.keys(e.values).filter((s)=>typeof t[t[s]]!=="number").map((s)=>t[s]),o=Array.from(new Set(n.map((s)=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Sh(e){return e.target==="openAi"?void 0:{not:he({...e,currentPath:[...e.currentPath,"not"]})}}function zh(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var vo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Eh(e,t){if(t.target==="openApi3")return Ph(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in vo)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=vo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((s)=>!n.includes(s))],[])};return Ph(e,t)}var Ph=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>F(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Th(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:vo[e.innerType._def.typeName],nullable:!0};return{type:[vo[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=F(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=F(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Rh(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Qu(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)X(r,"minimum",n.value,n.message,t);else X(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;X(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)X(r,"maximum",n.value,n.message,t);else X(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;X(r,"maximum",n.value,n.message,t)}break;case"multipleOf":X(r,"multipleOf",n.value,n.message,t);break}return r}function Oh(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=hS(c);if(u&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();u=!1}let l=F(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(l===void 0)continue;if(n.properties[a]=l,!u)o.push(a)}if(o.length)n.required=o;let i=mS(e,t);if(i!==void 0)n.additionalProperties=i;return n}function mS(e,t){if(e.catchall._def.typeName!=="ZodNever")return F(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 hS(e){try{return e.isOptional()}catch{return!0}}var Ih=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return F(e.innerType._def,t);let r=F(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:he(t)},r]}:he(t)};var Ah=(e,t)=>{if(t.pipeStrategy==="input")return F(e.in._def,t);else if(t.pipeStrategy==="output")return F(e.out._def,t);let r=F(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=F(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function Ch(e,t){return F(e.type._def,t)}function Nh(e,t){let n={type:"array",uniqueItems:!0,items:F(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)X(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)X(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function jh(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>F(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:F(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>F(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Zh(e){return{not:he(e)}}function Mh(e){return he(e)}var Dh=(e,t)=>F(e.innerType._def,t);var qh=(e,t,r)=>{switch(t){case w.ZodString:return Qs(e,r);case w.ZodNumber:return Rh(e,r);case w.ZodObject:return Oh(e,r);case w.ZodBigInt:return mh(e,r);case w.ZodBoolean:return hh();case w.ZodDate:return el(e,r);case w.ZodUndefined:return Zh(r);case w.ZodNull:return zh(r);case w.ZodArray:return fh(e,r);case w.ZodUnion:case w.ZodDiscriminatedUnion:return Eh(e,r);case w.ZodIntersection:return xh(e,r);case w.ZodTuple:return jh(e,r);case w.ZodRecord:return ei(e,r);case w.ZodLiteral:return bh(e,r);case w.ZodEnum:return vh(e);case w.ZodNativeEnum:return kh(e);case w.ZodNullable:return Th(e,r);case w.ZodOptional:return Ih(e,r);case w.ZodMap:return wh(e,r);case w.ZodSet:return Nh(e,r);case w.ZodLazy:return()=>e.getter()._def;case w.ZodPromise:return Ch(e,r);case w.ZodNaN:case w.ZodNever:return Sh(r);case w.ZodEffects:return yh(e,r);case w.ZodAny:return he(r);case w.ZodUnknown:return Mh(r);case w.ZodDefault:return _h(e,r);case w.ZodBranded:return Ys(e,r);case w.ZodReadonly:return Dh(e,r);case w.ZodCatch:return gh(e,r);case w.ZodPipeline:return Ah(e,r);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return((n)=>{return})(t)}};function F(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==lh)return a}if(n&&!r){let a=gS(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let s=qh(e,e.typeName,t),i=typeof s==="function"?F(s(),t):s;if(i)_S(e,t,i);if(t.postProcess){let a=t.postProcess(i,e,t);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var gS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Xs(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),he(t);return t.$refStrategy==="seen"?he(t):void 0}}},_S=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var nl=(e,t)=>{let r=ph(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:F(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??he(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=F(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??he(r),i=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(i!==void 0)s.title=i;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function yS(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function ol(e,t){if(xt(e))return wu(e,{target:yS(t?.target),io:t?.pipeStrategy??"input"});return nl(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function sl(e){let r=Xt(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=en(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function il(e,t){let r=Wt(e,t);if(!r.success)throw r.error;return r.data}var vS=60000;class al{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ws,(t)=>{this._oncancel(t)}),this.setNotificationHandler(Ss,(t)=>{this._onprogress(t)}),this.setRequestHandler(ks,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(zs,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new A(j.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Es,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new A(j.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let i;while(i=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(i.type==="response"||i.type==="error"){let a=i.message,c=a.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(a);else{let l=a,d=new A(l.error.code,l.error.message,l.error.data);u(d)}else{let l=i.type==="response"?"Response":"Error";this._onerror(Error(`${l} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}let s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new A(j.InvalidParams,`Task not found: ${o}`);if(!Yt(s.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(Yt(s.status)){let i=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...i,_meta:{...i._meta,[Jt]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Ts,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new A(j.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Os,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new A(j.InvalidParams,`Task not found: ${t.params.taskId}`);if(Yt(n.status))throw new A(j.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new A(j.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof A)throw n;throw new A(j.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),A.fromError(j.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{if(n?.(o,s),Gn(o)||Lm(o))this._onresponse(o);else if(Ru(o))this._onrequest(o,s);else if(qm(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=A.fromError(j.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Jt]?.taskId,s=n?.sessionId,i=this._taskStore,a=!0,c;if(o&&i&&this._taskMessageQueue&&s!==void 0)a=!1,c=(async()=>{if(!await i.getTask(o,s))throw new A(j.InvalidParams,`Task not found: ${o}`);a=!0})();if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:j.MethodNotFound,message:"Method not found"}};if(o&&c){let f={type:"error",message:p,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,f,s),()=>n?.send(p)).catch((h)=>this._onerror(Error(`Failed to send an error response: ${h}`)))}else if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},n?.sessionId).catch((f)=>this._onerror(Error(`Failed to enqueue error response: ${f}`)));else n?.send(p).catch((f)=>this._onerror(Error(`Failed to send an error response: ${f}`)));return}let u=new AbortController;this._requestHandlerAbortControllers.set(e.id,u);let l=Zm(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,m={signal:u.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(p)=>{if(u.signal.aborted)return;let f={relatedRequestId:e.id};if(o)f.relatedTask={taskId:o};await this.notification(p,f)},sendRequest:async(p,f,h)=>{if(u.signal.aborted)throw new A(j.ConnectionClosed,"Request was cancelled");let g={...h,relatedRequestId:e.id};if(o&&!g.relatedTask)g.relatedTask={taskId:o};let v=g.relatedTask?.taskId??o;if(v&&d)await d.updateTaskStatus(v,"input_required");return await this.request(p,f,g)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:l?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&u.signal.aborted)throw new A(j.ConnectionClosed,"Request was cancelled");if(l)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,m)).then(async(p)=>{if(u.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},n?.sessionId);else await n?.send(f)},async(p)=>{if(u.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:j.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};if(o&&this._taskMessageQueue&&a)await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},n?.sessionId);else await n?.send(f)}).catch((p)=>this._onerror(Error(`Failed to send response: ${p}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===u)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),Gn(e))r(e);else{let s=new A(e.error.code,e.error.message,e.error.data);r(s)}return}let n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(Gn(e)&&e.result&&typeof e.result==="object"){let s=e.result;if(s.task&&typeof s.task==="object"){let i=s.task;if(typeof i.taskId==="string")o=!0,this._taskProgressTokens.set(i.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(Gn(e))n(e);else{let s=A.fromError(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(s){yield{type:"error",error:s instanceof A?s:new A(j.InternalError,String(s))}}return}let o;try{let s=await this.request(e,Ur,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new A(j.InternalError,"Task creation did not return a task");while(!0){let i=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:i},Yt(i.status)){if(i.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(i.status==="failed")yield{type:"error",error:new A(j.InternalError,`Task ${o} failed`)};else if(i.status==="cancelled")yield{type:"error",error:new A(j.InternalError,`Task ${o} was cancelled`)};return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=i.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof A?s:new A(j.InternalError,String(s))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:i,relatedTask:a}=r??{};return new Promise((c,u)=>{let l=(v)=>{u(v)};if(!this._transport){l(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),i)this.assertTaskCapability(e.method)}catch(v){l(v);return}r?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};if(r?.onprogress)this._progressHandlers.set(d,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}};if(i)m.params={...m.params,task:i};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[Jt]:a}};let p=(v)=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch((M)=>this._onerror(Error(`Failed to send cancellation: ${M}`)));let T=v instanceof A?v:new A(j.RequestTimeout,String(v));u(T)};this._responseHandlers.set(d,(v)=>{if(r?.signal?.aborted)return;if(v instanceof Error)return u(v);try{let T=Wt(t,v.result);if(!T.success)u(T.error);else c(T.data)}catch(T){u(T)}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});let f=r?.timeout??vS,h=()=>p(A.fromError(j.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(d,f,r?.maxTotalTimeout,h,r?.resetTimeoutOnProgress??!1);let g=a?.taskId;if(g){let v=(T)=>{let M=this._responseHandlers.get(d);if(M)M(T);else this._onerror(Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(g,{type:"request",message:m,timestamp:Date.now()}).catch((T)=>{this._cleanupTimeout(d),u(T)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch((v)=>{this._cleanupTimeout(d),u(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Ps,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Rs,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Vm,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Jt]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Jt]:t.relatedTask}}};this._transport?.send(i,t).catch((a)=>this._onerror(a))});return}let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Jt]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let r=sl(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let s=il(e,n);return Promise.resolve(t(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=sl(e);this._notificationHandlers.set(r,(n)=>{let o=il(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&Ru(n.message)){let o=n.message.id,s=this._requestResolvers.get(o);if(s)s(new A(j.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e,r);if(o?.pollInterval)n=o.pollInterval}catch{}return new Promise((o,s)=>{if(t.aborted){s(new A(j.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(i),s(new A(j.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new A(j.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,s)=>{await r.storeTaskResult(n,o,s,t);let i=await r.getTask(n,t);if(i){let a=eo.parse({method:"notifications/tasks/status",params:i});if(await this.notification(a),Yt(i.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,s)=>{let i=await r.getTask(n,t);if(!i)throw new A(j.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Yt(i.status))throw new A(j.InvalidParams,`Cannot update task "${n}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,s,t);let a=await r.getTask(n,t);if(a){let c=eo.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Yt(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function Lh(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Fh(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];if(Lh(i)&&Lh(s))r[o]={...i,...s};else r[o]=s}return r}var tb=hd(Wl(),1),rb=hd(eb(),1);function f1(){let e=new tb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return rb.default(e),e}class sd{constructor(e){this._ajv=e??f1()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class id{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some((u)=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some((u)=>u.type==="tool_use");if(s){if(o.some((u)=>u.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter((d)=>d.type==="tool_use").map((d)=>d.id)),l=new Set(o.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(u.size!==l.size||![...u].every((d)=>l.has(d)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},no,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Br,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function nb(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function ob(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class ad extends al{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ro.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new sd,this.setRequestHandler(Au,(r)=>this._oninitialize(r)),this.setNotificationHandler(Cu,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(Lu,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=r.params,i=ro.safeParse(s);if(i.success)this._loggingLevels.set(o,i.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new id(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Fh(this._capabilities,e)}setRequestHandler(e,t){let n=Xt(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=en(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let i=async(a,c)=>{let u=Wt(Hr,a);if(!u.success){let p=u.error instanceof Error?u.error.message:String(u.error);throw new A(j.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=u.data,d=await Promise.resolve(t(a,c));if(l.task){let p=Wt(Ur,d);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new A(j.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let m=Wt(Ms,d);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new A(j.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){ob(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;nb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Cm.includes(t)?t:Eu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},$s)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],a=i.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(i.filter((l)=>l.type==="tool_use").map((l)=>l.id)),u=new Set(n.filter((l)=>l.type==="tool_result").map((l)=>l.toolUseId));if(c.size!==u.size||![...c].every((l)=>u.has(l)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},Fu,t);return this.request({method:"sampling/createMessage",params:e},no,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},Br,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},Br,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let i=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!i.valid)throw new A(j.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(s){if(s instanceof A)throw s;throw new A(j.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Uu,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var ib=Symbol.for("mcp.completable");function cd(e){return!!e&&typeof e==="object"&&ib in e}function ab(e){return e[ib]?.complete}var sb;(function(e){e.Completable="McpCompletable"})(sb||(sb={}));var m1=/^[A-Za-z0-9._-]{1,128}$/;function h1(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!m1.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function g1(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ud(e){let t=h1(e);return g1(e,t.warnings),t.isValid}class ld{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}function _1(e,t){let r=0,n=[e];while(n.length>0){let o=n.pop();if(o===null||typeof o!=="object")continue;if(Array.isArray(o))for(let s of o){if(++r>t)return r;if(s!==null&&typeof s==="object")n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>t)return r;let i=o[s];if(i!==null&&typeof i==="object")n.push(i)}}return r}function y1(e){if(e===void 0||e===1/0)return;if(typeof e!=="number"||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}class pd{constructor(e,t){if(this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ad(e,t),this._maxToolInputElements=y1(t?.maxToolInputElements),t?.capabilities?.tools)this.setToolRequestHandlers();if(t?.capabilities?.resources)this.setResourceRequestHandlers();if(t?.capabilities?.prompts)this.setPromptRequestHandlers()}get experimental(){if(!this._experimental)this._experimental={tasks:new ld(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(yr(Zs)),this.server.assertCanSetRequestHandler(yr(Hr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Zs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=Qr(t.inputSchema);return n?ol(n,{strictUnions:!0,pipeStrategy:"input"}):v1})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=Qr(t.outputSchema);if(n)r.outputSchema=ol(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Hr,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new A(j.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new A(j.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,s="createTask"in r.handler;if((o==="required"||o==="optional")&&!s)throw new A(j.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new A(j.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&s)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,i,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof A){if(r.code===j.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&_1(t,this._maxToolInputElements)>this._maxToolInputElements)throw new A(j.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let o=Qr(e.inputSchema)??e.inputSchema,s=await Gs(o,t??{});if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ws(i);throw new A(j.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return s.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new A(j.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Qr(e.outputSchema),o=await Gs(n,t.structuredContent);if(!o.success){let s="error"in o?o.error:"Unknown error",i=Ws(s);throw new A(j.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let s={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,s));else return await Promise.resolve(n.createTask(s))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,s={...r,taskStore:r.taskStore},i=n?await Promise.resolve(o.createTask(n,s)):await Promise.resolve(o.createTask(s)),a=i.task.taskId,c=i.task,u=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((d)=>setTimeout(d,u));let l=await r.taskStore.getTask(a);if(!l)throw new A(j.InternalError,`Task ${a} not found during polling`);c=l}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(yr(Ds)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ds,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return Wm(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Xm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new A(j.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new A(j.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new A(j.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return Ao;let o=Xt(r.argsSchema)?.[e.params.argument.name];if(!cd(o))return Ao;let s=ab(o);if(!s)return Ao;let i=await s(e.params.argument.value,e.params.context);return ub(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((s)=>s.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return Ao;throw new A(j.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Ao;let o=await n(e.params.argument.value,e.params.context);return ub(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(yr(Is)),this.server.assertCanSetRequestHandler(yr(As)),this.server.assertCanSetRequestHandler(yr(Cs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Is,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,s])=>s.enabled).map(([o,s])=>({uri:o,name:s.name,...s.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let s=await o.resourceTemplate.listCallback(t);for(let i of s.resources)n.push({...o.metadata,...i})}return{resources:[...r,...n]}}),this.server.setRequestHandler(As,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Cs,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new A(j.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let s=o.resourceTemplate.uriTemplate.match(r.toString());if(s)return o.readCallback(r,s,t)}throw new A(j.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(yr(Ns)),this.server.assertCanSetRequestHandler(yr(js)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ns,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?x1(t.argsSchema):void 0}))})),this.server.setRequestHandler(js,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new A(j.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new A(j.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Qr(r.argsSchema),o=await Gs(n,e.params.arguments??{});if(!o.success){let a="error"in o?o.error:"Unknown error",c=Ws(a);throw new A(j.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let s=o.data,i=r.callback;return await Promise.resolve(i(s,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let s={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:(i)=>{if(typeof i.uri<"u"&&i.uri!==r){if(delete this._registeredResources[r],i.uri)this._registeredResources[i.uri]=s}if(typeof i.name<"u")s.name=i.name;if(typeof i.title<"u")s.title=i.title;if(typeof i.metadata<"u")s.metadata=i.metadata;if(typeof i.callback<"u")s.readCallback=i.callback;if(typeof i.enabled<"u")s.enabled=i.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=s,s}_createRegisteredResourceTemplate(e,t,r,n,o){let s={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=s}if(typeof c.title<"u")s.title=c.title;if(typeof c.template<"u")s.resourceTemplate=c.template;if(typeof c.metadata<"u")s.metadata=c.metadata;if(typeof c.callback<"u")s.readCallback=c.callback;if(typeof c.enabled<"u")s.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let i=r.uriTemplate.variableNames;if(Array.isArray(i)&&i.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return s}_createRegisteredPrompt(e,t,r,n,o){let s={title:t,description:r,argsSchema:n===void 0?void 0:Er(n),callback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:(i)=>{if(typeof i.name<"u"&&i.name!==e){if(delete this._registeredPrompts[e],i.name)this._registeredPrompts[i.name]=s}if(typeof i.title<"u")s.title=i.title;if(typeof i.description<"u")s.description=i.description;if(typeof i.argsSchema<"u")s.argsSchema=Er(i.argsSchema);if(typeof i.callback<"u")s.callback=i.callback;if(typeof i.enabled<"u")s.enabled=i.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=s,n){if(Object.values(n).some((a)=>{let c=a instanceof ys?a._def?.innerType:a;return cd(c)}))this.setCompletionRequestHandler()}return s}_createRegisteredTool(e,t,r,n,o,s,i,a,c){ud(e);let u={title:t,description:r,inputSchema:cb(n),outputSchema:cb(o),annotations:s,execution:i,_meta:a,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:(l)=>{if(typeof l.name<"u"&&l.name!==e){if(typeof l.name==="string")ud(l.name);if(delete this._registeredTools[e],l.name)this._registeredTools[l.name]=u}if(typeof l.title<"u")u.title=l.title;if(typeof l.description<"u")u.description=l.description;if(typeof l.paramsSchema<"u")u.inputSchema=Er(l.paramsSchema);if(typeof l.outputSchema<"u")u.outputSchema=Er(l.outputSchema);if(typeof l.callback<"u")u.handler=l.callback;if(typeof l.annotations<"u")u.annotations=l.annotations;if(typeof l._meta<"u")u._meta=l._meta;if(typeof l.enabled<"u")u.enabled=l.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,s;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(dd(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!dd(t[0]))s=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,n,o,s,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:s,outputSchema:i,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,s,i,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],s=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:s}=t,i=this._createRegisteredPrompt(e,n,o,s,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var v1={type:"object",properties:{}};function lb(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function db(e){return"_def"in e||"_zod"in e||lb(e)}function dd(e){if(typeof e!=="object"||e===null)return!1;if(db(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(lb)}function cb(e){if(!e)return;if(dd(e))return Er(e);if(!db(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function x1(e){let t=Xt(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=ah(n),s=ch(n);return{name:r,description:o,required:!s}})}function yr(e){let r=Xt(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=en(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function ub(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ao={completion:{values:[],hasMore:!1}};var pb=["Actions","Forms","Navigation","Overlays","Feedback","Display","Charts","Layout","Appearance","Media","Utilities","Server"];function Hi(e){return Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,[r,n]])=>({slug:t,name:t.charAt(0).toUpperCase()+t.slice(1).replaceAll("-"," "),description:n,category:r}))}var fb={blocks:{label:"Blocks",description:"App-level pieces the apps shared copies of.",docs:Hi({"accent-toggle":["Appearance","The accent presets: a swatch strip on desktop, labelled rows on phones."],"auth-shell":["Layout","Centered sign-in layout: heading, optional brand and footer."],"bottom-nav":["Navigation","The phone tab bar: top-level destinations, the current one lit."],"command-palette":["Overlays","A ⌘K search over pages and actions: a dialog on desktop, a tall drawer on phones."],"copy-field":["Forms","Monospace value with a copy button and a promise toast."],"document-title":["Layout","The tab's <title> from the page title, suffixed with the app."],"empty-state":["Feedback","Icon, title, subtitle and an action for an empty list."],"error-page":["Layout","Status, message and error id, with a link back home."],fab:["Actions","Floating action button above the phone tab bar, with a haptic tap."],"icon-button":["Actions","Round icon button whose tooltip is its accessible name."],"install-prompt":["Overlays","One-time PWA install sheet: native prompt or the steps."],"music-player":["Media","An audio player bar with a queue: play, skip, seek and volume."],"nav-cards":["Navigation","Phone-only list of a section's tabs as cards."],"new-password-fields":["Forms","New password with a reveal button, a strength meter and the rules it must pass."],"option-group":["Forms","Radio cards for a settings choice, each with an icon or swatch."],"otp-field":["Forms","A one-time code: digits only, autofilled from SMS, posted as one field."],"password-input":["Forms","A password field with a button to reveal what was typed."],"responsive-sheet":["Overlays","A dialog on desktop, a bottom drawer on phones."],"setting-switch":["Forms","Labelled switch row for settings forms."],"stat-card":["Display","Glass card with an icon, a value and a hint, optionally a link."],stepper:["Navigation","A multi-step flow: labelled markers on desktop, a progress bar and the current step on phones."],"tab-nav":["Navigation","Pill tab bar of links, the current page's tab highlighted."],"tab-section":["Navigation","Tabbed section layout: tabs on desktop, nav cards on phones."],"time-range-picker":["Charts","Time range presets, plus a custom range in a calendar popover or a phone drawer."],"time-series-chart":["Charts","Line, area or bar chart over time: axes, readout, touch scrubbing and a data table."],"theme-picker":["Appearance","System, light and dark as radio cards."],"theme-toggle":["Appearance","System, light and dark: an icon strip on desktop, three rows on phones."],"top-loading-bar":["Feedback","Progress bar during SvelteKit navigations."],"video-player":["Media","A video player: scrubbing, chapters, subtitles, speed, fullscreen, gestures and shortcuts."]})},components:{label:"Components",description:"One import, data in: the everyday controls without assembling primitives.",docs:Hi({"file-dropzone":["Forms","Drop or pick files, folders too: type and size limits, a list to review, posted with the form."],breadcrumbs:["Navigation","A trail of pages from an array, collapsing the middle into a menu on phones."],"confirm-dialog":["Overlays","Ask before acting: waits on an async confirm, a drawer on phones."],menu:["Overlays","Actions from an array: a dropdown on desktop, a drawer of big rows on phones."],pagination:["Navigation","Page numbers from a total and a page size, prev and next on phones."],tabs:["Navigation","Tabs from an array, scrolling sideways when they run out of room."],form:["Forms","Fields from an array, laid out and posted to a form action, with errors under each field."],checkbox:["Forms","One checkbox with its label and description, the whole row tappable."],"checkbox-list":["Forms","Options in, a labelled group of checkboxes out, posting every checked value."],"radio-list":["Forms","Pick one option from a list or from cards, with a legend and errors."],"segmented-control":["Forms","A single choice as equal segments that fold to icons when space runs out."],switch:["Forms","A labelled switch row that posts true when on."],accordion:["Display","Questions and answers from an array: plain text or a snippet per item."],"avatar-group":["Display","Overlapping avatars with initials, a +N count and names in tooltips."],"bar-list":["Charts","A ranked list with proportional bars, links and a show-more toggle."],"data-table":["Display","Columns and rows in, a sortable table out: cards on phones, links per row."],"date-field":["Forms","A date with its label: calendar in a popover, a drawer on phones, ISO value."],select:["Forms","Options in, a labelled select out: searchable, and a drawer on phones."],"status-badge":["Feedback","A status pill with a tone, a dot and an optional pulse for live states."],textarea:["Forms","A multi-line field with its label, error and an optional character counter."],input:["Forms","A text field with its label, description and error in one: passwords get a reveal button."]})},primitives:{label:"Primitives",description:"The shadcn-svelte components, as the apps customised them.",docs:Hi({accordion:["Display","Stacked sections that expand one or several at a time."],alert:["Feedback","A callout for something the reader should notice."],"alert-dialog":["Overlays","A modal that asks to confirm before something drastic."],avatar:["Display","A user's picture, falling back to initials."],badge:["Display","A small label for a status or a count."],breadcrumb:["Navigation","The path from the root to the current page."],button:["Actions","Every button variant and size."],"button-group":["Actions","Buttons joined into one control."],calendar:["Forms","A month grid to pick a date."],card:["Display","A surface with a header, content and footer."],checkbox:["Forms","A checkbox, with a label through Field."],command:["Overlays","A searchable list of commands, also as a palette."],"context-menu":["Overlays","A menu on right click or long press."],dialog:["Overlays","A modal window over the page."],drawer:["Overlays","A panel sliding up from the bottom, made for phones."],"dropdown-menu":["Overlays","A menu opened from a button."],empty:["Feedback","The parts of an empty state, to compose your own."],field:["Forms","Label, control, description and error, laid out together."],input:["Forms","A text input; password managers stay off unless asked."],"input-group":["Forms","An input with addons: icons, text or buttons."],"input-otp":["Forms","One box per digit for a one-time code."],label:["Forms","A label for a form control."],menubar:["Navigation","A desktop-style bar of menus."],pagination:["Navigation","Links to the pages of a long list."],popover:["Overlays","Floating content anchored to a trigger."],progress:["Feedback","How far along something is."],"radio-group":["Forms","Pick one of a few options."],"range-calendar":["Forms","A month grid to pick a start and an end date."],resizable:["Layout","Panes split by a draggable handle."],"scroll-area":["Layout","A scrolling box with a styled scrollbar."],select:["Forms","Pick one option from a list."],separator:["Layout","A line between groups of content."],sheet:["Overlays","A panel sliding in from a side of the screen."],sidebar:["Navigation","The app sidebar: groups, menus, collapsing to icons."],skeleton:["Feedback","Placeholder shapes while content loads."],slider:["Forms","Pick a value or a range by dragging."],sonner:["Feedback","Toasts, styled by the theme."],spinner:["Feedback","An indeterminate loading indicator."],switch:["Forms","An on or off toggle."],table:["Display","Rows and columns of data."],tabs:["Navigation","In-page tabs that switch panels without navigating."],textarea:["Forms","A multi-line text input."],toggle:["Actions","A button that stays pressed."],"toggle-group":["Actions","Toggles where one or several stay pressed."],tooltip:["Overlays","A hint on hover or focus."]})},modules:{label:"Modules",description:"Helpers for toasts, titles, appearance and haptics, and the server side: logs, traces and hooks.",docs:Hi({hooks:["Server","SvelteKit hooks: one log line per request, and unexpected errors logged, traced and given an id."],logger:["Server","Scoped server logs as coloured text or JSON lines that carry the active trace id."],telemetry:["Server","OpenTelemetry tracing over OTLP, with SvelteKit's own handle, load and action spans."],appearance:["Appearance","Apply a saved accent, theme, font and corners to <html>."],haptics:["Feedback","A short vibration on tap, success or error."],"page-title":["Layout","One page title for the app bar, the header and the tab."],password:["Forms","The password rules and strength score, for the form and the server alike."],toast:["Feedback","Narrate a form action through one promise toast."],utils:["Utilities","cn to merge Tailwind classes, and the prop helper types."]})}};function Bi(){return Object.entries(fb).flatMap(([e,{docs:t}])=>t.map((r)=>({group:e,doc:r})))}function hb(e){let[t,r]=e.includes("/")?e.split("/",2):[void 0,e];return Bi().find((n)=>n.doc.slug===r&&(!t||n.group===t))}function b1(e,t){return e==="components"?`examples/components/${t}`:`examples/${t}`}function $1(e,t){if(e==="blocks"||e==="components")return`${e}/${t}`;return w1.has(t)?`server/${t}`:t}var w1=new Set(["hooks","logger","telemetry"]);function gb(e){let t=e.toLowerCase().split(/\s+/).filter(Boolean);return Bi().filter(({doc:r})=>{let n=`${r.slug} ${r.category} ${r.description}`.toLowerCase();return t.every((o)=>n.includes(o))})}function k1(e,t,r){let n=Object.entries(e.files);if(r==="tab-section")return n.filter(([a])=>a.startsWith("routes/section/")).map(([a,c])=>({name:a.slice(7),code:mb(c)}));let o=b1(t,r),s=e.files[`${o}.svelte`],i=n.flatMap(([a,c])=>a.startsWith(`${o}.`)&&a!==`${o}.svelte`?[{name:a.slice(`${o}.`.length),code:c}]:[]);if(s?.includes("<script"))i.unshift({name:"Example.svelte",code:s});return i.map(({name:a,code:c})=>({name:a,code:mb(c)}))}function mb(e){return e.replaceAll(/#lib\/components\/ui\/([\w-]+)\/index\.js/g,"@orochibraru/ui/$1").replaceAll(/#lib\/components\/blocks\/([\w-]+)\.svelte/g,"@orochibraru/ui/blocks/$1").replaceAll(/#lib\/components\/kit\/([\w-]+)\.svelte/g,"@orochibraru/ui/components/$1").replaceAll(/#lib\/((?:server\/)?[\w-]+)(?:\.svelte)?\.js/g,"@orochibraru/ui/$1")}function _b(e,{group:t,doc:r}){let n=$1(t,r.slug),o=k1(e,t,r.slug).map((s)=>`### ${s.name}
72
+ ]`;continue}if(o+=n[c],n[c]==="\\")s=!0;else if(i&&n[c]==="]")i=!1;else if(!i&&n[c]==="[")i=!0}try{new RegExp(o)}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 o}function ei(e,t){if(t.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(t.target==="openApi3"&&e.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:F(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??he(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:F(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===w.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Qs(e.keyType._def,t);return{...r,propertyNames:o}}else if(e.keyType?._def.typeName===w.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===w.ZodBranded&&e.keyType._def.type._def.typeName===w.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Ys(e.keyType._def,t);return{...r,propertyNames:o}}return r}function wh(e,t){if(t.mapStrategy==="record")return ei(e,t);let r=F(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||he(t),n=F(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||he(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function kh(e){let t=e.values,n=Object.keys(e.values).filter((s)=>typeof t[t[s]]!=="number").map((s)=>t[s]),o=Array.from(new Set(n.map((s)=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Sh(e){return e.target==="openAi"?void 0:{not:he({...e,currentPath:[...e.currentPath,"not"]})}}function zh(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var vo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Eh(e,t){if(t.target==="openApi3")return Ph(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every((n)=>(n._def.typeName in vo)&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=vo[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every((n)=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every((n)=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter((s)=>!n.includes(s))],[])};return Ph(e,t)}var Ph=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>F(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter((n)=>!!n&&(!t.strictUnions||typeof n==="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Th(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length)){if(t.target==="openApi3")return{type:vo[e.innerType._def.typeName],nullable:!0};return{type:[vo[e.innerType._def.typeName],"null"]}}if(t.target==="openApi3"){let n=F(e.innerType._def,{...t,currentPath:[...t.currentPath]});if(n&&"$ref"in n)return{allOf:[n],nullable:!0};return n&&{...n,nullable:!0}}let r=F(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Rh(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Qu(r,"type",n.message,t);break;case"min":if(t.target==="jsonSchema7")if(n.inclusive)X(r,"minimum",n.value,n.message,t);else X(r,"exclusiveMinimum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMinimum=!0;X(r,"minimum",n.value,n.message,t)}break;case"max":if(t.target==="jsonSchema7")if(n.inclusive)X(r,"maximum",n.value,n.message,t);else X(r,"exclusiveMaximum",n.value,n.message,t);else{if(!n.inclusive)r.exclusiveMaximum=!0;X(r,"maximum",n.value,n.message,t)}break;case"multipleOf":X(r,"multipleOf",n.value,n.message,t);break}return r}function Oh(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=hS(c);if(u&&r){if(c._def.typeName==="ZodOptional")c=c._def.innerType;if(!c.isNullable())c=c.nullable();u=!1}let l=F(c._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});if(l===void 0)continue;if(n.properties[a]=l,!u)o.push(a)}if(o.length)n.required=o;let i=mS(e,t);if(i!==void 0)n.additionalProperties=i;return n}function mS(e,t){if(e.catchall._def.typeName!=="ZodNever")return F(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 hS(e){try{return e.isOptional()}catch{return!0}}var Ih=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return F(e.innerType._def,t);let r=F(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:he(t)},r]}:he(t)};var Ah=(e,t)=>{if(t.pipeStrategy==="input")return F(e.in._def,t);else if(t.pipeStrategy==="output")return F(e.out._def,t);let r=F(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=F(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter((o)=>o!==void 0)}};function Ch(e,t){return F(e.type._def,t)}function Nh(e,t){let n={type:"array",uniqueItems:!0,items:F(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};if(e.minSize)X(n,"minItems",e.minSize.value,e.minSize.message,t);if(e.maxSize)X(n,"maxItems",e.maxSize.value,e.maxSize.message,t);return n}function jh(e,t){if(e.rest)return{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>F(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:F(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})};else return{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>F(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Zh(e){return{not:he(e)}}function Mh(e){return he(e)}var Dh=(e,t)=>F(e.innerType._def,t);var qh=(e,t,r)=>{switch(t){case w.ZodString:return Qs(e,r);case w.ZodNumber:return Rh(e,r);case w.ZodObject:return Oh(e,r);case w.ZodBigInt:return mh(e,r);case w.ZodBoolean:return hh();case w.ZodDate:return el(e,r);case w.ZodUndefined:return Zh(r);case w.ZodNull:return zh(r);case w.ZodArray:return fh(e,r);case w.ZodUnion:case w.ZodDiscriminatedUnion:return Eh(e,r);case w.ZodIntersection:return xh(e,r);case w.ZodTuple:return jh(e,r);case w.ZodRecord:return ei(e,r);case w.ZodLiteral:return bh(e,r);case w.ZodEnum:return vh(e);case w.ZodNativeEnum:return kh(e);case w.ZodNullable:return Th(e,r);case w.ZodOptional:return Ih(e,r);case w.ZodMap:return wh(e,r);case w.ZodSet:return Nh(e,r);case w.ZodLazy:return()=>e.getter()._def;case w.ZodPromise:return Ch(e,r);case w.ZodNaN:case w.ZodNever:return Sh(r);case w.ZodEffects:return yh(e,r);case w.ZodAny:return he(r);case w.ZodUnknown:return Mh(r);case w.ZodDefault:return _h(e,r);case w.ZodBranded:return Ys(e,r);case w.ZodReadonly:return Dh(e,r);case w.ZodCatch:return gh(e,r);case w.ZodPipeline:return Ah(e,r);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return((n)=>{return})(t)}};function F(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==lh)return a}if(n&&!r){let a=gS(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let s=qh(e,e.typeName,t),i=typeof s==="function"?F(s(),t):s;if(i)_S(e,t,i);if(t.postProcess){let a=t.postProcess(i,e,t);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var gS=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Xs(t.currentPath,e.path)};case"none":case"seen":{if(e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r))return console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),he(t);return t.$refStrategy==="seen"?he(t):void 0}}},_S=(e,t,r)=>{if(e.description){if(r.description=e.description,t.markdownDescription)r.markdownDescription=e.description}return r};var nl=(e,t)=>{let r=ph(t),n=typeof t==="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,l])=>({...c,[u]:F(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??he(r)}),{}):void 0,o=typeof t==="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=F(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??he(r),i=typeof t==="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;if(i!==void 0)s.title=i;if(r.flags.hasReferencedOpenAiAnyType){if(!n)n={};if(!n[r.openAiAnyTypeName])n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};if(r.target==="jsonSchema7")a.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")a.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in a)||("oneOf"in a)||("allOf"in a)||("type"in a)&&Array.isArray(a.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return a};function yS(e){if(!e)return"draft-7";if(e==="jsonSchema7"||e==="draft-7")return"draft-7";if(e==="jsonSchema2019-09"||e==="draft-2020-12")return"draft-2020-12";return"draft-7"}function ol(e,t){if(xt(e))return wu(e,{target:yS(t?.target),io:t?.pipeStrategy??"input"});return nl(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function sl(e){let r=Xt(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=en(r);if(typeof n!=="string")throw Error("Schema method literal must be a string");return n}function il(e,t){let r=Wt(e,t);if(!r.success)throw r.error;return r.data}var vS=60000;class al{constructor(e){if(this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ws,(t)=>{this._oncancel(t)}),this.setNotificationHandler(Ss,(t)=>{this._onprogress(t)}),this.setRequestHandler(ks,(t)=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore)this.setRequestHandler(zs,async(t,r)=>{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new A(j.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(Es,async(t,r)=>{let n=async()=>{let o=t.params.taskId;if(!await this._taskStore.getTask(o,r.sessionId))throw new A(j.InvalidParams,`Task not found: ${o}`);if(this._taskMessageQueue){let i;while(i=await this._taskMessageQueue.dequeue(o,r.sessionId)){if(i.type==="response"||i.type==="error"){let a=i.message,c=a.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(a);else{let l=a,d=new A(l.error.code,l.error.message,l.error.data);u(d)}else{let l=i.type==="response"?"Response":"Error";this._onerror(Error(`${l} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}let s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new A(j.InvalidParams,`Task not found: ${o}`);if(!Yt(s.status))return await this._waitForTaskUpdate(o,r.signal,r.sessionId),await n();if(Yt(s.status)){let i=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o,r.sessionId),{...i,_meta:{...i._meta,[Jt]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(Ts,async(t,r)=>{try{let{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new A(j.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(Os,async(t,r)=>{try{let n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new A(j.InvalidParams,`Task not found: ${t.params.taskId}`);if(Yt(n.status))throw new A(j.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId,r.sessionId);let o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new A(j.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){if(n instanceof A)throw n;throw new A(j.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}})}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),A.fromError(j.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);if(t)clearTimeout(t.timeoutId),this._timeoutInfo.delete(e)}async connect(e){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=(o)=>{r?.(o),this._onerror(o)};let n=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{if(n?.(o,s),Gn(o)||Lm(o))this._onresponse(o);else if(Ru(o))this._onrequest(o,s);else if(qm(o))this._onnotification(o);else this._onerror(Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let t=A.fromError(j.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;if(t===void 0)return;Promise.resolve().then(()=>t(e)).catch((r)=>this._onerror(Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[Jt]?.taskId,s=n?.sessionId,i=this._taskStore,a=!0,c;if(o&&i&&this._taskMessageQueue&&s!==void 0)a=!1,c=(async()=>{if(!await i.getTask(o,s))throw new A(j.InvalidParams,`Task not found: ${o}`);a=!0})();if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:j.MethodNotFound,message:"Method not found"}};if(o&&c){let f={type:"error",message:p,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(o,f,s),()=>n?.send(p)).catch((h)=>this._onerror(Error(`Failed to send an error response: ${h}`)))}else if(o&&this._taskMessageQueue)this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},n?.sessionId).catch((f)=>this._onerror(Error(`Failed to enqueue error response: ${f}`)));else n?.send(p).catch((f)=>this._onerror(Error(`Failed to send an error response: ${f}`)));return}let u=new AbortController;this._requestHandlerAbortControllers.set(e.id,u);let l=Zm(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,m={signal:u.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async(p)=>{if(u.signal.aborted)return;let f={relatedRequestId:e.id};if(o)f.relatedTask={taskId:o};await this.notification(p,f)},sendRequest:async(p,f,h)=>{if(u.signal.aborted)throw new A(j.ConnectionClosed,"Request was cancelled");let g={...h,relatedRequestId:e.id};if(o&&!g.relatedTask)g.relatedTask={taskId:o};let v=g.relatedTask?.taskId??o;if(v&&d)await d.updateTaskStatus(v,"input_required");return await this.request(p,f,g)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:d,taskRequestedTtl:l?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&u.signal.aborted)throw new A(j.ConnectionClosed,"Request was cancelled");if(l)this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,m)).then(async(p)=>{if(u.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};if(o&&this._taskMessageQueue)await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},n?.sessionId);else await n?.send(f)},async(p)=>{if(u.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:j.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};if(o&&this._taskMessageQueue&&a)await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},n?.sessionId);else await n?.send(f)}).catch((p)=>this._onerror(Error(`Failed to send response: ${p}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(e.id)===u)this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(a);return}o(r)}_onresponse(e){let t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),Gn(e))r(e);else{let s=new A(e.error.code,e.error.message,e.error.data);r(s)}return}let n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(Gn(e)&&e.result&&typeof e.result==="object"){let s=e.result;if(s.task&&typeof s.task==="object"){let i=s.task;if(typeof i.taskId==="string")o=!0,this._taskProgressTokens.set(i.taskId,t)}}if(!o)this._progressHandlers.delete(t);if(Gn(e))n(e);else{let s=A.fromError(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){let{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(s){yield{type:"error",error:s instanceof A?s:new A(j.InternalError,String(s))}}return}let o;try{let s=await this.request(e,Ur,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new A(j.InternalError,"Task creation did not return a task");while(!0){let i=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:i},Yt(i.status)){if(i.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};else if(i.status==="failed")yield{type:"error",error:new A(j.InternalError,`Task ${o} failed`)};else if(i.status==="cancelled")yield{type:"error",error:new A(j.InternalError,`Task ${o} was cancelled`)};return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}let a=i.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((c)=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof A?s:new A(j.InternalError,String(s))}}}request(e,t,r){let{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:i,relatedTask:a}=r??{};return new Promise((c,u)=>{let l=(v)=>{u(v)};if(!this._transport){l(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(e.method),i)this.assertTaskCapability(e.method)}catch(v){l(v);return}r?.signal?.throwIfAborted();let d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};if(r?.onprogress)this._progressHandlers.set(d,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}};if(i)m.params={...m.params,task:i};if(a)m.params={...m.params,_meta:{...m.params?._meta||{},[Jt]:a}};let p=(v)=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch((M)=>this._onerror(Error(`Failed to send cancellation: ${M}`)));let T=v instanceof A?v:new A(j.RequestTimeout,String(v));u(T)};this._responseHandlers.set(d,(v)=>{if(r?.signal?.aborted)return;if(v instanceof Error)return u(v);try{let T=Wt(t,v.result);if(!T.success)u(T.error);else c(T.data)}catch(T){u(T)}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});let f=r?.timeout??vS,h=()=>p(A.fromError(j.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(d,f,r?.maxTotalTimeout,h,r?.resetTimeoutOnProgress??!1);let g=a?.taskId;if(g){let v=(T)=>{let M=this._responseHandlers.get(d);if(M)M(T);else this._onerror(Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(g,{type:"request",message:m,timestamp:Date.now()}).catch((T)=>{this._cleanupTimeout(d),u(T)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch((v)=>{this._cleanupTimeout(d),u(v)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},Ps,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},Rs,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},Vm,t)}async notification(e,t){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);let r=t?.relatedTask?.taskId;if(r){let i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Jt]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};if(t?.relatedTask)i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Jt]:t.relatedTask}}};this._transport?.send(i,t).catch((a)=>this._onerror(a))});return}let s={...e,jsonrpc:"2.0"};if(t?.relatedTask)s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Jt]:t.relatedTask}}};await this._transport.send(s,t)}setRequestHandler(e,t){let r=sl(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{let s=il(e,n);return Promise.resolve(t(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let r=sl(e);this._notificationHandlers.set(r,(n)=>{let o=il(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);if(t!==void 0)this._progressHandlers.delete(t),this._taskProgressTokens.delete(e)}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,t);for(let n of r)if(n.type==="request"&&Ru(n.message)){let o=n.message.id,s=this._requestResolvers.get(o);if(s)s(new A(j.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o);else this._onerror(Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1000;try{let o=await this._taskStore?.getTask(e,r);if(o?.pollInterval)n=o.pollInterval}catch{}return new Promise((o,s)=>{if(t.aborted){s(new A(j.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);t.addEventListener("abort",()=>{clearTimeout(i),s(new A(j.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let r=this._taskStore;if(!r)throw Error("No task store configured");return{createTask:async(n)=>{if(!e)throw Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async(n)=>{let o=await r.getTask(n,t);if(!o)throw new A(j.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,s)=>{await r.storeTaskResult(n,o,s,t);let i=await r.getTask(n,t);if(i){let a=eo.parse({method:"notifications/tasks/status",params:i});if(await this.notification(a),Yt(i.status))this._cleanupTaskProgressHandler(n)}},getTaskResult:(n)=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,s)=>{let i=await r.getTask(n,t);if(!i)throw new A(j.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Yt(i.status))throw new A(j.InvalidParams,`Cannot update task "${n}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,s,t);let a=await r.getTask(n,t);if(a){let c=eo.parse({method:"notifications/tasks/status",params:a});if(await this.notification(c),Yt(a.status))this._cleanupTaskProgressHandler(n)}},listTasks:(n)=>r.listTasks(n,t)}}}function Lh(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function Fh(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];if(Lh(i)&&Lh(s))r[o]={...i,...s};else r[o]=s}return r}var tb=hd(Wl(),1),rb=hd(eb(),1);function f1(){let e=new tb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return rb.default(e),e}class sd{constructor(e){this._ajv=e??f1()}getValidator(e){let t="$id"in e&&typeof e.$id==="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return(r)=>{if(t(r))return{valid:!0,data:r,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}class id{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some((u)=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some((u)=>u.type==="tool_use");if(s){if(o.some((u)=>u.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!c)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter((d)=>d.type==="tool_use").map((d)=>d.id)),l=new Set(o.filter((d)=>d.type==="tool_result").map((d)=>d.toolUseId));if(u.size!==l.size||![...u].every((d)=>l.has(d)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},no,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),n=e.mode??"form";switch(n){case"url":{if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let o=n==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Br,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}function nb(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function ob(e,t,r){if(!e)throw Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}class ad extends al{constructor(e,t){super(t);if(this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ro.options.map((r,n)=>[r,n])),this.isMessageIgnored=(r,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new sd,this.setRequestHandler(Au,(r)=>this._oninitialize(r)),this.setNotificationHandler(Cu,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(Lu,async(r,n)=>{let o=n.sessionId||n.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=r.params,i=ro.safeParse(s);if(i.success)this._loggingLevels.set(o,i.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new id(this)};return this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=Fh(this._capabilities,e)}setRequestHandler(e,t){let n=Xt(e)?.method;if(!n)throw Error("Schema is missing a method literal");let o=en(n);if(typeof o!=="string")throw Error("Schema method literal must be a string");if(o==="tools/call"){let i=async(a,c)=>{let u=Wt(Hr,a);if(!u.success){let p=u.error instanceof Error?u.error.message:String(u.error);throw new A(j.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=u.data,d=await Promise.resolve(t(a,c));if(l.task){let p=Wt(Ur,d);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new A(j.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let m=Wt(Ms,d);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new A(j.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(!this._capabilities)return;switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){ob(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){if(!this._capabilities)return;nb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Cm.includes(t)?t:Eu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},$s)}async createMessage(e,t){if(e.tools||e.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(e.messages.length>0){let r=e.messages[e.messages.length-1],n=Array.isArray(r.content)?r.content:[r.content],o=n.some((c)=>c.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],a=i.some((c)=>c.type==="tool_use");if(o){if(n.some((c)=>c.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!a)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(a){let c=new Set(i.filter((l)=>l.type==="tool_use").map((l)=>l.id)),u=new Set(n.filter((l)=>l.type==="tool_result").map((l)=>l.toolUseId));if(c.size!==u.size||![...c].every((l)=>u.has(l)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(e.tools)return this.request({method:"sampling/createMessage",params:e},Fu,t);return this.request({method:"sampling/createMessage",params:e},no,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let n=e;return this.request({method:"elicitation/create",params:n},Br,t)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let n=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:n},Br,t);if(o.action==="accept"&&o.content&&n.requestedSchema)try{let i=this._jsonSchemaValidator.getValidator(n.requestedSchema)(o.content);if(!i.valid)throw new A(j.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(s){if(s instanceof A)throw s;throw new A(j.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return o}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Uu,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging){if(!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var ib=Symbol.for("mcp.completable");function cd(e){return!!e&&typeof e==="object"&&ib in e}function ab(e){return e[ib]?.complete}var sb;(function(e){e.Completable="McpCompletable"})(sb||(sb={}));var m1=/^[A-Za-z0-9._-]{1,128}$/;function h1(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" "))t.push("Tool name contains spaces, which may cause parsing issues");if(e.includes(","))t.push("Tool name contains commas, which may cause parsing issues");if(e.startsWith("-")||e.endsWith("-"))t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(e.startsWith(".")||e.endsWith("."))t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!m1.test(e)){let r=e.split("").filter((n)=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map((n)=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function g1(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function ud(e){let t=h1(e);return g1(e,t.warnings),t.isValid}class ld{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}}function _1(e,t){let r=0,n=[e];while(n.length>0){let o=n.pop();if(o===null||typeof o!=="object")continue;if(Array.isArray(o))for(let s of o){if(++r>t)return r;if(s!==null&&typeof s==="object")n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>t)return r;let i=o[s];if(i!==null&&typeof i==="object")n.push(i)}}return r}function y1(e){if(e===void 0||e===1/0)return;if(typeof e!=="number"||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}class pd{constructor(e,t){if(this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ad(e,t),this._maxToolInputElements=y1(t?.maxToolInputElements),t?.capabilities?.tools)this.setToolRequestHandlers();if(t?.capabilities?.resources)this.setResourceRequestHandlers();if(t?.capabilities?.prompts)this.setPromptRequestHandlers()}get experimental(){if(!this._experimental)this._experimental={tasks:new ld(this)};return this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(yr(Zs)),this.server.assertCanSetRequestHandler(yr(Hr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Zs,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=Qr(t.inputSchema);return n?ol(n,{strictUnions:!0,pipeStrategy:"input"}):v1})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=Qr(t.outputSchema);if(n)r.outputSchema=ol(n,{strictUnions:!0,pipeStrategy:"output"})}return r})})),this.server.setRequestHandler(Hr,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new A(j.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new A(j.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,o=r.execution?.taskSupport,s="createTask"in r.handler;if((o==="required"||o==="optional")&&!s)throw new A(j.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!n)throw new A(j.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!n&&s)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),a=await this.executeToolHandler(r,i,t);if(n)return a;return await this.validateToolOutput(r,a,e.params.name),a}catch(r){if(r instanceof A){if(r.code===j.UrlElicitationRequired)throw r}return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&_1(t,this._maxToolInputElements)>this._maxToolInputElements)throw new A(j.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let o=Qr(e.inputSchema)??e.inputSchema,s=await Gs(o,t??{});if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ws(i);throw new A(j.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${a}`)}return s.data}async validateToolOutput(e,t,r){if(!e.outputSchema)return;if(!("content"in t))return;if(t.isError)return;if(!t.structuredContent)throw new A(j.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=Qr(e.outputSchema),o=await Gs(n,t.structuredContent);if(!o.success){let s="error"in o?o.error:"Unknown error",i=Ws(s);throw new A(j.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw Error("No task store provided.");let s={...r,taskStore:r.taskStore};if(e.inputSchema)return await Promise.resolve(n.createTask(t,s));else return await Promise.resolve(n.createTask(s))}if(e.inputSchema)return await Promise.resolve(n(t,r));else return await Promise.resolve(n(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),o=e.handler,s={...r,taskStore:r.taskStore},i=n?await Promise.resolve(o.createTask(n,s)):await Promise.resolve(o.createTask(s)),a=i.task.taskId,c=i.task,u=c.pollInterval??5000;while(c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled"){await new Promise((d)=>setTimeout(d,u));let l=await r.taskStore.getTask(a);if(!l)throw new A(j.InternalError,`Task ${a} not found during polling`);c=l}return await r.taskStore.getTaskResult(a)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(yr(Ds)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ds,async(e)=>{switch(e.params.ref.type){case"ref/prompt":return Wm(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Xm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new A(j.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new A(j.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new A(j.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return Ao;let o=Xt(r.argsSchema)?.[e.params.argument.name];if(!cd(o))return Ao;let s=ab(o);if(!s)return Ao;let i=await s(e.params.argument.value,e.params.context);return ub(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find((s)=>s.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return Ao;throw new A(j.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Ao;let o=await n(e.params.argument.value,e.params.context);return ub(o)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(yr(Is)),this.server.assertCanSetRequestHandler(yr(As)),this.server.assertCanSetRequestHandler(yr(Cs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Is,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([o,s])=>s.enabled).map(([o,s])=>({uri:o,name:s.name,...s.metadata})),n=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let s=await o.resourceTemplate.listCallback(t);for(let i of s.resources)n.push({...o.metadata,...i})}return{resources:[...r,...n]}}),this.server.setRequestHandler(As,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Cs,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new A(j.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let o of Object.values(this._registeredResourceTemplates)){let s=o.resourceTemplate.uriTemplate.match(r.toString());if(s)return o.readCallback(r,s,t)}throw new A(j.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(yr(Ns)),this.server.assertCanSetRequestHandler(yr(js)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Ns,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?x1(t.argsSchema):void 0}))})),this.server.setRequestHandler(js,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new A(j.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new A(j.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=Qr(r.argsSchema),o=await Gs(n,e.params.arguments??{});if(!o.success){let a="error"in o?o.error:"Unknown error",c=Ws(a);throw new A(j.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${c}`)}let s=o.data,i=r.callback;return await Promise.resolve(i(s,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0}resource(e,t,...r){let n;if(typeof r[0]==="object")n=r.shift();let o=r[0];if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let s=this._createRegisteredResource(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,t,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,t,r,n){if(typeof t==="string"){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,t,r,n,o){let s={name:e,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:(i)=>{if(typeof i.uri<"u"&&i.uri!==r){if(delete this._registeredResources[r],i.uri)this._registeredResources[i.uri]=s}if(typeof i.name<"u")s.name=i.name;if(typeof i.title<"u")s.title=i.title;if(typeof i.metadata<"u")s.metadata=i.metadata;if(typeof i.callback<"u")s.readCallback=i.callback;if(typeof i.enabled<"u")s.enabled=i.enabled;this.sendResourceListChanged()}};return this._registeredResources[r]=s,s}_createRegisteredResourceTemplate(e,t,r,n,o){let s={resourceTemplate:r,title:t,metadata:n,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:(c)=>{if(typeof c.name<"u"&&c.name!==e){if(delete this._registeredResourceTemplates[e],c.name)this._registeredResourceTemplates[c.name]=s}if(typeof c.title<"u")s.title=c.title;if(typeof c.template<"u")s.resourceTemplate=c.template;if(typeof c.metadata<"u")s.metadata=c.metadata;if(typeof c.callback<"u")s.readCallback=c.callback;if(typeof c.enabled<"u")s.enabled=c.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let i=r.uriTemplate.variableNames;if(Array.isArray(i)&&i.some((c)=>!!r.completeCallback(c)))this.setCompletionRequestHandler();return s}_createRegisteredPrompt(e,t,r,n,o){let s={title:t,description:r,argsSchema:n===void 0?void 0:Er(n),callback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:(i)=>{if(typeof i.name<"u"&&i.name!==e){if(delete this._registeredPrompts[e],i.name)this._registeredPrompts[i.name]=s}if(typeof i.title<"u")s.title=i.title;if(typeof i.description<"u")s.description=i.description;if(typeof i.argsSchema<"u")s.argsSchema=Er(i.argsSchema);if(typeof i.callback<"u")s.callback=i.callback;if(typeof i.enabled<"u")s.enabled=i.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[e]=s,n){if(Object.values(n).some((a)=>{let c=a instanceof ys?a._def?.innerType:a;return cd(c)}))this.setCompletionRequestHandler()}return s}_createRegisteredTool(e,t,r,n,o,s,i,a,c){ud(e);let u={title:t,description:r,inputSchema:cb(n),outputSchema:cb(o),annotations:s,execution:i,_meta:a,handler:c,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:(l)=>{if(typeof l.name<"u"&&l.name!==e){if(typeof l.name==="string")ud(l.name);if(delete this._registeredTools[e],l.name)this._registeredTools[l.name]=u}if(typeof l.title<"u")u.title=l.title;if(typeof l.description<"u")u.description=l.description;if(typeof l.paramsSchema<"u")u.inputSchema=Er(l.paramsSchema);if(typeof l.outputSchema<"u")u.outputSchema=Er(l.outputSchema);if(typeof l.callback<"u")u.handler=l.callback;if(typeof l.annotations<"u")u.annotations=l.annotations;if(typeof l._meta<"u")u._meta=l._meta;if(typeof l.enabled<"u")u.enabled=l.enabled;this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r,n,o,s;if(typeof t[0]==="string")r=t.shift();if(t.length>1){let a=t[0];if(dd(a)){if(n=t.shift(),t.length>1&&typeof t[0]==="object"&&t[0]!==null&&!dd(t[0]))s=t.shift()}else if(typeof a==="object"&&a!==null){if(Object.values(a).some((c)=>typeof c==="object"&&c!==null))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,n,o,s,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:n,description:o,inputSchema:s,outputSchema:i,annotations:a,_meta:c}=t;return this._createRegisteredTool(e,n,o,s,i,a,{taskSupport:"forbidden"},c,r)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let r;if(typeof t[0]==="string")r=t.shift();let n;if(t.length>1)n=t.shift();let o=t[0],s=this._createRegisteredPrompt(e,void 0,r,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:n,description:o,argsSchema:s}=t,i=this._createRegisteredPrompt(e,n,o,s,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var v1={type:"object",properties:{}};function lb(e){return e!==null&&typeof e==="object"&&"parse"in e&&typeof e.parse==="function"&&"safeParse"in e&&typeof e.safeParse==="function"}function db(e){return"_def"in e||"_zod"in e||lb(e)}function dd(e){if(typeof e!=="object"||e===null)return!1;if(db(e))return!1;if(Object.keys(e).length===0)return!0;return Object.values(e).some(lb)}function cb(e){if(!e)return;if(dd(e))return Er(e);if(!db(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}function x1(e){let t=Xt(e);if(!t)return[];return Object.entries(t).map(([r,n])=>{let o=ah(n),s=ch(n);return{name:r,description:o,required:!s}})}function yr(e){let r=Xt(e)?.method;if(!r)throw Error("Schema is missing a method literal");let n=en(r);if(typeof n==="string")return n;throw Error("Schema method literal must be a string")}function ub(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ao={completion:{values:[],hasMore:!1}};var pb=["Actions","Forms","Navigation","Overlays","Feedback","Display","Charts","Layout","Appearance","Media","Utilities","Server"];function Hi(e){return Object.entries(e).toSorted(([t],[r])=>t.localeCompare(r)).map(([t,[r,n]])=>({slug:t,name:t.charAt(0).toUpperCase()+t.slice(1).replaceAll("-"," "),description:n,category:r}))}var fb={blocks:{label:"Blocks",description:"App-level pieces the apps shared copies of.",docs:Hi({"accent-toggle":["Appearance","The accent presets: a swatch strip on desktop, labelled rows on phones."],"auth-shell":["Layout","Centered sign-in layout: heading, optional brand and footer."],"bottom-nav":["Navigation","The phone tab bar: top-level destinations, the current one lit."],"command-palette":["Overlays","A ⌘K search over pages and actions: a dialog on desktop, a tall drawer on phones."],"copy-field":["Forms","Monospace value with a copy button and a promise toast."],"document-title":["Layout","The tab's <title> from the page title, suffixed with the app."],"empty-state":["Feedback","Icon, title, subtitle and an action for an empty list."],"error-page":["Layout","Status, message and error id, with a link back home."],fab:["Actions","Floating action button above the phone tab bar, with a haptic tap."],"icon-button":["Actions","Round icon button whose tooltip is its accessible name."],"install-prompt":["Overlays","One-time PWA install sheet: native prompt or the steps."],"music-player":["Media","An audio player bar with a queue: play, skip, seek and volume."],"nav-cards":["Navigation","Phone-only list of a section's tabs as cards."],"new-password-fields":["Forms","New password with a reveal button, a strength meter and the rules it must pass."],"option-group":["Forms","Radio cards for a settings choice, each with an icon or swatch."],"otp-field":["Forms","A one-time code: digits only, autofilled from SMS, posted as one field."],"password-input":["Forms","A password field with a button to reveal what was typed."],"responsive-sheet":["Overlays","A dialog on desktop, a bottom drawer on phones."],"setting-switch":["Forms","Labelled switch row for settings forms."],"stat-card":["Display","Glass card with an icon, a value and a hint, optionally a link."],stepper:["Navigation","A multi-step flow: labelled markers on desktop, a progress bar and the current step on phones."],"tab-nav":["Navigation","Pill tab bar of links, the current page's tab highlighted."],"tab-section":["Navigation","Tabbed section layout: tabs on desktop, nav cards on phones."],"time-range-picker":["Charts","Time range presets, plus a custom range in a calendar popover or a phone drawer."],"time-series-chart":["Charts","Line, area or bar chart over time: axes, readout, touch scrubbing and a data table."],"theme-picker":["Appearance","System, light and dark as radio cards."],"theme-toggle":["Appearance","System, light and dark: an icon strip on desktop, three rows on phones."],"top-loading-bar":["Feedback","Progress bar during SvelteKit navigations."],"video-player":["Media","A video player: scrubbing, chapters, subtitles, speed, fullscreen, gestures and shortcuts."]})},components:{label:"Components",description:"One import, data in: the everyday controls without assembling primitives.",docs:Hi({"file-dropzone":["Forms","Drop or pick files, folders too: type and size limits, a list to review, posted with the form."],breadcrumbs:["Navigation","A trail of pages from an array, collapsing the middle into a menu on phones."],"confirm-dialog":["Overlays","Ask before acting: waits on an async confirm, a drawer on phones."],menu:["Overlays","Actions from an array: a dropdown on desktop, a drawer of big rows on phones."],pagination:["Navigation","Page numbers from a total and a page size, prev and next on phones."],tabs:["Navigation","Tabs from an array, scrolling sideways when they run out of room."],form:["Forms","Fields from an array, laid out and posted to a form action, with errors under each field."],checkbox:["Forms","One checkbox with its label and description, the whole row tappable."],"checkbox-list":["Forms","Options in, a labelled group of checkboxes out, posting every checked value."],"radio-list":["Forms","Pick one option from a list or from cards, with a legend and errors."],"segmented-control":["Forms","A single choice as equal segments that fold to icons when space runs out."],switch:["Forms","A labelled switch row that posts true when on."],accordion:["Display","Questions and answers from an array: plain text or a snippet per item."],"avatar-group":["Display","Overlapping avatars with initials, a +N count and names in tooltips."],"bar-list":["Charts","A ranked list with proportional bars, links and a show-more toggle."],"data-table":["Display","Columns and rows in, a sortable table out: cards on phones, links per row."],"date-field":["Forms","A date with its label: calendar in a popover, a drawer on phones, ISO value."],select:["Forms","Options in, a labelled select out: searchable, and a drawer on phones."],"status-badge":["Feedback","A status pill with a tone, a dot and an optional pulse for live states."],textarea:["Forms","A multi-line field with its label, error and an optional character counter."],input:["Forms","A text field with its label, description and error in one: passwords get a reveal button."]})},primitives:{label:"Primitives",description:"The shadcn-svelte components, as the apps customised them.",docs:Hi({accordion:["Display","Stacked sections that expand one or several at a time."],alert:["Feedback","A callout for something the reader should notice."],"alert-dialog":["Overlays","A modal that asks to confirm before something drastic."],avatar:["Display","A user's picture, falling back to initials."],badge:["Display","A small label for a status or a count."],breadcrumb:["Navigation","The path from the root to the current page."],button:["Actions","Every button variant and size, and its loading state."],"button-group":["Actions","Buttons joined into one control."],calendar:["Forms","A month grid to pick a date."],card:["Display","A surface with a header, content and footer."],checkbox:["Forms","A checkbox, with a label through Field."],command:["Overlays","A searchable list of commands, also as a palette."],"context-menu":["Overlays","A menu on right click or long press."],dialog:["Overlays","A modal window over the page."],drawer:["Overlays","A panel sliding up from the bottom, made for phones."],"dropdown-menu":["Overlays","A menu opened from a button."],empty:["Feedback","The parts of an empty state, to compose your own."],field:["Forms","Label, control, description and error, laid out together."],input:["Forms","A text input; password managers stay off unless asked."],"input-group":["Forms","An input with addons: icons, text or buttons."],"input-otp":["Forms","One box per digit for a one-time code."],label:["Forms","A label for a form control."],menubar:["Navigation","A desktop-style bar of menus."],pagination:["Navigation","Links to the pages of a long list."],popover:["Overlays","Floating content anchored to a trigger."],progress:["Feedback","How far along something is."],"radio-group":["Forms","Pick one of a few options."],"range-calendar":["Forms","A month grid to pick a start and an end date."],resizable:["Layout","Panes split by a draggable handle."],"scroll-area":["Layout","A scrolling box with a styled scrollbar."],select:["Forms","Pick one option from a list."],separator:["Layout","A line between groups of content."],sheet:["Overlays","A panel sliding in from a side of the screen."],sidebar:["Navigation","The app sidebar: groups, menus, collapsing to icons."],skeleton:["Feedback","Placeholder shapes while content loads."],slider:["Forms","Pick a value or a range by dragging."],sonner:["Feedback","Toasts, styled by the theme."],spinner:["Feedback","An indeterminate loading indicator."],switch:["Forms","An on or off toggle."],table:["Display","Rows and columns of data."],tabs:["Navigation","In-page tabs that switch panels without navigating."],textarea:["Forms","A multi-line text input."],toggle:["Actions","A button that stays pressed."],"toggle-group":["Actions","Toggles where one or several stay pressed."],tooltip:["Overlays","A hint on hover or focus."]})},modules:{label:"Modules",description:"Helpers for toasts, titles, appearance and haptics, and the server side: logs, traces and hooks.",docs:Hi({hooks:["Server","SvelteKit hooks: one log line per request, and unexpected errors logged, traced and given an id."],logger:["Server","Scoped server logs as coloured text or JSON lines that carry the active trace id."],telemetry:["Server","OpenTelemetry tracing over OTLP, with SvelteKit's own handle, load and action spans."],appearance:["Appearance","Apply a saved accent, theme, font and corners to <html>."],haptics:["Feedback","A short vibration on tap, success or error."],"page-title":["Layout","One page title for the app bar, the header and the tab."],password:["Forms","The password rules and strength score, for the form and the server alike."],toast:["Feedback","Narrate a form action through one promise toast."],utils:["Utilities","cn to merge Tailwind classes, and the prop helper types."]})}};function Bi(){return Object.entries(fb).flatMap(([e,{docs:t}])=>t.map((r)=>({group:e,doc:r})))}function hb(e){let[t,r]=e.includes("/")?e.split("/",2):[void 0,e];return Bi().find((n)=>n.doc.slug===r&&(!t||n.group===t))}function b1(e,t){return e==="components"?`examples/components/${t}`:`examples/${t}`}function $1(e,t){if(e==="blocks"||e==="components")return`${e}/${t}`;return w1.has(t)?`server/${t}`:t}var w1=new Set(["hooks","logger","telemetry"]);function gb(e){let t=e.toLowerCase().split(/\s+/).filter(Boolean);return Bi().filter(({doc:r})=>{let n=`${r.slug} ${r.category} ${r.description}`.toLowerCase();return t.every((o)=>n.includes(o))})}function k1(e,t,r){let n=Object.entries(e.files);if(r==="tab-section")return n.filter(([a])=>a.startsWith("routes/section/")).map(([a,c])=>({name:a.slice(7),code:mb(c)}));let o=b1(t,r),s=e.files[`${o}.svelte`],i=n.flatMap(([a,c])=>a.startsWith(`${o}.`)&&a!==`${o}.svelte`?[{name:a.slice(`${o}.`.length),code:c}]:[]);if(s?.includes("<script"))i.unshift({name:"Example.svelte",code:s});return i.map(({name:a,code:c})=>({name:a,code:mb(c)}))}function mb(e){return e.replaceAll(/#lib\/components\/ui\/([\w-]+)\/index\.js/g,"@orochibraru/ui/$1").replaceAll(/#lib\/components\/blocks\/([\w-]+)\.svelte/g,"@orochibraru/ui/blocks/$1").replaceAll(/#lib\/components\/kit\/([\w-]+)\.svelte/g,"@orochibraru/ui/components/$1").replaceAll(/#lib\/((?:server\/)?[\w-]+)(?:\.svelte)?\.js/g,"@orochibraru/ui/$1")}function _b(e,{group:t,doc:r}){let n=$1(t,r.slug),o=k1(e,t,r.slug).map((s)=>`### ${s.name}
73
73
 
74
74
  \`\`\`${s.name.endsWith(".ts")?"ts":"svelte"}
75
75
  ${s.code.trimEnd()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orochibraru/ui",
3
- "version": "1.0.3",
3
+ "version": "1.0.4-canary.1",
4
4
  "description": "Svelte 5 components and theme shared by OpenCount, LocalAssistant, Homerun, Sergio's, Nuvio Web and Penombre.",
5
5
  "license": "MIT",
6
6
  "repository": {