@agentica/chat 0.16.9 → 0.17.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/assets/VendorConfigurationMovie-BmCyGR_z.js +4821 -0
- package/dist/assets/bbs/{index-B3ZMce__.js → index-jIN7wNcM.js} +1 -1
- package/dist/assets/index-BQXlvTX0.js +1 -0
- package/dist/assets/shopping/{index.html-CQZL56Nt.js → index.html-CHYFc9N4.js} +1 -1
- package/dist/assets/sse-Dla1ik5p.js +5 -0
- package/dist/assets/stdio-CygwPk2F.js +3 -0
- package/dist/assets/types-Co05Usx1.js +1 -0
- package/dist/assets/uploader/{index.html-B2oZle3K.js → index.html-DhuBJO7y.js} +1 -1
- package/dist/bbs/index.html +2 -2
- package/dist/shopping/index.html +2 -2
- package/dist/uploader/index.html +2 -2
- package/package.json +2 -2
- package/dist/assets/VendorConfigurationMovie-BIxuM71E.js +0 -4823
- package/dist/assets/index-BTLcqlbp.js +0 -1
- package/dist/assets/sse-Dwr9hmTq.js +0 -5
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as T,o as C,p as H,M as m,E as _,q as R,r as E,s as S,t as v,w as I,x as y,y as N,z as $,D as M,R as P,J as O,K as L}from"./VendorConfigurationMovie-BIxuM71E.js";import"./client-B3aq8qpT.js";const k=6e4;class x{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this.setNotificationHandler(T,r=>{const t=this._requestHandlerAbortControllers.get(r.params.requestId);t==null||t.abort(r.params.reason)}),this.setNotificationHandler(C,r=>{this._onprogress(r)}),this.setRequestHandler(H,r=>({}))}_setupTimeout(e,r,t,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:t,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const t=Date.now()-r.startTime;if(r.maxTotalTimeout&&t>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new m(_.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:t});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=r=>{this._onerror(r)},this._transport.onmessage=r=>{"method"in r?"id"in r?this._onrequest(r):this._onnotification(r):this._onresponse(r)},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);const t=new m(_.ConnectionClosed,"Connection closed");for(const s of r.values())s(t)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const t=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(s=>this._onerror(new Error(`Uncaught error in notification handler: ${s}`)))}_onrequest(e){var r,t,s;const o=(r=this._requestHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackRequestHandler;if(o===void 0){(t=this._transport)===null||t===void 0||t.send({jsonrpc:"2.0",id:e.id,error:{code:_.MethodNotFound,message:"Method not found"}}).catch(n=>this._onerror(new Error(`Failed to send an error response: ${n}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const c={signal:i.signal,sessionId:(s=this._transport)===null||s===void 0?void 0:s.sessionId};Promise.resolve().then(()=>o(e,c)).then(n=>{var l;if(!i.signal.aborted)return(l=this._transport)===null||l===void 0?void 0:l.send({result:n,jsonrpc:"2.0",id:e.id})},n=>{var l,u;if(!i.signal.aborted)return(l=this._transport)===null||l===void 0?void 0:l.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(n.code)?n.code:_.InternalError,message:(u=n.message)!==null&&u!==void 0?u:"Internal error"}})}).catch(n=>this._onerror(new Error(`Failed to send response: ${n}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...t}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const i=this._responseHandlers.get(s),c=this._timeoutInfo.get(s);if(c&&i&&c.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(n){i(n);return}o(t)}_onresponse(e){const r=Number(e.id),t=this._responseHandlers.get(r);if(t===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),"result"in e)t(e);else{const s=new m(e.error.code,e.error.message,e.error.data);t(s)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,t){return new Promise((s,o)=>{var i,c,n,l,u;if(!this._transport){o(new Error("Not connected"));return}((i=this._options)===null||i===void 0?void 0:i.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(c=t==null?void 0:t.signal)===null||c===void 0||c.throwIfAborted();const d=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:d};t!=null&&t.onprogress&&(this._progressHandlers.set(d,t.onprogress),b.params={...e.params,_meta:{progressToken:d}});const g=a=>{var h;this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),(h=this._transport)===null||h===void 0||h.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(a)}}).catch(p=>this._onerror(new Error(`Failed to send cancellation: ${p}`))),o(a)};this._responseHandlers.set(d,a=>{var h;if(!(!((h=t==null?void 0:t.signal)===null||h===void 0)&&h.aborted)){if(a instanceof Error)return o(a);try{const p=r.parse(a.result);s(p)}catch(p){o(p)}}}),(n=t==null?void 0:t.signal)===null||n===void 0||n.addEventListener("abort",()=>{var a;g((a=t==null?void 0:t.signal)===null||a===void 0?void 0:a.reason)});const w=(l=t==null?void 0:t.timeout)!==null&&l!==void 0?l:k,q=()=>g(new m(_.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(d,w,t==null?void 0:t.maxTotalTimeout,q,(u=t==null?void 0:t.resetTimeoutOnProgress)!==null&&u!==void 0?u:!1),this._transport.send(b).catch(a=>{this._cleanupTimeout(d),o(a)})})}async notification(e){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r={...e,jsonrpc:"2.0"};await this._transport.send(r)}setRequestHandler(e,r){const t=e.shape.method.value;this.assertRequestHandlerCapability(t),this._requestHandlers.set(t,(s,o)=>Promise.resolve(r(e.parse(s),o)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,t=>Promise.resolve(r(e.parse(t))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function A(f,e){return Object.entries(e).reduce((r,[t,s])=>(s&&typeof s=="object"?r[t]=r[t]?{...r[t],...s}:s:r[t]=s,r),{...f})}class j extends x{constructor(e,r){var t;super(r),this._clientInfo=e,this._capabilities=(t=r==null?void 0:r.capabilities)!==null&&t!==void 0?t:{}}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=A(this._capabilities,e)}assertCapability(e,r){var t;if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){await super.connect(e);try{const t=await this.request({method:"initialize",params:{protocolVersion:R,capabilities:this._capabilities,clientInfo:this._clientInfo}},E,r);if(t===void 0)throw new Error(`Server sent invalid initialize result: ${t}`);if(!S.includes(t.protocolVersion))throw new Error(`Server's protocol version is not supported: ${t.protocolVersion}`);this._serverCapabilities=t.capabilities,this._serverVersion=t.serverInfo,this._instructions=t.instructions,await this.notification({method:"notifications/initialized"})}catch(t){throw this.close(),t}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,t,s,o,i;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},v,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},I,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},v,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},y,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},N,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},$,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},M,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},P,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},v,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},v,r)}async callTool(e,r=O,t){return this.request({method:"tools/call",params:e},r,t)}async listTools(e,r){return this.request({method:"tools/list",params:e},L,r)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}export{j as Client};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{q as se,N as ie,Q as oe,U as ne,W as ae,X as he}from"./VendorConfigurationMovie-BIxuM71E.js";import"./client-B3aq8qpT.js";class K extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}function z(n){}function ce(n){if(typeof n=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=z,onError:t=z,onRetry:r=z,onComment:i}=n;let s="",o=!0,c,h="",u="";function L(l){const f=o?l.replace(/^\xEF\xBB\xBF/,""):l,[y,H]=le(`${s}${f}`);for(const D of y)O(D);s=H,o=!1}function O(l){if(l===""){$();return}if(l.startsWith(":")){i&&i(l.slice(l.startsWith(": ")?2:1));return}const f=l.indexOf(":");if(f!==-1){const y=l.slice(0,f),H=l[f+1]===" "?2:1,D=l.slice(f+H);x(y,D,l);return}x(l,"",l)}function x(l,f,y){switch(l){case"event":u=f;break;case"data":h=`${h}${f}
|
|
2
|
-
`;break;case"id":c=f.includes("\0")?void 0:f;break;case"retry":/^\d+$/.test(f)?r(parseInt(f,10)):t(new K(`Invalid \`retry\` value: "${f}"`,{type:"invalid-retry",value:f,line:y}));break;default:t(new K(`Unknown field "${l.length>20?`${l.slice(0,20)}…`:l}"`,{type:"unknown-field",field:l,value:f,line:y}));break}}function $(){h.length>0&&e({id:c,event:u||void 0,data:h.endsWith(`
|
|
3
|
-
`)?h.slice(0,-1):h}),c=void 0,h="",u=""}function A(l={}){s&&l.consume&&O(s),o=!0,c=void 0,h="",u="",s=""}return{feed:L,reset:A}}function le(n){const e=[];let t="",r=0;for(;r<n.length;){const i=n.indexOf("\r",r),s=n.indexOf(`
|
|
4
|
-
`,r);let o=-1;if(i!==-1&&s!==-1?o=Math.min(i,s):i!==-1?o=i:s!==-1&&(o=s),o===-1){t=n.slice(r);break}else{const c=n.slice(r,o);e.push(c),r=o+1,n[r-1]==="\r"&&n[r]===`
|
|
5
|
-
`&&r++}}return[e,t]}class Y extends Event{constructor(e,t){var r,i;super(e),this.code=(r=t==null?void 0:t.code)!=null?r:void 0,this.message=(i=t==null?void 0:t.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(ee(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(ee(this),t)}}function de(n){const e=globalThis.DOMException;return typeof e=="function"?new e(n,"SyntaxError"):new SyntaxError(n)}function V(n){return n instanceof Error?"errors"in n&&Array.isArray(n.errors)?n.errors.map(V).join(", "):"cause"in n&&n.cause instanceof Error?`${n}: ${V(n.cause)}`:n.message:`${n}`}function ee(n){return{type:n.type,message:n.message,code:n.code,defaultPrevented:n.defaultPrevented,cancelable:n.cancelable,timeStamp:n.timeStamp}}var re=n=>{throw TypeError(n)},X=(n,e,t)=>e.has(n)||re("Cannot "+t),a=(n,e,t)=>(X(n,e,"read from private field"),t?t.call(n):e.get(n)),p=(n,e,t)=>e.has(n)?re("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),d=(n,e,t,r)=>(X(n,e,"write to private field"),e.set(n,t),t),v=(n,e,t)=>(X(n,e,"access private method"),t),_,g,m,N,W,R,k,U,E,T,C,S,P,w,q,G,B,te,Z,j,I,J,Q;class M extends EventTarget{constructor(e,t){var r,i;super(),p(this,w),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,p(this,_),p(this,g),p(this,m),p(this,N),p(this,W),p(this,R),p(this,k),p(this,U,null),p(this,E),p(this,T),p(this,C,null),p(this,S,null),p(this,P,null),p(this,G,async s=>{var o;a(this,T).reset();const{body:c,redirected:h,status:u,headers:L}=s;if(u===204){v(this,w,I).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(h?d(this,m,new URL(s.url)):d(this,m,void 0),u!==200){v(this,w,I).call(this,`Non-200 status code (${u})`,u);return}if(!(L.get("content-type")||"").startsWith("text/event-stream")){v(this,w,I).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(a(this,_)===this.CLOSED)return;d(this,_,this.OPEN);const O=new Event("open");if((o=a(this,P))==null||o.call(this,O),this.dispatchEvent(O),typeof c!="object"||!c||!("getReader"in c)){v(this,w,I).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}const x=new TextDecoder,$=c.getReader();let A=!0;do{const{done:l,value:f}=await $.read();f&&a(this,T).feed(x.decode(f,{stream:!l})),l&&(A=!1,a(this,T).reset(),v(this,w,J).call(this))}while(A)}),p(this,B,s=>{d(this,E,void 0),!(s.name==="AbortError"||s.type==="aborted")&&v(this,w,J).call(this,V(s))}),p(this,Z,s=>{typeof s.id=="string"&&d(this,U,s.id);const o=new MessageEvent(s.event||"message",{data:s.data,origin:a(this,m)?a(this,m).origin:a(this,g).origin,lastEventId:s.id||""});a(this,S)&&(!s.event||s.event==="message")&&a(this,S).call(this,o),this.dispatchEvent(o)}),p(this,j,s=>{d(this,R,s)}),p(this,Q,()=>{d(this,k,void 0),a(this,_)===this.CONNECTING&&v(this,w,q).call(this)});try{if(e instanceof URL)d(this,g,e);else if(typeof e=="string")d(this,g,new URL(e,ue()));else throw new Error("Invalid URL")}catch{throw de("An invalid or illegal string was specified")}d(this,T,ce({onEvent:a(this,Z),onRetry:a(this,j)})),d(this,_,this.CONNECTING),d(this,R,3e3),d(this,W,(r=t==null?void 0:t.fetch)!=null?r:globalThis.fetch),d(this,N,(i=t==null?void 0:t.withCredentials)!=null?i:!1),v(this,w,q).call(this)}get readyState(){return a(this,_)}get url(){return a(this,g).href}get withCredentials(){return a(this,N)}get onerror(){return a(this,C)}set onerror(e){d(this,C,e)}get onmessage(){return a(this,S)}set onmessage(e){d(this,S,e)}get onopen(){return a(this,P)}set onopen(e){d(this,P,e)}addEventListener(e,t,r){const i=t;super.addEventListener(e,i,r)}removeEventListener(e,t,r){const i=t;super.removeEventListener(e,i,r)}close(){a(this,k)&&clearTimeout(a(this,k)),a(this,_)!==this.CLOSED&&(a(this,E)&&a(this,E).abort(),d(this,_,this.CLOSED),d(this,E,void 0))}}_=new WeakMap,g=new WeakMap,m=new WeakMap,N=new WeakMap,W=new WeakMap,R=new WeakMap,k=new WeakMap,U=new WeakMap,E=new WeakMap,T=new WeakMap,C=new WeakMap,S=new WeakMap,P=new WeakMap,w=new WeakSet,q=function(){d(this,_,this.CONNECTING),d(this,E,new AbortController),a(this,W)(a(this,g),v(this,w,te).call(this)).then(a(this,G)).catch(a(this,B))},G=new WeakMap,B=new WeakMap,te=function(){var n;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...a(this,U)?{"Last-Event-ID":a(this,U)}:void 0},cache:"no-store",signal:(n=a(this,E))==null?void 0:n.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Z=new WeakMap,j=new WeakMap,I=function(n,e){var t;a(this,_)!==this.CLOSED&&d(this,_,this.CLOSED);const r=new Y("error",{code:e,message:n});(t=a(this,C))==null||t.call(this,r),this.dispatchEvent(r)},J=function(n,e){var t;if(a(this,_)===this.CLOSED)return;d(this,_,this.CONNECTING);const r=new Y("error",{code:e,message:n});(t=a(this,C))==null||t.call(this,r),this.dispatchEvent(r),d(this,k,setTimeout(a(this,Q),a(this,R)))},Q=new WeakMap,M.CONNECTING=0,M.OPEN=1,M.CLOSED=2;function ue(){const n="document"in globalThis?globalThis.document:void 0;return n&&typeof n=="object"&&"baseURI"in n&&typeof n.baseURI=="string"?n.baseURI:void 0}class b extends Error{constructor(e){super(e??"Unauthorized")}}async function F(n,{serverUrl:e,authorizationCode:t}){const r=await fe(e);let i=await Promise.resolve(n.clientInformation());if(!i){if(t!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!n.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const h=await ve(e,{metadata:r,clientMetadata:n.clientMetadata});await n.saveClientInformation(h),i=h}if(t!==void 0){const h=await n.codeVerifier(),u=await _e(e,{metadata:r,clientInformation:i,authorizationCode:t,codeVerifier:h,redirectUri:n.redirectUrl});return await n.saveTokens(u),"AUTHORIZED"}const s=await n.tokens();if(s!=null&&s.refresh_token)try{const h=await we(e,{metadata:r,clientInformation:i,refreshToken:s.refresh_token});return await n.saveTokens(h),"AUTHORIZED"}catch(h){console.error("Could not refresh OAuth tokens:",h)}const{authorizationUrl:o,codeVerifier:c}=await pe(e,{metadata:r,clientInformation:i,redirectUrl:n.redirectUrl});return await n.saveCodeVerifier(c),await n.redirectToAuthorization(o),"REDIRECT"}async function fe(n,e){var t;const r=new URL("/.well-known/oauth-authorization-server",n);let i;try{i=await fetch(r,{headers:{"MCP-Protocol-Version":(t=e==null?void 0:e.protocolVersion)!==null&&t!==void 0?t:se}})}catch(s){if(s instanceof TypeError)i=await fetch(r);else throw s}if(i.status!==404){if(!i.ok)throw new Error(`HTTP ${i.status} trying to load well-known OAuth metadata`);return ie.parse(await i.json())}}async function pe(n,{metadata:e,clientInformation:t,redirectUrl:r}){const i="code",s="S256";let o;if(e){if(o=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(s))throw new Error(`Incompatible auth server: does not support code challenge method ${s}`)}else o=new URL("/authorize",n);const c=await ae(),h=c.code_verifier,u=c.code_challenge;return o.searchParams.set("response_type",i),o.searchParams.set("client_id",t.client_id),o.searchParams.set("code_challenge",u),o.searchParams.set("code_challenge_method",s),o.searchParams.set("redirect_uri",String(r)),{authorizationUrl:o,codeVerifier:h}}async function _e(n,{metadata:e,clientInformation:t,authorizationCode:r,codeVerifier:i,redirectUri:s}){const o="authorization_code";let c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(o))throw new Error(`Incompatible auth server: does not support grant type ${o}`)}else c=new URL("/token",n);const h=new URLSearchParams({grant_type:o,client_id:t.client_id,code:r,code_verifier:i,redirect_uri:String(s)});t.client_secret&&h.set("client_secret",t.client_secret);const u=await fetch(c,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:h});if(!u.ok)throw new Error(`Token exchange failed: HTTP ${u.status}`);return ne.parse(await u.json())}async function we(n,{metadata:e,clientInformation:t,refreshToken:r}){const i="refresh_token";let s;if(e){if(s=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support grant type ${i}`)}else s=new URL("/token",n);const o=new URLSearchParams({grant_type:i,client_id:t.client_id,refresh_token:r});t.client_secret&&o.set("client_secret",t.client_secret);const c=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o});if(!c.ok)throw new Error(`Token refresh failed: HTTP ${c.status}`);return ne.parse(await c.json())}async function ve(n,{metadata:e,clientMetadata:t}){let r;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");r=new URL(e.registration_endpoint)}else r=new URL("/register",n);const i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw new Error(`Dynamic client registration failed: HTTP ${i.status}`);return oe.parse(await i.json())}class Ee extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}}class me{constructor(e,t){this._url=e,this._eventSourceInit=t==null?void 0:t.eventSourceInit,this._requestInit=t==null?void 0:t.requestInit,this._authProvider=t==null?void 0:t.authProvider}async _authThenStart(){var e;if(!this._authProvider)throw new b("No auth provider");let t;try{t=await F(this._authProvider,{serverUrl:this._url})}catch(r){throw(e=this.onerror)===null||e===void 0||e.call(this,r),r}if(t!=="AUTHORIZED")throw new b;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}return e}_startOrAuth(){return new Promise((e,t)=>{var r;this._eventSource=new M(this._url.href,(r=this._eventSourceInit)!==null&&r!==void 0?r:{fetch:(i,s)=>this._commonHeaders().then(o=>fetch(i,{...s,headers:{...o,Accept:"text/event-stream"}}))}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var s;if(i.code===401&&this._authProvider){this._authThenStart().then(e,t);return}const o=new Ee(i.code,i.message,i);t(o),(s=this.onerror)===null||s===void 0||s.call(this,o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var s;const o=i;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(c){t(c),(s=this.onerror)===null||s===void 0||s.call(this,c),this.close();return}e()}),this._eventSource.onmessage=i=>{var s,o;const c=i;let h;try{h=he.parse(JSON.parse(c.data))}catch(u){(s=this.onerror)===null||s===void 0||s.call(this,u);return}(o=this.onmessage)===null||o===void 0||o.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new b("No auth provider");if(await F(this._authProvider,{serverUrl:this._url,authorizationCode:e})!=="AUTHORIZED")throw new b("Failed to authorize")}async close(){var e,t,r;(e=this._abortController)===null||e===void 0||e.abort(),(t=this._eventSource)===null||t===void 0||t.close(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e){var t,r,i;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders(),o=new Headers({...s,...(t=this._requestInit)===null||t===void 0?void 0:t.headers});o.set("content-type","application/json");const c={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},h=await fetch(this._endpoint,c);if(!h.ok){if(h.status===401&&this._authProvider){if(await F(this._authProvider,{serverUrl:this._url})!=="AUTHORIZED")throw new b;return this.send(e)}const u=await h.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${u}`)}}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}}export{me as SSEClientTransport,Ee as SseError};
|