@tencent-ai/codebuddy-code 0.0.1-beta.1 → 0.0.1-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{629.codebuddy.js → 368.codebuddy.js} +1 -1
- package/dist/codebuddy.js +1 -1
- package/lib/node/index.js +1 -0
- package/package.json +1 -1
- package/product.json +4 -4
package/README.md
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=629,exports.ids=[629],exports.modules={16010:(e,r,t)=>{t.r(r),t.d(r,{StreamableHTTPClientTransport:()=>StreamableHTTPClientTransport,StreamableHTTPError:()=>StreamableHTTPError});var o=t(13298);let n;async function random(e){const r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let t="";const o=await async function getRandomValues(e){return(await n).getRandomValues(new Uint8Array(e))}(e);for(let n=0;n<e;n++){t+=r[o[n]%66]}return t}async function generateChallenge(e){const r=await(await n).subtle.digest("SHA-256",(new TextEncoder).encode(e));return btoa(String.fromCharCode(...new Uint8Array(r))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pkceChallenge(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const r=await async function generateVerifier(e){return await random(e)}(e);return{code_verifier:r,code_challenge:await generateChallenge(r)}}n=globalThis.crypto?.webcrypto??globalThis.crypto??Promise.resolve().then(t.t.bind(t,77598,19)).then((e=>e.webcrypto));var i=t(46195);const a=i.z.object({resource:i.z.string().url(),authorization_servers:i.z.array(i.z.string().url()).optional(),jwks_uri:i.z.string().url().optional(),scopes_supported:i.z.array(i.z.string()).optional(),bearer_methods_supported:i.z.array(i.z.string()).optional(),resource_signing_alg_values_supported:i.z.array(i.z.string()).optional(),resource_name:i.z.string().optional(),resource_documentation:i.z.string().optional(),resource_policy_uri:i.z.string().url().optional(),resource_tos_uri:i.z.string().url().optional(),tls_client_certificate_bound_access_tokens:i.z.boolean().optional(),authorization_details_types_supported:i.z.array(i.z.string()).optional(),dpop_signing_alg_values_supported:i.z.array(i.z.string()).optional(),dpop_bound_access_tokens_required:i.z.boolean().optional()}).passthrough(),s=i.z.object({issuer:i.z.string(),authorization_endpoint:i.z.string(),token_endpoint:i.z.string(),registration_endpoint:i.z.string().optional(),scopes_supported:i.z.array(i.z.string()).optional(),response_types_supported:i.z.array(i.z.string()),response_modes_supported:i.z.array(i.z.string()).optional(),grant_types_supported:i.z.array(i.z.string()).optional(),token_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),service_documentation:i.z.string().optional(),revocation_endpoint:i.z.string().optional(),revocation_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),introspection_endpoint:i.z.string().optional(),introspection_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),code_challenge_methods_supported:i.z.array(i.z.string()).optional()}).passthrough(),c=i.z.object({access_token:i.z.string(),id_token:i.z.string().optional(),token_type:i.z.string(),expires_in:i.z.number().optional(),scope:i.z.string().optional(),refresh_token:i.z.string().optional()}).strip(),l=i.z.object({error:i.z.string(),error_description:i.z.string().optional(),error_uri:i.z.string().optional()}),d=i.z.object({redirect_uris:i.z.array(i.z.string()).refine((e=>e.every((e=>URL.canParse(e)))),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:i.z.string().optional(),grant_types:i.z.array(i.z.string()).optional(),response_types:i.z.array(i.z.string()).optional(),client_name:i.z.string().optional(),client_uri:i.z.string().optional(),logo_uri:i.z.string().optional(),scope:i.z.string().optional(),contacts:i.z.array(i.z.string()).optional(),tos_uri:i.z.string().optional(),policy_uri:i.z.string().optional(),jwks_uri:i.z.string().optional(),jwks:i.z.any().optional(),software_id:i.z.string().optional(),software_version:i.z.string().optional(),software_statement:i.z.string().optional()}).strip(),u=i.z.object({client_id:i.z.string(),client_secret:i.z.string().optional(),client_id_issued_at:i.z.number().optional(),client_secret_expires_at:i.z.number().optional()}).strip(),h=d.merge(u);i.z.object({error:i.z.string(),error_description:i.z.string().optional()}).strip(),i.z.object({token:i.z.string(),token_type_hint:i.z.string().optional()}).strip();class OAuthError extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class InvalidRequestError extends OAuthError{}InvalidRequestError.errorCode="invalid_request";class InvalidClientError extends OAuthError{}InvalidClientError.errorCode="invalid_client";class InvalidGrantError extends OAuthError{}InvalidGrantError.errorCode="invalid_grant";class UnauthorizedClientError extends OAuthError{}UnauthorizedClientError.errorCode="unauthorized_client";class UnsupportedGrantTypeError extends OAuthError{}UnsupportedGrantTypeError.errorCode="unsupported_grant_type";class InvalidScopeError extends OAuthError{}InvalidScopeError.errorCode="invalid_scope";class AccessDeniedError extends OAuthError{}AccessDeniedError.errorCode="access_denied";class ServerError extends OAuthError{}ServerError.errorCode="server_error";class TemporarilyUnavailableError extends OAuthError{}TemporarilyUnavailableError.errorCode="temporarily_unavailable";class UnsupportedResponseTypeError extends OAuthError{}UnsupportedResponseTypeError.errorCode="unsupported_response_type";class UnsupportedTokenTypeError extends OAuthError{}UnsupportedTokenTypeError.errorCode="unsupported_token_type";class InvalidTokenError extends OAuthError{}InvalidTokenError.errorCode="invalid_token";class MethodNotAllowedError extends OAuthError{}MethodNotAllowedError.errorCode="method_not_allowed";class TooManyRequestsError extends OAuthError{}TooManyRequestsError.errorCode="too_many_requests";class InvalidClientMetadataError extends OAuthError{}InvalidClientMetadataError.errorCode="invalid_client_metadata";class InsufficientScopeError extends OAuthError{}InsufficientScopeError.errorCode="insufficient_scope";const p={[InvalidRequestError.errorCode]:InvalidRequestError,[InvalidClientError.errorCode]:InvalidClientError,[InvalidGrantError.errorCode]:InvalidGrantError,[UnauthorizedClientError.errorCode]:UnauthorizedClientError,[UnsupportedGrantTypeError.errorCode]:UnsupportedGrantTypeError,[InvalidScopeError.errorCode]:InvalidScopeError,[AccessDeniedError.errorCode]:AccessDeniedError,[ServerError.errorCode]:ServerError,[TemporarilyUnavailableError.errorCode]:TemporarilyUnavailableError,[UnsupportedResponseTypeError.errorCode]:UnsupportedResponseTypeError,[UnsupportedTokenTypeError.errorCode]:UnsupportedTokenTypeError,[InvalidTokenError.errorCode]:InvalidTokenError,[MethodNotAllowedError.errorCode]:MethodNotAllowedError,[TooManyRequestsError.errorCode]:TooManyRequestsError,[InvalidClientMetadataError.errorCode]:InvalidClientMetadataError,[InsufficientScopeError.errorCode]:InsufficientScopeError};class UnauthorizedError extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function selectClientAuthMethod(e,r){const t=void 0!==e.client_secret;return 0===r.length?t?"client_secret_post":"none":t&&r.includes("client_secret_basic")?"client_secret_basic":t&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":t?"client_secret_post":"none"}function applyClientAuthentication(e,r,t,o){const{client_id:n,client_secret:i}=r;switch(e){case"client_secret_basic":return void function applyBasicAuth(e,r,t){if(!r)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${r}`);t.set("Authorization",`Basic ${o}`)}(n,i,t);case"client_secret_post":return void function applyPostAuth(e,r,t){t.set("client_id",e),r&&t.set("client_secret",r)}(n,i,o);case"none":return void function applyPublicAuth(e,r){r.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function parseErrorResponse(e){const r=e instanceof Response?e.status:void 0,t=e instanceof Response?await e.text():e;try{const e=l.parse(JSON.parse(t)),{error:r,error_description:o,error_uri:n}=e;return new(p[r]||ServerError)(o||"",n)}catch(e){return new ServerError(`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${e}. Raw body: ${t}`)}}async function auth(e,r){var t,o;try{return await authInternal(e,r)}catch(n){if(n instanceof InvalidClientError||n instanceof UnauthorizedClientError)return await(null===(t=e.invalidateCredentials)||void 0===t?void 0:t.call(e,"all")),await authInternal(e,r);if(n instanceof InvalidGrantError)return await(null===(o=e.invalidateCredentials)||void 0===o?void 0:o.call(e,"tokens")),await authInternal(e,r);throw n}}async function authInternal(e,{serverUrl:r,authorizationCode:t,scope:n,resourceMetadataUrl:i,fetchFn:l}){let d,u=r;try{d=await async function discoverOAuthProtectedResourceMetadata(e,r,t=fetch){const o=await discoverMetadataWithFallback(e,"oauth-protected-resource",t,{protocolVersion:null==r?void 0:r.protocolVersion,metadataUrl:null==r?void 0:r.resourceMetadataUrl});if(!o||404===o.status)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return a.parse(await o.json())}(r,{resourceMetadataUrl:i},l),d.authorization_servers&&d.authorization_servers.length>0&&(u=d.authorization_servers[0])}catch(e){}const p=await async function selectResourceURL(e,r,t){const o=function resourceUrlFromServerUrl(e){const r="string"==typeof e?new URL(e):new URL(e.href);return r.hash="",r}(e);if(r.validateResourceURL)return await r.validateResourceURL(o,null==t?void 0:t.resource);if(!t)return;if(!function checkResourceAllowed({requestedResource:e,configuredResource:r}){const t="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof r?new URL(r):new URL(r.href);if(t.origin!==o.origin)return!1;if(t.pathname.length<o.pathname.length)return!1;const n=t.pathname.endsWith("/")?t.pathname:t.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}({requestedResource:o,configuredResource:t.resource}))throw new Error(`Protected resource ${t.resource} does not match expected ${o} (or origin)`);return new URL(t.resource)}(r,e,d),_=await async function discoverOAuthMetadata(e,{authorizationServerUrl:r,protocolVersion:t}={},n=fetch){"string"==typeof e&&(e=new URL(e));r||(r=e);"string"==typeof r&&(r=new URL(r));null!=t||(t=o.LATEST_PROTOCOL_VERSION);const i=await discoverMetadataWithFallback(r,"oauth-authorization-server",n,{protocolVersion:t,metadataServerUrl:r});if(!i||404===i.status)return;if(!i.ok)throw new Error(`HTTP ${i.status} trying to load well-known OAuth metadata`);return s.parse(await i.json())}(r,{authorizationServerUrl:u},l);let f=await Promise.resolve(e.clientInformation());if(!f){if(void 0!==t)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const r=await async function registerClient(e,{metadata:r,clientMetadata:t,fetchFn:o}){let n;if(r){if(!r.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(r.registration_endpoint)}else n=new URL("/register",e);const i=await(null!=o?o:fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw await parseErrorResponse(i);return h.parse(await i.json())}(u,{metadata:_,clientMetadata:e.clientMetadata});await e.saveClientInformation(r),f=r}if(void 0!==t){const r=await e.codeVerifier(),o=await async function exchangeAuthorization(e,{metadata:r,clientInformation:t,authorizationCode:o,codeVerifier:n,redirectUri:i,resource:a,addClientAuthentication:s,fetchFn:l}){var d;const u="authorization_code",h=(null==r?void 0:r.token_endpoint)?new URL(r.token_endpoint):new URL("/token",e);if((null==r?void 0:r.grant_types_supported)&&!r.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),_=new URLSearchParams({grant_type:u,code:o,code_verifier:n,redirect_uri:String(i)});if(s)s(p,_,e,r);else{applyClientAuthentication(selectClientAuthMethod(t,null!==(d=null==r?void 0:r.token_endpoint_auth_methods_supported)&&void 0!==d?d:[]),t,p,_)}a&&_.set("resource",a.href);const f=await(null!=l?l:fetch)(h,{method:"POST",headers:p,body:_});if(!f.ok)throw await parseErrorResponse(f);return c.parse(await f.json())}(u,{metadata:_,clientInformation:f,authorizationCode:t,codeVerifier:r,redirectUri:e.redirectUrl,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:l});return await e.saveTokens(o),"AUTHORIZED"}const v=await e.tokens();if(null==v?void 0:v.refresh_token)try{const r=await async function refreshAuthorization(e,{metadata:r,clientInformation:t,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:a}){var s;const l="refresh_token";let d;if(r){if(d=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else d=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:l,refresh_token:o});if(i)i(u,h,e,r);else{applyClientAuthentication(selectClientAuthMethod(t,null!==(s=null==r?void 0:r.token_endpoint_auth_methods_supported)&&void 0!==s?s:[]),t,u,h)}n&&h.set("resource",n.href);const p=await(null!=a?a:fetch)(d,{method:"POST",headers:u,body:h});if(!p.ok)throw await parseErrorResponse(p);return c.parse({refresh_token:o,...await p.json()})}(u,{metadata:_,clientInformation:f,refreshToken:v.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication});return await e.saveTokens(r),"AUTHORIZED"}catch(e){if(e instanceof OAuthError&&!(e instanceof ServerError))throw e}const w=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function startAuthorization(e,{metadata:r,clientInformation:t,redirectUrl:o,scope:n,state:i,resource:a}){const s="code",c="S256";let l;if(r){if(l=new URL(r.authorization_endpoint),!r.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!r.code_challenge_methods_supported||!r.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL("/authorize",e);const d=await pkceChallenge(),u=d.code_verifier,h=d.code_challenge;l.searchParams.set("response_type",s),l.searchParams.set("client_id",t.client_id),l.searchParams.set("code_challenge",h),l.searchParams.set("code_challenge_method",c),l.searchParams.set("redirect_uri",String(o)),i&&l.searchParams.set("state",i);n&&l.searchParams.set("scope",n);(null==n?void 0:n.includes("offline_access"))&&l.searchParams.append("prompt","consent");a&&l.searchParams.set("resource",a.href);return{authorizationUrl:l,codeVerifier:u}}(u,{metadata:_,clientInformation:f,state:w,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:p});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}async function fetchWithCorsRetry(e,r,t=fetch){try{return await t(e,{headers:r})}catch(o){if(o instanceof TypeError)return r?fetchWithCorsRetry(e,void 0,t):void 0;throw o}}async function tryMetadataDiscovery(e,r,t=fetch){const o={"MCP-Protocol-Version":r};return await fetchWithCorsRetry(e,o,t)}async function discoverMetadataWithFallback(e,r,t,n){var i,a;const s=new URL(e),c=null!==(i=null==n?void 0:n.protocolVersion)&&void 0!==i?i:o.LATEST_PROTOCOL_VERSION;let l;if(null==n?void 0:n.metadataUrl)l=new URL(n.metadataUrl);else{const e=function buildWellKnownPath(e,r){let t=`/.well-known/${e}${r}`;return r.endsWith("/")&&(t=t.slice(0,-1)),t}(r,s.pathname);l=new URL(e,null!==(a=null==n?void 0:n.metadataServerUrl)&&void 0!==a?a:s),l.search=s.search}let d=await tryMetadataDiscovery(l,c,t);if(!(null==n?void 0:n.metadataUrl)&&function shouldAttemptFallback(e,r){return!e||404===e.status&&"/"!==r}(d,s.pathname)){const e=new URL(`/.well-known/${r}`,s);d=await tryMetadataDiscovery(e,c,t)}return d}class ParseError extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function noop(e){}function createParser(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=noop,onError:t=noop,onRetry:o=noop,onComment:n}=e;let i,a="",s=!0,c="",l="";function parseLine(e){if(""===e)return void function dispatchEvent(){c.length>0&&r({id:i,event:l||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),i=void 0,c="",l=""}();if(e.startsWith(":"))return void(n&&n(e.slice(e.startsWith(": ")?2:1)));const t=e.indexOf(":");if(-1===t)processField(e,"",e);else{const r=e.slice(0,t),o=" "===e[t+1]?2:1;processField(r,e.slice(t+o),e)}}function processField(e,r,n){switch(e){case"event":l=r;break;case"data":c=`${c}${r}\n`;break;case"id":i=r.includes("\0")?void 0:r;break;case"retry":/^\d+$/.test(r)?o(parseInt(r,10)):t(new ParseError(`Invalid \`retry\` value: "${r}"`,{type:"invalid-retry",value:r,line:n}));break;default:t(new ParseError(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:r,line:n}))}}return{feed:function feed(e){const r=s?e.replace(/^\xEF\xBB\xBF/,""):e,[t,o]=function splitLines(e){const r=[];let t="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),i=e.indexOf("\n",o);let a=-1;if(-1!==n&&-1!==i?a=Math.min(n,i):-1!==n?a=n:-1!==i&&(a=i),-1===a){t=e.slice(o);break}{const t=e.slice(o,a);r.push(t),o=a+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[r,t]}(`${a}${r}`);for(const e of t)parseLine(e);a=o,s=!1},reset:function reset(e={}){a&&e.consume&&parseLine(a),s=!0,i=void 0,c="",l="",a=""}}}class EventSourceParserStream extends TransformStream{constructor({onError:e,onRetry:r,onComment:t}={}){let o;super({start(n){o=createParser({onEvent:e=>{n.enqueue(e)},onError(r){"terminate"===e?n.error(r):"function"==typeof e&&e(r)},onRetry:r,onComment:t})},transform(e){o.feed(e)}})}}const _={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class StreamableHTTPError extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class StreamableHTTPClientTransport{constructor(e,r){var t;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch,this._sessionId=null==r?void 0:r.sessionId,this._reconnectionOptions=null!==(t=null==r?void 0:r.reconnectionOptions)&&void 0!==t?t:_}async _authThenStart(){var e;if(!this._authProvider)throw new UnauthorizedError("No auth provider");let r;try{r=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null===(e=this.onerror)||void 0===e||e.call(this,r),r}if("AUTHORIZED"!==r)throw new UnauthorizedError;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const t=this._normalizeHeaders(null===(e=this._requestInit)||void 0===e?void 0:e.headers);return new Headers({...r,...t})}async _startOrAuthSse(e){var r,t,o;const{resumptionToken:n}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),n&&o.set("last-event-id",n);const i=await(null!==(r=this._fetch)&&void 0!==r?r:fetch)(this._url,{method:"GET",headers:o,signal:null===(t=this._abortController)||void 0===t?void 0:t.signal});if(!i.ok){if(401===i.status&&this._authProvider)return await this._authThenStart();if(405===i.status)return;throw new StreamableHTTPError(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(e){throw null===(o=this.onerror)||void 0===o||o.call(this,e),e}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,t=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(t,e),o)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var t;const o=this._reconnectionOptions.maxRetries;if(o>0&&r>=o)return void(null===(t=this.onerror)||void 0===t||t.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`)));const n=this._getNextReconnectionDelay(r);setTimeout((()=>{this._startOrAuthSse(e).catch((t=>{var o;null===(o=this.onerror)||void 0===o||o.call(this,new Error(`Failed to reconnect SSE stream: ${t instanceof Error?t.message:String(t)}`)),this._scheduleReconnection(e,r+1)}))}),n)}_handleSseStream(e,r,t){if(!e)return;const{onresumptiontoken:n,replayMessageId:i}=r;let a;(async()=>{var r,s,c,l;try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).getReader();for(;;){const{value:e,done:c}=await t.read();if(c)break;if(e.id&&(a=e.id,null==n||n(e.id)),!e.event||"message"===e.event)try{const t=o.JSONRPCMessageSchema.parse(JSON.parse(e.data));void 0!==i&&(0,o.isJSONRPCResponse)(t)&&(t.id=i),null===(r=this.onmessage)||void 0===r||r.call(this,t)}catch(e){null===(s=this.onerror)||void 0===s||s.call(this,e)}}}catch(e){if(null===(c=this.onerror)||void 0===c||c.call(this,new Error(`SSE stream disconnected: ${e}`)),t&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:i},0)}catch(e){null===(l=this.onerror)||void 0===l||l.call(this,new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new UnauthorizedError("No auth provider");if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError("Failed to authorize")}async close(){var e,r;null===(e=this._abortController)||void 0===e||e.abort(),null===(r=this.onclose)||void 0===r||r.call(this)}async send(e,r){var t,n,i,a;try{const{resumptionToken:a,onresumptiontoken:s}=r||{};if(a)return void this._startOrAuthSse({resumptionToken:a,replayMessageId:(0,o.isJSONRPCRequest)(e)?e.id:void 0}).catch((e=>{var r;return null===(r=this.onerror)||void 0===r?void 0:r.call(this,e)}));const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const l={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:null===(t=this._abortController)||void 0===t?void 0:t.signal},d=await(null!==(n=this._fetch)&&void 0!==n?n:fetch)(this._url,l),u=d.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!d.ok){if(401===d.status&&this._authProvider){this._resourceMetadataUrl=function extractResourceMetadataUrl(e){const r=e.headers.get("WWW-Authenticate");if(!r)return;const[t,o]=r.split(" ");if("bearer"!==t.toLowerCase()||!o)return;const n=/resource_metadata="([^"]*)"/.exec(r);if(n)try{return new URL(n[1])}catch(e){return}}(d);if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError;return this.send(e)}const r=await d.text().catch((()=>null));throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${r}`)}if(202===d.status)return void((0,o.isInitializedNotification)(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch((e=>{var r;return null===(r=this.onerror)||void 0===r?void 0:r.call(this,e)})));const h=(Array.isArray(e)?e:[e]).filter((e=>"method"in e&&"id"in e&&void 0!==e.id)).length>0,p=d.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:s},!1);else{if(!(null==p?void 0:p.includes("application/json")))throw new StreamableHTTPError(-1,`Unexpected content type: ${p}`);{const e=await d.json(),r=Array.isArray(e)?e.map((e=>o.JSONRPCMessageSchema.parse(e))):[o.JSONRPCMessageSchema.parse(e)];for(const e of r)null===(i=this.onmessage)||void 0===i||i.call(this,e)}}}catch(e){throw null===(a=this.onerror)||void 0===a||a.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,t;if(this._sessionId)try{const t=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:t,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal},n=await(null!==(r=this._fetch)&&void 0!==r?r:fetch)(this._url,o);if(!n.ok&&405!==n.status)throw new StreamableHTTPError(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw null===(t=this.onerror)||void 0===t||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}}};
|
|
1
|
+
"use strict";exports.id=368,exports.ids=[368],exports.modules={87368:(e,r,t)=>{t.r(r),t.d(r,{StreamableHTTPClientTransport:()=>StreamableHTTPClientTransport,StreamableHTTPError:()=>StreamableHTTPError});var o=t(13298);let n;async function random(e){const r="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let t="";const o=await async function getRandomValues(e){return(await n).getRandomValues(new Uint8Array(e))}(e);for(let n=0;n<e;n++){t+=r[o[n]%66]}return t}async function generateChallenge(e){const r=await(await n).subtle.digest("SHA-256",(new TextEncoder).encode(e));return btoa(String.fromCharCode(...new Uint8Array(r))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pkceChallenge(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const r=await async function generateVerifier(e){return await random(e)}(e);return{code_verifier:r,code_challenge:await generateChallenge(r)}}n=globalThis.crypto?.webcrypto??globalThis.crypto??Promise.resolve().then(t.t.bind(t,77598,19)).then((e=>e.webcrypto));var i=t(46195);const a=i.z.object({resource:i.z.string().url(),authorization_servers:i.z.array(i.z.string().url()).optional(),jwks_uri:i.z.string().url().optional(),scopes_supported:i.z.array(i.z.string()).optional(),bearer_methods_supported:i.z.array(i.z.string()).optional(),resource_signing_alg_values_supported:i.z.array(i.z.string()).optional(),resource_name:i.z.string().optional(),resource_documentation:i.z.string().optional(),resource_policy_uri:i.z.string().url().optional(),resource_tos_uri:i.z.string().url().optional(),tls_client_certificate_bound_access_tokens:i.z.boolean().optional(),authorization_details_types_supported:i.z.array(i.z.string()).optional(),dpop_signing_alg_values_supported:i.z.array(i.z.string()).optional(),dpop_bound_access_tokens_required:i.z.boolean().optional()}).passthrough(),s=i.z.object({issuer:i.z.string(),authorization_endpoint:i.z.string(),token_endpoint:i.z.string(),registration_endpoint:i.z.string().optional(),scopes_supported:i.z.array(i.z.string()).optional(),response_types_supported:i.z.array(i.z.string()),response_modes_supported:i.z.array(i.z.string()).optional(),grant_types_supported:i.z.array(i.z.string()).optional(),token_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),token_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),service_documentation:i.z.string().optional(),revocation_endpoint:i.z.string().optional(),revocation_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),introspection_endpoint:i.z.string().optional(),introspection_endpoint_auth_methods_supported:i.z.array(i.z.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:i.z.array(i.z.string()).optional(),code_challenge_methods_supported:i.z.array(i.z.string()).optional()}).passthrough(),c=i.z.object({access_token:i.z.string(),id_token:i.z.string().optional(),token_type:i.z.string(),expires_in:i.z.number().optional(),scope:i.z.string().optional(),refresh_token:i.z.string().optional()}).strip(),l=i.z.object({error:i.z.string(),error_description:i.z.string().optional(),error_uri:i.z.string().optional()}),d=i.z.object({redirect_uris:i.z.array(i.z.string()).refine((e=>e.every((e=>URL.canParse(e)))),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:i.z.string().optional(),grant_types:i.z.array(i.z.string()).optional(),response_types:i.z.array(i.z.string()).optional(),client_name:i.z.string().optional(),client_uri:i.z.string().optional(),logo_uri:i.z.string().optional(),scope:i.z.string().optional(),contacts:i.z.array(i.z.string()).optional(),tos_uri:i.z.string().optional(),policy_uri:i.z.string().optional(),jwks_uri:i.z.string().optional(),jwks:i.z.any().optional(),software_id:i.z.string().optional(),software_version:i.z.string().optional(),software_statement:i.z.string().optional()}).strip(),u=i.z.object({client_id:i.z.string(),client_secret:i.z.string().optional(),client_id_issued_at:i.z.number().optional(),client_secret_expires_at:i.z.number().optional()}).strip(),h=d.merge(u);i.z.object({error:i.z.string(),error_description:i.z.string().optional()}).strip(),i.z.object({token:i.z.string(),token_type_hint:i.z.string().optional()}).strip();class OAuthError extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class InvalidRequestError extends OAuthError{}InvalidRequestError.errorCode="invalid_request";class InvalidClientError extends OAuthError{}InvalidClientError.errorCode="invalid_client";class InvalidGrantError extends OAuthError{}InvalidGrantError.errorCode="invalid_grant";class UnauthorizedClientError extends OAuthError{}UnauthorizedClientError.errorCode="unauthorized_client";class UnsupportedGrantTypeError extends OAuthError{}UnsupportedGrantTypeError.errorCode="unsupported_grant_type";class InvalidScopeError extends OAuthError{}InvalidScopeError.errorCode="invalid_scope";class AccessDeniedError extends OAuthError{}AccessDeniedError.errorCode="access_denied";class ServerError extends OAuthError{}ServerError.errorCode="server_error";class TemporarilyUnavailableError extends OAuthError{}TemporarilyUnavailableError.errorCode="temporarily_unavailable";class UnsupportedResponseTypeError extends OAuthError{}UnsupportedResponseTypeError.errorCode="unsupported_response_type";class UnsupportedTokenTypeError extends OAuthError{}UnsupportedTokenTypeError.errorCode="unsupported_token_type";class InvalidTokenError extends OAuthError{}InvalidTokenError.errorCode="invalid_token";class MethodNotAllowedError extends OAuthError{}MethodNotAllowedError.errorCode="method_not_allowed";class TooManyRequestsError extends OAuthError{}TooManyRequestsError.errorCode="too_many_requests";class InvalidClientMetadataError extends OAuthError{}InvalidClientMetadataError.errorCode="invalid_client_metadata";class InsufficientScopeError extends OAuthError{}InsufficientScopeError.errorCode="insufficient_scope";const p={[InvalidRequestError.errorCode]:InvalidRequestError,[InvalidClientError.errorCode]:InvalidClientError,[InvalidGrantError.errorCode]:InvalidGrantError,[UnauthorizedClientError.errorCode]:UnauthorizedClientError,[UnsupportedGrantTypeError.errorCode]:UnsupportedGrantTypeError,[InvalidScopeError.errorCode]:InvalidScopeError,[AccessDeniedError.errorCode]:AccessDeniedError,[ServerError.errorCode]:ServerError,[TemporarilyUnavailableError.errorCode]:TemporarilyUnavailableError,[UnsupportedResponseTypeError.errorCode]:UnsupportedResponseTypeError,[UnsupportedTokenTypeError.errorCode]:UnsupportedTokenTypeError,[InvalidTokenError.errorCode]:InvalidTokenError,[MethodNotAllowedError.errorCode]:MethodNotAllowedError,[TooManyRequestsError.errorCode]:TooManyRequestsError,[InvalidClientMetadataError.errorCode]:InvalidClientMetadataError,[InsufficientScopeError.errorCode]:InsufficientScopeError};class UnauthorizedError extends Error{constructor(e){super(null!=e?e:"Unauthorized")}}function selectClientAuthMethod(e,r){const t=void 0!==e.client_secret;return 0===r.length?t?"client_secret_post":"none":t&&r.includes("client_secret_basic")?"client_secret_basic":t&&r.includes("client_secret_post")?"client_secret_post":r.includes("none")?"none":t?"client_secret_post":"none"}function applyClientAuthentication(e,r,t,o){const{client_id:n,client_secret:i}=r;switch(e){case"client_secret_basic":return void function applyBasicAuth(e,r,t){if(!r)throw new Error("client_secret_basic authentication requires a client_secret");const o=btoa(`${e}:${r}`);t.set("Authorization",`Basic ${o}`)}(n,i,t);case"client_secret_post":return void function applyPostAuth(e,r,t){t.set("client_id",e),r&&t.set("client_secret",r)}(n,i,o);case"none":return void function applyPublicAuth(e,r){r.set("client_id",e)}(n,o);default:throw new Error(`Unsupported client authentication method: ${e}`)}}async function parseErrorResponse(e){const r=e instanceof Response?e.status:void 0,t=e instanceof Response?await e.text():e;try{const e=l.parse(JSON.parse(t)),{error:r,error_description:o,error_uri:n}=e;return new(p[r]||ServerError)(o||"",n)}catch(e){return new ServerError(`${r?`HTTP ${r}: `:""}Invalid OAuth error response: ${e}. Raw body: ${t}`)}}async function auth(e,r){var t,o;try{return await authInternal(e,r)}catch(n){if(n instanceof InvalidClientError||n instanceof UnauthorizedClientError)return await(null===(t=e.invalidateCredentials)||void 0===t?void 0:t.call(e,"all")),await authInternal(e,r);if(n instanceof InvalidGrantError)return await(null===(o=e.invalidateCredentials)||void 0===o?void 0:o.call(e,"tokens")),await authInternal(e,r);throw n}}async function authInternal(e,{serverUrl:r,authorizationCode:t,scope:n,resourceMetadataUrl:i,fetchFn:l}){let d,u=r;try{d=await async function discoverOAuthProtectedResourceMetadata(e,r,t=fetch){const o=await discoverMetadataWithFallback(e,"oauth-protected-resource",t,{protocolVersion:null==r?void 0:r.protocolVersion,metadataUrl:null==r?void 0:r.resourceMetadataUrl});if(!o||404===o.status)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return a.parse(await o.json())}(r,{resourceMetadataUrl:i},l),d.authorization_servers&&d.authorization_servers.length>0&&(u=d.authorization_servers[0])}catch(e){}const p=await async function selectResourceURL(e,r,t){const o=function resourceUrlFromServerUrl(e){const r="string"==typeof e?new URL(e):new URL(e.href);return r.hash="",r}(e);if(r.validateResourceURL)return await r.validateResourceURL(o,null==t?void 0:t.resource);if(!t)return;if(!function checkResourceAllowed({requestedResource:e,configuredResource:r}){const t="string"==typeof e?new URL(e):new URL(e.href),o="string"==typeof r?new URL(r):new URL(r.href);if(t.origin!==o.origin)return!1;if(t.pathname.length<o.pathname.length)return!1;const n=t.pathname.endsWith("/")?t.pathname:t.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}({requestedResource:o,configuredResource:t.resource}))throw new Error(`Protected resource ${t.resource} does not match expected ${o} (or origin)`);return new URL(t.resource)}(r,e,d),_=await async function discoverOAuthMetadata(e,{authorizationServerUrl:r,protocolVersion:t}={},n=fetch){"string"==typeof e&&(e=new URL(e));r||(r=e);"string"==typeof r&&(r=new URL(r));null!=t||(t=o.LATEST_PROTOCOL_VERSION);const i=await discoverMetadataWithFallback(r,"oauth-authorization-server",n,{protocolVersion:t,metadataServerUrl:r});if(!i||404===i.status)return;if(!i.ok)throw new Error(`HTTP ${i.status} trying to load well-known OAuth metadata`);return s.parse(await i.json())}(r,{authorizationServerUrl:u},l);let f=await Promise.resolve(e.clientInformation());if(!f){if(void 0!==t)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const r=await async function registerClient(e,{metadata:r,clientMetadata:t,fetchFn:o}){let n;if(r){if(!r.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(r.registration_endpoint)}else n=new URL("/register",e);const i=await(null!=o?o:fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw await parseErrorResponse(i);return h.parse(await i.json())}(u,{metadata:_,clientMetadata:e.clientMetadata});await e.saveClientInformation(r),f=r}if(void 0!==t){const r=await e.codeVerifier(),o=await async function exchangeAuthorization(e,{metadata:r,clientInformation:t,authorizationCode:o,codeVerifier:n,redirectUri:i,resource:a,addClientAuthentication:s,fetchFn:l}){var d;const u="authorization_code",h=(null==r?void 0:r.token_endpoint)?new URL(r.token_endpoint):new URL("/token",e);if((null==r?void 0:r.grant_types_supported)&&!r.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),_=new URLSearchParams({grant_type:u,code:o,code_verifier:n,redirect_uri:String(i)});if(s)s(p,_,e,r);else{applyClientAuthentication(selectClientAuthMethod(t,null!==(d=null==r?void 0:r.token_endpoint_auth_methods_supported)&&void 0!==d?d:[]),t,p,_)}a&&_.set("resource",a.href);const f=await(null!=l?l:fetch)(h,{method:"POST",headers:p,body:_});if(!f.ok)throw await parseErrorResponse(f);return c.parse(await f.json())}(u,{metadata:_,clientInformation:f,authorizationCode:t,codeVerifier:r,redirectUri:e.redirectUrl,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:l});return await e.saveTokens(o),"AUTHORIZED"}const v=await e.tokens();if(null==v?void 0:v.refresh_token)try{const r=await async function refreshAuthorization(e,{metadata:r,clientInformation:t,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:a}){var s;const l="refresh_token";let d;if(r){if(d=new URL(r.token_endpoint),r.grant_types_supported&&!r.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else d=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:l,refresh_token:o});if(i)i(u,h,e,r);else{applyClientAuthentication(selectClientAuthMethod(t,null!==(s=null==r?void 0:r.token_endpoint_auth_methods_supported)&&void 0!==s?s:[]),t,u,h)}n&&h.set("resource",n.href);const p=await(null!=a?a:fetch)(d,{method:"POST",headers:u,body:h});if(!p.ok)throw await parseErrorResponse(p);return c.parse({refresh_token:o,...await p.json()})}(u,{metadata:_,clientInformation:f,refreshToken:v.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication});return await e.saveTokens(r),"AUTHORIZED"}catch(e){if(e instanceof OAuthError&&!(e instanceof ServerError))throw e}const w=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:y}=await async function startAuthorization(e,{metadata:r,clientInformation:t,redirectUrl:o,scope:n,state:i,resource:a}){const s="code",c="S256";let l;if(r){if(l=new URL(r.authorization_endpoint),!r.response_types_supported.includes(s))throw new Error(`Incompatible auth server: does not support response type ${s}`);if(!r.code_challenge_methods_supported||!r.code_challenge_methods_supported.includes(c))throw new Error(`Incompatible auth server: does not support code challenge method ${c}`)}else l=new URL("/authorize",e);const d=await pkceChallenge(),u=d.code_verifier,h=d.code_challenge;l.searchParams.set("response_type",s),l.searchParams.set("client_id",t.client_id),l.searchParams.set("code_challenge",h),l.searchParams.set("code_challenge_method",c),l.searchParams.set("redirect_uri",String(o)),i&&l.searchParams.set("state",i);n&&l.searchParams.set("scope",n);(null==n?void 0:n.includes("offline_access"))&&l.searchParams.append("prompt","consent");a&&l.searchParams.set("resource",a.href);return{authorizationUrl:l,codeVerifier:u}}(u,{metadata:_,clientInformation:f,state:w,redirectUrl:e.redirectUrl,scope:n||e.clientMetadata.scope,resource:p});return await e.saveCodeVerifier(y),await e.redirectToAuthorization(m),"REDIRECT"}async function fetchWithCorsRetry(e,r,t=fetch){try{return await t(e,{headers:r})}catch(o){if(o instanceof TypeError)return r?fetchWithCorsRetry(e,void 0,t):void 0;throw o}}async function tryMetadataDiscovery(e,r,t=fetch){const o={"MCP-Protocol-Version":r};return await fetchWithCorsRetry(e,o,t)}async function discoverMetadataWithFallback(e,r,t,n){var i,a;const s=new URL(e),c=null!==(i=null==n?void 0:n.protocolVersion)&&void 0!==i?i:o.LATEST_PROTOCOL_VERSION;let l;if(null==n?void 0:n.metadataUrl)l=new URL(n.metadataUrl);else{const e=function buildWellKnownPath(e,r){let t=`/.well-known/${e}${r}`;return r.endsWith("/")&&(t=t.slice(0,-1)),t}(r,s.pathname);l=new URL(e,null!==(a=null==n?void 0:n.metadataServerUrl)&&void 0!==a?a:s),l.search=s.search}let d=await tryMetadataDiscovery(l,c,t);if(!(null==n?void 0:n.metadataUrl)&&function shouldAttemptFallback(e,r){return!e||404===e.status&&"/"!==r}(d,s.pathname)){const e=new URL(`/.well-known/${r}`,s);d=await tryMetadataDiscovery(e,c,t)}return d}class ParseError extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function noop(e){}function createParser(e){if("function"==typeof e)throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=noop,onError:t=noop,onRetry:o=noop,onComment:n}=e;let i,a="",s=!0,c="",l="";function parseLine(e){if(""===e)return void function dispatchEvent(){c.length>0&&r({id:i,event:l||void 0,data:c.endsWith("\n")?c.slice(0,-1):c}),i=void 0,c="",l=""}();if(e.startsWith(":"))return void(n&&n(e.slice(e.startsWith(": ")?2:1)));const t=e.indexOf(":");if(-1===t)processField(e,"",e);else{const r=e.slice(0,t),o=" "===e[t+1]?2:1;processField(r,e.slice(t+o),e)}}function processField(e,r,n){switch(e){case"event":l=r;break;case"data":c=`${c}${r}\n`;break;case"id":i=r.includes("\0")?void 0:r;break;case"retry":/^\d+$/.test(r)?o(parseInt(r,10)):t(new ParseError(`Invalid \`retry\` value: "${r}"`,{type:"invalid-retry",value:r,line:n}));break;default:t(new ParseError(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:r,line:n}))}}return{feed:function feed(e){const r=s?e.replace(/^\xEF\xBB\xBF/,""):e,[t,o]=function splitLines(e){const r=[];let t="",o=0;for(;o<e.length;){const n=e.indexOf("\r",o),i=e.indexOf("\n",o);let a=-1;if(-1!==n&&-1!==i?a=Math.min(n,i):-1!==n?a=n:-1!==i&&(a=i),-1===a){t=e.slice(o);break}{const t=e.slice(o,a);r.push(t),o=a+1,"\r"===e[o-1]&&"\n"===e[o]&&o++}}return[r,t]}(`${a}${r}`);for(const e of t)parseLine(e);a=o,s=!1},reset:function reset(e={}){a&&e.consume&&parseLine(a),s=!0,i=void 0,c="",l="",a=""}}}class EventSourceParserStream extends TransformStream{constructor({onError:e,onRetry:r,onComment:t}={}){let o;super({start(n){o=createParser({onEvent:e=>{n.enqueue(e)},onError(r){"terminate"===e?n.error(r):"function"==typeof e&&e(r)},onRetry:r,onComment:t})},transform(e){o.feed(e)}})}}const _={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class StreamableHTTPError extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class StreamableHTTPClientTransport{constructor(e,r){var t;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=null==r?void 0:r.requestInit,this._authProvider=null==r?void 0:r.authProvider,this._fetch=null==r?void 0:r.fetch,this._sessionId=null==r?void 0:r.sessionId,this._reconnectionOptions=null!==(t=null==r?void 0:r.reconnectionOptions)&&void 0!==t?t:_}async _authThenStart(){var e;if(!this._authProvider)throw new UnauthorizedError("No auth provider");let r;try{r=await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(r){throw null===(e=this.onerror)||void 0===e||e.call(this,r),r}if("AUTHORIZED"!==r)throw new UnauthorizedError;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const e=await this._authProvider.tokens();e&&(r.Authorization=`Bearer ${e.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const t=this._normalizeHeaders(null===(e=this._requestInit)||void 0===e?void 0:e.headers);return new Headers({...r,...t})}async _startOrAuthSse(e){var r,t,o;const{resumptionToken:n}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),n&&o.set("last-event-id",n);const i=await(null!==(r=this._fetch)&&void 0!==r?r:fetch)(this._url,{method:"GET",headers:o,signal:null===(t=this._abortController)||void 0===t?void 0:t.signal});if(!i.ok){if(401===i.status&&this._authProvider)return await this._authThenStart();if(405===i.status)return;throw new StreamableHTTPError(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(e){throw null===(o=this.onerror)||void 0===o||o.call(this,e),e}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,t=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(t,e),o)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var t;const o=this._reconnectionOptions.maxRetries;if(o>0&&r>=o)return void(null===(t=this.onerror)||void 0===t||t.call(this,new Error(`Maximum reconnection attempts (${o}) exceeded.`)));const n=this._getNextReconnectionDelay(r);setTimeout((()=>{this._startOrAuthSse(e).catch((t=>{var o;null===(o=this.onerror)||void 0===o||o.call(this,new Error(`Failed to reconnect SSE stream: ${t instanceof Error?t.message:String(t)}`)),this._scheduleReconnection(e,r+1)}))}),n)}_handleSseStream(e,r,t){if(!e)return;const{onresumptiontoken:n,replayMessageId:i}=r;let a;(async()=>{var r,s,c,l;try{const t=e.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).getReader();for(;;){const{value:e,done:c}=await t.read();if(c)break;if(e.id&&(a=e.id,null==n||n(e.id)),!e.event||"message"===e.event)try{const t=o.JSONRPCMessageSchema.parse(JSON.parse(e.data));void 0!==i&&(0,o.isJSONRPCResponse)(t)&&(t.id=i),null===(r=this.onmessage)||void 0===r||r.call(this,t)}catch(e){null===(s=this.onerror)||void 0===s||s.call(this,e)}}}catch(e){if(null===(c=this.onerror)||void 0===c||c.call(this,new Error(`SSE stream disconnected: ${e}`)),t&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:i},0)}catch(e){null===(l=this.onerror)||void 0===l||l.call(this,new Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new UnauthorizedError("No auth provider");if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError("Failed to authorize")}async close(){var e,r;null===(e=this._abortController)||void 0===e||e.abort(),null===(r=this.onclose)||void 0===r||r.call(this)}async send(e,r){var t,n,i,a;try{const{resumptionToken:a,onresumptiontoken:s}=r||{};if(a)return void this._startOrAuthSse({resumptionToken:a,replayMessageId:(0,o.isJSONRPCRequest)(e)?e.id:void 0}).catch((e=>{var r;return null===(r=this.onerror)||void 0===r?void 0:r.call(this,e)}));const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const l={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:null===(t=this._abortController)||void 0===t?void 0:t.signal},d=await(null!==(n=this._fetch)&&void 0!==n?n:fetch)(this._url,l),u=d.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!d.ok){if(401===d.status&&this._authProvider){this._resourceMetadataUrl=function extractResourceMetadataUrl(e){const r=e.headers.get("WWW-Authenticate");if(!r)return;const[t,o]=r.split(" ");if("bearer"!==t.toLowerCase()||!o)return;const n=/resource_metadata="([^"]*)"/.exec(r);if(n)try{return new URL(n[1])}catch(e){return}}(d);if("AUTHORIZED"!==await auth(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch}))throw new UnauthorizedError;return this.send(e)}const r=await d.text().catch((()=>null));throw new Error(`Error POSTing to endpoint (HTTP ${d.status}): ${r}`)}if(202===d.status)return void((0,o.isInitializedNotification)(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch((e=>{var r;return null===(r=this.onerror)||void 0===r?void 0:r.call(this,e)})));const h=(Array.isArray(e)?e:[e]).filter((e=>"method"in e&&"id"in e&&void 0!==e.id)).length>0,p=d.headers.get("content-type");if(h)if(null==p?void 0:p.includes("text/event-stream"))this._handleSseStream(d.body,{onresumptiontoken:s},!1);else{if(!(null==p?void 0:p.includes("application/json")))throw new StreamableHTTPError(-1,`Unexpected content type: ${p}`);{const e=await d.json(),r=Array.isArray(e)?e.map((e=>o.JSONRPCMessageSchema.parse(e))):[o.JSONRPCMessageSchema.parse(e)];for(const e of r)null===(i=this.onmessage)||void 0===i||i.call(this,e)}}}catch(e){throw null===(a=this.onerror)||void 0===a||a.call(this,e),e}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,t;if(this._sessionId)try{const t=await this._commonHeaders(),o={...this._requestInit,method:"DELETE",headers:t,signal:null===(e=this._abortController)||void 0===e?void 0:e.signal},n=await(null!==(r=this._fetch)&&void 0!==r?r:fetch)(this._url,o);if(!n.ok&&405!==n.status)throw new StreamableHTTPError(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw null===(t=this.onerror)||void 0===t||t.call(this,e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}}};
|