@githits/mcp 0.31.0 → 0.33.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.
@@ -0,0 +1,1524 @@
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 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}}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{response,body}=await this.request("/search",{method:"POST",headers:this.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);if(!response.ok){throw this.createError(response,body)}return body})}headers(){return{...this.runtime.clientHeaders?.(),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: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(token.startsWith("ghi-")||!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.";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; until then, use search, grep, list, or read for evidence. 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. Try again.");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.signal,this.runtime.timeoutMs??AGENTIC_ASK_REQUEST_TIMEOUT_MS2))}async executeAsk(token,request,signal){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");let response;try{response=await this.fetchFn(`${apiUrl.replace(/\/+$/,"")}/ask`,{method:"POST",headers:{...this.runtime.clientHeaders?.(),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 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===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===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"];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"};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
+ }
62
+ resolvedRequested {
63
+ kind
64
+ registry
65
+ packageName
66
+ version
67
+ repoUrl
68
+ gitRef
69
+ commitSha
70
+ committedAt
71
+ }
72
+ served {
73
+ kind
74
+ registry
75
+ packageName
76
+ version
77
+ repoUrl
78
+ gitRef
79
+ commitSha
80
+ committedAt
81
+ }
82
+ freshness
83
+ freshnessReason
84
+ indexingRef
85
+ availableVersions {
86
+ version
87
+ ref
88
+ }
89
+ ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
90
+ ${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
91
+ }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
92
+ availableVersions {
93
+ version
94
+ ref
95
+ }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
96
+ availableVersions {
97
+ version
98
+ ref
99
+ }
100
+ availableRefs {
101
+ version
102
+ ref
103
+ }
104
+ ${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var UNIFIED_SEARCH_LOCATOR_SELECTION=`
105
+ registry
106
+ packageName
107
+ version
108
+ pageId
109
+ docsReadTarget
110
+ sourceKind
111
+ sourceUrl
112
+ repoUrl
113
+ gitRef
114
+ commitSha
115
+ requestedRef
116
+ filePath
117
+ repositoryFilePath
118
+ startLine
119
+ endLine
120
+ evidenceRange {
121
+ startLine
122
+ endLine
123
+ matchLine
124
+ rangeKind
125
+ matchSpansTruncated
126
+ }
127
+ indexedRange {
128
+ startLine
129
+ endLine
130
+ }
131
+ symbolContext {
132
+ name
133
+ qualifiedPath
134
+ kind
135
+ relation
136
+ definitionRange {
137
+ filePath
138
+ repositoryFilePath
139
+ startLine
140
+ endLine
141
+ }
142
+ }
143
+ fileContentHash
144
+ symbolRef
145
+ qualifiedPath
146
+ kind
147
+ category
148
+ language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
149
+ repositoryEvidence {
150
+ bm25MatchFields
151
+ semanticContext {
152
+ scopes {
153
+ name
154
+ qualifiedPath
155
+ kind
156
+ parentQualifiedPath
157
+ declarationStartLine
158
+ declarationEndLine
159
+ parameterNames
160
+ returnType
161
+ symbolRef
162
+ }
163
+ scopeChainTruncated
164
+ preferredRead {
165
+ targetLabel
166
+ registry
167
+ packageName
168
+ version
169
+ repoUrl
170
+ gitRef
171
+ commitSha
172
+ requestedRef
173
+ filePath
174
+ repositoryFilePath
175
+ startLine
176
+ endLine
177
+ }
178
+ }
179
+ matchedSource {
180
+ startLine
181
+ endLine
182
+ matchLine
183
+ rangeKind
184
+ matchSpansTruncated
185
+ linesOmittedBefore
186
+ linesOmittedAfter
187
+ lines {
188
+ lineNumber
189
+ text
190
+ highlights
191
+ prefixTruncated
192
+ suffixTruncated
193
+ }
194
+ }
195
+ }`;var UNIFIED_SEARCH_QUERY=`
196
+ query UnifiedSearch(
197
+ $targets: [SearchPackageInput!]!
198
+ $query: String!
199
+ $sources: [DiscoverySearchSource!]
200
+ $filters: DiscoverySearchFiltersInput
201
+ $allowPartialResults: Boolean
202
+ $limit: Int
203
+ $offset: Int
204
+ $waitTimeoutMs: Int
205
+ ) {
206
+ search(
207
+ targets: $targets
208
+ query: $query
209
+ sources: $sources
210
+ filters: $filters
211
+ allowPartialResults: $allowPartialResults
212
+ limit: $limit
213
+ offset: $offset
214
+ waitTimeoutMs: $waitTimeoutMs
215
+ ) {
216
+ completed
217
+ searchRef
218
+ result {
219
+ query
220
+ queryWarnings
221
+ sources
222
+ results {
223
+ readTarget { ${READ_TARGET_SELECTION} }
224
+ id
225
+ resultType
226
+ targetLabel
227
+ requestedTargetLabel
228
+ freshTargetLabel
229
+ servedTargetLabel
230
+ freshness
231
+ title
232
+ score
233
+ highlights {
234
+ title
235
+ }
236
+ documentationPreview {
237
+ text
238
+ highlights
239
+ }
240
+ ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
241
+ locator {
242
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
243
+ }
244
+ }
245
+ page {
246
+ offset
247
+ limit
248
+ returned
249
+ hasMore
250
+ }
251
+ partialResults
252
+ evidenceNotice
253
+ sourceStatus {
254
+ source
255
+ targetLabel
256
+ requestedTargetLabel
257
+ freshTargetLabel
258
+ servedTargetLabel
259
+ ${TARGET_RESOLUTION_SELECTION}
260
+ indexingStatus
261
+ codeIndexState
262
+ resultCount
263
+ appliedFilters
264
+ ignoredFilters
265
+ incompatibleFilters
266
+ appliedQueryFeatures
267
+ ignoredQueryFeatures
268
+ incompatibleQueryFeatures
269
+ suggestedSiteTargets
270
+ suggestedSiteTargetsTruncated
271
+ note
272
+ ${DOC_COVERAGE_SELECTION}
273
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
274
+ }
275
+ }
276
+ progress {
277
+ searchRef
278
+ status
279
+ targetsTotal
280
+ targetsReady
281
+ elapsedMs
282
+ ${INDEXING_ESTIMATES_SELECTION}
283
+ query
284
+ queryWarnings
285
+ sources
286
+ requestedSources
287
+ targetMode
288
+ requestedTargets {
289
+ registry
290
+ name
291
+ version
292
+ repoUrl
293
+ gitRef
294
+ site
295
+ }
296
+ filters {
297
+ fileIntent
298
+ kind
299
+ category
300
+ publicOnly
301
+ pathPrefix
302
+ }
303
+ limit
304
+ offset
305
+ targets {
306
+ requested
307
+ resolvedRequested
308
+ served
309
+ freshness
310
+ indexingRef
311
+ requestedRefKind
312
+ ${TARGET_RESOLUTION_SELECTION}
313
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
314
+ ${DOC_COVERAGE_SELECTION}
315
+ }
316
+ expiresAt
317
+ }
318
+ }
319
+ }`;var UNIFIED_SEARCH_STATUS_QUERY=`
320
+ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
321
+ discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
322
+ searchRef
323
+ status
324
+ targetsTotal
325
+ targetsReady
326
+ elapsedMs
327
+ ${INDEXING_ESTIMATES_SELECTION}
328
+ query
329
+ queryWarnings
330
+ sources
331
+ requestedSources
332
+ targetMode
333
+ requestedTargets {
334
+ registry
335
+ name
336
+ version
337
+ repoUrl
338
+ gitRef
339
+ site
340
+ }
341
+ filters {
342
+ fileIntent
343
+ kind
344
+ category
345
+ publicOnly
346
+ pathPrefix
347
+ }
348
+ limit
349
+ offset
350
+ targets {
351
+ requested
352
+ resolvedRequested
353
+ served
354
+ freshness
355
+ indexingRef
356
+ requestedRefKind
357
+ ${TARGET_RESOLUTION_SELECTION}
358
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
359
+ ${DOC_COVERAGE_SELECTION}
360
+ }
361
+ expiresAt
362
+ results {
363
+ query
364
+ queryWarnings
365
+ sources
366
+ results {
367
+ readTarget { ${READ_TARGET_SELECTION} }
368
+ id
369
+ resultType
370
+ targetLabel
371
+ requestedTargetLabel
372
+ freshTargetLabel
373
+ servedTargetLabel
374
+ freshness
375
+ title
376
+ score
377
+ highlights {
378
+ title
379
+ }
380
+ documentationPreview {
381
+ text
382
+ highlights
383
+ }
384
+ ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
385
+ locator {
386
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
387
+ }
388
+ }
389
+ page {
390
+ offset
391
+ limit
392
+ returned
393
+ hasMore
394
+ }
395
+ partialResults
396
+ evidenceNotice
397
+ sourceStatus {
398
+ source
399
+ targetLabel
400
+ requestedTargetLabel
401
+ freshTargetLabel
402
+ servedTargetLabel
403
+ ${TARGET_RESOLUTION_SELECTION}
404
+ indexingStatus
405
+ codeIndexState
406
+ resultCount
407
+ appliedFilters
408
+ ignoredFilters
409
+ incompatibleFilters
410
+ appliedQueryFeatures
411
+ ignoredQueryFeatures
412
+ incompatibleQueryFeatures
413
+ suggestedSiteTargets
414
+ suggestedSiteTargetsTruncated
415
+ note
416
+ ${DOC_COVERAGE_SELECTION}
417
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
418
+ }
419
+ }
420
+ }
421
+ }`;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(),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 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({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 {
422
+ registry
423
+ name
424
+ repoUrl
425
+ }
426
+ fromResolution {
427
+ requested
428
+ resolvedVersion
429
+ ref
430
+ commitSha
431
+ refKind
432
+ versionSource
433
+ }
434
+ toResolution {
435
+ requested
436
+ resolvedVersion
437
+ ref
438
+ commitSha
439
+ refKind
440
+ versionSource
441
+ }
442
+ raw {
443
+ summary {
444
+ filesChanged
445
+ added
446
+ deleted
447
+ modified
448
+ modeChanged
449
+ typeChanged
450
+ inventoryComplete
451
+ unprojectableFiles
452
+ }
453
+ scope {
454
+ status
455
+ fromSubpath
456
+ toSubpath
457
+ pathPrefix
458
+ pathGlob
459
+ }
460
+ contentCoverage
461
+ contentFailure {
462
+ code
463
+ retryable
464
+ retryAfterMs
465
+ stage
466
+ limitKind
467
+ }
468
+ files {
469
+ path
470
+ pathEncoding
471
+ status
472
+ modeChanged
473
+ typeChanged
474
+ contentStatus
475
+ contentSafety {
476
+ filtered
477
+ modifications
478
+ }`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
479
+ additions
480
+ deletions`:`
481
+ additions
482
+ deletions
483
+ patch
484
+ contentOmissionReason`;return`
485
+ query CodeDiff(
486
+ $registry: Registry
487
+ $name: String
488
+ $fromVersion: String
489
+ $toVersion: String
490
+ $repoUrl: String
491
+ $fromRef: String
492
+ $toRef: String
493
+ $rawOptions: RawCodeDiffOptions
494
+ ) {
495
+ codeDiff(
496
+ registry: $registry
497
+ name: $name
498
+ fromVersion: $fromVersion
499
+ toVersion: $toVersion
500
+ repoUrl: $repoUrl
501
+ fromRef: $fromRef
502
+ toRef: $toRef
503
+ rawOptions: $rawOptions
504
+ ) {
505
+ ${CODE_DIFF_COMMON_SELECTION}${contentFields}
506
+ }
507
+ hasMoreFiles
508
+ }
509
+ }
510
+ }`}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=`
511
+ query ListRepoFiles(
512
+ $registry: Registry
513
+ $packageName: String
514
+ $repoUrl: String
515
+ $gitRef: String
516
+ $version: String
517
+ $pathPrefix: String
518
+ $pathSelectors: [FilePathSelectorInput!]
519
+ $extensions: [String!]
520
+ $fileTypes: [String!]
521
+ $languages: [String!]
522
+ $fileIntent: FileIntent
523
+ $fileIntents: [FileIntent!]
524
+ $excludeFileIntents: [FileIntent!]
525
+ $excludeDocFiles: Boolean
526
+ $excludeTestFiles: Boolean
527
+ $includeHidden: Boolean
528
+ $limit: Int
529
+ $waitTimeoutMs: Int
530
+ ) {
531
+ listRepoFiles(
532
+ registry: $registry
533
+ packageName: $packageName
534
+ repoUrl: $repoUrl
535
+ gitRef: $gitRef
536
+ version: $version
537
+ pathPrefix: $pathPrefix
538
+ pathSelectors: $pathSelectors
539
+ extensions: $extensions
540
+ fileTypes: $fileTypes
541
+ languages: $languages
542
+ fileIntent: $fileIntent
543
+ fileIntents: $fileIntents
544
+ excludeFileIntents: $excludeFileIntents
545
+ excludeDocFiles: $excludeDocFiles
546
+ excludeTestFiles: $excludeTestFiles
547
+ includeHidden: $includeHidden
548
+ limit: $limit
549
+ waitTimeoutMs: $waitTimeoutMs
550
+ ) {
551
+ files {
552
+ path
553
+ name
554
+ language
555
+ fileType
556
+ byteSize
557
+ }
558
+ total
559
+ hasMore
560
+ indexedVersion
561
+ resolution {
562
+ requestedVersion
563
+ requestedRef
564
+ resolvedRef
565
+ commitSha
566
+ }
567
+ ${TARGET_RESOLUTION_SELECTION}
568
+ diagnostics {
569
+ hint
570
+ }
571
+ codeIndexState
572
+ indexingRef
573
+ availableVersions {
574
+ version
575
+ ref
576
+ }
577
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
578
+ ${INDEXING_ESTIMATES_SELECTION}
579
+ }
580
+ }`;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=`
581
+ query FetchCodeContext(
582
+ $registry: Registry
583
+ $packageName: String
584
+ $repoUrl: String
585
+ $gitRef: String
586
+ $version: String
587
+ $filePath: String!
588
+ $startLine: Int
589
+ $endLine: Int
590
+ $waitTimeoutMs: Int
591
+ ) {
592
+ fetchCodeContext(
593
+ registry: $registry
594
+ packageName: $packageName
595
+ repoUrl: $repoUrl
596
+ gitRef: $gitRef
597
+ version: $version
598
+ filePath: $filePath
599
+ startLine: $startLine
600
+ endLine: $endLine
601
+ waitTimeoutMs: $waitTimeoutMs
602
+ ) {
603
+ content
604
+ filePath
605
+ language
606
+ totalLines
607
+ startLine
608
+ endLine
609
+ repoUrl
610
+ gitRef
611
+ isBinary
612
+ codeIndexState
613
+ indexingRef
614
+ ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
615
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
616
+ ${INDEXING_ESTIMATES_SELECTION}
617
+ ${TARGET_RESOLUTION_SELECTION}
618
+ }
619
+ }`;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(`
620
+ `);const symbolBlock=symbolSelection.length>0?`
621
+ symbol {
622
+ ${symbolSelection}
623
+ }`:"";return`
624
+ query GrepRepo(
625
+ $registry: Registry
626
+ $packageName: String
627
+ $repoUrl: String
628
+ $gitRef: String
629
+ $version: String
630
+ $waitTimeoutMs: Int
631
+ $pattern: String!
632
+ $patternType: GrepPatternType
633
+ $caseSensitive: Boolean
634
+ $pathSelectors: [GrepPathSelectorInput!]
635
+ $extensions: [String!]
636
+ $excludeDocFiles: Boolean
637
+ $excludeTestFiles: Boolean
638
+ $allowUnscoped: Boolean
639
+ $contextLinesBefore: Int
640
+ $contextLinesAfter: Int
641
+ $maxMatches: Int
642
+ $maxMatchesPerFile: Int
643
+ $cursor: String
644
+ $symbolFields: [String!]
645
+ ) {
646
+ grepRepo(
647
+ registry: $registry
648
+ packageName: $packageName
649
+ repoUrl: $repoUrl
650
+ gitRef: $gitRef
651
+ version: $version
652
+ waitTimeoutMs: $waitTimeoutMs
653
+ pattern: $pattern
654
+ patternType: $patternType
655
+ caseSensitive: $caseSensitive
656
+ pathSelectors: $pathSelectors
657
+ extensions: $extensions
658
+ excludeDocFiles: $excludeDocFiles
659
+ excludeTestFiles: $excludeTestFiles
660
+ allowUnscoped: $allowUnscoped
661
+ contextLinesBefore: $contextLinesBefore
662
+ contextLinesAfter: $contextLinesAfter
663
+ maxMatches: $maxMatches
664
+ maxMatchesPerFile: $maxMatchesPerFile
665
+ cursor: $cursor
666
+ symbolFields: $symbolFields
667
+ ) {
668
+ matches {
669
+ filePath
670
+ line
671
+ matchStartByte
672
+ matchEndByte
673
+ lineContent
674
+ contextBefore
675
+ contextAfter
676
+ fileContentHash
677
+ fileIntent
678
+ symbolRowId${symbolBlock}
679
+ }
680
+ nextCursor
681
+ totalMatches
682
+ hasMore
683
+ truncatedReason
684
+ routeTaken
685
+ filesScanned
686
+ filesInScope
687
+ binaryFilesSkipped
688
+ filesTooLargeSkipped
689
+ uniqueFilesMatched
690
+ indexedVersion
691
+ resolution {
692
+ requestedVersion
693
+ requestedRef
694
+ resolvedRef
695
+ commitSha
696
+ }
697
+ ${TARGET_RESOLUTION_SELECTION}
698
+ codeIndexState
699
+ indexingRef
700
+ availableVersions {
701
+ version
702
+ ref
703
+ }
704
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
705
+ ${INDEXING_ESTIMATES_SELECTION}
706
+ }
707
+ }`}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{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.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 z6}from"zod";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=z6.object({stargazersCount:z6.number().int().nullable().optional(),forksCount:z6.number().int().nullable().optional(),openIssuesCount:z6.number().int().nullable().optional(),archived:z6.boolean().nullable().optional(),language:z6.string().nullable().optional(),topics:z6.array(z6.string()).nullable().optional(),pushedAt:z6.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z6.object({name:z6.string().nullable().optional(),registry:z6.string().nullable().optional(),description:z6.string().nullable().optional(),latestVersion:z6.string().nullable().optional(),latestVersionPublishedAt:z6.string().nullable().optional(),versionCount:z6.number().int().nullable().optional(),downloadsRefreshedAt:z6.string().nullable().optional(),homepage:z6.string().nullable().optional(),repositoryUrl:z6.string().nullable().optional(),license:z6.string().nullable().optional(),downloadsLastMonth:z6.number().int().nullable().optional(),downloadsTotal:z6.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z6.object({osvId:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),publishedAt:z6.string().nullable().optional()});var packageSecurityOverviewSchema=z6.object({vulnerabilityCount:z6.number().int().nullable().optional(),allVulnerabilityCount:z6.number().int(),hasCurrentVulnerabilities:z6.boolean().nullable().optional(),recentVulnerabilities:z6.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z6.object({version:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional(),body:z6.string().nullable().optional()});var packageSummaryResponseSchema=z6.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z6.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z6.object({message:z6.string(),extensions:z6.record(z6.string(),z6.unknown()).optional(),path:z6.array(z6.union([z6.string(),z6.number().int()])).optional()});var registryRepositorySchema=z6.object({id:z6.string(),name:z6.string(),url:z6.string()});var graphQLResponseSchema=z6.object({data:z6.object({packageSummary:packageSummaryResponseSchema.nullable().optional(),provenance:z6.object({selectedVersion:z6.object({resolvedVersion:z6.string(),registryRepository:registryRepositorySchema.nullable().optional()})}).nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
708
+ query PackageSummary(
709
+ $registry: Registry!
710
+ $name: String!
711
+ $includeVerboseFields: Boolean! = true
712
+ ) {
713
+ packageSummary(registry: $registry, name: $name) {
714
+ package {
715
+ name
716
+ registry
717
+ description
718
+ latestVersion
719
+ latestVersionPublishedAt
720
+ homepage
721
+ repositoryUrl
722
+ license
723
+ downloadsLastMonth
724
+ downloadsTotal
725
+ versionCount @include(if: $includeVerboseFields)
726
+ downloadsRefreshedAt @include(if: $includeVerboseFields)
727
+ githubRepository {
728
+ stargazersCount
729
+ forksCount
730
+ openIssuesCount
731
+ archived
732
+ language @include(if: $includeVerboseFields)
733
+ topics @include(if: $includeVerboseFields)
734
+ pushedAt @include(if: $includeVerboseFields)
735
+ }
736
+ }
737
+ security {
738
+ vulnerabilityCount
739
+ allVulnerabilityCount
740
+ hasCurrentVulnerabilities
741
+ recentVulnerabilities @include(if: $includeVerboseFields) {
742
+ osvId
743
+ summary
744
+ severityScore
745
+ publishedAt
746
+ }
747
+ }
748
+ latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
749
+ version
750
+ publishedAt
751
+ body
752
+ }
753
+ }
754
+ provenance: packageInfo(registry: $registry, name: $name) {
755
+ selectedVersion {
756
+ resolvedVersion
757
+ registryRepository { id name url }
758
+ }
759
+ }
760
+ }`;var packageVersionIdentitySchema=z6.object({name:z6.string().nullable().optional(),registry:z6.string().nullable().optional(),version:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional(),deprecated:z6.boolean().nullable().optional(),deprecationReason:z6.string().nullable().optional(),registryRepository:registryRepositorySchema.nullable().optional()});var vulnerabilityDetailSchema=z6.object({assessmentStatus:z6.string().nullable().optional(),assessmentReasons:z6.array(z6.string()).nullable().optional(),osvId:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),severityType:z6.string().nullable().optional(),affectedVersionRanges:z6.array(z6.string()).nullable().optional(),affectedVersionRangesCount:z6.number().int(),affectedVersionRangesTruncated:z6.boolean(),fixedInVersions:z6.array(z6.string()).nullable().optional(),publishedAt:z6.string().nullable().optional(),modifiedAt:z6.string().nullable().optional(),withdrawnAt:z6.string().nullable().optional(),aliases:z6.array(z6.string()).nullable().optional(),isMalicious:z6.boolean().nullable().optional(),affectsInspectedVersion:z6.boolean(),matchedAffectedVersionRanges:z6.array(z6.string()),duplicateIds:z6.array(z6.string())});var pageInfoSchema=z6.object({hasNextPage:z6.boolean(),endCursor:z6.string().nullable().optional(),totalCount:z6.number().int()});var vulnerabilityAdvisoryPageSchema=z6.object({entries:z6.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z6.object({unknownVulnerabilityCount:z6.number().int().nonnegative().nullable().optional(),assessmentStatus:z6.string().nullable().optional(),affectedVulnerabilityCount:z6.number().int(),nonAffectingVulnerabilityCount:z6.number().int(),allVulnerabilityCount:z6.number().int(),currentVersionAffected:z6.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z6.array(z6.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z6.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z6.object({data:z6.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});var transitiveAuditAdvisorySchema=z6.object({osvId:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),affectedVersionRanges:z6.array(z6.string()).nullable().optional(),fixedInVersions:z6.array(z6.string()).nullable().optional(),publishedAt:z6.string().nullable().optional(),modifiedAt:z6.string().nullable().optional(),aliases:z6.array(z6.string()).nullable().optional(),isMalicious:z6.boolean().nullable().optional()});var transitiveAuditOccurrenceSchema=z6.object({assessmentStatus:z6.string().nullable().optional(),assessmentReasons:z6.array(z6.string()).nullable().optional(),version:z6.string(),affectsResolvedVersion:z6.boolean(),matchedAffectedVersionRanges:z6.array(z6.string()),fixVersionsAboveResolved:z6.array(z6.string()),nearestFixedVersion:z6.string().nullable().optional(),advisory:transitiveAuditAdvisorySchema});var transitiveAuditPackageSchema=z6.object({registry:z6.string(),name:z6.string(),affectedCount:z6.number().int().nonnegative(),nonAffectingCount:z6.number().int().nonnegative(),unknownCount:z6.number().int().nonnegative(),totalCount:z6.number().int().nonnegative(),advisoryOccurrences:z6.array(transitiveAuditOccurrenceSchema).nullable().optional()});var transitiveAuditCountSchema=z6.object({totalVulnerabilities:z6.number().int().nonnegative()});var transitiveAuditSummarySchema=z6.object({affected:transitiveAuditCountSchema,nonAffecting:transitiveAuditCountSchema,unknown:transitiveAuditCountSchema,combined:transitiveAuditCountSchema,totalPackagesAnalyzed:z6.number().int().nonnegative(),packages:z6.array(transitiveAuditPackageSchema),calculatedAt:z6.string().nullable().optional()});var transitiveAuditResponseSchema=z6.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:z6.object({transitive:z6.object({vulnerabilitySummary:transitiveAuditSummarySchema.nullable().optional()}).nullable().optional()}).nullable().optional()});var transitiveAuditGraphQLResponseSchema=z6.object({data:z6.object({packageDependencies:transitiveAuditResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
761
+ query PackageVulnerabilities(
762
+ $registry: Registry!
763
+ $name: String!
764
+ $version: String
765
+ $minSeverity: Float
766
+ $includeWithdrawn: Boolean
767
+ $scope: VulnerabilityScope = AFFECTED
768
+ $after: String
769
+ ) {
770
+ packageVulnerabilities(
771
+ registry: $registry
772
+ name: $name
773
+ version: $version
774
+ minSeverity: $minSeverity
775
+ includeWithdrawn: $includeWithdrawn
776
+ ) {
777
+ package {
778
+ name
779
+ registry
780
+ version
781
+ registryRepository { id name url }
782
+ }
783
+ security {
784
+ unknownVulnerabilityCount
785
+ assessmentStatus
786
+ affectedVulnerabilityCount
787
+ nonAffectingVulnerabilityCount
788
+ allVulnerabilityCount
789
+ currentVersionAffected
790
+ upgradePaths
791
+ advisories(scope: $scope, first: 100, after: $after) {
792
+ entries {
793
+ osvId
794
+ summary
795
+ severityScore
796
+ severityType
797
+ affectedVersionRanges
798
+ affectedVersionRangesCount
799
+ affectedVersionRangesTruncated
800
+ fixedInVersions
801
+ publishedAt
802
+ modifiedAt
803
+ withdrawnAt
804
+ aliases
805
+ isMalicious
806
+ affectsInspectedVersion
807
+ assessmentStatus
808
+ assessmentReasons
809
+ matchedAffectedVersionRanges
810
+ duplicateIds
811
+ }
812
+ pageInfo {
813
+ hasNextPage
814
+ endCursor
815
+ totalCount
816
+ }
817
+ }
818
+ }
819
+ }
820
+ }`;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`
821
+ query PackageTransitiveVulnerabilityAudit(
822
+ $registry: Registry!
823
+ $name: String!
824
+ $version: String!
825
+ $minSeverity: Float
826
+ $scope: VulnerabilityScope!
827
+ $includeTransitiveAdvisoryDetails: Boolean! = false
828
+ ) {
829
+ packageDependencies(
830
+ registry: $registry
831
+ name: $name
832
+ version: $version
833
+ includeTransitive: true
834
+ ) {
835
+ package {
836
+ name
837
+ registry
838
+ version
839
+ }
840
+ dependencies {
841
+ transitive {
842
+ vulnerabilitySummary(minSeverity: $minSeverity) {
843
+ affected { totalVulnerabilities }
844
+ nonAffecting { totalVulnerabilities }
845
+ unknown { totalVulnerabilities }
846
+ combined { totalVulnerabilities }
847
+ totalPackagesAnalyzed
848
+ calculatedAt
849
+ packages {
850
+ registry
851
+ name
852
+ affectedCount
853
+ nonAffectingCount
854
+ unknownCount
855
+ totalCount
856
+ advisoryOccurrences(scope: $scope, minSeverity: $minSeverity) {
857
+ version
858
+ affectsResolvedVersion
859
+ ${scope==="ALL"||scope==="UNKNOWN"?"assessmentStatus":""}
860
+ assessmentReasons ${scope==="ALL"||scope==="UNKNOWN"?"":"@include(if: $includeTransitiveAdvisoryDetails)"}
861
+ matchedAffectedVersionRanges
862
+ fixVersionsAboveResolved
863
+ nearestFixedVersion
864
+ advisory {
865
+ osvId
866
+ summary
867
+ severityScore
868
+ affectedVersionRanges @include(if: $includeTransitiveAdvisoryDetails)
869
+ fixedInVersions @include(if: $includeTransitiveAdvisoryDetails)
870
+ publishedAt
871
+ modifiedAt
872
+ aliases
873
+ isMalicious
874
+ }
875
+ }
876
+ }
877
+ }
878
+ }
879
+ }
880
+ }
881
+ }`}var directDependencySchema=z6.object({name:z6.string().nullable().optional(),versionConstraint:z6.string().nullable().optional(),type:z6.string().nullable().optional()});var dependencyGraphNodeSchema=z6.object({registry:z6.string(),name:z6.string(),version:z6.string().nullable().optional()});var dependencyGraphEdgeSchema=z6.object({fromIndex:z6.number().int().nullable().optional(),toIndex:z6.number().int(),constraint:z6.string().nullable().optional(),dependencyType:z6.string().nullable().optional()});var dependencyGraphSchema=z6.object({formatVersion:z6.number().int(),nodes:z6.array(dependencyGraphNodeSchema),edges:z6.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z6.object({totalVulnerabilities:z6.number().int(),critical:z6.number().int(),high:z6.number().int(),medium:z6.number().int(),low:z6.number().int(),unknown:z6.number().int()});var vulnerabilitySummaryDetailSchema=z6.object({osvId:z6.string().nullable().optional(),registry:z6.string().nullable().optional(),packageName:z6.string().nullable().optional(),summary:z6.string().nullable().optional(),severityScore:z6.number().nullable().optional(),severityType:z6.string().nullable().optional(),affectedVersionRanges:z6.array(z6.string()).nullable().optional(),fixedInVersions:z6.array(z6.string()).nullable().optional(),publishedAt:z6.string().nullable().optional(),modifiedAt:z6.string().nullable().optional(),withdrawnAt:z6.string().nullable().optional(),aliases:z6.array(z6.string()).nullable().optional(),isMalicious:z6.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z6.object({version:z6.string(),affectsResolvedVersion:z6.boolean(),matchedAffectedVersionRanges:z6.array(z6.string()),fixVersionsAboveResolved:z6.array(z6.string()),nearestFixedVersion:z6.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z6.object({registry:z6.string(),name:z6.string(),versions:z6.array(z6.string()),affectedCount:z6.number().int(),nonAffectingCount:z6.number().int(),totalCount:z6.number().int(),maxSeverityScore:z6.number().nullable().optional(),maxSeverityLabel:z6.string().nullable().optional(),advisoryIds:z6.array(z6.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z6.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z6.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z6.number().int(),affectedPackageCount:z6.number().int(),packages:z6.array(transitiveVulnerablePackageSchema),calculatedAt:z6.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z6.object({version:z6.string(),reason:z6.string().nullable().optional()});var deprecatedDependencySchema=z6.object({registry:z6.string(),name:z6.string(),versions:z6.array(z6.string()),reasons:z6.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z6.object({version:z6.string(),severity:z6.string()});var outdatedDependencySchema=z6.object({registry:z6.string(),name:z6.string(),latestVersion:z6.string().nullable().optional(),severity:z6.string(),versions:z6.array(outdatedDependencyVersionSchema),repositoryUrl:z6.string().nullable().optional()});var duplicateDependencySchema=z6.object({registry:z6.string().nullable().optional(),name:z6.string(),versions:z6.array(z6.string())});var dependencyConflictEdgeSchema=z6.object({fromIndex:z6.number().int().nullable().optional(),toIndex:z6.number().int(),versionConstraint:z6.string(),dependencyType:z6.string()});var dependencyConflictSchema=z6.object({packageName:z6.string(),requiredVersions:z6.array(z6.string()),conflictingEdges:z6.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z6.object({registry:z6.string().nullable().optional(),name:z6.string(),versions:z6.array(z6.string()),requiredVersions:z6.array(z6.string()),conflictingEdges:z6.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z6.object({totalCount:z6.number().int(),deprecatedCount:z6.number().int(),outdatedCount:z6.number().int(),duplicateCount:z6.number().int(),conflictCount:z6.number().int(),deprecatedPackages:z6.array(deprecatedDependencySchema),outdatedPackages:z6.array(outdatedDependencySchema),duplicatePackages:z6.array(duplicateDependencySchema),conflicts:z6.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z6.object({cycleStart:z6.string(),circularPath:z6.array(z6.string()),displayChain:z6.string()});var environmentMarkerSchema=z6.object({type:z6.string().nullable().optional(),value:z6.string().nullable().optional(),raw:z6.string().nullable().optional()});var transitiveDependencySchema=z6.object({totalEdges:z6.number().int().nullable().optional(),uniquePackagesCount:z6.number().int().nullable().optional(),uniqueDependencies:z6.array(z6.string()).nullable().optional(),dependencyConflicts:z6.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z6.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z6.object({direct:z6.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z6.object({name:z6.string(),constraint:z6.string().nullable().optional()});var dependencyGroupSchema=z6.object({name:z6.string(),lifecycle:z6.string(),conditionType:z6.string(),conditionValue:z6.string().nullable().optional(),selectionMode:z6.string(),exclusiveGroup:z6.string().nullable().optional(),fallbackPriority:z6.number().int().nullable().optional(),compatibleWith:z6.array(z6.string()).nullable().optional(),defaultEnabled:z6.boolean().nullable().optional(),dependencies:z6.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z6.object({primaryGroup:z6.string().nullable().optional(),environmentMarkers:z6.array(environmentMarkerSchema).nullable().optional(),groups:z6.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z6.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z6.object({data:z6.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
882
+ query PackageDependencies(
883
+ $registry: Registry!
884
+ $name: String!
885
+ $version: String
886
+ $includeTransitive: Boolean
887
+ $includeTransitiveDetails: Boolean! = true
888
+ $includeDependencyGraph: Boolean! = true
889
+ $includeGroups: Boolean! = true
890
+ $includeDependencyIssues: Boolean! = false
891
+ $maxDepth: Int
892
+ $lifecycle: [String!]
893
+ ) {
894
+ packageDependencies(
895
+ registry: $registry
896
+ name: $name
897
+ version: $version
898
+ includeTransitive: $includeTransitive
899
+ maxDepth: $maxDepth
900
+ lifecycle: $lifecycle
901
+ ) {
902
+ package {
903
+ name
904
+ registry
905
+ version
906
+ registryRepository { id name url }
907
+ }
908
+ dependencies {
909
+ # Backend-side summary block intentionally not selected — our
910
+ # envelope computes runtime.count client-side from direct[].length
911
+ # so the invariant runtime.count === runtime.items.length always
912
+ # holds regardless of backend-side drift.
913
+ direct {
914
+ name
915
+ versionConstraint
916
+ type
917
+ }
918
+ transitive {
919
+ totalEdges @include(if: $includeTransitiveDetails)
920
+ uniquePackagesCount @include(if: $includeTransitiveDetails)
921
+ uniqueDependencies @include(if: $includeTransitiveDetails)
922
+ dependencyConflicts @include(if: $includeTransitiveDetails) {
923
+ packageName
924
+ requiredVersions
925
+ conflictingEdges {
926
+ fromIndex
927
+ toIndex
928
+ versionConstraint
929
+ dependencyType
930
+ }
931
+ }
932
+ circularDependencyCycles @include(if: $includeTransitiveDetails) {
933
+ cycleStart
934
+ circularPath
935
+ displayChain
936
+ }
937
+ dependencyGraph @include(if: $includeDependencyGraph) {
938
+ formatVersion
939
+ nodes {
940
+ registry
941
+ name
942
+ version
943
+ }
944
+ edges {
945
+ fromIndex
946
+ toIndex
947
+ constraint
948
+ dependencyType
949
+ }
950
+ }
951
+ dependencyIssues @include(if: $includeDependencyIssues) {
952
+ totalCount
953
+ deprecatedCount
954
+ outdatedCount
955
+ duplicateCount
956
+ conflictCount
957
+ deprecatedPackages {
958
+ registry
959
+ name
960
+ versions
961
+ reasons {
962
+ version
963
+ reason
964
+ }
965
+ }
966
+ outdatedPackages {
967
+ registry
968
+ name
969
+ latestVersion
970
+ severity
971
+ versions {
972
+ version
973
+ severity
974
+ }
975
+ repositoryUrl
976
+ }
977
+ duplicatePackages {
978
+ registry
979
+ name
980
+ versions
981
+ }
982
+ conflicts {
983
+ registry
984
+ name
985
+ versions
986
+ requiredVersions
987
+ conflictingEdges {
988
+ fromIndex
989
+ toIndex
990
+ versionConstraint
991
+ dependencyType
992
+ }
993
+ }
994
+ }
995
+ }
996
+ }
997
+ dependencyGroups @include(if: $includeGroups) {
998
+ primaryGroup
999
+ environmentMarkers {
1000
+ type
1001
+ value
1002
+ raw
1003
+ }
1004
+ groups {
1005
+ name
1006
+ lifecycle
1007
+ conditionType
1008
+ conditionValue
1009
+ selectionMode
1010
+ exclusiveGroup
1011
+ fallbackPriority
1012
+ compatibleWith
1013
+ defaultEnabled
1014
+ dependencies {
1015
+ name
1016
+ constraint
1017
+ }
1018
+ }
1019
+ }
1020
+ }
1021
+ }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
1022
+ query PackageUpgradeDependencyProbe(
1023
+ $registry: Registry!
1024
+ $name: String!
1025
+ $version: String!
1026
+ $includeTransitiveRisk: Boolean!
1027
+ $includeTransitiveSecurity: Boolean!
1028
+ $includeDependencyIssues: Boolean!
1029
+ $includeDependencyChanges: Boolean!
1030
+ $includeGroups: Boolean!
1031
+ $lifecycle: [String!]
1032
+ $minSeverity: Float
1033
+ ) {
1034
+ packageDependencies(
1035
+ registry: $registry
1036
+ name: $name
1037
+ version: $version
1038
+ includeTransitive: $includeTransitiveRisk
1039
+ lifecycle: $lifecycle
1040
+ ) {
1041
+ package {
1042
+ name
1043
+ registry
1044
+ version
1045
+ registryRepository { id name url }
1046
+ publishedAt
1047
+ deprecated
1048
+ deprecationReason
1049
+ }
1050
+ dependencies {
1051
+ direct {
1052
+ name
1053
+ versionConstraint
1054
+ type
1055
+ }
1056
+ transitive @include(if: $includeTransitiveRisk) {
1057
+ dependencyGraph @include(if: $includeDependencyChanges) {
1058
+ formatVersion
1059
+ nodes {
1060
+ registry
1061
+ name
1062
+ version
1063
+ }
1064
+ edges {
1065
+ fromIndex
1066
+ toIndex
1067
+ constraint
1068
+ dependencyType
1069
+ }
1070
+ }
1071
+ vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
1072
+ affected {
1073
+ totalVulnerabilities
1074
+ critical
1075
+ high
1076
+ medium
1077
+ low
1078
+ unknown
1079
+ }
1080
+ nonAffecting {
1081
+ totalVulnerabilities
1082
+ critical
1083
+ high
1084
+ medium
1085
+ low
1086
+ unknown
1087
+ }
1088
+ combined {
1089
+ totalVulnerabilities
1090
+ critical
1091
+ high
1092
+ medium
1093
+ low
1094
+ unknown
1095
+ }
1096
+ totalPackagesAnalyzed
1097
+ affectedPackageCount
1098
+ calculatedAt
1099
+ packages {
1100
+ registry
1101
+ name
1102
+ versions
1103
+ affectedCount
1104
+ nonAffectingCount
1105
+ totalCount
1106
+ maxSeverityScore
1107
+ maxSeverityLabel
1108
+ advisoryIds(scope: AFFECTED)
1109
+ mostCritical {
1110
+ osvId
1111
+ registry
1112
+ packageName
1113
+ summary
1114
+ severityScore
1115
+ severityType
1116
+ affectedVersionRanges
1117
+ fixedInVersions
1118
+ publishedAt
1119
+ modifiedAt
1120
+ withdrawnAt
1121
+ aliases
1122
+ isMalicious
1123
+ }
1124
+ advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
1125
+ version
1126
+ affectsResolvedVersion
1127
+ matchedAffectedVersionRanges
1128
+ fixVersionsAboveResolved
1129
+ nearestFixedVersion
1130
+ advisory {
1131
+ osvId
1132
+ registry
1133
+ packageName
1134
+ summary
1135
+ severityScore
1136
+ severityType
1137
+ affectedVersionRanges
1138
+ fixedInVersions
1139
+ publishedAt
1140
+ modifiedAt
1141
+ withdrawnAt
1142
+ aliases
1143
+ isMalicious
1144
+ }
1145
+ }
1146
+ }
1147
+ }
1148
+ dependencyIssues @include(if: $includeDependencyIssues) {
1149
+ totalCount
1150
+ deprecatedCount
1151
+ outdatedCount
1152
+ duplicateCount
1153
+ conflictCount
1154
+ deprecatedPackages {
1155
+ registry
1156
+ name
1157
+ versions
1158
+ reasons {
1159
+ version
1160
+ reason
1161
+ }
1162
+ }
1163
+ outdatedPackages {
1164
+ registry
1165
+ name
1166
+ latestVersion
1167
+ severity
1168
+ versions {
1169
+ version
1170
+ severity
1171
+ }
1172
+ repositoryUrl
1173
+ }
1174
+ duplicatePackages {
1175
+ registry
1176
+ name
1177
+ versions
1178
+ }
1179
+ conflicts {
1180
+ registry
1181
+ name
1182
+ versions
1183
+ requiredVersions
1184
+ conflictingEdges {
1185
+ fromIndex
1186
+ toIndex
1187
+ versionConstraint
1188
+ dependencyType
1189
+ }
1190
+ }
1191
+ }
1192
+ }
1193
+ }
1194
+ dependencyGroups @include(if: $includeGroups) {
1195
+ primaryGroup
1196
+ environmentMarkers {
1197
+ type
1198
+ value
1199
+ raw
1200
+ }
1201
+ groups {
1202
+ name
1203
+ lifecycle
1204
+ conditionType
1205
+ conditionValue
1206
+ selectionMode
1207
+ exclusiveGroup
1208
+ fallbackPriority
1209
+ compatibleWith
1210
+ defaultEnabled
1211
+ dependencies {
1212
+ name
1213
+ constraint
1214
+ }
1215
+ }
1216
+ }
1217
+ }
1218
+ }`;var packageUpgradeAdvisorySchema=z6.object({assessmentStatus:z6.string().nullable().optional(),assessmentReasons:z6.array(z6.string()).nullable().optional(),id:z6.string().nullable().optional(),aliases:z6.array(z6.string()),summary:z6.string().nullable().optional(),severity:z6.number().nullable().optional(),severityLabel:z6.string().nullable().optional(),fixedIn:z6.array(z6.string()),isMalicious:z6.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z6.object({unknownVulnerabilityCount:z6.number().int().nonnegative().nullable().optional(),assessmentStatus:z6.string().nullable().optional(),version:z6.string(),publishedAt:z6.string().nullable().optional(),deprecated:z6.boolean().nullable().optional(),deprecationReason:z6.string().nullable().optional(),affectedCount:z6.number().int(),nonAffectingCount:z6.number().int(),allCount:z6.number().int(),lastModifiedAt:z6.string().nullable().optional(),advisories:z6.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z6.object({entries:z6.array(z6.object({id:z6.string(),registry:z6.string(),name:z6.string(),versions:z6.array(z6.string()),affectedCount:z6.number().int(),maxSeverityScore:z6.number().nullable().optional(),maxSeverityLabel:z6.string().nullable().optional(),advisoryIds:z6.array(z6.string())})),totalCount:z6.number().int(),truncated:z6.boolean()});var packageUpgradeTransitiveSecuritySchema=z6.object({currentAffected:z6.number().int(),targetAffected:z6.number().int(),introducedPackages:z6.array(z6.string()),fixedPackages:z6.array(z6.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z6.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z6.array(packageUpgradeAdvisorySchema),removed:z6.array(packageUpgradeAdvisorySchema),notAddressed:z6.array(packageUpgradeAdvisorySchema),fixed:z6.array(packageUpgradeAdvisorySchema),introduced:z6.array(packageUpgradeAdvisorySchema),unchanged:z6.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z6.object({detailSource:z6.string().nullable(),version:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional(),htmlUrl:z6.string().nullable().optional(),body:z6.string().nullable().optional(),bodyPreview:z6.string().nullable().optional(),headline:z6.string().nullable().optional(),signals:z6.array(z6.string())});var changelogKindSchema=z6.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=z6.object({versionsClassified:z6.number().int(),versionsNotAssessed:z6.number().int(),versionsWithoutNotes:z6.number().int(),versionsUnparseable:z6.number().int(),unitsNoImpact:z6.number().int(),itemsMustActConfident:z6.number().int(),itemsMustActAmbiguous:z6.number().int(),itemsShouldKnowConfident:z6.number().int(),itemsShouldKnowAmbiguous:z6.number().int(),itemsUnclassified:z6.number().int()});var changelogStatementClassificationSchema=z6.object({tier:z6.enum(["MUST_ACT","SHOULD_KNOW","NO_IMPACT","UNCLASSIFIED"]),ambiguous:z6.boolean(),kind:changelogKindSchema,tierConfidence:z6.number().min(0).max(1).nullable().optional(),kindConfidence:z6.number().min(0).max(1).nullable().optional(),model:z6.string().optional(),formulation:z6.string().optional()});var changelogStatementContextSchema=z6.object({heading:z6.string().nullable(),text:z6.string(),textTruncated:z6.boolean(),fullText:z6.string().optional()});var changelogStatementSchema=z6.object({version:z6.string(),position:z6.number().int().nonnegative(),sourceIndex:z6.number().int().nonnegative(),sourcePosition:z6.number().int().nonnegative().optional(),heading:z6.string().nullable(),source:z6.string().nullable(),url:z6.string().nullable(),text:z6.string(),textTruncated:z6.boolean(),fullText:z6.string().optional(),context:changelogStatementContextSchema.nullable(),classification:changelogStatementClassificationSchema.nullable()});var changelogStatementCoverageSchema=z6.object({version:z6.string(),status:z6.enum(["CLASSIFIED","NOT_ASSESSED","WITHOUT_NOTES","UNPARSEABLE"]),statementsTotal:z6.number().int().nonnegative(),statementsAssessed:z6.number().int().nonnegative().optional(),statementsNotAssessed:z6.number().int().nonnegative().optional(),statementsNoImpact:z6.number().int().nonnegative().optional(),statementsUnclassified:z6.number().int().nonnegative().optional()});var changelogStatementPageSchema=z6.object({items:z6.array(changelogStatementSchema),coverage:z6.array(changelogStatementCoverageSchema),totalCount:z6.number().int().nonnegative(),matchingCount:z6.number().int().nonnegative(),remainingCount:z6.number().int().nonnegative(),nextOffset:z6.number().int().nonnegative().nullable(),hasMore:z6.boolean()});var packageUpgradeChangelogSchema=z6.object({statements:changelogStatementPageSchema.optional(),riskCoverage:packageUpgradeChangelogRiskCoverageSchema,source:z6.string().nullable().optional(),fallback:z6.string().nullable().optional(),entries:z6.array(packageUpgradeChangelogEntrySchema).optional(),sampledEntries:z6.array(packageUpgradeChangelogEntrySchema).optional(),keywordEntries:z6.array(packageUpgradeChangelogEntrySchema).optional(),totalKeywordEntries:z6.number().int(),totalEntries:z6.number().int(),totalEntriesWithBodies:z6.number().int(),truncated:z6.boolean(),hasReleaseNoteBodies:z6.boolean(),breakingSignals:z6.array(z6.string()),migrationSignals:z6.array(z6.string())});var packageUpgradeCompatibilitySchema=z6.object({peerDependencyChanges:z6.array(z6.string()),notes:z6.array(z6.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z6.object({name:z6.string(),registry:z6.string().nullable().optional(),version:z6.string().nullable().optional(),fromVersions:z6.array(z6.string()),toVersions:z6.array(z6.string()),constraint:z6.string().nullable().optional(),type:z6.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z6.object({added:z6.array(packageUpgradeDependencyChangeItemSchema),removed:z6.array(packageUpgradeDependencyChangeItemSchema),changed:z6.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z6.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z6.object({currentTotal:z6.number().int(),targetTotal:z6.number().int(),introducedDeprecated:z6.array(z6.string()),introducedDuplicates:z6.array(z6.string()),introducedConflicts:z6.array(z6.string()),introducedOutdated:z6.array(z6.string())}).nullable().optional();var packageUpgradeReviewSchema=z6.object({registry:z6.string(),name:z6.string(),currentVersion:z6.string(),targetVersion:z6.string(),latestVersion:z6.string().nullable().optional(),versionDelta:z6.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknownDetails:z6.array(z6.object({section:z6.string(),code:z6.string(),message:z6.string(),retryable:z6.boolean().nullable().optional()})).nullable().optional()});var packageUpgradeReviewResponseSchema=z6.object({summary:z6.object({total:z6.number().int(),withUnknowns:z6.number().int(),withAddedAdvisories:z6.number().int(),withBreakingSignals:z6.number().int(),withDirectDependencyChanges:z6.number().int(),withTransitiveVulnerabilityAdditions:z6.number().int()}),reviews:z6.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z6.object({data:z6.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.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(
1219
+ $packages: [PackageUpgradeReviewPackageInput!]! $offset: Int! $tiers: [ChangelogStatementTier!]
1220
+ ) {
1221
+ packageUpgradeReview(packages: $packages, includeTransitiveSecurity: false, changelogLimit: 1) {
1222
+ reviews { registry name currentVersion targetVersion changelog { ${statements} } }
1223
+ }
1224
+ }`;return`
1225
+ query PackageUpgradeReview(
1226
+ ${view!=="triage"?"$offset: Int! $tiers: [ChangelogStatementTier!]":""}
1227
+ $packages: [PackageUpgradeReviewPackageInput!]!
1228
+ $includeTransitiveSecurity: Boolean!
1229
+ $includeDependencyIssues: Boolean!
1230
+ $minSeverity: Float
1231
+ $changelogLimit: Int!
1232
+ ) {
1233
+ packageUpgradeReview(
1234
+ packages: $packages
1235
+ includeTransitiveSecurity: $includeTransitiveSecurity
1236
+ minSeverity: $minSeverity
1237
+ changelogLimit: $changelogLimit
1238
+ ) {
1239
+ summary {
1240
+ total
1241
+ withUnknowns
1242
+ withAddedAdvisories
1243
+ withBreakingSignals
1244
+ withDirectDependencyChanges
1245
+ withTransitiveVulnerabilityAdditions
1246
+ }
1247
+ reviews {
1248
+ registry
1249
+ name
1250
+ currentVersion
1251
+ targetVersion
1252
+ latestVersion
1253
+ versionDelta
1254
+ security {
1255
+ current {
1256
+ version
1257
+ publishedAt
1258
+ deprecated
1259
+ deprecationReason
1260
+ affectedCount
1261
+ nonAffectingCount
1262
+ unknownVulnerabilityCount
1263
+ assessmentStatus
1264
+ allCount
1265
+ lastModifiedAt
1266
+ advisories {
1267
+ ...PackageUpgradeAdvisoryFields
1268
+ }
1269
+ }
1270
+ target {
1271
+ version
1272
+ publishedAt
1273
+ deprecated
1274
+ deprecationReason
1275
+ affectedCount
1276
+ nonAffectingCount
1277
+ unknownVulnerabilityCount
1278
+ assessmentStatus
1279
+ allCount
1280
+ lastModifiedAt
1281
+ advisories {
1282
+ ...PackageUpgradeAdvisoryFields
1283
+ }
1284
+ }
1285
+ added {
1286
+ ...PackageUpgradeAdvisoryFields
1287
+ }
1288
+ removed {
1289
+ ...PackageUpgradeAdvisoryFields
1290
+ }
1291
+ notAddressed {
1292
+ ...PackageUpgradeAdvisoryFields
1293
+ }
1294
+ fixed {
1295
+ ...PackageUpgradeAdvisoryFields
1296
+ }
1297
+ introduced {
1298
+ ...PackageUpgradeAdvisoryFields
1299
+ }
1300
+ unchanged {
1301
+ ...PackageUpgradeAdvisoryFields
1302
+ }
1303
+ transitive @include(if: $includeTransitiveSecurity) {
1304
+ currentAffected
1305
+ targetAffected
1306
+ introducedPackages
1307
+ fixedPackages
1308
+ introducedPackageDetails(first: 50) {
1309
+ ...PackageUpgradeTransitivePackagePageFields
1310
+ }
1311
+ fixedPackageDetails(first: 50) {
1312
+ ...PackageUpgradeTransitivePackagePageFields
1313
+ }
1314
+ stillAffectedPackageDetails(first: 50) {
1315
+ ...PackageUpgradeTransitivePackagePageFields
1316
+ }
1317
+ }
1318
+ }
1319
+ changelog {
1320
+ ${statements}
1321
+ riskCoverage {
1322
+ versionsClassified
1323
+ versionsNotAssessed
1324
+ versionsWithoutNotes
1325
+ versionsUnparseable
1326
+ unitsNoImpact
1327
+ itemsMustActConfident
1328
+ itemsMustActAmbiguous
1329
+ itemsShouldKnowConfident
1330
+ itemsShouldKnowAmbiguous
1331
+ itemsUnclassified
1332
+ }
1333
+ source
1334
+ fallback
1335
+ ${view==="triage"?"":`entries { detailSource version publishedAt htmlUrl signals ${view==="json"?"body bodyPreview headline":""} }
1336
+ sampledEntries { detailSource version publishedAt htmlUrl signals ${view==="json"?"body bodyPreview headline":""} }
1337
+ keywordEntries { detailSource version publishedAt htmlUrl signals body ${view==="json"?"bodyPreview headline":""} }`}
1338
+ totalKeywordEntries
1339
+ totalEntries
1340
+ totalEntriesWithBodies
1341
+ truncated
1342
+ hasReleaseNoteBodies
1343
+ breakingSignals
1344
+ migrationSignals
1345
+ }
1346
+ compatibility {
1347
+ peerDependencyChanges
1348
+ notes
1349
+ }
1350
+ dependencyChanges {
1351
+ direct {
1352
+ ...PackageUpgradeDependencyChangeGroupFields
1353
+ }
1354
+ transitive {
1355
+ ...PackageUpgradeDependencyChangeGroupFields
1356
+ }
1357
+ }
1358
+ dependencyIssues @include(if: $includeDependencyIssues) {
1359
+ currentTotal
1360
+ targetTotal
1361
+ introducedDeprecated
1362
+ introducedDuplicates
1363
+ introducedConflicts
1364
+ introducedOutdated
1365
+ }
1366
+ unknownDetails { section code message ${view==="json"?"retryable":""} }
1367
+ }
1368
+ }
1369
+ }
1370
+
1371
+ fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1372
+ ${view!=="triage"?"assessmentStatus assessmentReasons":""}
1373
+ id
1374
+ aliases
1375
+ summary
1376
+ severity
1377
+ severityLabel
1378
+ fixedIn
1379
+ isMalicious
1380
+ }
1381
+
1382
+ fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1383
+ entries {
1384
+ id
1385
+ registry
1386
+ name
1387
+ versions
1388
+ affectedCount
1389
+ maxSeverityScore
1390
+ maxSeverityLabel
1391
+ advisoryIds
1392
+ }
1393
+ totalCount
1394
+ truncated
1395
+ }
1396
+
1397
+ fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1398
+ added {
1399
+ name
1400
+ registry
1401
+ version
1402
+ fromVersions
1403
+ toVersions
1404
+ constraint
1405
+ type
1406
+ }
1407
+ removed {
1408
+ name
1409
+ registry
1410
+ version
1411
+ fromVersions
1412
+ toVersions
1413
+ constraint
1414
+ type
1415
+ }
1416
+ changed {
1417
+ name
1418
+ registry
1419
+ version
1420
+ fromVersions
1421
+ toVersions
1422
+ constraint
1423
+ type
1424
+ }
1425
+ }`}var changelogEntryDetailSchema=z6.object({version:z6.string().nullable().optional(),normalizedVersion:z6.string().nullable().optional(),body:z6.string().nullable().optional(),htmlUrl:z6.string().nullable().optional(),publishedAt:z6.string().nullable().optional()});var changelogReportResponseSchema=z6.object({source:z6.string().nullable().optional(),entries:z6.array(changelogEntryDetailSchema).nullable().optional(),statements:changelogStatementPageSchema.optional()});var exactChangelogDetailSchema=z6.object({detailSource:z6.string().nullable().optional(),hasChangelog:z6.boolean().optional(),entry:changelogEntryDetailSchema.nullable().optional(),statements:changelogStatementPageSchema.optional()});var changelogGraphQLResponseSchema=z6.object({data:z6.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});var exactChangelogGraphQLResponseSchema=z6.object({data:z6.object({packageInfo:z6.object({selectedVersion:z6.object({resolvedVersion:z6.string().optional(),changelog:exactChangelogDetailSchema.nullable().optional()}).nullable().optional()}).nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});function changelogStatementSelection(json,assessment){return`statements(first: 100, offset: $offset, tiers: $tiers) {
1426
+ totalCount matchingCount remainingCount nextOffset hasMore
1427
+ coverage { version status statementsTotal ${assessment?"statementsAssessed statementsNotAssessed statementsNoImpact statementsUnclassified":""} }
1428
+ items {
1429
+ version position sourceIndex heading source url text textTruncated
1430
+ ${json?"sourcePosition fullText":""}
1431
+ context { heading text textTruncated ${json?"fullText":""} }
1432
+ classification { tier ambiguous kind ${json?"tierConfidence kindConfidence model formulation":""} }
1433
+ }
1434
+ }`}var upgradeStatementContinuationSchema=z6.object({data:z6.object({packageUpgradeReview:z6.object({reviews:z6.array(z6.object({registry:z6.string(),name:z6.string(),currentVersion:z6.string(),targetVersion:z6.string(),changelog:z6.object({statements:changelogStatementPageSchema})}))}).nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});function validateChangelogStatementPage(page,offset,json){if(json&&page.items.some((item)=>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]))}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(
1435
+ $registry: Registry! $name: String! $version: String ${pageVars}
1436
+ ) {
1437
+ packageInfo(registry: $registry, name: $name, version: $version) { selectedVersion {
1438
+ ${firstPage?"resolvedVersion":""}
1439
+ changelog { ${firstPage?`${json?"detailSource":""} ${json||!statementView?"hasChangelog":""} entry { ${entry} }`:""} ${statements} }
1440
+ } }
1441
+ }`;return`query PackageChangelog(
1442
+ $registry: Registry! $name: String! $fromVersion: String $toVersion: String $limit: Int ${pageVars}
1443
+ ) {
1444
+ packageChangelog(registry: $registry, name: $name, fromVersion: $fromVersion, toVersion: $toVersion, limit: $limit) {
1445
+ ${firstPage?`${json?"source":""} entries { ${entry} }`:""} ${statements}
1446
+ }
1447
+ }`}function normaliseChangelogStatement(item){return{...stripNullProperties(item),classification:item.classification===null?null:stripNullProperties(item.classification)}}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.");return c}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: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}});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=z6.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z6.object({id:z6.string().nullable().optional(),readTarget:readTargetSchema,title:z6.string().nullable().optional(),slug:z6.string().nullable().optional(),order:z6.number().int().nullable().optional(),linkName:z6.string().nullable().optional(),lastUpdatedAt:z6.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z6.string().nullable().optional(),repoUrl:z6.string().nullable().optional(),gitRef:z6.string().nullable().optional(),requestedRef:z6.string().nullable().optional(),filePath:z6.string().nullable().optional()});var packageDocsPageInfoSchema=z6.object({hasNextPage:z6.boolean(),endCursor:z6.string().nullable().optional(),totalCount:z6.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z6.object({indexingEstimates:indexingEstimatesSchema,registry:z6.string().nullable().optional(),packageName:z6.string().nullable().optional(),version:z6.string().nullable().optional(),stale:z6.boolean().nullable().optional(),codeIndexState:z6.string().nullable().optional(),pages:z6.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z6.object({url:z6.string().nullable().optional(),label:z6.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z6.object({id:z6.string().nullable().optional(),docsReadTarget:z6.string(),title:z6.string().nullable().optional(),content:z6.string().nullable().optional(),contentFormat:z6.string().nullable().optional(),breadcrumbs:z6.array(z6.string()).nullable().optional(),linkName:z6.string().nullable().optional(),lastUpdatedAt:z6.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z6.string().nullable().optional(),gitRef:z6.string().nullable().optional(),requestedRef:z6.string().nullable().optional(),filePath:z6.string().nullable().optional(),baseUrl:z6.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z6.object({registry:z6.string().nullable().optional(),packageName:z6.string().nullable().optional(),version:z6.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),contentRange:z6.object({startLine:z6.number().int().positive().nullable(),endLine:z6.number().int().positive().nullable(),totalLines:z6.number().int().nonnegative(),anchor:z6.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=z6.object({data:z6.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z6.object({data:z6.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z6.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
1448
+ query ListPackageDocs(
1449
+ $registry: Registry!
1450
+ $packageName: String!
1451
+ $version: String
1452
+ $limit: Int
1453
+ $after: String
1454
+ ) {
1455
+ listPackageDocs(
1456
+ registry: $registry
1457
+ packageName: $packageName
1458
+ version: $version
1459
+ limit: $limit
1460
+ after: $after
1461
+ ) {
1462
+ registry
1463
+ packageName
1464
+ version
1465
+ stale
1466
+ codeIndexState
1467
+ ${INDEXING_ESTIMATES_SELECTION}
1468
+ pages {
1469
+ id
1470
+ readTarget { target }
1471
+ title
1472
+ slug
1473
+ order
1474
+ linkName
1475
+ lastUpdatedAt
1476
+ sourceKind
1477
+ sourceUrl
1478
+ repoUrl
1479
+ gitRef
1480
+ requestedRef
1481
+ filePath
1482
+ }
1483
+ pageInfo {
1484
+ hasNextPage
1485
+ endCursor
1486
+ totalCount
1487
+ }
1488
+ }
1489
+ }`;var READ_PACKAGE_DOC_QUERY=`
1490
+ query ReadPackageDoc($pageId: String!, $startLine: Int, $endLine: Int) {
1491
+ getDocPage(pageId: $pageId, startLine: $startLine, endLine: $endLine) {
1492
+ registry
1493
+ packageName
1494
+ version
1495
+ sourceKind
1496
+ contentRange {
1497
+ startLine
1498
+ endLine
1499
+ totalLines
1500
+ anchor
1501
+ }
1502
+ page {
1503
+ id
1504
+ docsReadTarget
1505
+ title
1506
+ content
1507
+ contentFormat
1508
+ breadcrumbs
1509
+ linkName
1510
+ lastUpdatedAt
1511
+ sourceKind
1512
+ source {
1513
+ url
1514
+ label
1515
+ }
1516
+ repoUrl
1517
+ gitRef
1518
+ requestedRef
1519
+ filePath
1520
+ baseUrl
1521
+ }
1522
+ }
1523
+ }`;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&&selected?.resolvedVersion===summary.package.latestVersion){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||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,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 seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after,signal);if(!firstPage)firstPage=page;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.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:PACKAGE_VULNERABILITIES_QUERY,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.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}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 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]));if(first&&(first.totalCount!==statements.totalCount||first.matchingCount!==statements.matchingCount||signature(first)!==signature(statements)))throw new PackageIntelligenceBackendError("Changelog evidence changed during retrieval; classification 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}
1524
+ export{parseHttpErrorDetail,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,CodeNavigationServiceImpl2,createCodeNavigationHttpError,createCodeNavigationGraphQLError,parseCodeContextResult,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceDocumentationSectionUnresolvedError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceServiceImpl2,parsePackageDocResult,createPackageIntelligenceHttpError,createPackageIntelligenceTransportError,createPackageIntelligenceGraphQLError};