@githits/mcp 0.40.2 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1542 +0,0 @@
1
- var MAX_ERROR_DETAIL_LENGTH=500;function parseHttpErrorDetail(body,fields){if(!body)return;let parsed;try{parsed=JSON.parse(body)}catch{return}if(!isRecord(parsed))return;for(const field of fields){const value=parsed[field];if(typeof value!=="string")continue;const normalized=normalizeSingleLineText(value);if(!normalized)continue;if(normalized.length<=MAX_ERROR_DETAIL_LENGTH)return normalized;return`${normalized.slice(0,MAX_ERROR_DETAIL_LENGTH-3)}...`}return}function normalizeSingleLineText(value){const withoutControlCharacters=Array.from(value,(character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127?" ":character}).join("");return withoutControlCharacters.replace(/\s+/g," ").trim()}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}var RECOVERY_URLS=new Set(["https://app.githits.com/auth/reauth","https://dev.githits.com/auth/reauth"]);class ProviderReauthenticationRequiredError2 extends Error{code="REAUTH_REQUIRED";reauthUrl;constructor(reauthUrl){super("Please sign in again to continue.");this.name="ProviderReauthenticationRequiredError";this.reauthUrl=reauthUrl&&RECOVERY_URLS.has(reauthUrl)?reauthUrl:undefined}}function throwIfProviderReauthenticationRequired(body){let payload;try{payload=JSON.parse(body)}catch{return}if(!payload||typeof payload!=="object"||!("code"in payload))return;if(payload.code!=="REAUTH_REQUIRED")return;throw new ProviderReauthenticationRequiredError2("reauth_url"in payload&&typeof payload.reauth_url==="string"?payload.reauth_url:undefined)}var TERMS_ACCEPTANCE_REQUIRED_CODE="TERMS_ACCEPTANCE_REQUIRED";var TERMS_URL="https://githits.com/legal/terms-of-service/";var TERMS_ACCEPTANCE_URL="https://app.githits.com/settings/privacy";class TermsAcceptanceRequiredError2 extends Error{code=TERMS_ACCEPTANCE_REQUIRED_CODE;termsUrl;acceptanceUrl;constructor(remediation={}){super("Terms acceptance required.");this.name="TermsAcceptanceRequiredError";this.termsUrl=remediation.termsUrl??TERMS_URL;this.acceptanceUrl=remediation.acceptanceUrl??TERMS_ACCEPTANCE_URL}}function createTermsAcceptanceError(payload){const record=parseErrorRecord(payload);if(!record)return;const contract=record.code===TERMS_ACCEPTANCE_REQUIRED_CODE?record:firstGraphQLErrorExtensions(record);if(contract?.code!==TERMS_ACCEPTANCE_REQUIRED_CODE)return;return new TermsAcceptanceRequiredError2({termsUrl:stringField(contract,"terms_url"),acceptanceUrl:stringField(contract,"acceptance_url")})}function throwIfTermsAcceptanceRequired(payload){const error=createTermsAcceptanceError(payload);if(error)throw error}function parseErrorRecord(payload){if(typeof payload==="string"){try{return parseErrorRecord(JSON.parse(payload))}catch{return}}return payload&&typeof payload==="object"?payload:undefined}function firstGraphQLErrorExtensions(record){const firstError=Array.isArray(record.errors)?record.errors[0]:undefined;if(!firstError||typeof firstError!=="object")return;const extensions=firstError.extensions;return extensions&&typeof extensions==="object"?extensions:undefined}function stringField(record,field){return typeof record[field]==="string"?record[field]:undefined}import{z}from"zod";var DEFAULT_MCP_URL2="https://mcp.githits.com";var DEFAULT_API_URL2="https://api.githits.com";var DEFAULT_CODE_NAV_URL2="https://oss.githits.dev";var ENVIRONMENT_SCHEMA=z.enum(["prod","dev"]);var SERVICE_URL_DEFAULTS={prod:{mcpUrl:DEFAULT_MCP_URL2,apiUrl:DEFAULT_API_URL2,codeNavigationUrl:DEFAULT_CODE_NAV_URL2},dev:{mcpUrl:"https://mcp-dev.githits.com",apiUrl:"https://api-dev.githits.com",codeNavigationUrl:"https://oss-dev.githits.dev"}};class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getGitHitsEnvironment(env=process.env){const value=env.GITHITS_ENV;const parsed=ENVIRONMENT_SCHEMA.safeParse(value===undefined||value.trim()===""?"prod":value);if(!parsed.success){throw new ServiceUrlConfigError("Invalid GITHITS_ENV: use prod or dev.")}return parsed.data}function getServiceUrlDefaults(environment){return SERVICE_URL_DEFAULTS[environment]}function getMcpUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_MCP_URL",defaults.mcpUrl,env)}function getApiUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_API_URL",defaults.apiUrl,env)}function getCodeNavigationUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_CODE_NAV_URL",defaults.codeNavigationUrl,env)}function validateServiceUrl(value,source){let parsed;try{parsed=new URL(value)}catch{throw new ServiceUrlConfigError(`Invalid ${source}: expected an HTTPS URL or an HTTP loopback URL.`)}if(parsed.protocol==="https:")return value;const hostname=parsed.hostname.replace(/^\[|\]$/g,"");const isLoopback=hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1";if(parsed.protocol==="http:"&&isLoopback)return value;throw new ServiceUrlConfigError(`Invalid ${source}: use HTTPS. Plain HTTP is allowed only for localhost, 127.0.0.1, or [::1].`)}function resolveServiceUrl(envName,defaultUrl,env){const override=env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken2(){return process.env.GITHITS_API_TOKEN}var DEFAULT_FETCH_TIMEOUT_MS=120000;var DEFAULT_WAIT_TIMEOUT_MS=30000;function indexingRequestTimeoutMs(waitTimeoutMs){return Math.max(DEFAULT_FETCH_TIMEOUT_MS,waitTimeoutMs+30000)}class FetchTimeoutError2 extends Error{timeoutMs;constructor(timeoutMs,options){super(`Request timed out after ${timeoutMs}ms.`,options);this.name="FetchTimeoutError";this.timeoutMs=timeoutMs}}async function fetchWithTimeout(input,init={},options={},consumeResponse){const timeoutMs=options.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const timeoutSignal=AbortSignal.timeout(timeoutMs);const signal=init.signal?AbortSignal.any([init.signal,timeoutSignal]):timeoutSignal;const fetchFn=options.fetchFn??globalThis.fetch;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new FetchTimeoutError2(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}).then((response)=>consumeResponse?consumeResponse(response):response),timeout])}catch(cause){if(cause instanceof FetchTimeoutError2)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError2(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError2}var AUTHENTICATION_REQUIRED_MESSAGE="Authentication required.";var LOCAL_AUTHENTICATION_MISSING_MESSAGE="No local GitHits authentication token found.";var SERVER_AUTHENTICATION_REJECTED_MESSAGE="GitHits could not accept the authentication token.";class AuthenticationError2 extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}class ApiRateLimitError2 extends Error{status=429;retryAfterSeconds;constructor(message="Request rate limited.",retryAfterSeconds){super(message);this.name="ApiRateLimitError";this.retryAfterSeconds=retryAfterSeconds}}var PROGRESS_ERROR_HEADER="X-GitHits-Progress-Error";function readProgressRejection(response){if(response.ok)return;const code=response.headers.get(PROGRESS_ERROR_HEADER)?.trim();return code?code:undefined}async function discardResponseBody(response){try{await response.body?.cancel()}catch{}}function withServiceDiagnostics(diagnostics,name,operation){return diagnostics?diagnostics.withOperation(name,operation):operation()}var DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS=240000;function isTokenRefreshableError(error){return error instanceof AuthenticationError2||error instanceof TermsAcceptanceRequiredError2}function parseRetryAfterSeconds(value,nowMs){const normalized=value?.trim();if(!normalized)return;if(/^\d+$/.test(normalized)){const delaySeconds=Number(normalized);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}if(/^[+-]?\d+(?:\.\d+)?$/.test(normalized))return;const isHttpDate=/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]+, \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]{2} [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(normalized);if(!isHttpDate)return;const retryAtMs=Date.parse(normalized);if(!Number.isFinite(retryAtMs))return;const delayMs=retryAtMs-nowMs;if(delayMs<0)return;const delaySeconds=Math.ceil(delayMs/1000);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}class GitHitsServiceImpl2{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=undefined,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params,options){options?.signal?.throwIfAborted();return withServiceDiagnostics(this.runtime.diagnostics,"githits.search.request",async()=>{const send=(progress)=>this.request("/search",{method:"POST",headers:this.headers(progress?.headers),body:JSON.stringify({query:params.query,source_format:params.sourceFormat,language:params.language,license_mode:params.licenseMode??"strict",include_explanation:params.includeExplanation??false}),...options?.signal?{signal:options.signal}:{}},this.runtime.exampleRequestTimeoutMs??DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS);let{response,body}=await send(options?.progress);const progressRejection=options?.progress&&readProgressRejection(response);if(progressRejection){options.progress?.rejected(progressRejection);({response,body}=await send())}if(!response.ok){throw this.createError(response,body)}return body})}headers(extra){return{...this.runtime.clientHeaders?.(),...extra,Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"}}fetchOptions(defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs??defaultTimeoutMs}}async request(path,init,defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");const fetchOptions=this.fetchOptions(defaultTimeoutMs);try{return await fetchWithTimeout(`${apiUrl.replace(/\/+$/,"")}${path}`,init,fetchOptions,async(response)=>({response,body:await response.text()}))}catch(cause){if(isCallerAbort(cause,init.signal))throw cause;if(isFetchTimeoutError(cause)||isAbortError(cause)){throw new GitHitsRequestTimeoutError(fetchOptions.timeoutMs,cause)}if(cause instanceof TypeError){throw new Error("Could not connect to GitHits. Check your connection and GITHITS_API_URL, then try again.",{cause})}throw cause}}createError(response,body){const status=response.status;const detail=parseHttpErrorDetail(body,["detail"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:throwIfProviderReauthenticationRequired(body);return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(detail||"Resource not found.");case 429:return new ApiRateLimitError2(undefined,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()));default:{if(status>=500){return new Error(`Server error (${status}). Try again shortly.${detail?` ${detail}`:""}`)}return new Error(`Request failed with status ${status}.${detail?` ${detail}`:""}`)}}}}class GitHitsRequestTimeoutError extends FetchTimeoutError2{constructor(timeoutMs,cause){super(timeoutMs,{cause});this.name="GitHitsRequestTimeoutError";this.message="Request to GitHits timed out. Try again."}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}function isCallerAbort(error,signal){return Boolean(signal?.aborted&&(error===signal.reason||isAbortError(error)))}async function executeWithTokenRefresh(options){const{signal}=options;signal?.throwIfAborted();const token=await callerFirst(signal,()=>options.getToken());signal?.throwIfAborted();if(!token){throw new AuthenticationError2(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){signal?.throwIfAborted();if(!options.shouldRefresh(error)){throw error}const refreshedToken=await callerFirst(signal,()=>options.forceRefresh());signal?.throwIfAborted();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}async function callerFirst(signal,step){try{return await step()}catch(error){signal?.throwIfAborted();throw error}}var AGENTIC_ASK_REQUEST_TIMEOUT_MS2=210000;var AGENTIC_ASK_MAX_RESPONSE_BYTES=4*1024*1024;var ERROR_DETAIL_MAX_BYTES=16384;var AGENTIC_ASK_REQUEST_RATE_LIMIT_MESSAGE="Research request rate limit reached. Wait the returned delay, or pause briefly if none is given, before any Research call, including other targets, questions, or threads. Use direct lookups only for a specific missing fact.";var AGENTIC_ASK_DAILY_LIMIT_DETAIL="research daily request limit exceeded; try again after 00:00 utc";var AGENTIC_ASK_DAILY_LIMIT_MESSAGE="Research daily request limit reached for this account or project. Try again after 00:00 UTC; do not retry before then. Reuse existing results or use a direct package/code/docs lookup for a specific remaining gap. Report required facts that remain unavailable. If this persists, contact support@githits.com.";var UUID_V7_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;class AgenticAskHttpError extends Error{code;status;toolCallId;retryAfterSeconds;threadId;targetError;rateLimitScope;retryable;constructor(code,message,status,toolCallId,retryAfterSeconds,retryable=false,threadId,targetError=undefined,rateLimitScope){super(message);this.code=code;this.status=status;this.toolCallId=toolCallId;this.retryAfterSeconds=retryAfterSeconds;this.threadId=threadId;this.targetError=targetError;this.rateLimitScope=rateLimitScope;this.name="AgenticAskHttpError";this.retryable=retryable}}class AgenticAskRequestTimeoutError extends Error{timeoutMs;constructor(timeoutMs){super("Research timed out. Reuse existing results or a direct lookup where sufficient; retry only if still needed and the caller allows enough execution time.");this.timeoutMs=timeoutMs;this.name="AgenticAskRequestTimeoutError"}}class AgenticAskConnectionError extends Error{constructor(options){super("Could not connect to GitHits. Check your connection and try again.",{cause:options?.cause});this.name="AgenticAskConnectionError"}}class MalformedAgenticAskResponseError extends Error{constructor(options){super("GitHits returned an invalid Research response.",{cause:options?.cause});this.name="MalformedAgenticAskResponseError"}}class AgenticAskResponseTooLargeError extends Error{maxBytes;constructor(maxBytes=AGENTIC_ASK_MAX_RESPONSE_BYTES){super("GitHits returned a Research response that was too large.");this.maxBytes=maxBytes;this.name="AgenticAskResponseTooLargeError"}}class AgenticAskServiceImpl2{apiUrl;tokenProvider;fetchFn;runtime;constructor(apiUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async ask(request,options){return this.askRequest(request,options)}async askRequest(request,options={}){return withServiceDiagnostics(this.runtime.diagnostics,"agentic-ask.request",()=>withRequestDeadline((signal)=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AgenticAskHttpError&&error.code==="AUTH_REQUIRED"||isTokenRefreshableError(error),executeWithToken:(token)=>this.executeAsk(token,request,signal,options.progress)}),options.signal,this.runtime.timeoutMs??AGENTIC_ASK_REQUEST_TIMEOUT_MS2))}async executeAsk(token,request,signal,progress){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");let response;try{response=await this.fetchFn(`${apiUrl.replace(/\/+$/,"")}/ask`,{method:"POST",headers:{...this.runtime.clientHeaders?.(),...progress?.headers,Authorization:`Bearer ${token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"},body:JSON.stringify({...request.target!==undefined?{target:request.target}:{thread_id:request.threadId},question:request.question,source_format:request.sourceFormat??"cli"}),signal})}catch(cause){if(signal.aborted||isAbortError2(cause))throw cause;if(cause instanceof TypeError){throw new AgenticAskConnectionError({cause})}throw cause}const progressRejection=progress&&readProgressRejection(response);if(progressRejection){progress.rejected(progressRejection);await discardResponseBody(response);return this.executeAsk(token,request,signal)}const toolCallId=readAgenticAskResponseId(response.headers.get("X-GitHits-Tool-Call-Id"));const threadId=readAgenticAskResponseId(response.headers.get("X-GitHits-Thread-Id"));if(!response.ok){let targetError;let rateLimitScope;if(response.status===401||response.status===403||response.status===400||response.status===429){let body="";try{body=await readBoundedResponseBody(response,response.status===403?AGENTIC_ASK_MAX_RESPONSE_BYTES:ERROR_DETAIL_MAX_BYTES)}catch(cause){if(signal.aborted)throw signal.reason??cause}if(response.status===401)throwIfProviderReauthenticationRequired(body);else if(response.status===403)throwIfTermsAcceptanceRequired(body);else if(response.status===400)targetError=parseTargetError(body);else rateLimitScope=parseRateLimitScope(body)}else{await response.body?.cancel().catch(()=>{return})}throw createHttpError(response,toolCallId,threadId,request,targetError,rateLimitScope)}let body;try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted||cause instanceof AgenticAskResponseTooLargeError){throw cause}throw new AgenticAskConnectionError({cause})}try{return JSON.parse(body)}catch(cause){throw new MalformedAgenticAskResponseError({cause})}}}function readAgenticAskResponseId(value){return value||undefined}function normalizeAgenticAskThreadId(value){return normalizeUuidV7(value)}function normalizeUuidV7(value){if(!value||value!==value.trim())return;if(value.includes(",")||hasControlCharacters(value))return;return UUID_V7_PATTERN.test(value)?value.toLowerCase():undefined}async function readBoundedResponseBody(response,maxBytes=AGENTIC_ASK_MAX_RESPONSE_BYTES){const declaredLength=response.headers.get("Content-Length");if(isDeclaredBodyTooLarge(declaredLength,maxBytes)){await response.body?.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}if(!response.body)return"";const reader=response.body.getReader();const decoder=new TextDecoder;let totalBytes=0;let text="";try{while(true){const{done,value}=await reader.read();if(done)break;totalBytes+=value.byteLength;if(totalBytes>maxBytes){await reader.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}text+=decoder.decode(value,{stream:true})}return text+decoder.decode()}finally{reader.releaseLock()}}function isDeclaredBodyTooLarge(value,maxBytes){if(!value||!/^\d+$/.test(value))return false;try{return BigInt(value)>BigInt(maxBytes)}catch{return false}}function parseTargetError(body){try{const detail=JSON.parse(body)?.detail;if(!detail||typeof detail.code!=="string"||typeof detail.message!=="string"||typeof detail.hint!=="string")return;return detail}catch{return}}function parseRateLimitScope(body){const detail=parseHttpErrorDetail(body,["detail"]);return detail?.trim().toLowerCase()===AGENTIC_ASK_DAILY_LIMIT_DETAIL?"daily":"request"}function createHttpError(response,toolCallId,threadId,request,targetError,rateLimitScope){const status=response.status;switch(status){case 400:return new AgenticAskHttpError("INVALID_TARGET",targetError?`${targetError.message} ${targetError.hint}`:request.target===undefined&&request.threadId===undefined?"GitHits could not answer this question for a supported target. Clarify the question or specify a public package or repository.":"GitHits could not validate this Research request or its target. Check the question and use a repository such as github:owner/repo@ref or a package such as npm:prisma@version. To correct a follow-up, keep thread_id and name the exact project or version in the question.",status,toolCallId,undefined,false,threadId,targetError);case 401:return new AgenticAskHttpError("AUTH_REQUIRED","GitHits could not accept the authentication token.",status,toolCallId,undefined,false,threadId);case 403:return new AgenticAskHttpError("ACCESS_DENIED","Access to Research is denied.",status,toolCallId,undefined,false,threadId);case 404:return new AgenticAskHttpError("THREAD_NOT_FOUND","Research thread was not found.",status,toolCallId,undefined,false,threadId);case 409:return new AgenticAskHttpError("INVALID_REQUEST","This Research thread cannot accept another follow-up.",status,toolCallId,undefined,false,threadId);case 422:return new AgenticAskHttpError("INVALID_REQUEST","GitHits rejected the Research request.",status,toolCallId,undefined,false,threadId);case 429:{const retryAfterSeconds=parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now());return rateLimitScope==="daily"?new AgenticAskHttpError("RATE_LIMITED",AGENTIC_ASK_DAILY_LIMIT_MESSAGE,status,toolCallId,retryAfterSeconds,false,threadId,undefined,"daily"):new AgenticAskHttpError("RATE_LIMITED",AGENTIC_ASK_REQUEST_RATE_LIMIT_MESSAGE,status,toolCallId,retryAfterSeconds,true,threadId,undefined,"request")}case 500:return new AgenticAskHttpError("EXECUTION_FAILED","Research failed.",status,toolCallId,undefined,false,threadId);case 503:return new AgenticAskHttpError("SERVICE_UNAVAILABLE","Research is temporarily unavailable.",status,toolCallId,undefined,true,threadId);case 504:return new AgenticAskHttpError("TIMEOUT","Research timed out.",status,toolCallId,undefined,true,threadId);default:return new AgenticAskHttpError("HTTP_ERROR",`Research request failed with status ${status}.`,status,toolCallId,undefined,status>=500,threadId)}}async function withRequestDeadline(operation,callerSignal,timeoutMs){callerSignal?.throwIfAborted();const timeoutController=new AbortController;const timeoutError=new AgenticAskRequestTimeoutError(timeoutMs);const signal=callerSignal?AbortSignal.any([callerSignal,timeoutController.signal]):timeoutController.signal;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timeoutController.abort(timeoutError);reject(timeoutError)},timeoutMs)});try{return await Promise.race([operation(signal),timeout])}catch(cause){if(callerSignal?.aborted){throw callerSignal.reason??cause}if(timeoutController.signal.aborted)throw timeoutError;throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function hasControlCharacters(value){return Array.from(value).some((character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159})}function isAbortError2(error){return error instanceof Error&&error.name==="AbortError"}var CLIENT_UPDATE_REQUIRED_REASON="Backend protocol changed";class ClientUpdateRequiredError extends Error{reason;currentVersion;constructor(message=`Update required: ${CLIENT_UPDATE_REQUIRED_REASON}`,reason=CLIENT_UPDATE_REQUIRED_REASON,currentVersion=undefined){super(message);this.reason=reason;this.currentVersion=currentVersion;this.name="ClientUpdateRequiredError"}}function isClientUpdateRequiredGraphQLError(input){return input.code==="CLIENT_UPDATE_REQUIRED"}function isGraphQLSchemaMismatchError(input){if(!isGraphQLSchemaMismatchMessage(input.message))return false;return!input.code||input.code==="GRAPHQL_VALIDATION_FAILED"||input.code==="BAD_USER_INPUT"}function isGraphQLSchemaMismatchMessage(message){return/Cannot query field|Field .* does not exist|Unknown argument|Unknown type|Unknown field/i.test(message)}import{z as z5}from"zod";function parseAvailableArtifacts(raw){if(!Array.isArray(raw))return;const parsed=[];for(const item of raw){if(item&&typeof item==="object"&&"ref"in item){const entry=item;if(typeof entry.ref==="string"){parsed.push({ref:entry.ref,version:typeof entry.version==="string"?entry.version:undefined})}}}return parsed.length>0?parsed:undefined}class PkgseerTransportError extends Error{constructor(message,options){super(message,options);this.name="PkgseerTransportError"}}function baseUrl(endpointUrl){return endpointUrl.replace(/\/+$/,"")}async function postPkgseerGraphql(request){const userAgent=request.userAgent??"githits-cli";const timeoutMs=request.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const endpointUrl=validateServiceUrl(request.endpointUrl,"package/source service URL");const clientHeaders=request.clientHeaders?.();let received;try{received=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",signal:request.signal,headers:{...clientHeaders,Authorization:`Bearer ${request.token}`,"Content-Type":"application/json","User-Agent":userAgent},body:JSON.stringify({query:request.query,variables:request.variables})},{fetchFn:request.fetchFn,timeoutMs},async(response)=>({response,responseBody:await response.text()}))}catch(cause){request.signal?.throwIfAborted();if(request.diagnostics?.isEnabled("pkg-graphql")){request.diagnostics.debug("pkg-graphql",{event:"transport-error",errorName:cause instanceof Error?cause.name:typeof cause,hasCause:true})}throw new PkgseerTransportError("Network request failed before a complete response was received. Caller should re-wrap with a domain-specific message.",{cause})}const{response,responseBody}=received;request.signal?.throwIfAborted();const parsedBody=parseJsonOrNull(responseBody);throwIfTermsAcceptanceRequired(parsedBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift","pub"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT",pub:"PUB"};var PKGSEER_REGISTRY_VALUES=Object.values(registryMap);var PKGSEER_REGISTRY_LIST2=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry2(registry){return registryMap[registry]}function toPkgseerRegistryLowercase2(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return Object.hasOwn(registryMap,value)}function parsePkgseerRegistryArg(value){const normalized=value.trim().toLowerCase();if(normalized==="cargo")return"crates";return isKnownPkgseerRegistryArg(normalized)?normalized:undefined}import{z as z2}from"zod";var INDEXING_DURATION_ESTIMATE_FIELDS=`
2
- lowerSeconds
3
- upperSeconds
4
- elapsedSeconds
5
- sampleCount
6
- source`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
7
- indexingEstimate {
8
- ${INDEXING_DURATION_ESTIMATE_FIELDS}
9
- }`;var INDEXING_ESTIMATES_SELECTION=`
10
- indexingEstimates {
11
- kind
12
- targets
13
- repositoryUrl
14
- commitSha
15
- estimate {
16
- ${INDEXING_DURATION_ESTIMATE_FIELDS}
17
- }
18
- unavailableReason
19
- }`;var indexingDurationEstimateSchema=z2.object({lowerSeconds:z2.number().int().nullable().optional(),upperSeconds:z2.number().int().nullable().optional(),elapsedSeconds:z2.number().int().nullable().optional(),sampleCount:z2.number().int().nullable().optional(),source:z2.string().nullable().optional()}).nullable().optional();var discoveryIndexingEstimateSchema=z2.object({kind:z2.enum(["REPOSITORY","DOCUMENTATION"]),targets:z2.array(z2.string()),repositoryUrl:z2.string().nullish(),commitSha:z2.string().nullish(),estimate:indexingDurationEstimateSchema,unavailableReason:z2.enum(["NO_HISTORY","UNSUPPORTED_WORK"]).nullish()});function normaliseIndexingDurationEstimate(estimate){if(!estimate)return;const out={};if(typeof estimate.lowerSeconds==="number"){out.lowerSeconds=estimate.lowerSeconds}if(typeof estimate.upperSeconds==="number"){out.upperSeconds=estimate.upperSeconds}if(typeof estimate.elapsedSeconds==="number"){out.elapsedSeconds=estimate.elapsedSeconds}if(typeof estimate.sampleCount==="number"){out.sampleCount=estimate.sampleCount}if(typeof estimate.source==="string")out.source=estimate.source;return Object.keys(out).length>0?out:undefined}var indexingEstimatesSchema=z2.array(discoveryIndexingEstimateSchema).transform((entries)=>entries.map((entry)=>({kind:entry.kind,targets:[...entry.targets],repositoryUrl:entry.repositoryUrl??undefined,commitSha:entry.commitSha??undefined,unavailableReason:entry.unavailableReason??undefined,estimate:normaliseIndexingDurationEstimate(entry.estimate)})));function parseIndexingDurationEstimate(extensions){const raw=extensions?.estimated_indexing_duration??extensions?.estimatedIndexingDuration??extensions?.indexing_estimate??extensions?.indexingEstimate;const parsed=indexingDurationEstimateSchema.safeParse(normaliseRawIndexingDurationEstimate(raw));if(!parsed.success)return;return normaliseIndexingDurationEstimate(parsed.data)}function normaliseRawIndexingDurationEstimate(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;const record=raw;return{lowerSeconds:record.lowerSeconds??record.lower_seconds,upperSeconds:record.upperSeconds??record.upper_seconds,elapsedSeconds:record.elapsedSeconds??record.elapsed_seconds,sampleCount:record.sampleCount??record.sample_count,source:record.source}}import{z as z3}from"zod";var READ_TARGET_SELECTION="target path selector startLine endLine";var positiveLineSchema=z3.number().int().positive();var readTargetInputSchema=z3.object({target:z3.string().min(1),path:z3.string().nullable().optional(),selector:z3.string().nullable().optional(),startLine:positiveLineSchema.nullable().optional(),endLine:positiveLineSchema.nullable().optional()}).superRefine((value,context)=>{if(value.startLine!=null&&value.endLine!=null&&value.endLine<value.startLine){context.addIssue({code:z3.ZodIssueCode.custom,path:["endLine"],message:"endLine must be greater than or equal to startLine"})}});function normaliseReadTarget(value){return{target:value.target,...value.path==null?{}:{path:value.path},...value.selector==null?{}:{selector:value.selector},...value.startLine==null?{}:{startLine:value.startLine},...value.endLine==null?{}:{endLine:value.endLine}}}var readTargetSchema=readTargetInputSchema.transform(normaliseReadTarget);var selectedReadTargetSchema=readTargetInputSchema.safeExtend({path:z3.string().nullable(),selector:z3.string().nullable(),startLine:positiveLineSchema.nullable(),endLine:positiveLineSchema.nullable()}).transform(normaliseReadTarget);import{z as z4}from"zod";var text=z4.string().refine((value)=>value.trim().length>0);var versions=z4.array(z4.string().min(1));var refs=z4.array(z4.object({ref:z4.string().min(1),version:z4.string().nullable().optional()}));function parseVersionRefRecovery(extensions){const code=extensions?.code;if(code!=="VERSION_NOT_FOUND"&&code!=="REF_NOT_FOUND")return;const result={code};if(typeof extensions?.retryable==="boolean")result.retryable=extensions.retryable;for(const[wire,key]of[["package","package"],["requested_version","requestedVersion"],["git_ref","requestedRef"],["repo_url","repoUrl"],["latest_version","latestVersion"],["latest_indexed","latestIndexed"]]){const raw=extensions?.[wire]??(wire==="repo_url"?extensions?.repoUrl:wire==="git_ref"?extensions?.gitRef:undefined);const parsed=text.safeParse(raw);if(parsed.success)result[key]=parsed.data}const published=versions.safeParse(extensions?.available_package_versions);if(published.success)result.availablePackageVersions=published.data;for(const[wire,key]of[["available_versions","availableVersions"],["available_refs","availableRefs"],["suggested_refs","suggestedRefs"]]){const parsed=refs.safeParse(extensions?.[wire]??extensions?.[key]);if(parsed.success)result[key]=parsed.data}const path=z4.array(z4.union([z4.string(),z4.number().int().nonnegative()])).safeParse(extensions?.input_path);if(path.success)result.inputPath=path.data;for(const[wire,key]of[["target_index","targetIndex"],["target_count","targetCount"]]){const parsed=z4.number().int().nonnegative().safeParse(extensions?.[wire]);if(parsed.success)result[key]=parsed.data}return result}class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;indexingEstimate;hint;indexingEstimates;repoUrl;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined,indexingEstimates=undefined,repoUrl=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;this.indexingEstimates=indexingEstimates;this.repoUrl=repoUrl;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeDiffError2 extends Error{details;partial;constructor(message,details=undefined,partial=undefined){super(message);this.details=details;this.partial=partial;this.name="CodeDiffError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;repoUrl;requestedRef;metadata;constructor(message,availableVersions,repoUrl,requestedRef,metadata=undefined){super(message);this.availableVersions=availableVersions;this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.metadata=metadata;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{recovery;constructor(message,recovery){super(message);this.recovery=recovery;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{recovery;constructor(message,recovery){super(message);this.recovery=recovery;this.name="CodeNavigationRefNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;metadata;constructor(message,status,graphqlCode,retryable,metadata=undefined){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.metadata=metadata;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
20
- availableRefs {
21
- version
22
- ref
23
- }`;var TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION=`
24
- suggestedRefs {
25
- version
26
- ref
27
- }`;var DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION=`
28
- suggestedRefs {
29
- version
30
- ref
31
- }`;var DOC_COVERAGE_SELECTION=`
32
- coverage {
33
- coverageState
34
- coverageReason
35
- pagesCrawled
36
- frontierRemaining
37
- artifactOverflowPageCount
38
- estimatedTotalPages
39
- note
40
- }`;var DOCUMENTATION_CONTRIBUTORS_SELECTION=`
41
- contributors {
42
- kind
43
- state
44
- freshness
45
- resultCount
46
- repositoryUrl
47
- commitSha
48
- siteKey
49
- siteUrl
50
- ${DOC_COVERAGE_SELECTION}
51
- }`;var TARGET_RESOLUTION_SELECTION=`
52
- targetResolution {
53
- requested {
54
- kind
55
- registry
56
- packageName
57
- version
58
- repoUrl
59
- gitRef
60
- commitSha
61
- releaseCorrespondence
62
- }
63
- resolvedRequested {
64
- kind
65
- registry
66
- packageName
67
- version
68
- repoUrl
69
- gitRef
70
- commitSha
71
- releaseCorrespondence
72
- committedAt
73
- }
74
- served {
75
- kind
76
- registry
77
- packageName
78
- version
79
- repoUrl
80
- gitRef
81
- commitSha
82
- releaseCorrespondence
83
- committedAt
84
- }
85
- freshness
86
- freshnessReason
87
- indexingRef
88
- availableVersions {
89
- version
90
- ref
91
- }
92
- ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
93
- ${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
94
- }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
95
- availableVersions {
96
- version
97
- ref
98
- }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
99
- availableVersions {
100
- version
101
- ref
102
- }
103
- availableRefs {
104
- version
105
- ref
106
- }
107
- ${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var UNIFIED_SEARCH_LOCATOR_SELECTION=`
108
- registry
109
- packageName
110
- version
111
- pageId
112
- docsReadTarget
113
- sourceKind
114
- sourceUrl
115
- repoUrl
116
- gitRef
117
- commitSha
118
- requestedRef
119
- filePath
120
- repositoryFilePath
121
- startLine
122
- endLine
123
- evidenceRange {
124
- startLine
125
- endLine
126
- matchLine
127
- rangeKind
128
- matchSpansTruncated
129
- }
130
- indexedRange {
131
- startLine
132
- endLine
133
- }
134
- symbolContext {
135
- name
136
- qualifiedPath
137
- kind
138
- relation
139
- definitionRange {
140
- filePath
141
- repositoryFilePath
142
- startLine
143
- endLine
144
- }
145
- }
146
- fileContentHash
147
- symbolRef
148
- qualifiedPath
149
- kind
150
- category
151
- language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
152
- repositoryEvidence {
153
- bm25MatchFields
154
- semanticContext {
155
- scopes {
156
- name
157
- qualifiedPath
158
- kind
159
- parentQualifiedPath
160
- declarationStartLine
161
- declarationEndLine
162
- parameterNames
163
- returnType
164
- symbolRef
165
- }
166
- scopeChainTruncated
167
- preferredRead {
168
- targetLabel
169
- registry
170
- packageName
171
- version
172
- repoUrl
173
- gitRef
174
- commitSha
175
- requestedRef
176
- filePath
177
- repositoryFilePath
178
- startLine
179
- endLine
180
- }
181
- }
182
- matchedSource {
183
- startLine
184
- endLine
185
- matchLine
186
- rangeKind
187
- matchSpansTruncated
188
- linesOmittedBefore
189
- linesOmittedAfter
190
- lines {
191
- lineNumber
192
- text
193
- highlights
194
- prefixTruncated
195
- suffixTruncated
196
- }
197
- }
198
- }`;var UNIFIED_SEARCH_QUERY=`
199
- query UnifiedSearch(
200
- $targets: [SearchPackageInput!]!
201
- $query: String!
202
- $sources: [DiscoverySearchSource!]
203
- $filters: DiscoverySearchFiltersInput
204
- $allowPartialResults: Boolean
205
- $limit: Int
206
- $offset: Int
207
- $waitTimeoutMs: Int
208
- ) {
209
- search(
210
- targets: $targets
211
- query: $query
212
- sources: $sources
213
- filters: $filters
214
- allowPartialResults: $allowPartialResults
215
- limit: $limit
216
- offset: $offset
217
- waitTimeoutMs: $waitTimeoutMs
218
- ) {
219
- completed
220
- searchRef
221
- result {
222
- query
223
- queryWarnings
224
- sources
225
- results {
226
- readTarget { ${READ_TARGET_SELECTION} }
227
- id
228
- resultType
229
- targetLabel
230
- requestedTargetLabel
231
- freshTargetLabel
232
- servedTargetLabel
233
- freshness
234
- title
235
- score
236
- highlights {
237
- title
238
- }
239
- documentationPreview {
240
- text
241
- highlights
242
- }
243
- ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
244
- locator {
245
- ${UNIFIED_SEARCH_LOCATOR_SELECTION}
246
- }
247
- }
248
- page {
249
- offset
250
- limit
251
- returned
252
- hasMore
253
- }
254
- partialResults
255
- evidenceNotice
256
- sourceStatus {
257
- source
258
- targetLabel
259
- requestedTargetLabel
260
- freshTargetLabel
261
- servedTargetLabel
262
- ${TARGET_RESOLUTION_SELECTION}
263
- indexingStatus
264
- codeIndexState
265
- resultCount
266
- appliedFilters
267
- ignoredFilters
268
- incompatibleFilters
269
- appliedQueryFeatures
270
- ignoredQueryFeatures
271
- incompatibleQueryFeatures
272
- suggestedSiteTargets
273
- suggestedSiteTargetsTruncated
274
- note
275
- ${DOC_COVERAGE_SELECTION}
276
- ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
277
- }
278
- }
279
- progress {
280
- searchRef
281
- status
282
- targetsTotal
283
- targetsReady
284
- elapsedMs
285
- ${INDEXING_ESTIMATES_SELECTION}
286
- query
287
- queryWarnings
288
- sources
289
- requestedSources
290
- targetMode
291
- requestedTargets {
292
- registry
293
- name
294
- version
295
- repoUrl
296
- gitRef
297
- site
298
- }
299
- filters {
300
- fileIntent
301
- kind
302
- category
303
- publicOnly
304
- pathPrefix
305
- }
306
- limit
307
- offset
308
- targets {
309
- requested
310
- resolvedRequested
311
- served
312
- freshness
313
- indexingRef
314
- requestedRefKind
315
- ${TARGET_RESOLUTION_SELECTION}
316
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
317
- ${DOC_COVERAGE_SELECTION}
318
- }
319
- expiresAt
320
- }
321
- }
322
- }`;var UNIFIED_SEARCH_STATUS_QUERY=`
323
- query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
324
- discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
325
- searchRef
326
- status
327
- targetsTotal
328
- targetsReady
329
- elapsedMs
330
- ${INDEXING_ESTIMATES_SELECTION}
331
- query
332
- queryWarnings
333
- sources
334
- requestedSources
335
- targetMode
336
- requestedTargets {
337
- registry
338
- name
339
- version
340
- repoUrl
341
- gitRef
342
- site
343
- }
344
- filters {
345
- fileIntent
346
- kind
347
- category
348
- publicOnly
349
- pathPrefix
350
- }
351
- limit
352
- offset
353
- targets {
354
- requested
355
- resolvedRequested
356
- served
357
- freshness
358
- indexingRef
359
- requestedRefKind
360
- ${TARGET_RESOLUTION_SELECTION}
361
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
362
- ${DOC_COVERAGE_SELECTION}
363
- }
364
- expiresAt
365
- results {
366
- query
367
- queryWarnings
368
- sources
369
- results {
370
- readTarget { ${READ_TARGET_SELECTION} }
371
- id
372
- resultType
373
- targetLabel
374
- requestedTargetLabel
375
- freshTargetLabel
376
- servedTargetLabel
377
- freshness
378
- title
379
- score
380
- highlights {
381
- title
382
- }
383
- documentationPreview {
384
- text
385
- highlights
386
- }
387
- ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
388
- locator {
389
- ${UNIFIED_SEARCH_LOCATOR_SELECTION}
390
- }
391
- }
392
- page {
393
- offset
394
- limit
395
- returned
396
- hasMore
397
- }
398
- partialResults
399
- evidenceNotice
400
- sourceStatus {
401
- source
402
- targetLabel
403
- requestedTargetLabel
404
- freshTargetLabel
405
- servedTargetLabel
406
- ${TARGET_RESOLUTION_SELECTION}
407
- indexingStatus
408
- codeIndexState
409
- resultCount
410
- appliedFilters
411
- ignoredFilters
412
- incompatibleFilters
413
- appliedQueryFeatures
414
- ignoredQueryFeatures
415
- incompatibleQueryFeatures
416
- suggestedSiteTargets
417
- suggestedSiteTargetsTruncated
418
- note
419
- ${DOC_COVERAGE_SELECTION}
420
- ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
421
- }
422
- }
423
- }
424
- }`;function debugUnifiedSearchRequest(variables,diagnostics){if(!diagnostics?.isEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);diagnostics.debug("code-nav",{event:"request",operation:"search",targetCount:Array.isArray(serialised.targets)?serialised.targets.length:0,sources:Array.isArray(serialised.sources)?serialised.sources:[],hasFilters:filters!==undefined,filterKeys:filters?Object.keys(filters).sort():[],fileIntent:filters&&typeof filters.fileIntent==="string"?filters.fileIntent:"omitted",allowPartialResults:serialised.allowPartialResults===true,presentVariableKeys:Object.keys(serialised).sort(),hasLimit:typeof serialised.limit==="number",hasOffset:typeof serialised.offset==="number",waitTimeoutMs:typeof serialised.waitTimeoutMs==="number"?serialised.waitTimeoutMs:undefined})}function debugGraphqlWireRequest(operation,graphqlQuery,variables,diagnostics){if(!diagnostics?.isEnabled("code-nav-wire"))return;diagnostics.debug("code-nav-wire",{event:"wire-request",operation,graphqlQuery,variables:serialiseForDebug(variables)})}function serialiseForDebug(value){try{const text=JSON.stringify(value);if(!text)return{};const parsed=JSON.parse(text);return asRecord(parsed)??{}}catch{return{}}}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value)){return value}return}var availableVersionSchema=z5.object({version:z5.string().nullable().optional(),ref:z5.string()});var targetResolutionIdentitySchema=z5.object({kind:z5.string().nullable().optional(),registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),version:z5.string().nullable().optional(),repoUrl:z5.string().nullable().optional(),gitRef:z5.string().nullable().optional(),commitSha:z5.string().nullable().optional(),committedAt:z5.string().nullable().optional(),releaseCorrespondence:z5.string().nullable().optional(),site:z5.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z5.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z5.string().nullable().optional(),freshnessReason:z5.string().nullable().optional(),indexingRef:z5.string().nullable().optional(),availableVersions:z5.array(availableVersionSchema).nullable().optional(),availableRefs:z5.array(availableVersionSchema).nullable().optional(),suggestedRefs:z5.array(availableVersionSchema).nullable().optional()}).nullable().optional();var requiredTargetResolutionSchema=targetResolutionSchema.unwrap().unwrap().transform((value)=>normaliseTargetResolution(value));var unifiedSearchSourceSchema=z5.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z5.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLineRangeSchema=z5.object({startLine:z5.number().int().positive(),endLine:z5.number().int().positive()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchEvidenceRangeSchema=unifiedSearchLineRangeSchema.extend({matchLine:z5.number().int().positive().nullable().optional(),rangeKind:z5.string().nullable().optional(),matchSpansTruncated:z5.boolean()});var unifiedSearchDefinitionRangeSchema=unifiedSearchLineRangeSchema.extend({filePath:z5.string(),repositoryFilePath:z5.string()});var unifiedSearchSymbolContextBaseSchema=z5.object({name:z5.string(),qualifiedPath:z5.string().nullable().optional(),kind:z5.string().nullable().optional()});var unifiedSearchSymbolContextSchema=z5.discriminatedUnion("relation",[unifiedSearchSymbolContextBaseSchema.extend({relation:z5.literal("ENCLOSES_MATCH"),definitionRange:unifiedSearchDefinitionRangeSchema}),unifiedSearchSymbolContextBaseSchema.extend({relation:z5.literal("ASSOCIATED_WITH_INDEXED_CHUNK"),definitionRange:unifiedSearchDefinitionRangeSchema.nullable().optional()})]);var unifiedSearchLocatorSchema=z5.object({registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),version:z5.string().nullable().optional(),pageId:z5.string().nullable().optional(),docsReadTarget:z5.string().nullable().optional(),sourceKind:z5.string().nullable().optional(),sourceUrl:z5.string().nullable().optional(),repoUrl:z5.string().nullable().optional(),gitRef:z5.string().nullable().optional(),commitSha:z5.string().nullable().optional(),requestedRef:z5.string().nullable().optional(),filePath:z5.string().nullable().optional(),repositoryFilePath:z5.string().nullable().optional(),startLine:z5.number().int().nullable().optional(),endLine:z5.number().int().nullable().optional(),evidenceRange:unifiedSearchEvidenceRangeSchema.nullable().optional(),indexedRange:unifiedSearchLineRangeSchema.nullable().optional(),symbolContext:unifiedSearchSymbolContextSchema.nullable().optional(),fileContentHash:z5.string().nullable().optional(),symbolRef:z5.string().nullable().optional(),qualifiedPath:z5.string().nullable().optional(),kind:z5.string().nullable().optional(),category:z5.string().nullable().optional(),language:z5.string().nullable().optional()});var unifiedSearchSemanticPreferredReadSchema=z5.object({targetLabel:z5.string(),registry:z5.string().nullable(),packageName:z5.string().nullable(),version:z5.string().nullable(),repoUrl:z5.string(),gitRef:z5.string(),commitSha:z5.string(),requestedRef:z5.string().nullable(),filePath:z5.string(),repositoryFilePath:z5.string(),startLine:unifiedSearchLineRangeSchema.shape.startLine,endLine:unifiedSearchLineRangeSchema.shape.endLine}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchSemanticScopeSchema=z5.object({name:z5.string(),qualifiedPath:z5.string(),kind:z5.string(),parentQualifiedPath:z5.string().nullable(),declarationStartLine:z5.number().int().positive(),declarationEndLine:z5.number().int().positive(),parameterNames:z5.array(z5.string()),returnType:z5.string().nullable(),symbolRef:z5.string()}).refine((range)=>range.declarationStartLine<=range.declarationEndLine,{message:"declarationStartLine must be less than or equal to declarationEndLine"});var unifiedSearchSemanticContextSchema=z5.object({scopes:z5.array(unifiedSearchSemanticScopeSchema),scopeChainTruncated:z5.boolean(),preferredRead:unifiedSearchSemanticPreferredReadSchema});var unifiedSearchHighlightSchema=z5.tuple([z5.number().int().nonnegative(),z5.number().int().nonnegative()]).refine(([start,end])=>start<=end,{message:"highlight start must be less than or equal to end"});var unifiedSearchFocusedSourceLineSchema=z5.object({lineNumber:z5.number().int().positive(),text:z5.string(),highlights:z5.array(unifiedSearchHighlightSchema),prefixTruncated:z5.boolean(),suffixTruncated:z5.boolean()});var unifiedSearchBm25MatchFieldSchema=z5.enum(["SYMBOL_NAME","FILE_PATH","DOCUMENTATION","SOURCE_IDENTIFIER"]);var unifiedSearchMatchedSourceSchema=unifiedSearchLineRangeSchema.extend({matchLine:z5.number().int().positive().nullable(),rangeKind:z5.string(),matchSpansTruncated:z5.boolean(),lines:z5.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z5.boolean(),linesOmittedAfter:z5.boolean()});var unifiedSearchDocumentationPreviewSchema=z5.object({text:z5.string().min(1),highlights:z5.array(unifiedSearchHighlightSchema)});var unifiedSearchRepositoryEvidenceSchema=z5.object({semanticContext:unifiedSearchSemanticContextSchema.nullable(),bm25MatchFields:z5.array(unifiedSearchBm25MatchFieldSchema).min(1).nullable().optional(),matchedSource:unifiedSearchMatchedSourceSchema.nullable().optional()});var contentSafetySchema=z5.object({filtered:z5.boolean(),modifications:z5.array(z5.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var unifiedSearchHitSchema=z5.object({readTarget:selectedReadTargetSchema.nullable(),id:z5.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z5.string(),requestedTargetLabel:z5.string().nullable().optional(),freshTargetLabel:z5.string().nullable().optional(),servedTargetLabel:z5.string().nullable().optional(),freshness:z5.string().nullable().optional(),title:z5.string().nullable().optional(),score:z5.number().nullable().optional(),highlights:z5.object({title:z5.array(z5.tuple([z5.number().int(),z5.number().int()])).nullable().optional()}).nullable().optional(),repositoryEvidence:unifiedSearchRepositoryEvidenceSchema.nullable().optional(),documentationPreview:unifiedSearchDocumentationPreviewSchema.nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z5.object({offset:z5.number().int(),limit:z5.number().int(),returned:z5.number().int(),hasMore:z5.boolean()});var docCoverageSchema=z5.object({coverageState:z5.string(),coverageReason:z5.string().nullable().optional(),pagesCrawled:z5.number().int().nullable().optional(),frontierRemaining:z5.number().int().nullable().optional(),artifactOverflowPageCount:z5.number().int().nullable().optional(),estimatedTotalPages:z5.number().int().nullable().optional(),note:z5.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z5.object({kind:z5.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z5.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z5.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z5.number().int().nonnegative(),repositoryUrl:z5.string().nullable().optional(),commitSha:z5.string().nullable().optional(),siteKey:z5.string().nullable().optional(),siteUrl:z5.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z5.object({source:unifiedSearchSourceSchema,targetLabel:z5.string(),requestedTargetLabel:z5.string().nullable().optional(),freshTargetLabel:z5.string().nullable().optional(),servedTargetLabel:z5.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z5.string().nullable().optional(),codeIndexState:z5.string().nullable().optional(),resultCount:z5.number().int().nullable().optional(),appliedFilters:z5.array(z5.string()),ignoredFilters:z5.array(z5.string()),incompatibleFilters:z5.array(z5.string()),appliedQueryFeatures:z5.array(z5.string()),ignoredQueryFeatures:z5.array(z5.string()),incompatibleQueryFeatures:z5.array(z5.string()),suggestedSiteTargets:z5.array(z5.string()),suggestedSiteTargetsTruncated:z5.boolean(),note:z5.string().nullable().optional(),coverage:docCoverageSchema,contributors:z5.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z5.object({query:z5.string(),queryWarnings:z5.array(z5.string()),sources:z5.array(unifiedSearchSourceSchema),results:z5.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z5.boolean(),sourceStatus:z5.array(unifiedSearchSourceStatusSchema),evidenceNotice:z5.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z5.string().min(1);var unifiedSearchFiltersSchema=z5.object({fileIntent:z5.string().nullable().optional(),kind:z5.string().nullable().optional(),category:z5.string().nullable().optional(),publicOnly:z5.boolean().nullable().optional(),pathPrefix:z5.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z5.object({requested:z5.string().nullable().optional(),resolvedRequested:z5.string().nullable().optional(),served:z5.string().nullable().optional(),freshness:z5.string().nullable().optional(),indexingRef:z5.string().nullable().optional(),requestedRefKind:z5.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z5.array(availableVersionSchema).nullable().optional(),availableRefs:z5.array(availableVersionSchema).nullable().optional(),suggestedRefs:z5.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z5.object({registry:z5.string().nullable().optional(),name:z5.string().nullable().optional(),version:z5.string().nullable().optional(),repoUrl:z5.string().nullable().optional(),gitRef:z5.string().nullable().optional(),site:z5.string().nullable().optional()});var unifiedSearchProgressSchema=z5.object({searchRef:z5.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z5.number().int(),targetsReady:z5.number().int(),elapsedMs:z5.number().int(),query:z5.string(),queryWarnings:z5.array(z5.string()),sources:z5.array(unifiedSearchSourceSchema),requestedSources:z5.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z5.string().nullable().optional(),requestedTargets:z5.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z5.number().int().nullable().optional(),offset:z5.number().int().nullable().optional(),targets:z5.array(unifiedSearchProgressTargetSchema).nullable().optional(),indexingEstimates:indexingEstimatesSchema,expiresAt:z5.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z5.object({completed:z5.boolean(),searchRef:z5.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z5.object({message:z5.string(),extensions:z5.record(z5.string(),z5.unknown()).optional()});var codeDiffGraphQLErrorSchema=z5.object({message:z5.string(),path:z5.array(z5.union([z5.string(),z5.number().int()])).nullable().optional(),extensions:z5.record(z5.string(),z5.unknown()).optional()});var codeDiffRegistrySchema=z5.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z5.object({registry:codeDiffRegistrySchema,name:z5.string(),repoUrl:z5.string()});var codeDiffRefResolutionSchema=z5.object({releaseCorrespondence:z5.string().nullable().optional(),requested:z5.string(),resolvedVersion:z5.string().nullable().optional(),ref:z5.string(),commitSha:z5.string(),refKind:z5.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z5.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z5.object({filesChanged:z5.number().int(),added:z5.number().int(),deleted:z5.number().int(),modified:z5.number().int(),modeChanged:z5.number().int(),typeChanged:z5.number().int(),inventoryComplete:z5.boolean(),unprojectableFiles:z5.number().int()});var rawCodeDiffScopeSchema=z5.object({status:z5.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z5.string().nullable().optional(),toSubpath:z5.string().nullable().optional(),pathPrefix:z5.string().nullable().optional(),pathGlob:z5.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z5.object({code:z5.string(),retryable:z5.boolean(),retryAfterMs:z5.number().int().nullable().optional(),stage:z5.string().nullable().optional(),limitKind:z5.string().nullable().optional()});var rawCodeDiffFileSchema=z5.object({path:z5.string(),pathEncoding:z5.enum(["UTF8","BYTE_ESCAPED"]),status:z5.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z5.boolean(),typeChanged:z5.boolean(),additions:z5.number().int().nullable().optional(),deletions:z5.number().int().nullable().optional(),patch:z5.string().nullable().optional(),contentStatus:z5.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z5.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z5.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z5.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z5.array(rawCodeDiffFileSchema),hasMoreFiles:z5.boolean()});var codeDiffResultSchema=z5.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z5.object({data:z5.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z5.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
425
- registry
426
- name
427
- repoUrl
428
- }
429
- fromResolution {
430
- requested
431
- resolvedVersion
432
- ref
433
- commitSha
434
- refKind
435
- versionSource
436
- releaseCorrespondence
437
- }
438
- toResolution {
439
- requested
440
- resolvedVersion
441
- ref
442
- commitSha
443
- refKind
444
- versionSource
445
- releaseCorrespondence
446
- }
447
- raw {
448
- summary {
449
- filesChanged
450
- added
451
- deleted
452
- modified
453
- modeChanged
454
- typeChanged
455
- inventoryComplete
456
- unprojectableFiles
457
- }
458
- scope {
459
- status
460
- fromSubpath
461
- toSubpath
462
- pathPrefix
463
- pathGlob
464
- }
465
- contentCoverage
466
- contentFailure {
467
- code
468
- retryable
469
- retryAfterMs
470
- stage
471
- limitKind
472
- }
473
- files {
474
- path
475
- pathEncoding
476
- status
477
- modeChanged
478
- typeChanged
479
- contentStatus
480
- contentSafety {
481
- filtered
482
- modifications
483
- }`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
484
- additions
485
- deletions`:`
486
- additions
487
- deletions
488
- patch
489
- contentOmissionReason`;return`
490
- query CodeDiff(
491
- $registry: Registry
492
- $name: String
493
- $fromVersion: String
494
- $toVersion: String
495
- $repoUrl: String
496
- $fromRef: String
497
- $toRef: String
498
- $rawOptions: RawCodeDiffOptions
499
- ) {
500
- codeDiff(
501
- registry: $registry
502
- name: $name
503
- fromVersion: $fromVersion
504
- toVersion: $toVersion
505
- repoUrl: $repoUrl
506
- fromRef: $fromRef
507
- toRef: $toRef
508
- rawOptions: $rawOptions
509
- ) {
510
- ${CODE_DIFF_COMMON_SELECTION}${contentFields}
511
- }
512
- hasMoreFiles
513
- }
514
- }
515
- }`}var navigationResolutionSchema=z5.object({requestedVersion:z5.string().nullable().optional(),requestedRef:z5.string().nullable().optional(),resolvedRef:z5.string().nullable().optional(),commitSha:z5.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z5.object({hint:z5.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z5.object({path:z5.string(),name:z5.string().nullable().optional(),language:z5.string().nullable().optional(),fileType:z5.string().nullable().optional(),byteSize:z5.number().int().nullable().optional()});var listRepoFilesResponseSchema=z5.object({files:z5.array(repoFileEntrySchema),total:z5.number().int(),hasMore:z5.boolean(),indexedVersion:z5.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z5.string(),indexingRef:z5.string().nullable().optional(),availableVersions:z5.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,indexingEstimates:indexingEstimatesSchema});var listRepoFilesGraphQLResponseSchema=z5.object({data:z5.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
516
- query ListRepoFiles(
517
- $registry: Registry
518
- $packageName: String
519
- $repoUrl: String
520
- $gitRef: String
521
- $version: String
522
- $pathPrefix: String
523
- $pathSelectors: [FilePathSelectorInput!]
524
- $extensions: [String!]
525
- $fileTypes: [String!]
526
- $languages: [String!]
527
- $fileIntent: FileIntent
528
- $fileIntents: [FileIntent!]
529
- $excludeFileIntents: [FileIntent!]
530
- $excludeDocFiles: Boolean
531
- $excludeTestFiles: Boolean
532
- $includeHidden: Boolean
533
- $limit: Int
534
- $waitTimeoutMs: Int
535
- ) {
536
- listRepoFiles(
537
- registry: $registry
538
- packageName: $packageName
539
- repoUrl: $repoUrl
540
- gitRef: $gitRef
541
- version: $version
542
- pathPrefix: $pathPrefix
543
- pathSelectors: $pathSelectors
544
- extensions: $extensions
545
- fileTypes: $fileTypes
546
- languages: $languages
547
- fileIntent: $fileIntent
548
- fileIntents: $fileIntents
549
- excludeFileIntents: $excludeFileIntents
550
- excludeDocFiles: $excludeDocFiles
551
- excludeTestFiles: $excludeTestFiles
552
- includeHidden: $includeHidden
553
- limit: $limit
554
- waitTimeoutMs: $waitTimeoutMs
555
- ) {
556
- files {
557
- path
558
- name
559
- language
560
- fileType
561
- byteSize
562
- }
563
- total
564
- hasMore
565
- indexedVersion
566
- resolution {
567
- requestedVersion
568
- requestedRef
569
- resolvedRef
570
- commitSha
571
- }
572
- ${TARGET_RESOLUTION_SELECTION}
573
- diagnostics {
574
- hint
575
- }
576
- codeIndexState
577
- indexingRef
578
- availableVersions {
579
- version
580
- ref
581
- }
582
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
583
- ${INDEXING_ESTIMATES_SELECTION}
584
- }
585
- }`;var codeContextResponseSchema=z5.object({content:z5.string().nullable().optional(),filePath:z5.string().nullable().optional(),language:z5.string().nullable().optional(),totalLines:z5.number().int().nullable().optional(),startLine:z5.number().int().nullable().optional(),endLine:z5.number().int().nullable().optional(),repoUrl:z5.string().nullable().optional(),gitRef:z5.string().nullable().optional(),isBinary:z5.boolean().nullable().optional(),codeIndexState:z5.string(),indexingRef:z5.string().nullable().optional(),availableVersions:z5.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,indexingEstimates:indexingEstimatesSchema,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z5.object({data:z5.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
586
- query FetchCodeContext(
587
- $registry: Registry
588
- $packageName: String
589
- $repoUrl: String
590
- $gitRef: String
591
- $version: String
592
- $filePath: String!
593
- $startLine: Int
594
- $endLine: Int
595
- $waitTimeoutMs: Int
596
- ) {
597
- fetchCodeContext(
598
- registry: $registry
599
- packageName: $packageName
600
- repoUrl: $repoUrl
601
- gitRef: $gitRef
602
- version: $version
603
- filePath: $filePath
604
- startLine: $startLine
605
- endLine: $endLine
606
- waitTimeoutMs: $waitTimeoutMs
607
- ) {
608
- content
609
- filePath
610
- language
611
- totalLines
612
- startLine
613
- endLine
614
- repoUrl
615
- gitRef
616
- isBinary
617
- codeIndexState
618
- indexingRef
619
- ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
620
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
621
- ${INDEXING_ESTIMATES_SELECTION}
622
- ${TARGET_RESOLUTION_SELECTION}
623
- }
624
- }`;var grepRepoMatchSchema=z5.object({filePath:z5.string(),line:z5.number().int(),matchStartByte:z5.number().int(),matchEndByte:z5.number().int(),lineContent:z5.string(),contextBefore:z5.array(z5.string()).nullable().optional(),contextAfter:z5.array(z5.string()).nullable().optional(),fileContentHash:z5.string().nullable().optional(),fileIntent:z5.string().nullable().optional(),symbolRowId:z5.string().nullable().optional(),symbol:z5.object({symbolRef:z5.string().optional(),name:z5.string().optional(),qualifiedPath:z5.string().nullable().optional(),kind:z5.string().nullable().optional(),category:z5.string().nullable().optional(),arity:z5.number().int().nullable().optional(),isPublic:z5.boolean().nullable().optional(),filePath:z5.string().nullable().optional(),startLine:z5.number().int().nullable().optional(),endLine:z5.number().int().nullable().optional(),contentHash:z5.string().nullable().optional(),parentPath:z5.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z5.object({matches:z5.array(grepRepoMatchSchema),nextCursor:z5.string().nullable().optional(),hasMore:z5.boolean(),truncatedReason:z5.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z5.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z5.number().int(),filesInScope:z5.number().int(),binaryFilesSkipped:z5.number().int(),filesTooLargeSkipped:z5.number().int(),totalMatches:z5.number().int(),uniqueFilesMatched:z5.number().int(),indexedVersion:z5.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z5.string(),indexingRef:z5.string().nullable().optional(),availableVersions:z5.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,indexingEstimates:indexingEstimatesSchema});var grepRepoGraphQLResponseSchema=z5.object({data:z5.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema).optional()});var GREP_REPO_SYMBOL_SELECTIONS={symbol_ref:"symbolRef",name:"name",qualified_path:"qualifiedPath",kind:"kind",category:"category",arity:"arity",is_public:"isPublic",file_path:"filePath",start_line:"startLine",end_line:"endLine",content_hash:"contentHash",parent_path:"parentPath"};function buildGrepRepoQuery(symbolFields){const symbolSelection=(symbolFields??[]).map((field)=>GREP_REPO_SYMBOL_SELECTIONS[field]).filter((field)=>Boolean(field)).filter((field,index,fields)=>fields.indexOf(field)===index).join(`
625
- `);const symbolBlock=symbolSelection.length>0?`
626
- symbol {
627
- ${symbolSelection}
628
- }`:"";return`
629
- query GrepRepo(
630
- $registry: Registry
631
- $packageName: String
632
- $repoUrl: String
633
- $gitRef: String
634
- $version: String
635
- $waitTimeoutMs: Int
636
- $pattern: String!
637
- $patternType: GrepPatternType
638
- $caseSensitive: Boolean
639
- $pathSelectors: [GrepPathSelectorInput!]
640
- $extensions: [String!]
641
- $excludeDocFiles: Boolean
642
- $excludeTestFiles: Boolean
643
- $allowUnscoped: Boolean
644
- $contextLinesBefore: Int
645
- $contextLinesAfter: Int
646
- $maxMatches: Int
647
- $maxMatchesPerFile: Int
648
- $cursor: String
649
- $symbolFields: [String!]
650
- ) {
651
- grepRepo(
652
- registry: $registry
653
- packageName: $packageName
654
- repoUrl: $repoUrl
655
- gitRef: $gitRef
656
- version: $version
657
- waitTimeoutMs: $waitTimeoutMs
658
- pattern: $pattern
659
- patternType: $patternType
660
- caseSensitive: $caseSensitive
661
- pathSelectors: $pathSelectors
662
- extensions: $extensions
663
- excludeDocFiles: $excludeDocFiles
664
- excludeTestFiles: $excludeTestFiles
665
- allowUnscoped: $allowUnscoped
666
- contextLinesBefore: $contextLinesBefore
667
- contextLinesAfter: $contextLinesAfter
668
- maxMatches: $maxMatches
669
- maxMatchesPerFile: $maxMatchesPerFile
670
- cursor: $cursor
671
- symbolFields: $symbolFields
672
- ) {
673
- matches {
674
- filePath
675
- line
676
- matchStartByte
677
- matchEndByte
678
- lineContent
679
- contextBefore
680
- contextAfter
681
- fileContentHash
682
- fileIntent
683
- symbolRowId${symbolBlock}
684
- }
685
- nextCursor
686
- totalMatches
687
- hasMore
688
- truncatedReason
689
- routeTaken
690
- filesScanned
691
- filesInScope
692
- binaryFilesSkipped
693
- filesTooLargeSkipped
694
- uniqueFilesMatched
695
- indexedVersion
696
- resolution {
697
- requestedVersion
698
- requestedRef
699
- resolvedRef
700
- commitSha
701
- }
702
- ${TARGET_RESOLUTION_SELECTION}
703
- codeIndexState
704
- indexingRef
705
- availableVersions {
706
- version
707
- ref
708
- }
709
- ${INDEXING_DURATION_ESTIMATE_SELECTION}
710
- ${INDEXING_ESTIMATES_SELECTION}
711
- }
712
- }`}var unifiedSearchGraphQLResponseSchema=z5.object({data:z5.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z5.object({data:z5.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl2{codeNavigationUrl;tokenProvider;fetchFn;runtime;constructor(codeNavigationUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.codeNavigationUrl=codeNavigationUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async postGraphqlWithTargetResolutionFallback(input){const response=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:input.query,variables:input.variables,timeoutMs:input.timeoutMs,signal:input.signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){if(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"target-resolution-query-fallback"})}const fallbackResponse=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:fallbackQuery,variables:input.variables,timeoutMs:input.timeoutMs,signal:input.signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal:options?.signal,executeWithToken:(token)=>this.executeUnifiedSearch(token,{...params,waitTimeoutMs:params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS},options)})}async searchStatus(searchRef,waitTimeoutMs=DEFAULT_WAIT_TIMEOUT_MS,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal:options?.signal,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options)})}async codeDiff(params,options){validateCodeDiffParams(params);const signal=options?.signal;return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executeCodeDiff(token,params,signal)})}async executeCodeDiff(token,params,signal){const query=buildCodeDiffQuery(params.mode);const variables=buildCodeDiffVariables(params);debugGraphqlWireRequest("codeDiff",query,variables,this.runtime.diagnostics);let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query,variables,signal})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=codeDiffGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const data=parsed.data.data?.codeDiff;const errors=parsed.data.errors??[];if(errors.length>0){const rawErrors=errors.filter(isCodeDiffRawError);if(rawErrors.length>0){throw new CodeDiffError2(rawErrors.map((error)=>error.message).join(", "),parseCodeDiffErrorDetails(rawErrors),data?normaliseCodeDiffPartial(data):undefined)}throw this.createCodeDiffRootError(errors)}if(!data?.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return normaliseCodeDiffResult(data)}createCodeDiffRootError(errors){const graphQLErrors=errors.map(({message,extensions})=>({message,extensions}));const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(code==="UNAUTHORIZED"||code==="FORBIDDEN"||code==="FEATURE_FLAG_REQUIRED"||isClientUpdateRequiredGraphQLError({message,code})||isGraphQLSchemaMismatchError({message,code})||code===undefined&&isAuthMessage(message)){return this.createGraphQLError(graphQLErrors)}return new CodeDiffError2(message,parseCodeDiffErrorDetails(errors))}async executeUnifiedSearch(token,params,options){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef,site:target.site})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??true,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables,this.runtime.diagnostics);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables,this.runtime.diagnostics);try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_QUERY,variables,timeoutMs:indexingRequestTimeoutMs(params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS),signal:options?.signal})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.search;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return this.normaliseUnifiedSearchOutcome(data)}async executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,timeoutMs:indexingRequestTimeoutMs(waitTimeoutMs),signal:options?.signal,variables:{searchRef,includeResults:true,waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){return createCodeNavigationHttpError(response)}createTransportError(error){return createCodeNavigationTransportError(error)}createGraphQLError(errors){return createCodeNavigationGraphQLError(errors,this.runtime)}normaliseUnifiedSearchOutcome(data){const progress=data.progress?this.normaliseUnifiedSearchProgress(data.progress):undefined;if(data.completed){if(!data.result){throw new MalformedCodeNavigationResponseError("Completed unified search response missing result payload.")}return{state:"completed",completed:true,searchRef:data.searchRef??undefined,result:this.normaliseUnifiedSearchResult(data.result),progress}}const searchRef=data.searchRef??progress?.searchRef;if(!searchRef){throw new MalformedCodeNavigationResponseError("Incomplete unified search response missing search reference.")}const result=data.result?this.normaliseUnifiedSearchResult(data.result):undefined;return{state:"incomplete",completed:false,searchRef,result,progress}}normaliseUnifiedSearchResult(result){return{query:result.query,queryWarnings:result.queryWarnings,sources:result.sources,results:result.results.map((entry)=>({readTarget:entry.readTarget,id:entry.id,resultType:entry.resultType,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,freshness:entry.freshness??undefined,title:entry.title??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined}:undefined,repositoryEvidence:entry.repositoryEvidence,documentationPreview:entry.documentationPreview,locator:normaliseUnifiedSearchLocator(entry.locator)})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,suggestedSiteTargets:entry.suggestedSiteTargets,suggestedSiteTargetsTruncated:entry.suggestedSiteTargetsTruncated,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage),contributors:entry.contributors.map((contributor)=>({kind:contributor.kind,state:contributor.state,freshness:contributor.freshness??undefined,resultCount:contributor.resultCount,repositoryUrl:contributor.repositoryUrl??undefined,commitSha:contributor.commitSha??undefined,siteKey:contributor.siteKey??undefined,siteUrl:contributor.siteUrl??undefined,coverage:normaliseDocCoverage(contributor.coverage,{preserveNone:true})}))})),evidenceNotice:result.evidenceNotice??undefined}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),indexingEstimates:progress.indexingEstimates,expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){throwIfCodeContextIndexing(data)}async listFiles(params){params={...params,waitTimeoutMs:params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS};return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListFiles(token,params)})}async executeListFiles(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({timeoutMs:indexingRequestTimeoutMs(params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS),token,query:LIST_REPO_FILES_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,pathPrefix:params.pathPrefix,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,fileTypes:params.fileTypes,languages:params.languages,fileIntent:params.fileIntent,fileIntents:params.fileIntents,excludeFileIntents:params.excludeFileIntents,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,includeHidden:params.includeHidden,limit:params.limit,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=listRepoFilesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.listRepoFiles;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{files:data.files.map((entry)=>({path:entry.path,name:entry.name??undefined,language:entry.language??undefined,fileType:entry.fileType??undefined,byteSize:entry.byteSize??undefined})),total:data.total,hasMore:data.hasMore,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),hint:data.diagnostics?.hint??undefined,indexingEstimates:data.indexingEstimates}}async readFile(params){params={...params,waitTimeoutMs:params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS};return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadFile(token,params)})}async executeReadFile(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({timeoutMs:indexingRequestTimeoutMs(params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS),token,query:FETCH_CODE_CONTEXT_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,filePath:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=fetchCodeContextGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.fetchCodeContext;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return normaliseCodeContextResult(data)}async grepRepo(params){params={...params,waitTimeoutMs:params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS};return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeGrepRepo(token,params)})}async executeGrepRepo(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({timeoutMs:indexingRequestTimeoutMs(params.waitTimeoutMs??DEFAULT_WAIT_TIMEOUT_MS),token,query:buildGrepRepoQuery(params.symbolFields),variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,waitTimeoutMs:params.waitTimeoutMs,pattern:params.pattern,patternType:params.patternType,caseSensitive:params.caseSensitive,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,allowUnscoped:params.allowUnscoped,contextLinesBefore:params.contextLinesBefore,contextLinesAfter:params.contextLinesAfter,maxMatches:params.maxMatches,maxMatchesPerFile:params.maxMatchesPerFile,cursor:params.cursor,symbolFields:params.symbolFields}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=grepRepoGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.grepRepo;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{matches:data.matches.map((entry)=>({filePath:entry.filePath,line:entry.line,matchStartByte:entry.matchStartByte,matchEndByte:entry.matchEndByte,lineContent:entry.lineContent,contextBefore:entry.contextBefore??undefined,contextAfter:entry.contextAfter??undefined,fileContentHash:entry.fileContentHash??undefined,fileIntent:entry.fileIntent??undefined,symbolRowId:entry.symbolRowId??undefined,symbol:entry.symbol?{symbolRef:entry.symbol.symbolRef,name:entry.symbol.name,qualifiedPath:entry.symbol.qualifiedPath??undefined,kind:entry.symbol.kind??undefined,category:entry.symbol.category??undefined,arity:entry.symbol.arity??undefined,isPublic:entry.symbol.isPublic??undefined,filePath:entry.symbol.filePath??undefined,startLine:entry.symbol.startLine??undefined,endLine:entry.symbol.endLine??undefined,contentHash:entry.symbol.contentHash??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),indexingEstimates:data.indexingEstimates}}}function normaliseUnifiedSearchLocator(value){return{registry:value.registry??undefined,packageName:value.packageName??undefined,version:value.version??undefined,pageId:value.pageId??undefined,docsReadTarget:value.docsReadTarget??undefined,sourceKind:value.sourceKind??undefined,sourceUrl:value.sourceUrl??undefined,repoUrl:value.repoUrl??undefined,gitRef:value.gitRef??undefined,commitSha:value.commitSha??undefined,requestedRef:value.requestedRef??undefined,filePath:value.filePath??undefined,repositoryFilePath:value.repositoryFilePath??undefined,startLine:value.startLine??undefined,endLine:value.endLine??undefined,evidenceRange:value.evidenceRange?{startLine:value.evidenceRange.startLine,endLine:value.evidenceRange.endLine,matchLine:value.evidenceRange.matchLine??undefined,rangeKind:value.evidenceRange.rangeKind??undefined,matchSpansTruncated:value.evidenceRange.matchSpansTruncated}:undefined,indexedRange:value.indexedRange?{startLine:value.indexedRange.startLine,endLine:value.indexedRange.endLine}:undefined,symbolContext:value.symbolContext?normaliseUnifiedSearchSymbolContext(value.symbolContext):undefined,fileContentHash:value.fileContentHash??undefined,symbolRef:value.symbolRef??undefined,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined,category:value.category??undefined,language:value.language??undefined}}function normaliseUnifiedSearchSymbolContext(value){const identity={name:value.name,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined};if(value.relation==="ENCLOSES_MATCH"){return{...identity,relation:"encloses_match",definitionRange:normaliseUnifiedSearchDefinitionRange(value.definitionRange)}}return{...identity,relation:"associated_with_indexed_chunk",definitionRange:value.definitionRange?normaliseUnifiedSearchDefinitionRange(value.definitionRange):undefined}}function normaliseUnifiedSearchDefinitionRange(value){return{filePath:value.filePath,repositoryFilePath:value.repositoryFilePath,startLine:value.startLine,endLine:value.endLine}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{...value.releaseCorrespondence!==undefined?{releaseCorrespondence:value.releaseCorrespondence}:{},requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}const availableVersions=parseCodeDiffErrorRefs(extensions.available_versions);if(availableVersions)details.availableVersions=availableVersions;if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function createCodeNavigationHttpError(response){const status=response.status;const detail=parseHttpErrorDetail(response.responseBody,["detail","error"]);if(status===401){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}function createCodeNavigationTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createCodeNavigationGraphQLError(errors,runtime={}){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);const errorMetadata=parseGraphQLErrorMetadata(extensions,indexingEstimate);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=code-nav-wire to inspect GraphQL details during local development.";if(runtime.diagnostics?.isEnabled("code-nav")){runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(runtime.diagnostics?.isEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(message,indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions),indexingEstimate,typeof extensions?.hint==="string"?extensions.hint:undefined,undefined,parseGraphQLRepoUrl(extensions));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,{...parseVersionRefRecovery(extensions),code:"VERSION_NOT_FOUND"});case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,{...parseVersionRefRecovery(extensions),code:"REF_NOT_FOUND"});case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"REPOSITORY_NOT_FOUND":return new CodeNavigationTargetNotFoundError(message,undefined,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"FILE_NOT_FOUND":return new CodeNavigationFileNotFoundError(message,typeof extensions?.file_path==="string"?extensions.file_path:typeof extensions?.filePath==="string"?extensions.filePath:undefined);case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new CodeNavigationValidationError(message);case"FEATURE_FLAG_REQUIRED":return new CodeNavigationFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"GREP_FILE_TOO_LARGE":case"GREP_TIMEOUT":case"GREP_SERVICE_UNAVAILABLE":case"GREP_FAILED":case"GREP_INDEX_NOT_AVAILABLE":case"FILE_PATH_EXCLUDED":case"SOURCE_FILE_INVENTORY_UNKNOWN":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata);default:break}if(code===undefined){if(isAuthMessage(message)){return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.")}if(isUnresolvableMessage(message)){return new CodeNavigationUnresolvableError(message)}if(isTargetNotFoundMessage(message)){return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata)}}return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata)}function buildTargetResolutionFallbackQueries(query){const withoutSuggestedRefs=query.replaceAll(TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION,"");const candidates=[withoutSuggestedRefs,withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),withoutSuggestedRefs.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),withoutSuggestedRefs.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,"").replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,"")];return candidates.filter((candidate,index,all)=>candidate!==query&&all.indexOf(candidate)===index)}function hasSchemaMismatchErrors(parsedBody){if(!parsedBody||typeof parsedBody!=="object")return false;const errors=parsedBody.errors;if(!Array.isArray(errors))return false;return errors.some((entry)=>{if(!entry||typeof entry!=="object")return false;const error=entry;if(typeof error.message!=="string")return false;const code=typeof error.extensions?.code==="string"?error.extensions.code:undefined;return isGraphQLSchemaMismatchError({message:error.message,code})})}function getPrimaryExtensions(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function getGraphQLIndexingRef(errors){for(const error of errors){const indexingRef=error.extensions?.indexing_ref??error.extensions?.indexingRef;if(typeof indexingRef==="string")return indexingRef}return}function parseAvailableVersions(extensions){const raw=extensions?.available_versions??extensions?.availableVersions;return parseAvailableArtifacts(raw)}function parseAvailableRefs(extensions){const raw=extensions?.available_refs??extensions?.availableRefs;return parseAvailableArtifacts(raw)}function parseSuggestedRefs(extensions){const raw=extensions?.suggested_refs??extensions?.suggestedRefs;return parseAvailableArtifacts(raw)}function parseGraphQLErrorMetadata(extensions,indexingEstimate){const metadata={};if(typeof extensions?.hint==="string")metadata.hint=extensions.hint;const filePath=extensions?.file_path??extensions?.filePath;if(typeof filePath==="string")metadata.filePath=filePath;const exclusionReason=extensions?.exclusion_reason??extensions?.exclusionReason;if(typeof exclusionReason==="string"){metadata.exclusionReason=exclusionReason}const availableVersions=parseAvailableVersions(extensions);if(availableVersions?.length)metadata.availableVersions=availableVersions;const availableRefs=parseAvailableRefs(extensions);if(availableRefs?.length)metadata.availableRefs=availableRefs;const suggestedRefs=parseSuggestedRefs(extensions);if(suggestedRefs?.length)metadata.suggestedRefs=suggestedRefs;const targetResolution=parseTargetResolution(extensions);if(targetResolution)metadata.targetResolution=targetResolution;if(indexingEstimate)metadata.indexingEstimate=indexingEstimate;return Object.keys(metadata).length>0?metadata:undefined}function parseGraphQLRepoUrl(extensions){return typeof extensions?.repo_url==="string"?extensions.repo_url:typeof extensions?.repoUrl==="string"?extensions.repoUrl:undefined}function parseGraphQLGitRef(extensions){return typeof extensions?.git_ref==="string"?extensions.git_ref:typeof extensions?.gitRef==="string"?extensions.gitRef:undefined}function parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}function normaliseCodeContextResult(data){return{filePath:data.filePath??undefined,language:data.language??undefined,totalLines:data.totalLines??undefined,startLine:data.startLine??undefined,endLine:data.endLine??undefined,content:data.content??undefined,isBinary:data.isBinary??undefined,targetResolution:normaliseTargetResolution(data.targetResolution),availableVersions:normaliseAvailableVersions(data.availableVersions),indexingEstimates:data.indexingEstimates}}function throwIfCodeContextIndexing(data){if(data.codeIndexState!=="INDEXING")return;const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError("Target is indexing.",data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate,undefined,data.indexingEstimates)}function parseCodeContextResult(data){const parsed=codeContextResponseSchema.safeParse(data);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}throwIfCodeContextIndexing(parsed.data);return normaliseCodeContextResult(parsed.data)}function normaliseAvailableVersions(entries){if(!entries||entries.length===0)return;return entries.map((entry)=>({version:entry.version??undefined,ref:entry.ref}))}function normaliseTargetResolution(resolution){if(!resolution)return;return{requested:normaliseTargetResolutionIdentity(resolution.requested),resolvedRequested:normaliseTargetResolutionIdentity(resolution.resolvedRequested),served:normaliseTargetResolutionIdentity(resolution.served),freshness:resolution.freshness??undefined,freshnessReason:resolution.freshnessReason??undefined,indexingRef:resolution.indexingRef??undefined,availableVersions:normaliseAvailableVersions(resolution.availableVersions)??[],availableRefs:normaliseAvailableVersions(resolution.availableRefs)??[],suggestedRefs:normaliseAvailableVersions(resolution.suggestedRefs)??[]}}function normaliseDocCoverage(coverage,options={}){if(!coverage)return;if(coverage.coverageState==="NONE"&&!options.preserveNone){return}const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"||coverage.frontierRemaining===null){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){out.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function normaliseTargetResolutionIdentity(identity){if(!identity)return;const out={};if(identity.kind)out.kind=identity.kind;if(identity.registry)out.registry=identity.registry;if(identity.packageName)out.packageName=identity.packageName;if(identity.version)out.version=identity.version;if(identity.repoUrl)out.repoUrl=identity.repoUrl;if(identity.gitRef)out.gitRef=identity.gitRef;if(identity.commitSha)out.commitSha=identity.commitSha;if(identity.committedAt)out.committedAt=identity.committedAt;if(identity.releaseCorrespondence!==undefined)out.releaseCorrespondence=identity.releaseCorrespondence;if(identity.site)out.site=identity.site;return Object.keys(out).length>0?out:undefined}function isAuthMessage(message){const lower=message.toLowerCase();return lower.includes("unauthorized")||lower.includes("forbidden")||lower.includes("permission")||lower.includes("authentication")}function normaliseTargetMode(value){if(value==="PACKAGES"||value==="REPO"||value==="MIXED"||value==="SITES"||value==="SITE"){return value}return}function normaliseRequestedRefKind(value){switch(value){case"OMITTED_VERSION":case"LATEST_VERSION":case"EXACT_VERSION":case"DEFAULT_BRANCH":case"HEAD":case"BRANCH":case"SHA":return value;default:return}}function normaliseProgressFilters(filters){if(!filters)return;const out={};if(filters.fileIntent)out.fileIntent=filters.fileIntent;if(filters.kind)out.kind=filters.kind;if(filters.category)out.category=filters.category;if(typeof filters.publicOnly==="boolean"){out.publicOnly=filters.publicOnly}if(filters.pathPrefix)out.pathPrefix=filters.pathPrefix;return Object.keys(out).length>0?out:undefined}function isTargetNotFoundMessage(message){const lower=message.toLowerCase();return lower.includes("not found")||lower.includes("unknown package")||lower.includes("no such package")||lower.includes("does not exist")}function isUnresolvableMessage(message){const lower=message.toLowerCase();return lower.includes("could not resolve")||lower.includes("cannot resolve")}import{z as z7}from"zod";import{z as z6}from"zod";var osvSourceMetadataSchema=z6.object({schemaVersion:z6.string(),relatedIds:z6.array(z6.string()),upstreamIds:z6.array(z6.string()),credits:z6.array(z6.object({name:z6.string(),contact:z6.array(z6.string()),type:z6.string().nullable()}))});var OSV_SOURCE_DETAILS_FIELDS=`
713
- osvId aliases summary details sourceUrl publishedAt modifiedAt withdrawnAt
714
- schemaVersion relatedIds upstreamIds credits { name contact type }
715
- severity { type score source } references { type url }
716
- contentSafety { filtered modifications }
717
- `;var osvSourceDetailsSchema=osvSourceMetadataSchema.extend({osvId:z6.string(),aliases:z6.array(z6.string()),summary:z6.string().nullable(),details:z6.string().nullable(),sourceUrl:z6.string(),publishedAt:z6.string().nullable(),modifiedAt:z6.string(),withdrawnAt:z6.string().nullable(),severity:z6.array(z6.object({type:z6.string(),score:z6.string(),source:z6.string().nullable()})),references:z6.array(z6.object({type:z6.string(),url:z6.string().nullable()})),contentSafety:z6.object({filtered:z6.boolean(),modifications:z6.array(z6.string())})});function promoteGenericVersionNotFound(error,params){if(!(error instanceof PackageIntelligenceBackendError))return error;if(error.graphqlCode!==undefined)return error;const requestedVersion=pickRequestedVersion(params);if(!requestedVersion)return error;if(!/no matching version/i.test(error.message))return error;const qualifiedName=synthesizeQualifiedName(params);return new PackageIntelligenceVersionNotFoundError(error.message,qualifiedName,requestedVersion,undefined)}function pickRequestedVersion(params){if(params.version)return params.version;if(params.fromVersion)return params.fromVersion;if(params.toVersion)return params.toVersion;return}function synthesizeQualifiedName(params){if(!params.registry||!params.packageName)return;return`${params.registry.toLowerCase()}:${params.packageName}`}class PackageIntelligenceAccessError extends Error{constructor(message){super(message);this.name="PackageIntelligenceAccessError"}}class PackageIntelligenceFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="PackageIntelligenceFeatureFlagRequiredError"}}class PackageIntelligenceNetworkError extends Error{constructor(message,options){super(message,options);this.name="PackageIntelligenceNetworkError"}}class PackageIntelligenceBackendError extends Error{status;graphqlCode;retryable;recovery;constructor(message,status,graphqlCode,retryable,recovery=undefined){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.recovery=recovery;this.name="PackageIntelligenceBackendError"}}class PackageIntelligenceGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="PackageIntelligenceGraphQLError"}}class PackageIntelligenceTargetNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceTargetNotFoundError"}}class PackageIntelligenceValidationError extends Error{constructor(message){super(message);this.name="PackageIntelligenceValidationError"}}class PackageIntelligenceDocumentationSectionUnresolvedError extends Error{reason;constructor(message,reason){super(message);this.reason=reason;this.name="PackageIntelligenceDocumentationSectionUnresolvedError"}}class PackageIntelligenceVersionNotFoundError extends Error{packageName;requestedVersion;availableVersions;recovery;constructor(message,packageName,requestedVersion,availableVersions,recovery=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.availableVersions=availableVersions;this.recovery=recovery;this.name="PackageIntelligenceVersionNotFoundError"}}class MalformedPackageIntelligenceResponseError extends Error{constructor(message){super(message);this.name="MalformedPackageIntelligenceResponseError"}}var githubRepositorySchema=z7.object({stargazersCount:z7.number().int().nullable().optional(),forksCount:z7.number().int().nullable().optional(),openIssuesCount:z7.number().int().nullable().optional(),archived:z7.boolean().nullable().optional(),language:z7.string().nullable().optional(),topics:z7.array(z7.string()).nullable().optional(),pushedAt:z7.string().nullable().optional()}).nullable().optional();var registryLatestDifferenceSchema=z7.object({version:z7.string(),reason:z7.enum(["DEPRECATED","YANKED","NO_FILES","UNLISTED","PRERELEASE_EXCLUDED"])});var packageIdentitySchema=z7.object({name:z7.string().nullable().optional(),registry:z7.string().nullable().optional(),description:z7.string().nullable().optional(),version:z7.string().nullable().optional(),publishedAt:z7.string().nullable().optional(),registryLatestDifference:registryLatestDifferenceSchema.nullable().optional(),latestVersion:z7.string().nullable().optional(),latestVersionPublishedAt:z7.string().nullable().optional(),versionCount:z7.number().int().nullable().optional(),downloadsRefreshedAt:z7.string().nullable().optional(),homepage:z7.string().nullable().optional(),repositoryUrl:z7.string().nullable().optional(),license:z7.string().nullable().optional(),downloadsLastMonth:z7.number().int().nullable().optional(),downloadsTotal:z7.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z7.object({osvId:z7.string().nullable().optional(),summary:z7.string().nullable().optional(),severityScore:z7.number().nullable().optional(),publishedAt:z7.string().nullable().optional()});var packageSecurityOverviewSchema=z7.object({vulnerabilityCount:z7.number().int().nullable().optional(),allVulnerabilityCount:z7.number().int(),hasCurrentVulnerabilities:z7.boolean().nullable().optional(),recentVulnerabilities:z7.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z7.object({version:z7.string().nullable().optional(),publishedAt:z7.string().nullable().optional(),body:z7.string().nullable().optional()});var packageSummaryResponseSchema=z7.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z7.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z7.object({message:z7.string(),extensions:z7.record(z7.string(),z7.unknown()).optional(),path:z7.array(z7.union([z7.string(),z7.number().int()])).optional()});var registryRepositorySchema=z7.object({id:z7.string(),name:z7.string(),url:z7.string()});var graphQLResponseSchema=z7.object({data:z7.object({packageSummary:packageSummaryResponseSchema.nullable().optional(),provenance:z7.object({selectedVersion:z7.object({resolvedVersion:z7.string(),registryRepository:registryRepositorySchema.nullable().optional()})}).nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
718
- query PackageSummary(
719
- $registry: Registry!
720
- $name: String!
721
- $includeVerboseFields: Boolean! = true
722
- ) {
723
- packageSummary(registry: $registry, name: $name) {
724
- package {
725
- name
726
- registry
727
- description
728
- version
729
- publishedAt
730
- registryLatestDifference {
731
- version
732
- reason
733
- }
734
- latestVersion @include(if: $includeVerboseFields)
735
- latestVersionPublishedAt @include(if: $includeVerboseFields)
736
- homepage
737
- repositoryUrl
738
- license
739
- downloadsLastMonth
740
- downloadsTotal
741
- versionCount @include(if: $includeVerboseFields)
742
- downloadsRefreshedAt @include(if: $includeVerboseFields)
743
- githubRepository {
744
- stargazersCount
745
- forksCount
746
- openIssuesCount
747
- archived
748
- language @include(if: $includeVerboseFields)
749
- topics @include(if: $includeVerboseFields)
750
- pushedAt @include(if: $includeVerboseFields)
751
- }
752
- }
753
- security {
754
- vulnerabilityCount
755
- allVulnerabilityCount
756
- hasCurrentVulnerabilities
757
- recentVulnerabilities @include(if: $includeVerboseFields) {
758
- osvId
759
- summary
760
- severityScore
761
- publishedAt
762
- }
763
- }
764
- latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
765
- version
766
- publishedAt
767
- body
768
- }
769
- }
770
- provenance: packageInfo(registry: $registry, name: $name) {
771
- selectedVersion {
772
- resolvedVersion
773
- registryRepository { id name url }
774
- }
775
- }
776
- }`;var packageVersionIdentitySchema=z7.object({name:z7.string().nullable().optional(),registry:z7.string().nullable().optional(),version:z7.string().nullable().optional(),publishedAt:z7.string().nullable().optional(),deprecated:z7.boolean().nullable().optional(),deprecationReason:z7.string().nullable().optional(),registryRepository:registryRepositorySchema.nullable().optional()});var vulnerabilityDetailSchema=z7.object({sourceDetails:osvSourceDetailsSchema.nullable().optional(),assessmentStatus:z7.string().nullable().optional(),assessmentReasons:z7.array(z7.string()).nullable().optional(),osvId:z7.string().nullable().optional(),summary:z7.string().nullable().optional(),severityScore:z7.number().nullable().optional(),severityType:z7.string().nullable().optional(),affectedVersionRanges:z7.array(z7.string()).nullable().optional(),affectedVersionRangesCount:z7.number().int(),affectedVersionRangesTruncated:z7.boolean(),fixedInVersions:z7.array(z7.string()).nullable().optional(),publishedAt:z7.string().nullable().optional(),modifiedAt:z7.string().nullable().optional(),withdrawnAt:z7.string().nullable().optional(),aliases:z7.array(z7.string()).nullable().optional(),isMalicious:z7.boolean().nullable().optional(),affectsInspectedVersion:z7.boolean(),matchedAffectedVersionRanges:z7.array(z7.string()),duplicateIds:z7.array(z7.string())});var pageInfoSchema=z7.object({hasNextPage:z7.boolean(),endCursor:z7.string().nullable().optional(),totalCount:z7.number().int()});var vulnerabilityAdvisoryPageSchema=z7.object({entries:z7.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z7.object({unknownVulnerabilityCount:z7.number().int().nonnegative().nullable().optional(),assessmentStatus:z7.string().nullable().optional(),affectedVulnerabilityCount:z7.number().int(),nonAffectingVulnerabilityCount:z7.number().int(),allVulnerabilityCount:z7.number().int(),currentVersionAffected:z7.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z7.array(z7.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z7.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z7.object({data:z7.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});var transitiveAuditAdvisorySchema=z7.object({osvId:z7.string().nullable().optional(),summary:z7.string().nullable().optional(),severityScore:z7.number().nullable().optional(),affectedVersionRanges:z7.array(z7.string()).nullable().optional(),fixedInVersions:z7.array(z7.string()).nullable().optional(),publishedAt:z7.string().nullable().optional(),modifiedAt:z7.string().nullable().optional(),aliases:z7.array(z7.string()).nullable().optional(),isMalicious:z7.boolean().nullable().optional()});var transitiveAuditOccurrenceSchema=z7.object({assessmentStatus:z7.string().nullable().optional(),assessmentReasons:z7.array(z7.string()).nullable().optional(),version:z7.string(),affectsResolvedVersion:z7.boolean(),matchedAffectedVersionRanges:z7.array(z7.string()),fixVersionsAboveResolved:z7.array(z7.string()),nearestFixedVersion:z7.string().nullable().optional(),advisory:transitiveAuditAdvisorySchema});var transitiveAuditPackageSchema=z7.object({registry:z7.string(),name:z7.string(),affectedCount:z7.number().int().nonnegative(),nonAffectingCount:z7.number().int().nonnegative(),unknownCount:z7.number().int().nonnegative(),totalCount:z7.number().int().nonnegative(),advisoryOccurrences:z7.array(transitiveAuditOccurrenceSchema).nullable().optional()});var transitiveAuditCountSchema=z7.object({totalVulnerabilities:z7.number().int().nonnegative()});var transitiveAuditSummarySchema=z7.object({affected:transitiveAuditCountSchema,nonAffecting:transitiveAuditCountSchema,unknown:transitiveAuditCountSchema,combined:transitiveAuditCountSchema,totalPackagesAnalyzed:z7.number().int().nonnegative(),packages:z7.array(transitiveAuditPackageSchema),calculatedAt:z7.string().nullable().optional()});var transitiveAuditResponseSchema=z7.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:z7.object({transitive:z7.object({vulnerabilitySummary:transitiveAuditSummarySchema.nullable().optional()}).nullable().optional()}).nullable().optional()});var transitiveAuditGraphQLResponseSchema=z7.object({data:z7.object({packageDependencies:transitiveAuditResponseSchema.nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});function packageVulnerabilitiesQuery(includeSourceDetails){return`
777
- query PackageVulnerabilities(
778
- $registry: Registry!
779
- $name: String!
780
- $version: String
781
- $minSeverity: Float
782
- $includeWithdrawn: Boolean
783
- $scope: VulnerabilityScope = AFFECTED
784
- $after: String
785
- ) {
786
- packageVulnerabilities(
787
- registry: $registry
788
- name: $name
789
- version: $version
790
- minSeverity: $minSeverity
791
- includeWithdrawn: $includeWithdrawn
792
- ) {
793
- package {
794
- name
795
- registry
796
- version
797
- registryRepository { id name url }
798
- }
799
- security {
800
- unknownVulnerabilityCount
801
- assessmentStatus
802
- affectedVulnerabilityCount
803
- nonAffectingVulnerabilityCount
804
- allVulnerabilityCount
805
- currentVersionAffected
806
- upgradePaths
807
- advisories(scope: $scope, first: ${includeSourceDetails?3:100}, after: $after) {
808
- entries {
809
- osvId
810
- summary
811
- severityScore
812
- severityType
813
- affectedVersionRanges
814
- affectedVersionRangesCount
815
- affectedVersionRangesTruncated
816
- fixedInVersions
817
- publishedAt
818
- modifiedAt
819
- withdrawnAt
820
- aliases
821
- isMalicious
822
- affectsInspectedVersion
823
- assessmentStatus
824
- assessmentReasons
825
- matchedAffectedVersionRanges
826
- duplicateIds
827
- ${includeSourceDetails?`sourceDetails { ${OSV_SOURCE_DETAILS_FIELDS} }`:""}
828
- }
829
- pageInfo {
830
- hasNextPage
831
- endCursor
832
- totalCount
833
- }
834
- }
835
- }
836
- }
837
- }`}var TRANSITIVE_AUDIT_SCOPE_FIELDS={AFFECTED:{summary:"affected",packageCount:"affectedCount"},NON_AFFECTING:{summary:"nonAffecting",packageCount:"nonAffectingCount"},UNKNOWN:{summary:"unknown",packageCount:"unknownCount"},ALL:{summary:"combined",packageCount:"totalCount"}};function buildPackageTransitiveVulnerabilityAuditQuery(scope){return`
838
- query PackageTransitiveVulnerabilityAudit(
839
- $registry: Registry!
840
- $name: String!
841
- $version: String!
842
- $minSeverity: Float
843
- $scope: VulnerabilityScope!
844
- $includeTransitiveAdvisoryDetails: Boolean! = false
845
- ) {
846
- packageDependencies(
847
- registry: $registry
848
- name: $name
849
- version: $version
850
- includeTransitive: true
851
- ) {
852
- package {
853
- name
854
- registry
855
- version
856
- }
857
- dependencies {
858
- transitive {
859
- vulnerabilitySummary(minSeverity: $minSeverity) {
860
- affected { totalVulnerabilities }
861
- nonAffecting { totalVulnerabilities }
862
- unknown { totalVulnerabilities }
863
- combined { totalVulnerabilities }
864
- totalPackagesAnalyzed
865
- calculatedAt
866
- packages {
867
- registry
868
- name
869
- affectedCount
870
- nonAffectingCount
871
- unknownCount
872
- totalCount
873
- advisoryOccurrences(scope: $scope, minSeverity: $minSeverity) {
874
- version
875
- affectsResolvedVersion
876
- ${scope==="ALL"||scope==="UNKNOWN"?"assessmentStatus":""}
877
- assessmentReasons ${scope==="ALL"||scope==="UNKNOWN"?"":"@include(if: $includeTransitiveAdvisoryDetails)"}
878
- matchedAffectedVersionRanges
879
- fixVersionsAboveResolved
880
- nearestFixedVersion
881
- advisory {
882
- osvId
883
- summary
884
- severityScore
885
- affectedVersionRanges @include(if: $includeTransitiveAdvisoryDetails)
886
- fixedInVersions @include(if: $includeTransitiveAdvisoryDetails)
887
- publishedAt
888
- modifiedAt
889
- aliases
890
- isMalicious
891
- }
892
- }
893
- }
894
- }
895
- }
896
- }
897
- }
898
- }`}var directDependencySchema=z7.object({name:z7.string().nullable().optional(),versionConstraint:z7.string().nullable().optional(),type:z7.string().nullable().optional()});var dependencyGraphNodeSchema=z7.object({registry:z7.string(),name:z7.string(),version:z7.string().nullable().optional()});var dependencyGraphEdgeSchema=z7.object({fromIndex:z7.number().int().nullable().optional(),toIndex:z7.number().int(),constraint:z7.string().nullable().optional(),dependencyType:z7.string().nullable().optional()});var dependencyGraphSchema=z7.object({formatVersion:z7.number().int(),nodes:z7.array(dependencyGraphNodeSchema),edges:z7.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z7.object({totalVulnerabilities:z7.number().int(),critical:z7.number().int(),high:z7.number().int(),medium:z7.number().int(),low:z7.number().int(),unknown:z7.number().int()});var vulnerabilitySummaryDetailSchema=z7.object({osvId:z7.string().nullable().optional(),registry:z7.string().nullable().optional(),packageName:z7.string().nullable().optional(),summary:z7.string().nullable().optional(),severityScore:z7.number().nullable().optional(),severityType:z7.string().nullable().optional(),affectedVersionRanges:z7.array(z7.string()).nullable().optional(),fixedInVersions:z7.array(z7.string()).nullable().optional(),publishedAt:z7.string().nullable().optional(),modifiedAt:z7.string().nullable().optional(),withdrawnAt:z7.string().nullable().optional(),aliases:z7.array(z7.string()).nullable().optional(),isMalicious:z7.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z7.object({version:z7.string(),affectsResolvedVersion:z7.boolean(),matchedAffectedVersionRanges:z7.array(z7.string()),fixVersionsAboveResolved:z7.array(z7.string()),nearestFixedVersion:z7.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z7.object({registry:z7.string(),name:z7.string(),versions:z7.array(z7.string()),affectedCount:z7.number().int(),nonAffectingCount:z7.number().int(),totalCount:z7.number().int(),maxSeverityScore:z7.number().nullable().optional(),maxSeverityLabel:z7.string().nullable().optional(),advisoryIds:z7.array(z7.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z7.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z7.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z7.number().int(),affectedPackageCount:z7.number().int(),packages:z7.array(transitiveVulnerablePackageSchema),calculatedAt:z7.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z7.object({version:z7.string(),reason:z7.string().nullable().optional()});var deprecatedDependencySchema=z7.object({registry:z7.string(),name:z7.string(),versions:z7.array(z7.string()),reasons:z7.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z7.object({version:z7.string(),severity:z7.string()});var outdatedDependencySchema=z7.object({registry:z7.string(),name:z7.string(),latestVersion:z7.string().nullable().optional(),severity:z7.string(),versions:z7.array(outdatedDependencyVersionSchema),repositoryUrl:z7.string().nullable().optional()});var duplicateDependencySchema=z7.object({registry:z7.string().nullable().optional(),name:z7.string(),versions:z7.array(z7.string())});var dependencyConflictEdgeSchema=z7.object({fromIndex:z7.number().int().nullable().optional(),toIndex:z7.number().int(),versionConstraint:z7.string(),dependencyType:z7.string()});var dependencyConflictSchema=z7.object({packageName:z7.string(),requiredVersions:z7.array(z7.string()),conflictingEdges:z7.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z7.object({registry:z7.string().nullable().optional(),name:z7.string(),versions:z7.array(z7.string()),requiredVersions:z7.array(z7.string()),conflictingEdges:z7.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z7.object({totalCount:z7.number().int(),deprecatedCount:z7.number().int(),outdatedCount:z7.number().int(),duplicateCount:z7.number().int(),conflictCount:z7.number().int(),deprecatedPackages:z7.array(deprecatedDependencySchema),outdatedPackages:z7.array(outdatedDependencySchema),duplicatePackages:z7.array(duplicateDependencySchema),conflicts:z7.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z7.object({cycleStart:z7.string(),circularPath:z7.array(z7.string()),displayChain:z7.string()});var environmentMarkerSchema=z7.object({type:z7.string().nullable().optional(),value:z7.string().nullable().optional(),raw:z7.string().nullable().optional()});var transitiveDependencySchema=z7.object({totalEdges:z7.number().int().nullable().optional(),uniquePackagesCount:z7.number().int().nullable().optional(),uniqueDependencies:z7.array(z7.string()).nullable().optional(),dependencyConflicts:z7.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z7.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z7.object({direct:z7.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z7.object({name:z7.string(),constraint:z7.string().nullable().optional()});var dependencyGroupSchema=z7.object({name:z7.string(),lifecycle:z7.string(),conditionType:z7.string(),conditionValue:z7.string().nullable().optional(),selectionMode:z7.string(),exclusiveGroup:z7.string().nullable().optional(),fallbackPriority:z7.number().int().nullable().optional(),compatibleWith:z7.array(z7.string()).nullable().optional(),defaultEnabled:z7.boolean().nullable().optional(),dependencies:z7.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z7.object({primaryGroup:z7.string().nullable().optional(),environmentMarkers:z7.array(environmentMarkerSchema).nullable().optional(),groups:z7.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z7.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z7.object({data:z7.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
899
- query PackageDependencies(
900
- $registry: Registry!
901
- $name: String!
902
- $version: String
903
- $includeTransitive: Boolean
904
- $includeTransitiveDetails: Boolean! = true
905
- $includeDependencyGraph: Boolean! = true
906
- $includeGroups: Boolean! = true
907
- $includeDependencyIssues: Boolean! = false
908
- $maxDepth: Int
909
- $lifecycle: [String!]
910
- ) {
911
- packageDependencies(
912
- registry: $registry
913
- name: $name
914
- version: $version
915
- includeTransitive: $includeTransitive
916
- maxDepth: $maxDepth
917
- lifecycle: $lifecycle
918
- ) {
919
- package {
920
- name
921
- registry
922
- version
923
- registryRepository { id name url }
924
- }
925
- dependencies {
926
- # Backend-side summary block intentionally not selected — our
927
- # envelope computes runtime.count client-side from direct[].length
928
- # so the invariant runtime.count === runtime.items.length always
929
- # holds regardless of backend-side drift.
930
- direct {
931
- name
932
- versionConstraint
933
- type
934
- }
935
- transitive {
936
- totalEdges @include(if: $includeTransitiveDetails)
937
- uniquePackagesCount @include(if: $includeTransitiveDetails)
938
- uniqueDependencies @include(if: $includeTransitiveDetails)
939
- dependencyConflicts @include(if: $includeTransitiveDetails) {
940
- packageName
941
- requiredVersions
942
- conflictingEdges {
943
- fromIndex
944
- toIndex
945
- versionConstraint
946
- dependencyType
947
- }
948
- }
949
- circularDependencyCycles @include(if: $includeTransitiveDetails) {
950
- cycleStart
951
- circularPath
952
- displayChain
953
- }
954
- dependencyGraph @include(if: $includeDependencyGraph) {
955
- formatVersion
956
- nodes {
957
- registry
958
- name
959
- version
960
- }
961
- edges {
962
- fromIndex
963
- toIndex
964
- constraint
965
- dependencyType
966
- }
967
- }
968
- dependencyIssues @include(if: $includeDependencyIssues) {
969
- totalCount
970
- deprecatedCount
971
- outdatedCount
972
- duplicateCount
973
- conflictCount
974
- deprecatedPackages {
975
- registry
976
- name
977
- versions
978
- reasons {
979
- version
980
- reason
981
- }
982
- }
983
- outdatedPackages {
984
- registry
985
- name
986
- latestVersion
987
- severity
988
- versions {
989
- version
990
- severity
991
- }
992
- repositoryUrl
993
- }
994
- duplicatePackages {
995
- registry
996
- name
997
- versions
998
- }
999
- conflicts {
1000
- registry
1001
- name
1002
- versions
1003
- requiredVersions
1004
- conflictingEdges {
1005
- fromIndex
1006
- toIndex
1007
- versionConstraint
1008
- dependencyType
1009
- }
1010
- }
1011
- }
1012
- }
1013
- }
1014
- dependencyGroups @include(if: $includeGroups) {
1015
- primaryGroup
1016
- environmentMarkers {
1017
- type
1018
- value
1019
- raw
1020
- }
1021
- groups {
1022
- name
1023
- lifecycle
1024
- conditionType
1025
- conditionValue
1026
- selectionMode
1027
- exclusiveGroup
1028
- fallbackPriority
1029
- compatibleWith
1030
- defaultEnabled
1031
- dependencies {
1032
- name
1033
- constraint
1034
- }
1035
- }
1036
- }
1037
- }
1038
- }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
1039
- query PackageUpgradeDependencyProbe(
1040
- $registry: Registry!
1041
- $name: String!
1042
- $version: String!
1043
- $includeTransitiveRisk: Boolean!
1044
- $includeTransitiveSecurity: Boolean!
1045
- $includeDependencyIssues: Boolean!
1046
- $includeDependencyChanges: Boolean!
1047
- $includeGroups: Boolean!
1048
- $lifecycle: [String!]
1049
- $minSeverity: Float
1050
- ) {
1051
- packageDependencies(
1052
- registry: $registry
1053
- name: $name
1054
- version: $version
1055
- includeTransitive: $includeTransitiveRisk
1056
- lifecycle: $lifecycle
1057
- ) {
1058
- package {
1059
- name
1060
- registry
1061
- version
1062
- registryRepository { id name url }
1063
- publishedAt
1064
- deprecated
1065
- deprecationReason
1066
- }
1067
- dependencies {
1068
- direct {
1069
- name
1070
- versionConstraint
1071
- type
1072
- }
1073
- transitive @include(if: $includeTransitiveRisk) {
1074
- dependencyGraph @include(if: $includeDependencyChanges) {
1075
- formatVersion
1076
- nodes {
1077
- registry
1078
- name
1079
- version
1080
- }
1081
- edges {
1082
- fromIndex
1083
- toIndex
1084
- constraint
1085
- dependencyType
1086
- }
1087
- }
1088
- vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
1089
- affected {
1090
- totalVulnerabilities
1091
- critical
1092
- high
1093
- medium
1094
- low
1095
- unknown
1096
- }
1097
- nonAffecting {
1098
- totalVulnerabilities
1099
- critical
1100
- high
1101
- medium
1102
- low
1103
- unknown
1104
- }
1105
- combined {
1106
- totalVulnerabilities
1107
- critical
1108
- high
1109
- medium
1110
- low
1111
- unknown
1112
- }
1113
- totalPackagesAnalyzed
1114
- affectedPackageCount
1115
- calculatedAt
1116
- packages {
1117
- registry
1118
- name
1119
- versions
1120
- affectedCount
1121
- nonAffectingCount
1122
- totalCount
1123
- maxSeverityScore
1124
- maxSeverityLabel
1125
- advisoryIds(scope: AFFECTED)
1126
- mostCritical {
1127
- osvId
1128
- registry
1129
- packageName
1130
- summary
1131
- severityScore
1132
- severityType
1133
- affectedVersionRanges
1134
- fixedInVersions
1135
- publishedAt
1136
- modifiedAt
1137
- withdrawnAt
1138
- aliases
1139
- isMalicious
1140
- }
1141
- advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
1142
- version
1143
- affectsResolvedVersion
1144
- matchedAffectedVersionRanges
1145
- fixVersionsAboveResolved
1146
- nearestFixedVersion
1147
- advisory {
1148
- osvId
1149
- registry
1150
- packageName
1151
- summary
1152
- severityScore
1153
- severityType
1154
- affectedVersionRanges
1155
- fixedInVersions
1156
- publishedAt
1157
- modifiedAt
1158
- withdrawnAt
1159
- aliases
1160
- isMalicious
1161
- }
1162
- }
1163
- }
1164
- }
1165
- dependencyIssues @include(if: $includeDependencyIssues) {
1166
- totalCount
1167
- deprecatedCount
1168
- outdatedCount
1169
- duplicateCount
1170
- conflictCount
1171
- deprecatedPackages {
1172
- registry
1173
- name
1174
- versions
1175
- reasons {
1176
- version
1177
- reason
1178
- }
1179
- }
1180
- outdatedPackages {
1181
- registry
1182
- name
1183
- latestVersion
1184
- severity
1185
- versions {
1186
- version
1187
- severity
1188
- }
1189
- repositoryUrl
1190
- }
1191
- duplicatePackages {
1192
- registry
1193
- name
1194
- versions
1195
- }
1196
- conflicts {
1197
- registry
1198
- name
1199
- versions
1200
- requiredVersions
1201
- conflictingEdges {
1202
- fromIndex
1203
- toIndex
1204
- versionConstraint
1205
- dependencyType
1206
- }
1207
- }
1208
- }
1209
- }
1210
- }
1211
- dependencyGroups @include(if: $includeGroups) {
1212
- primaryGroup
1213
- environmentMarkers {
1214
- type
1215
- value
1216
- raw
1217
- }
1218
- groups {
1219
- name
1220
- lifecycle
1221
- conditionType
1222
- conditionValue
1223
- selectionMode
1224
- exclusiveGroup
1225
- fallbackPriority
1226
- compatibleWith
1227
- defaultEnabled
1228
- dependencies {
1229
- name
1230
- constraint
1231
- }
1232
- }
1233
- }
1234
- }
1235
- }`;var packageUpgradeAdvisorySchema=z7.object({assessmentStatus:z7.string().nullable().optional(),assessmentReasons:z7.array(z7.string()).nullable().optional(),id:z7.string().nullable().optional(),aliases:z7.array(z7.string()),summary:z7.string().nullable().optional(),severity:z7.number().nullable().optional(),severityLabel:z7.string().nullable().optional(),fixedIn:z7.array(z7.string()),isMalicious:z7.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z7.object({unknownVulnerabilityCount:z7.number().int().nonnegative().nullable().optional(),assessmentStatus:z7.string().nullable().optional(),version:z7.string(),publishedAt:z7.string().nullable().optional(),deprecated:z7.boolean().nullable().optional(),deprecationReason:z7.string().nullable().optional(),affectedCount:z7.number().int(),nonAffectingCount:z7.number().int(),allCount:z7.number().int(),lastModifiedAt:z7.string().nullable().optional(),advisories:z7.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z7.object({entries:z7.array(z7.object({id:z7.string(),registry:z7.string(),name:z7.string(),versions:z7.array(z7.string()),affectedCount:z7.number().int(),maxSeverityScore:z7.number().nullable().optional(),maxSeverityLabel:z7.string().nullable().optional(),advisoryIds:z7.array(z7.string())})),totalCount:z7.number().int(),truncated:z7.boolean()});var packageUpgradeTransitiveSecuritySchema=z7.object({currentAffected:z7.number().int(),targetAffected:z7.number().int(),introducedPackages:z7.array(z7.string()),fixedPackages:z7.array(z7.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z7.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z7.array(packageUpgradeAdvisorySchema),removed:z7.array(packageUpgradeAdvisorySchema),notAddressed:z7.array(packageUpgradeAdvisorySchema),fixed:z7.array(packageUpgradeAdvisorySchema),introduced:z7.array(packageUpgradeAdvisorySchema),unchanged:z7.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z7.object({detailSource:z7.string().nullable(),version:z7.string().nullable().optional(),publishedAt:z7.string().nullable().optional(),htmlUrl:z7.string().nullable().optional(),body:z7.string().nullable().optional(),bodyPreview:z7.string().nullable().optional(),headline:z7.string().nullable().optional(),signals:z7.array(z7.string())});var changelogKindSchema=z7.enum(["REMOVES_OR_RENAMES_API","CHANGES_BEHAVIOR_OR_DEFAULT","RAISES_RUNTIME_OR_PLATFORM_REQUIREMENT","CHANGES_PACKAGING_OR_MODULE_FORMAT","DEPRECATES_WITHOUT_REMOVAL","SECURITY_FIX","NOTABLE_CHANGE"]).nullable();var packageUpgradeChangelogRiskCoverageSchema=z7.object({versionsClassified:z7.number().int(),versionsNotAssessed:z7.number().int(),versionsWithoutNotes:z7.number().int(),versionsUnparseable:z7.number().int(),unitsNoImpact:z7.number().int(),itemsMustActConfident:z7.number().int(),itemsMustActAmbiguous:z7.number().int(),itemsShouldKnowConfident:z7.number().int(),itemsShouldKnowAmbiguous:z7.number().int(),itemsUnclassified:z7.number().int()});var changelogStatementClassificationSchema=z7.object({tier:z7.enum(["MUST_ACT","SHOULD_KNOW","NO_IMPACT","UNCLASSIFIED"]),ambiguous:z7.boolean(),kind:changelogKindSchema,tierConfidence:z7.number().min(0).max(1).nullable().optional(),kindConfidence:z7.number().min(0).max(1).nullable().optional(),model:z7.string().optional(),formulation:z7.string().optional()});var changelogStatementContextSchema=z7.object({heading:z7.string().nullable(),text:z7.string(),textTruncated:z7.boolean(),fullText:z7.string().optional()});var changelogStatementSchema=z7.object({version:z7.string(),position:z7.number().int().nonnegative(),sourceIndex:z7.number().int().nonnegative(),sourcePosition:z7.number().int().nonnegative().optional(),heading:z7.string().nullable(),source:z7.string().nullable(),url:z7.string().nullable(),commits:z7.array(z7.object({sha:z7.string(),url:z7.string().nullable()})).nullable().optional(),text:z7.string(),textTruncated:z7.boolean(),fullText:z7.string().optional(),context:changelogStatementContextSchema.nullable(),classification:changelogStatementClassificationSchema.nullable()});var changelogStatementCoverageSchema=z7.object({version:z7.string(),status:z7.enum(["CLASSIFIED","NOT_ASSESSED","WITHOUT_NOTES","UNPARSEABLE"]),statementsTotal:z7.number().int().nonnegative(),statementsAssessed:z7.number().int().nonnegative().optional(),statementsNotAssessed:z7.number().int().nonnegative().optional(),statementsNoImpact:z7.number().int().nonnegative().optional(),statementsUnclassified:z7.number().int().nonnegative().optional(),generation:z7.object({status:z7.enum(["GENERATED","PENDING","NOT_GENERATED"]),reason:z7.string().nullable()}).nullable()});var changelogStatementPageSchema=z7.object({items:z7.array(changelogStatementSchema),coverage:z7.array(changelogStatementCoverageSchema),totalCount:z7.number().int().nonnegative(),matchingCount:z7.number().int().nonnegative(),remainingCount:z7.number().int().nonnegative(),nextOffset:z7.number().int().nonnegative().nullable(),hasMore:z7.boolean()});var packageUpgradeChangelogSchema=z7.object({statements:changelogStatementPageSchema.optional(),riskCoverage:packageUpgradeChangelogRiskCoverageSchema,source:z7.string().nullable().optional(),fallback:z7.string().nullable().optional(),entries:z7.array(packageUpgradeChangelogEntrySchema).optional(),sampledEntries:z7.array(packageUpgradeChangelogEntrySchema).optional(),keywordEntries:z7.array(packageUpgradeChangelogEntrySchema).optional(),totalKeywordEntries:z7.number().int(),totalEntries:z7.number().int(),totalEntriesWithBodies:z7.number().int(),truncated:z7.boolean(),hasReleaseNoteBodies:z7.boolean(),breakingSignals:z7.array(z7.string()),migrationSignals:z7.array(z7.string())});var packageUpgradeCompatibilitySchema=z7.object({peerDependencyChanges:z7.array(z7.string()),notes:z7.array(z7.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z7.object({name:z7.string(),registry:z7.string().nullable().optional(),version:z7.string().nullable().optional(),fromVersions:z7.array(z7.string()),toVersions:z7.array(z7.string()),constraint:z7.string().nullable().optional(),type:z7.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z7.object({added:z7.array(packageUpgradeDependencyChangeItemSchema),removed:z7.array(packageUpgradeDependencyChangeItemSchema),changed:z7.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z7.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z7.object({currentTotal:z7.number().int(),targetTotal:z7.number().int(),introducedDeprecated:z7.array(z7.string()),introducedDuplicates:z7.array(z7.string()),introducedConflicts:z7.array(z7.string()),introducedOutdated:z7.array(z7.string())}).nullable().optional();var packageUpgradeReviewSchema=z7.object({registry:z7.string(),name:z7.string(),currentVersion:z7.string(),targetVersion:z7.string(),latestVersion:z7.string().nullable().optional(),versionDelta:z7.string(),migrationGuides:z7.array(z7.object({url:z7.string(),label:z7.string().nullable().optional()})).nullable().optional(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknownDetails:z7.array(z7.object({section:z7.string(),code:z7.string(),message:z7.string(),retryable:z7.boolean().nullable().optional()})).nullable().optional()});var packageUpgradeReviewResponseSchema=z7.object({summary:z7.object({total:z7.number().int(),withUnknowns:z7.number().int(),withAddedAdvisories:z7.number().int(),withBreakingSignals:z7.number().int(),withDirectDependencyChanges:z7.number().int(),withTransitiveVulnerabilityAdditions:z7.number().int()}),reviews:z7.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z7.object({data:z7.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});function packageUpgradeReviewQuery(params,continuation=false){const view=params.changelogView??"text";const statements=view==="triage"?"":changelogStatementSelection(view==="json",true);if(continuation)return`query PackageUpgradeReviewStatements(
1236
- $packages: [PackageUpgradeReviewPackageInput!]! $offset: Int! $tiers: [ChangelogStatementTier!]
1237
- ) {
1238
- packageUpgradeReview(packages: $packages, includeTransitiveSecurity: false, changelogLimit: 1) {
1239
- reviews { registry name currentVersion targetVersion changelog { ${statements} } }
1240
- }
1241
- }`;return`
1242
- query PackageUpgradeReview(
1243
- ${view!=="triage"?"$offset: Int! $tiers: [ChangelogStatementTier!]":""}
1244
- $packages: [PackageUpgradeReviewPackageInput!]!
1245
- $includeTransitiveSecurity: Boolean!
1246
- $includeDependencyIssues: Boolean!
1247
- $minSeverity: Float
1248
- $changelogLimit: Int!
1249
- ) {
1250
- packageUpgradeReview(
1251
- packages: $packages
1252
- includeTransitiveSecurity: $includeTransitiveSecurity
1253
- minSeverity: $minSeverity
1254
- changelogLimit: $changelogLimit
1255
- ) {
1256
- summary {
1257
- total
1258
- withUnknowns
1259
- withAddedAdvisories
1260
- withBreakingSignals
1261
- withDirectDependencyChanges
1262
- withTransitiveVulnerabilityAdditions
1263
- }
1264
- reviews {
1265
- registry
1266
- name
1267
- currentVersion
1268
- targetVersion
1269
- latestVersion
1270
- versionDelta
1271
- migrationGuides { url label }
1272
- security {
1273
- current {
1274
- version
1275
- publishedAt
1276
- deprecated
1277
- deprecationReason
1278
- affectedCount
1279
- nonAffectingCount
1280
- unknownVulnerabilityCount
1281
- assessmentStatus
1282
- allCount
1283
- lastModifiedAt
1284
- advisories {
1285
- ...PackageUpgradeAdvisoryFields
1286
- }
1287
- }
1288
- target {
1289
- version
1290
- publishedAt
1291
- deprecated
1292
- deprecationReason
1293
- affectedCount
1294
- nonAffectingCount
1295
- unknownVulnerabilityCount
1296
- assessmentStatus
1297
- allCount
1298
- lastModifiedAt
1299
- advisories {
1300
- ...PackageUpgradeAdvisoryFields
1301
- }
1302
- }
1303
- added {
1304
- ...PackageUpgradeAdvisoryFields
1305
- }
1306
- removed {
1307
- ...PackageUpgradeAdvisoryFields
1308
- }
1309
- notAddressed {
1310
- ...PackageUpgradeAdvisoryFields
1311
- }
1312
- fixed {
1313
- ...PackageUpgradeAdvisoryFields
1314
- }
1315
- introduced {
1316
- ...PackageUpgradeAdvisoryFields
1317
- }
1318
- unchanged {
1319
- ...PackageUpgradeAdvisoryFields
1320
- }
1321
- transitive @include(if: $includeTransitiveSecurity) {
1322
- currentAffected
1323
- targetAffected
1324
- introducedPackages
1325
- fixedPackages
1326
- introducedPackageDetails(first: 50) {
1327
- ...PackageUpgradeTransitivePackagePageFields
1328
- }
1329
- fixedPackageDetails(first: 50) {
1330
- ...PackageUpgradeTransitivePackagePageFields
1331
- }
1332
- stillAffectedPackageDetails(first: 50) {
1333
- ...PackageUpgradeTransitivePackagePageFields
1334
- }
1335
- }
1336
- }
1337
- changelog {
1338
- ${statements}
1339
- riskCoverage {
1340
- versionsClassified
1341
- versionsNotAssessed
1342
- versionsWithoutNotes
1343
- versionsUnparseable
1344
- unitsNoImpact
1345
- itemsMustActConfident
1346
- itemsMustActAmbiguous
1347
- itemsShouldKnowConfident
1348
- itemsShouldKnowAmbiguous
1349
- itemsUnclassified
1350
- }
1351
- source
1352
- fallback
1353
- ${view==="triage"?"":`entries { detailSource version publishedAt htmlUrl signals ${view==="json"?"body bodyPreview headline":""} }
1354
- sampledEntries { detailSource version publishedAt htmlUrl signals ${view==="json"?"body bodyPreview headline":""} }
1355
- keywordEntries { detailSource version publishedAt htmlUrl signals body ${view==="json"?"bodyPreview headline":""} }`}
1356
- totalKeywordEntries
1357
- totalEntries
1358
- totalEntriesWithBodies
1359
- truncated
1360
- hasReleaseNoteBodies
1361
- breakingSignals
1362
- migrationSignals
1363
- }
1364
- compatibility {
1365
- peerDependencyChanges
1366
- notes
1367
- }
1368
- dependencyChanges {
1369
- direct {
1370
- ...PackageUpgradeDependencyChangeGroupFields
1371
- }
1372
- transitive {
1373
- ...PackageUpgradeDependencyChangeGroupFields
1374
- }
1375
- }
1376
- dependencyIssues @include(if: $includeDependencyIssues) {
1377
- currentTotal
1378
- targetTotal
1379
- introducedDeprecated
1380
- introducedDuplicates
1381
- introducedConflicts
1382
- introducedOutdated
1383
- }
1384
- unknownDetails { section code message ${view==="json"?"retryable":""} }
1385
- }
1386
- }
1387
- }
1388
-
1389
- fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1390
- ${view!=="triage"?"assessmentStatus assessmentReasons":""}
1391
- id
1392
- aliases
1393
- summary
1394
- severity
1395
- severityLabel
1396
- fixedIn
1397
- isMalicious
1398
- }
1399
-
1400
- fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1401
- entries {
1402
- id
1403
- registry
1404
- name
1405
- versions
1406
- affectedCount
1407
- maxSeverityScore
1408
- maxSeverityLabel
1409
- advisoryIds
1410
- }
1411
- totalCount
1412
- truncated
1413
- }
1414
-
1415
- fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1416
- added {
1417
- name
1418
- registry
1419
- version
1420
- fromVersions
1421
- toVersions
1422
- constraint
1423
- type
1424
- }
1425
- removed {
1426
- name
1427
- registry
1428
- version
1429
- fromVersions
1430
- toVersions
1431
- constraint
1432
- type
1433
- }
1434
- changed {
1435
- name
1436
- registry
1437
- version
1438
- fromVersions
1439
- toVersions
1440
- constraint
1441
- type
1442
- }
1443
- }`}var changelogEntryDetailSchema=z7.object({version:z7.string().nullable().optional(),normalizedVersion:z7.string().nullable().optional(),body:z7.string().nullable().optional(),htmlUrl:z7.string().nullable().optional(),publishedAt:z7.string().nullable().optional()});var changelogReportResponseSchema=z7.object({source:z7.string().nullable().optional(),entries:z7.array(changelogEntryDetailSchema).nullable().optional(),statements:changelogStatementPageSchema.optional()});var exactChangelogDetailSchema=z7.object({detailSource:z7.string().nullable().optional(),hasChangelog:z7.boolean().optional(),entry:changelogEntryDetailSchema.nullable().optional(),statements:changelogStatementPageSchema.optional()});var changelogGraphQLResponseSchema=z7.object({data:z7.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});var exactChangelogGraphQLResponseSchema=z7.object({data:z7.object({packageInfo:z7.object({selectedVersion:z7.object({resolvedVersion:z7.string().optional(),changelog:exactChangelogDetailSchema.nullable().optional()}).nullable().optional()}).nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});function changelogStatementSelection(json,assessment){return`statements(first: 100, offset: $offset, tiers: $tiers) {
1444
- totalCount matchingCount remainingCount nextOffset hasMore
1445
- coverage { version status statementsTotal generation { status reason } ${assessment?"statementsAssessed statementsNotAssessed statementsNoImpact statementsUnclassified":""} }
1446
- items {
1447
- version position sourceIndex heading source url text textTruncated
1448
- ${json?"commits { sha url } sourcePosition fullText":""}
1449
- context { heading text textTruncated ${json?"fullText":""} }
1450
- classification { tier ambiguous kind ${json?"tierConfidence kindConfidence model formulation":""} }
1451
- }
1452
- }`}var upgradeStatementContinuationSchema=z7.object({data:z7.object({packageUpgradeReview:z7.object({reviews:z7.array(z7.object({registry:z7.string(),name:z7.string(),currentVersion:z7.string(),targetVersion:z7.string(),changelog:z7.object({statements:changelogStatementPageSchema})}))}).nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});function validateChangelogStatementPage(page,offset,json){if(json&&page.items.some((item)=>item.commits===undefined||item.fullText===undefined||item.sourcePosition===undefined||item.context&&item.context.fullText===undefined||item.classification&&(item.classification.model===undefined||item.classification.formulation===undefined||item.classification.tierConfidence===undefined||item.classification.kindConfidence===undefined)))throw new MalformedPackageIntelligenceResponseError("Missing selected changelog statement evidence fields.");const next=offset+page.items.length;if(page.items.length>100||page.remainingCount!==page.matchingCount-next||page.hasMore!==page.remainingCount>0||(page.hasMore?page.nextOffset!==next||next<=offset:page.nextOffset!==null))throw new MalformedPackageIntelligenceResponseError("Invalid changelog statement page progress.")}function changelogCoverageSignature(coverage){return JSON.stringify(coverage.map((c)=>[c.version,c.status,c.statementsTotal,c.statementsAssessed,c.statementsNotAssessed,c.statementsNoImpact,c.statementsUnclassified,c.generation??null]))}function validateUpgradeStatementCounts(statements,counters,tiers){const coverage=statements.coverage;const versionCounts=["CLASSIFIED","NOT_ASSESSED","WITHOUT_NOTES","UNPARSEABLE"].map((status)=>coverage.filter((c)=>c.status===status).length);const expectedVersions=[counters.versionsClassified,counters.versionsNotAssessed,counters.versionsWithoutNotes,counters.versionsUnparseable];const selected=tiers?.length?tiers:["MUST_ACT","SHOULD_KNOW","UNCLASSIFIED","NO_IMPACT"];const count=(tier,ambiguous)=>statements.items.filter((item)=>item.classification?.tier===tier&&item.classification.ambiguous===ambiguous).length;if(JSON.stringify(versionCounts)!==JSON.stringify(expectedVersions)||coverage.reduce((sum,c)=>sum+c.statementsNoImpact,0)!==counters.unitsNoImpact||selected.includes("MUST_ACT")&&(count("MUST_ACT",false)!==counters.itemsMustActConfident||count("MUST_ACT",true)!==counters.itemsMustActAmbiguous)||selected.includes("SHOULD_KNOW")&&(count("SHOULD_KNOW",false)!==counters.itemsShouldKnowConfident||count("SHOULD_KNOW",true)!==counters.itemsShouldKnowAmbiguous)||selected.includes("UNCLASSIFIED")&&statements.items.filter((item)=>item.classification?.tier==="UNCLASSIFIED").length!==counters.itemsUnclassified||!tiers?.length&&statements.items.filter((item)=>item.classification?.tier==="NO_IMPACT").length!==counters.unitsNoImpact)throw new MalformedPackageIntelligenceResponseError("Upgrade statement evidence disagrees with whole-range counters.")}function packageChangelogQuery(params,offset){const statementView=(params.view??"statements")==="statements";const json=params.includeJsonFields===true;const firstPage=offset===0;const entry=`${params.version===undefined?"version":""} ${json?"normalizedVersion":""} htmlUrl publishedAt ${params.view==="verbatim"?"body":""}`;const statements=statementView?changelogStatementSelection(json,Boolean(params.statementTiers?.length)):"";const pageVars=statementView?"$offset: Int! $tiers: [ChangelogStatementTier!]":"";if(params.version!==undefined)return`query PackageChangelogExact(
1453
- $registry: Registry! $name: String! $version: String ${pageVars}
1454
- ) {
1455
- packageInfo(registry: $registry, name: $name, version: $version) { selectedVersion {
1456
- ${firstPage?"resolvedVersion":""}
1457
- changelog { ${firstPage?`${json?"detailSource":""} ${json||!statementView?"hasChangelog":""} entry { ${entry} }`:""} ${statements} }
1458
- } }
1459
- }`;return`query PackageChangelog(
1460
- $registry: Registry! $name: String! $fromVersion: String $toVersion: String $limit: Int ${pageVars}
1461
- ) {
1462
- packageChangelog(registry: $registry, name: $name, fromVersion: $fromVersion, toVersion: $toVersion, limit: $limit) {
1463
- ${firstPage?`${json?"source":""} entries { ${entry} }`:""} ${statements}
1464
- }
1465
- }`}function normaliseChangelogStatement(item){return{...stripNullProperties(item),classification:item.classification===null?null:stripNullProperties(item.classification),...item.commits==null?{}:{commits:item.commits}}}function collectChangelogStatements(pages,filtered){const first=pages[0];if(!first)throw new MalformedPackageIntelligenceResponseError("Missing selected changelog statements.");const coverage=first.coverage;if(new Set(coverage.map((c)=>c.version)).size!==coverage.length)throw new MalformedPackageIntelligenceResponseError("Duplicate changelog coverage versions.");const sourceIndices=new Map;const items=[];const positions=new Map;let lastVersionIndex=-1;for(const page of pages){for(const item of page.items){const index=coverage.findIndex((c)=>c.version===item.version);const previous=positions.get(item.version)??-1;if(index<lastVersionIndex||index<0||item.position<=previous||item.position>=(coverage[index]?.statementsTotal??0)||item.sourceIndex<(sourceIndices.get(item.version)??-1)||!filtered&&item.position!==previous+1)throw new MalformedPackageIntelligenceResponseError("Invalid changelog statement ordering or duplicate positions.");lastVersionIndex=index;positions.set(item.version,item.position);sourceIndices.set(item.version,item.sourceIndex);items.push(normaliseChangelogStatement(item))}}if(items.length!==first.matchingCount||coverage.reduce((sum,c)=>sum+c.statementsTotal,0)!==first.totalCount||!filtered&&first.matchingCount!==first.totalCount)throw new MalformedPackageIntelligenceResponseError("Inconsistent changelog statement counts.");const finalCoverage=coverage.map((c)=>{if(filtered){if(c.statementsAssessed===undefined||c.statementsNotAssessed===undefined||c.statementsNoImpact===undefined||c.statementsUnclassified===undefined||c.statementsAssessed+c.statementsNotAssessed!==c.statementsTotal||c.statementsNoImpact+c.statementsUnclassified>c.statementsAssessed)throw new MalformedPackageIntelligenceResponseError("Missing or inconsistent selected changelog coverage counts.");const{generation,...counts}=c;return{...counts,...generation?{generation}:{}}}const releaseItems=items.filter((item)=>item.version===c.version);if(releaseItems.length!==c.statementsTotal)throw new MalformedPackageIntelligenceResponseError("Incomplete changelog release statements.");const assessed=releaseItems.filter((item)=>item.classification!==null).length;return{version:c.version,statementsTotal:c.statementsTotal,status:c.statementsTotal===0||c.status==="WITHOUT_NOTES"||c.status==="UNPARSEABLE"?c.status:assessed===c.statementsTotal?"CLASSIFIED":"NOT_ASSESSED",statementsAssessed:assessed,statementsNotAssessed:c.statementsTotal-assessed,statementsNoImpact:releaseItems.filter((item)=>item.classification?.tier==="NO_IMPACT").length,statementsUnclassified:releaseItems.filter((item)=>item.classification?.tier==="UNCLASSIFIED").length,...c.generation?{generation:c.generation}:{}}});return{items,totalCount:first.totalCount,matchingCount:first.matchingCount,coverage:finalCoverage}}function normaliseChangelogSource(raw){const trimmed=raw?.trim();if(!trimmed)return;return trimmed.toLowerCase()}var packageDocSourceKindSchema=z7.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z7.object({id:z7.string().nullable().optional(),readTarget:readTargetSchema,title:z7.string().nullable().optional(),slug:z7.string().nullable().optional(),order:z7.number().int().nullable().optional(),linkName:z7.string().nullable().optional(),lastUpdatedAt:z7.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z7.string().nullable().optional(),repoUrl:z7.string().nullable().optional(),gitRef:z7.string().nullable().optional(),requestedRef:z7.string().nullable().optional(),filePath:z7.string().nullable().optional()});var packageDocsPageInfoSchema=z7.object({hasNextPage:z7.boolean(),endCursor:z7.string().nullable().optional(),totalCount:z7.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z7.object({indexingEstimates:indexingEstimatesSchema,registry:z7.string().nullable().optional(),packageName:z7.string().nullable().optional(),version:z7.string().nullable().optional(),stale:z7.boolean().nullable().optional(),codeIndexState:z7.string().nullable().optional(),pages:z7.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z7.object({url:z7.string().nullable().optional(),label:z7.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z7.object({id:z7.string().nullable().optional(),docsReadTarget:z7.string(),title:z7.string().nullable().optional(),content:z7.string().nullable().optional(),contentFormat:z7.string().nullable().optional(),breadcrumbs:z7.array(z7.string()).nullable().optional(),linkName:z7.string().nullable().optional(),lastUpdatedAt:z7.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z7.string().nullable().optional(),gitRef:z7.string().nullable().optional(),requestedRef:z7.string().nullable().optional(),filePath:z7.string().nullable().optional(),baseUrl:z7.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z7.object({registry:z7.string().nullable().optional(),packageName:z7.string().nullable().optional(),version:z7.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),contentRange:z7.object({startLine:z7.number().int().positive().nullable(),endLine:z7.number().int().positive().nullable(),totalLines:z7.number().int().nonnegative(),anchor:z7.string().nullable()}).superRefine((range,context)=>{const empty=range.totalLines===0;if(empty&&(range.startLine!==null||range.endLine!==null)){context.addIssue({code:"custom",message:"Empty documentation must have null range bounds."})}if(!empty&&(range.startLine===null||range.endLine===null)){context.addIssue({code:"custom",message:"Non-empty documentation must have range bounds."})}if(range.startLine!==null&&range.endLine!==null&&(range.startLine>range.endLine||range.endLine>range.totalLines)){context.addIssue({code:"custom",message:"Documentation range must fit within the complete page."})}}),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z7.object({data:z7.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z7.object({data:z7.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z7.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
1466
- query ListPackageDocs(
1467
- $registry: Registry!
1468
- $packageName: String!
1469
- $version: String
1470
- $limit: Int
1471
- $after: String
1472
- ) {
1473
- listPackageDocs(
1474
- registry: $registry
1475
- packageName: $packageName
1476
- version: $version
1477
- limit: $limit
1478
- after: $after
1479
- ) {
1480
- registry
1481
- packageName
1482
- version
1483
- stale
1484
- codeIndexState
1485
- ${INDEXING_ESTIMATES_SELECTION}
1486
- pages {
1487
- id
1488
- readTarget { target }
1489
- title
1490
- slug
1491
- order
1492
- linkName
1493
- lastUpdatedAt
1494
- sourceKind
1495
- sourceUrl
1496
- repoUrl
1497
- gitRef
1498
- requestedRef
1499
- filePath
1500
- }
1501
- pageInfo {
1502
- hasNextPage
1503
- endCursor
1504
- totalCount
1505
- }
1506
- }
1507
- }`;var READ_PACKAGE_DOC_QUERY=`
1508
- query ReadPackageDoc($pageId: String!, $startLine: Int, $endLine: Int) {
1509
- getDocPage(pageId: $pageId, startLine: $startLine, endLine: $endLine) {
1510
- registry
1511
- packageName
1512
- version
1513
- sourceKind
1514
- contentRange {
1515
- startLine
1516
- endLine
1517
- totalLines
1518
- anchor
1519
- }
1520
- page {
1521
- id
1522
- docsReadTarget
1523
- title
1524
- content
1525
- contentFormat
1526
- breadcrumbs
1527
- linkName
1528
- lastUpdatedAt
1529
- sourceKind
1530
- source {
1531
- url
1532
- label
1533
- }
1534
- repoUrl
1535
- gitRef
1536
- requestedRef
1537
- filePath
1538
- baseUrl
1539
- }
1540
- }
1541
- }`;class PackageIntelligenceServiceImpl2{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executePackageSummary(token,params,signal)}))}async executePackageSummary(token,params,signal){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName,includeVerboseFields:params.includeVerboseFields!==false},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}const data=parsed.data.data?.packageSummary;const errors=parsed.data.errors??[];const primaryErrors=errors.filter((error)=>error.path?.[0]!=="provenance");if(primaryErrors.length>0||!data&&errors.length>0){throw this.createGraphQLError(primaryErrors.length>0?primaryErrors:errors)}for(const error of errors){const mapped=this.createGraphQLError([error]);if(mapped instanceof AuthenticationError2||mapped instanceof PackageIntelligenceAccessError||mapped instanceof ClientUpdateRequiredError){throw mapped}}if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const summary=this.normalise(data);const selected=parsed.data.data?.provenance?.selectedVersion;if(errors.length===0&&summary.package.version!==undefined&&selected?.resolvedVersion===summary.package.version){summary.package.registryRepository=selected.registryRepository??undefined}return summary}createHttpError(response){return createPackageIntelligenceHttpError(response)}createTransportError(error){return createPackageIntelligenceTransportError(error)}createGraphQLError(errors){return createPackageIntelligenceGraphQLError(errors,this.runtime.clientVersion,this.runtime.diagnostics)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,version:pkg?.version??undefined,publishedAt:pkg?.publishedAt??undefined,registryLatestDifference:pkg?.registryLatestDifference??undefined,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,versionCount:pkg?.versionCount??undefined,downloadsRefreshedAt:pkg?.downloadsRefreshedAt??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,allVulnerabilityCount:data.security.allVulnerabilityCount,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params,signal)}))}async executePackageVulnerabilities(token,params,signal){let after=null;let firstPage;const entries=[];const sourceDetails=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after,signal);if(!firstPage)firstPage=page;sourceDetails.push(...page.sourceDetails??[]);const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;const report=this.normaliseVulnerabilityReport(data);if(params.includeSourceDetails===true)report.sourceDetails=sourceDetails;if(params.includeTransitive===true){report.transitive=await this.fetchTransitiveVulnerabilityAudit(token,report.package,params.minSeverity,params.advisoryScope??"AFFECTED",params,signal)}return report}async fetchPackageVulnerabilitiesPage(token,params,after,signal){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:packageVulnerabilitiesQuery(params.includeSourceDetails===true),variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}const data=parsed.data.data?.packageVulnerabilities;const sourceDetails=params.includeSourceDetails===true?data?.security?.advisories.entries.map((entry)=>{if(entry.sourceDetails===undefined||entry.sourceDetails!==null&&entry.sourceDetails.osvId!==entry.osvId){throw new MalformedPackageIntelligenceResponseError("Vulnerability source response omitted selected data or changed the representative ID.")}return{advisoryId:entry.osvId??null,source:entry.sourceDetails}})??[]:undefined;const fatalErrors=[];for(const error of parsed.data.errors??[]){const path=error.path;const code=error.extensions?.code;const index=path?.[4];const source=typeof index==="number"&&Number.isInteger(index)&&index>=0?sourceDetails?.[index]:undefined;if(path?.length!==6||path[0]!=="packageVulnerabilities"||path[1]!=="security"||path[2]!=="advisories"||path[3]!=="entries"||path[5]!=="sourceDetails"||!source||source.source!==null||typeof code!=="string"||!["NOT_FOUND","RATE_LIMITED","TIMEOUT","UPSTREAM_ERROR"].includes(code)){fatalErrors.push(error);continue}const retryAfterMs=error.extensions?.retry_after_ms;source.error={code,message:`Current OSV source unavailable (${code}).`,retryable:error.extensions?.retryable===true,...typeof retryAfterMs==="number"&&Number.isFinite(retryAfterMs)&&retryAfterMs>=0?{retryAfterSeconds:retryAfterMs/1000}:{}}}if(fatalErrors.length){throw promoteGenericVersionNotFound(this.createGraphQLError(fatalErrors),params)}if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return{...data,...sourceDetails?{sourceDetails}:{}}}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined,registryRepository:data.package?.registryRepository??undefined};const security=data.security?{unknownVulnerabilityCount:data.security.unknownVulnerabilityCount??undefined,assessmentStatus:data.security.assessmentStatus??undefined,affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,assessmentStatus:vuln.assessmentStatus??undefined,assessmentReasons:vuln.assessmentReasons??undefined,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async fetchTransitiveVulnerabilityAudit(token,directIdentity,minSeverity,advisoryScope,params,signal){if(!directIdentity.registry){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing registry for transitive audit.")}let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:buildPackageTransitiveVulnerabilityAuditQuery(advisoryScope),variables:{registry:params.registry,name:directIdentity.name,version:directIdentity.version,minSeverity,scope:advisoryScope,includeTransitiveAdvisoryDetails:params.includeTransitiveAdvisoryDetails===true},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=transitiveAuditGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),{registry:params.registry,packageName:directIdentity.name,version:directIdentity.version})}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const packageIdentity=data.package;if(packageIdentity?.name!==directIdentity.name||packageIdentity.registry!==directIdentity.registry||packageIdentity.version!==directIdentity.version){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response package identity differs from the direct report.")}const summary=data.dependencies?.transitive?.vulnerabilitySummary;if(!summary){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response missing vulnerability summary.")}return this.normaliseTransitiveVulnerabilityAudit(summary,advisoryScope)}normaliseTransitiveVulnerabilityAudit(summary,advisoryScope){const fields=TRANSITIVE_AUDIT_SCOPE_FIELDS[advisoryScope];const packages=summary.packages.filter((pkg)=>pkg[fields.packageCount]>0).map((pkg)=>{const selectedCount=pkg[fields.packageCount];const occurrences=pkg.advisoryOccurrences??[];if(occurrences.length!==selectedCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit package occurrence count differs from selected count.")}return{registry:pkg.registry,name:pkg.name,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,unknownCount:pkg.unknownCount,totalCount:pkg.totalCount,occurrenceCount:selectedCount,occurrences:occurrences.map((occurrence)=>{const isAffected=occurrence.affectsResolvedVersion;if(advisoryScope==="AFFECTED"&&!isAffected||(advisoryScope==="NON_AFFECTING"||advisoryScope==="UNKNOWN")&&isAffected){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence differs from the requested scope.")}const hasMatchedAffectedRange=occurrence.matchedAffectedVersionRanges.length>0;if(isAffected!==hasMatchedAffectedRange){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence has inconsistent affectedness proof.")}const hasHigherFixes=occurrence.fixVersionsAboveResolved.length>0;const nearestFixedVersion=occurrence.nearestFixedVersion??undefined;const hasNearestFix=nearestFixedVersion!==undefined;if(!isAffected&&(hasHigherFixes||hasNearestFix)||hasHigherFixes!==hasNearestFix||hasNearestFix&&!occurrence.fixVersionsAboveResolved.includes(nearestFixedVersion)){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit fix metadata is inconsistent.")}return{version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,assessmentStatus:occurrence.assessmentStatus??undefined,assessmentReasons:occurrence.assessmentReasons??undefined,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion,advisory:this.normaliseTransitiveAuditAdvisory(occurrence.advisory)}})}});const normalisedOccurrenceCount=packages.reduce((total,pkg)=>total+pkg.occurrences.length,0);const occurrenceCount=summary[fields.summary].totalVulnerabilities;if(normalisedOccurrenceCount!==occurrenceCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence count differs from selected total.")}return{advisoryScope,affectedCount:summary.affected.totalVulnerabilities,nonAffectingCount:summary.nonAffecting.totalVulnerabilities,unknownCount:summary.unknown.totalVulnerabilities,totalCount:summary.combined.totalVulnerabilities,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,packageCount:packages.length,occurrenceCount,calculatedAt:summary.calculatedAt??undefined,packages}}async packageDependencies(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executePackageDependencies(token,params,signal)}))}async packageUpgradeDependencyProbe(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params,signal)}))}async packageUpgradeReview(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params,signal)}))}async executePackageUpgradeReview(token,params,signal){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:packageUpgradeReviewQuery(params),variables:{...(params.changelogView??"text")==="triage"?{}:{offset:0,tiers:params.statementTiers},packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageUpgradeReviewGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageUpgradeReview;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const reviews=data.reviews.map((review)=>({...review,unknowns:(review.unknownDetails??[]).map((detail)=>detail.message)}));const detailed=(params.changelogView??"text")!=="triage";if(!detailed)return stripNullProperties({...data,reviews});const result={summary:data.summary,reviews:[]};for(const review of reviews){const page=review.changelog.statements;if(!page||!review.changelog.entries||!review.changelog.sampledEntries||!review.changelog.keywordEntries)throw new MalformedPackageIntelligenceResponseError("Missing selected upgrade changelog evidence.");const pages=[];let current=page;let offset=0;while(true){if(current.items.some((item)=>params.statementTiers?.length&&(!item.classification||!params.statementTiers.includes(item.classification.tier))))throw new MalformedPackageIntelligenceResponseError("Statement does not match selected tiers.");if(current.totalCount!==page.totalCount||current.matchingCount!==page.matchingCount||changelogCoverageSignature(current.coverage)!==changelogCoverageSignature(page.coverage))throw new PackageIntelligenceBackendError("Changelog evidence changed during retrieval; classification or note generation may still be in progress. Rerun to retrieve the current view.",undefined,undefined,true);validateChangelogStatementPage(current,offset,params.changelogView==="json");pages.push(current);if(current.nextOffset===null)break;offset=current.nextOffset;current=await this.fetchUpgradeStatementPage(token,params,review,offset,signal)}const collected=collectChangelogStatements(pages,Boolean(params.statementTiers?.length));if(changelogCoverageSignature(collected.coverage)!==changelogCoverageSignature(page.coverage))throw new MalformedPackageIntelligenceResponseError("Upgrade statement assessment coverage disagrees with collected evidence.");validateUpgradeStatementCounts(collected,review.changelog.riskCoverage,params.statementTiers);const normalizedReview=stripNullProperties(review);normalizedReview.changelog.statements=collected;result.reviews.push(normalizedReview)}return result}async fetchUpgradeStatementPage(token,params,identity,offset,signal){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:packageUpgradeReviewQuery(params,true),variables:{packages:[{registry:identity.registry,name:identity.name,currentVersion:identity.currentVersion,targetVersion:identity.targetVersion}],offset,tiers:params.statementTiers},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError)throw this.createTransportError(cause);throw cause}if(response.status<200||response.status>=300)throw this.createHttpError(response);const parsed=upgradeStatementContinuationSchema.safeParse(response.parsedBody);if(!parsed.success)throw new MalformedPackageIntelligenceResponseError("Malformed upgrade statement continuation.");if(parsed.data.errors?.length)throw this.createGraphQLError(parsed.data.errors);const reviews=parsed.data.data?.packageUpgradeReview?.reviews;const review=reviews?.[0];if(reviews?.length!==1||!review||["registry","name","currentVersion","targetVersion"].some((key)=>review[key]!==identity[key]))throw new MalformedPackageIntelligenceResponseError("Upgrade statement continuation identity mismatch.");return review.changelog.statements}async executePackageUpgradeDependencyProbe(token,params,signal){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params,signal){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeDependencyIssues===true?true:params.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true||params.includeDependencyIssues===true,includeDependencyIssues:params.includeDependencyIssues===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const report=this.normaliseDependencyReport(data);if(params.includeDependencyIssues===true){const transitive=report.dependencies?.transitive;if(!transitive?.dependencyIssues){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency issues.")}if(!transitive.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency graph.")}}if(params.includeTransitive===true){const transitive=report.dependencies?.transitive;const hasConflictEdges=transitive?.dependencyConflicts?.some((conflict)=>conflict.conflictingEdges.length>0);if(hasConflictEdges&&!transitive?.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Transitive dependency conflict edges response missing dependency graph.")}}return report}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined,registryRepository:data.package?.registryRepository??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseTransitiveAuditAdvisory(advisory){return{osvId:advisory.osvId??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,affectedVersionRanges:advisory.affectedVersionRanges?.length?advisory.affectedVersionRanges:undefined,fixedInVersions:advisory.fixedInVersions?.length?advisory.fixedInVersions:undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version)=>({version:version.version,severity:version.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executePackageChangelog(token,params,signal)}))}async executePackageChangelog(token,params,signal){const pages=[];let nextOffset=0;let report;while(nextOffset!==null){const offset=nextOffset;const page=await this.fetchPackageChangelogPage(token,params,offset,signal);if(offset===0)report=page.report;if((params.view??"statements")!=="statements")break;const statements=page.statements;if(!statements)throw new MalformedPackageIntelligenceResponseError("Missing selected changelog statements.");validateChangelogStatementPage(statements,offset,params.includeJsonFields===true);pages.push(statements);if(pages.length>1){const first=pages[0];const signature=(p)=>JSON.stringify(params.statementTiers?.length?p.coverage:p.coverage.map((c)=>[c.version,c.statementsTotal,c.statementsTotal===0?c.status:null,c.generation]));if(first&&(first.totalCount!==statements.totalCount||first.matchingCount!==statements.matchingCount||signature(first)!==signature(statements)))throw new PackageIntelligenceBackendError("Changelog evidence changed during retrieval; classification or note generation may still be in progress. Rerun to retrieve the current view.",undefined,undefined,true)}if(!statements.hasMore)break;nextOffset=statements.nextOffset}if(!report)throw new MalformedPackageIntelligenceResponseError("Empty changelog response.");if((params.view??"statements")==="statements"){report.statements=collectChangelogStatements(pages,Boolean(params.statementTiers?.length));const versions=report.entries.map((entry)=>entry.version);if(JSON.stringify(versions)!==JSON.stringify(report.statements.coverage.map((c)=>c.version)))throw new MalformedPackageIntelligenceResponseError("Changelog coverage does not match the selected releases.")}return report}async fetchPackageChangelogPage(token,params,offset,signal){const exact=params.version!==undefined;const statementView=(params.view??"statements")==="statements";let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:packageChangelogQuery(params,offset),variables:{registry:params.registry,name:params.packageName,...exact?{version:params.version}:{fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit},...statementView?{offset,tiers:params.statementTiers}:{}},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError)throw this.createTransportError(cause);throw cause}if(response.status<200||response.status>=300)throw this.createHttpError(response);const parsed=(exact?exactChangelogGraphQLResponseSchema:changelogGraphQLResponseSchema).safeParse(response.parsedBody);if(!parsed.success)throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.");if(parsed.data.errors?.length)throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params);const data=parsed.data.data;if(exact){const selected=data&&"packageInfo"in data?data.packageInfo?.selectedVersion:undefined;if(!selected?.changelog||offset===0&&(selected.resolvedVersion===undefined||(params.includeJsonFields||!statementView)&&selected.changelog.hasChangelog===undefined))throw new MalformedPackageIntelligenceResponseError("Empty selected-release changelog response.");const c=selected.changelog;return{statements:c.statements,report:{source:normaliseChangelogSource(c.detailSource),entries:offset===0?[{version:selected.resolvedVersion,normalizedVersion:c.entry?.normalizedVersion??undefined,htmlUrl:c.entry?.htmlUrl??undefined,publishedAt:c.entry?.publishedAt??undefined,body:params.view==="verbatim"?c.entry?.body??undefined:undefined,hasChangelog:c.hasChangelog}]:[]}}}const changelog=data&&"packageChangelog"in data?data.packageChangelog:undefined;if(!changelog||offset===0&&changelog.entries===undefined)throw new MalformedPackageIntelligenceResponseError("Empty changelog response.");return{statements:changelog.statements,report:{source:normaliseChangelogSource(changelog.source),entries:(changelog.entries??[]).map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined,body:params.view==="verbatim"?entry.body??undefined:undefined}))}}}async listPackageDocs(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executeListPackageDocs(token,params,signal)}))}async executeListPackageDocs(token,params,signal){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,codeIndexState:data.codeIndexState??undefined,indexingEstimates:data.indexingEstimates,pages:data.pages?.map((page)=>({id:page.id??undefined,docsReadTarget:page.readTarget.target,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params,options){const signal=options?.signal;return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,signal,executeWithToken:(token)=>this.executeReadPackageDoc(token,params,signal)}))}async executeReadPackageDoc(token,params,signal){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId,...params.startLine!==undefined?{startLine:params.startLine}:{},...params.endLine!==undefined?{endLine:params.endLine}:{}},signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return normalisePackageDocResult(data)}}function normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,contentRange:{startLine:data.contentRange.startLine??undefined,endLine:data.contentRange.endLine??undefined,totalLines:data.contentRange.totalLines,anchor:data.contentRange.anchor??undefined},page:data.page?{id:data.page.id??undefined,docsReadTarget:data.page.docsReadTarget,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}function parsePackageDocResult(data){const parsed=packageDocResultResponseSchema.safeParse(data);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}return normalisePackageDocResult(parsed.data)}function stripNullProperties(value){if(Array.isArray(value))return value.map(stripNullProperties);if(!value||typeof value!=="object")return value;const result={};for(const[key,child]of Object.entries(value)){if(child!==null)result[key]=stripNullProperties(child)}return result}function createPackageIntelligenceHttpError(response){const status=response.status;const detail=parseHttpErrorDetail(response.responseBody,["detail","error"]);if(status===401){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}function createPackageIntelligenceTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createPackageIntelligenceGraphQLError(errors,clientVersion,diagnostics){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=pkg-graphql to inspect GraphQL details during local development.";if(diagnostics?.isEnabled("pkg-graphql")){diagnostics.debug("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new PackageIntelligenceBackendError(diagnostics?.isEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":{const recovery=parseVersionRefRecovery(extensions);return new PackageIntelligenceVersionNotFoundError(message,recovery?.package,recovery?.requestedVersion,recovery?.availablePackageVersions,recovery)}case"REF_NOT_FOUND":return new PackageIntelligenceBackendError(message,undefined,code,retryable,parseVersionRefRecovery(extensions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"DOCUMENTATION_SECTION_UNRESOLVED":return new PackageIntelligenceDocumentationSectionUnresolvedError(message,parseDocumentationSectionUnresolvedReason(extensions?.reason));case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:return new PackageIntelligenceBackendError(message,undefined,code,retryable)}}function parseDocumentationSectionUnresolvedReason(value){switch(value){case"not_found":case"ambiguous":case"inexact_range":case"unsupported_format":return value;default:return}}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}
1542
- export{parseHttpErrorDetail,ProviderReauthenticationRequiredError2,TermsAcceptanceRequiredError2,DEFAULT_MCP_URL2,DEFAULT_API_URL2,DEFAULT_CODE_NAV_URL2,getMcpUrl2,getApiUrl2,getCodeNavigationUrl2,getEnvApiToken2,DEFAULT_WAIT_TIMEOUT_MS,indexingRequestTimeoutMs,FetchTimeoutError2,isFetchTimeoutError,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError2,ApiRateLimitError2,withServiceDiagnostics,isTokenRefreshableError,GitHitsServiceImpl2,executeWithTokenRefresh,AGENTIC_ASK_REQUEST_TIMEOUT_MS2,AgenticAskHttpError,AgenticAskRequestTimeoutError,AgenticAskConnectionError,MalformedAgenticAskResponseError,AgenticAskResponseTooLargeError,AgenticAskServiceImpl2,normalizeAgenticAskThreadId,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,isClientUpdateRequiredGraphQLError,isGraphQLSchemaMismatchError,parseAvailableArtifacts,PkgseerTransportError,postPkgseerGraphql,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,INDEXING_DURATION_ESTIMATE_SELECTION,INDEXING_ESTIMATES_SELECTION,indexingEstimatesSchema,parseIndexingDurationEstimate,READ_TARGET_SELECTION,selectedReadTargetSchema,parseVersionRefRecovery,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError2,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,TARGET_RESOLUTION_SELECTION,CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,requiredTargetResolutionSchema,CodeNavigationServiceImpl2,createCodeNavigationHttpError,createCodeNavigationGraphQLError,parseCodeContextResult,osvSourceMetadataSchema,osvSourceDetailsSchema,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceDocumentationSectionUnresolvedError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceServiceImpl2,parsePackageDocResult,createPackageIntelligenceHttpError,createPackageIntelligenceTransportError,createPackageIntelligenceGraphQLError};