githits 0.15.0 → 0.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/.plugin/plugin.json +1 -1
- package/README.md +3 -0
- package/dist/cli.js +19 -14
- package/dist/index.js +1 -1
- package/dist/shared/{chunk-xv200wks.js → chunk-w8790ap4.js} +1 -1
- package/dist/shared/{chunk-wpf4f5ex.js → chunk-xnhkyxcf.js} +1 -1
- package/dist/shared/{chunk-ssx1aqhw.js → chunk-z5hkz8mf.js} +1479 -1478
- package/gemini-extension.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +2 -2
|
@@ -1,1598 +1,1599 @@
|
|
|
1
|
-
import{version2}from"./chunk-xv200wks.js";import{createHash,randomBytes}from"node:crypto";function generateCodeVerifier(){return randomBytes(32).toString("base64url")}function generateCodeChallenge(verifier){return createHash("sha256").update(verifier).digest("base64url")}function generateState(){return randomBytes(32).toString("hex")}import{z as z2}from"zod";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 TermsAcceptanceRequiredError 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 TermsAcceptanceRequiredError({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}var DEFAULT_MCP_URL="https://mcp.githits.com";var DEFAULT_API_URL="https://api.githits.com";var DEFAULT_CODE_NAV_URL="https://pkgseer.dev";class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getMcpUrl(){return resolveServiceUrl("GITHITS_MCP_URL",DEFAULT_MCP_URL)}function getMcpStorageKeyUrl(){return process.env.GITHITS_MCP_URL??DEFAULT_MCP_URL}function getApiUrl(){return resolveServiceUrl("GITHITS_API_URL",DEFAULT_API_URL)}function getCodeNavigationUrl(){if(process.env.GITHITS_CODE_NAV_URL!==undefined){return validateServiceUrl(process.env.GITHITS_CODE_NAV_URL,"GITHITS_CODE_NAV_URL")}if(process.env.PKGSEER_URL!==undefined){return validateServiceUrl(process.env.PKGSEER_URL,"PKGSEER_URL")}return DEFAULT_CODE_NAV_URL}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){const override=process.env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken(){return process.env.GITHITS_API_TOKEN}import{z}from"zod";var DEFAULT_FETCH_TIMEOUT_MS=120000;class FetchTimeoutError 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={}){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 FetchTimeoutError(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}),timeout])}catch(cause){if(cause instanceof FetchTimeoutError)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError}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 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 AuthenticationError extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}class ApiRateLimitError 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 AuthenticationError||error instanceof TermsAcceptanceRequiredError}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}var LANGUAGE_SCHEMA=z.object({id:z.string(),name:z.string(),display_name:z.string(),aliases:z.array(z.string()),search_priority:z.number().optional()});var LANGUAGES_SCHEMA=z.array(LANGUAGE_SCHEMA);class GitHitsServiceImpl{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=await this.request("/search",{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,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 await this.createError(response)}return response.text()})}async getLanguages(){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.request",async()=>{const response=await this.request("/languages",{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async searchLanguages(query,limit=5){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await this.request(`/languages?${params.toString()}`,{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async submitFeedback(params){return withServiceDiagnostics(this.runtime.diagnostics,"githits.feedback.request",async()=>{const response=await this.request("/feedbacks",{method:"POST",headers:this.headers(),body:JSON.stringify({...params.exampleId!==undefined&&{example_id:params.exampleId},...params.solutionId!==undefined&&{solution_id:params.solutionId},accepted:params.accepted,feedback_text:params.feedbackText??null,...params.toolName!==undefined&&{tool_name:params.toolName}})});if(!response.ok){throw await this.createError(response)}return{success:true,message:"Feedback submitted successfully"}})}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)}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}}async parseLanguages(response){let data;try{data=await response.json()}catch(cause){throw new Error("GitHits returned an invalid languages response.",{cause})}const parsed=LANGUAGES_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("GitHits returned an invalid languages response.",{cause:parsed.error})}return parsed.data}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,["detail"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:return new AuthenticationError(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 ApiRateLimitError(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 FetchTimeoutError{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 token=await options.getToken();if(!token){throw new AuthenticationError(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(token.startsWith("ghi-")||!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}var AGENTIC_ASK_REQUEST_TIMEOUT_MS=210000;var AGENTIC_ASK_MAX_RESPONSE_BYTES=4*1024*1024;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;var sourceLineRangeSchema=z2.string().regex(/^\d+-\d+$/);var cliSourceArgumentsSchema=z2.union([z2.tuple([z2.literal("githits@latest"),z2.literal("code"),z2.literal("read"),z2.literal("--lines"),sourceLineRangeSchema,z2.literal("--"),z2.string().min(1),z2.string().min(1)]),z2.tuple([z2.literal("githits@latest"),z2.literal("docs"),z2.literal("read"),z2.literal("--lines"),sourceLineRangeSchema,z2.literal("--"),z2.string().min(1)])]);var cliSourceCallSchema=z2.object({command:z2.literal("npx"),arguments:cliSourceArgumentsSchema});var cliResponseSchema=z2.object({source_format:z2.literal("cli"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(cliSourceCallSchema)});var mcpCodeReadSourceCallSchema=z2.object({name:z2.literal("code_read"),arguments:z2.object({target:z2.string().min(1),path:z2.string().min(1),start_line:z2.number().int().min(1),end_line:z2.number().int().min(1)})});var mcpDocumentationReadSourceCallSchema=z2.object({name:z2.literal("docs_read"),arguments:z2.object({page_id:z2.string().min(1),start_line:z2.number().int().min(1),end_line:z2.number().int().min(1)})});var mcpResponseSchema=z2.object({source_format:z2.literal("mcp"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(z2.discriminatedUnion("name",[mcpCodeReadSourceCallSchema,mcpDocumentationReadSourceCallSchema]))});var upstreamUrlSchema=z2.string().refine((value)=>value===value.trim()&&!hasControlCharacters(value)).pipe(z2.string().url()).refine((value)=>{if(!URL.canParse(value))return false;const protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"});var urlResponseSchema=z2.object({source_format:z2.literal("url"),tool_call_id:z2.string().regex(UUID_V7_PATTERN),thread_id:z2.string().regex(UUID_V7_PATTERN),answer_markdown:z2.string().min(1),sources:z2.array(z2.object({url:upstreamUrlSchema}))});class AgenticAskHttpError extends Error{code;status;toolCallId;retryAfterSeconds;threadId;retryable;constructor(code,message,status,toolCallId,retryAfterSeconds,retryable=false,threadId){super(message);this.code=code;this.status=status;this.toolCallId=toolCallId;this.retryAfterSeconds=retryAfterSeconds;this.threadId=threadId;this.name="AgenticAskHttpError";this.retryable=retryable}}class AgenticAskRequestTimeoutError extends Error{timeoutMs;constructor(timeoutMs){super("Agentic Ask 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 Agentic Ask response.",{cause:options?.cause});this.name="MalformedAgenticAskResponseError"}}class AgenticAskResponseTooLargeError extends Error{maxBytes;constructor(maxBytes=AGENTIC_ASK_MAX_RESPONSE_BYTES){super("GitHits returned an Agentic Ask response that was too large.");this.maxBytes=maxBytes;this.name="AgenticAskResponseTooLargeError"}}class AgenticAskServiceImpl{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_MS))}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=parseAgenticAskToolCallId(response.headers.get("X-GitHits-Tool-Call-Id"));const threadId=normalizeAgenticAskThreadId(response.headers.get("X-GitHits-Thread-Id"));if(!response.ok){if(response.status===403){let body="";try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted)throw signal.reason??cause}throwIfTermsAcceptanceRequired(body)}else{await response.body?.cancel().catch(()=>{return})}throw createHttpError(response,toolCallId,threadId,request)}let body;try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted||cause instanceof AgenticAskResponseTooLargeError){throw cause}throw new AgenticAskConnectionError({cause})}let raw;try{raw=JSON.parse(body)}catch(cause){throw new MalformedAgenticAskResponseError({cause})}const responseSchema=request.sourceFormat==="mcp"?mcpResponseSchema:request.sourceFormat==="url"?urlResponseSchema:cliResponseSchema;const parsed=responseSchema.safeParse(raw);if(!parsed.success){throw new MalformedAgenticAskResponseError({cause:parsed.error})}return parsed.data}}function parseAgenticAskToolCallId(value){return normalizeUuidV7(value)}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){const declaredLength=response.headers.get("Content-Length");if(isDeclaredBodyTooLarge(declaredLength)){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>AGENTIC_ASK_MAX_RESPONSE_BYTES){await reader.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}text+=decoder.decode(value,{stream:true})}return text+decoder.decode()}finally{reader.releaseLock()}}function isDeclaredBodyTooLarge(value){if(!value||!/^\d+$/.test(value))return false;try{return BigInt(value)>BigInt(AGENTIC_ASK_MAX_RESPONSE_BYTES)}catch{return false}}function createHttpError(response,toolCallId,threadId,request){const status=response.status;switch(status){case 400:return new AgenticAskHttpError("INVALID_TARGET",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 rejected the Agentic Ask target.",status,toolCallId,undefined,false,threadId);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 Agentic Ask is denied.",status,toolCallId,undefined,false,threadId);case 404:return new AgenticAskHttpError("THREAD_NOT_FOUND","Agentic Ask thread was not found.",status,toolCallId,undefined,false,threadId);case 409:return new AgenticAskHttpError("INVALID_REQUEST","This Agentic Ask thread cannot accept another follow-up.",status,toolCallId,undefined,false,threadId);case 422:return new AgenticAskHttpError("INVALID_REQUEST","GitHits rejected the Agentic Ask request.",status,toolCallId,undefined,false,threadId);case 429:return new AgenticAskHttpError("RATE_LIMITED","Agentic Ask is rate limited.",status,toolCallId,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()),true,threadId);case 500:return new AgenticAskHttpError("EXECUTION_FAILED","Agentic Ask failed.",status,toolCallId,undefined,false,threadId);case 503:return new AgenticAskHttpError("SERVICE_UNAVAILABLE","Agentic Ask is temporarily unavailable.",status,toolCallId,undefined,true,threadId);case 504:return new AgenticAskHttpError("TIMEOUT","Agentic Ask timed out.",status,toolCallId,undefined,true,threadId);default:return new AgenticAskHttpError("HTTP_ERROR",`Agentic Ask 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 z3}from"zod";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");let response;try{response=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",headers:{...request.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})}catch(cause){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 response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");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_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(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)}var INDEXING_WAIT_HINT="Wait until ready with CLI `--wait 60000` or MCP `wait_timeout_ms: 60000`.";var GREP_REPO_SYMBOL_FIELDS=["symbol_ref","name","qualified_path","kind","category","arity","is_public","file_path","start_line","end_line","content_hash","parent_path"];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;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;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 CodeDiffError 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{packageName;requestedVersion;latestIndexed;availableVersions;metadata;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions,metadata=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.metadata=metadata;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;metadata;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs,metadata=undefined){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;this.metadata=metadata;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=`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}`;var DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION=`
|
|
10
|
-
suggestedRefs {
|
|
11
|
-
version
|
|
12
|
-
ref
|
|
13
|
-
}`;var DOC_COVERAGE_SELECTION=`
|
|
14
|
-
coverage {
|
|
15
|
-
coverageState
|
|
16
|
-
coverageReason
|
|
17
|
-
pagesCrawled
|
|
18
|
-
frontierRemaining
|
|
19
|
-
artifactOverflowPageCount
|
|
20
|
-
estimatedTotalPages
|
|
21
|
-
note
|
|
22
|
-
}`;var DOCUMENTATION_CONTRIBUTORS_SELECTION=`
|
|
23
|
-
contributors {
|
|
24
|
-
kind
|
|
25
|
-
state
|
|
26
|
-
freshness
|
|
27
|
-
resultCount
|
|
28
|
-
repositoryUrl
|
|
29
|
-
commitSha
|
|
30
|
-
siteKey
|
|
31
|
-
siteUrl
|
|
32
|
-
${DOC_COVERAGE_SELECTION}
|
|
33
|
-
}`;var TARGET_RESOLUTION_SELECTION=`
|
|
34
|
-
targetResolution {
|
|
35
|
-
requested {
|
|
36
|
-
kind
|
|
37
|
-
registry
|
|
38
|
-
packageName
|
|
39
|
-
version
|
|
40
|
-
repoUrl
|
|
41
|
-
gitRef
|
|
42
|
-
commitSha
|
|
43
|
-
}
|
|
44
|
-
resolvedRequested {
|
|
45
|
-
kind
|
|
46
|
-
registry
|
|
47
|
-
packageName
|
|
48
|
-
version
|
|
49
|
-
repoUrl
|
|
50
|
-
gitRef
|
|
51
|
-
commitSha
|
|
52
|
-
}
|
|
53
|
-
served {
|
|
54
|
-
kind
|
|
55
|
-
registry
|
|
56
|
-
packageName
|
|
57
|
-
version
|
|
58
|
-
repoUrl
|
|
59
|
-
gitRef
|
|
60
|
-
commitSha
|
|
61
|
-
}
|
|
62
|
-
freshness
|
|
63
|
-
freshnessReason
|
|
64
|
-
indexingRef
|
|
65
|
-
availableVersions {
|
|
66
|
-
version
|
|
67
|
-
ref
|
|
68
|
-
}
|
|
69
|
-
${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
|
|
70
|
-
${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
|
|
71
|
-
}`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
|
|
72
|
-
availableVersions {
|
|
73
|
-
version
|
|
74
|
-
ref
|
|
75
|
-
}`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
|
|
76
|
-
availableVersions {
|
|
77
|
-
version
|
|
78
|
-
ref
|
|
79
|
-
}
|
|
80
|
-
availableRefs {
|
|
81
|
-
version
|
|
82
|
-
ref
|
|
83
|
-
}
|
|
84
|
-
${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
|
|
85
|
-
indexingEstimate {
|
|
86
|
-
lowerSeconds
|
|
87
|
-
upperSeconds
|
|
88
|
-
elapsedSeconds
|
|
89
|
-
sampleCount
|
|
90
|
-
source
|
|
91
|
-
}`;var UNIFIED_SEARCH_LOCATOR_SELECTION=`
|
|
92
|
-
registry
|
|
93
|
-
packageName
|
|
94
|
-
version
|
|
95
|
-
pageId
|
|
96
|
-
docsReadTarget
|
|
97
|
-
sourceKind
|
|
98
|
-
sourceUrl
|
|
99
|
-
repoUrl
|
|
100
|
-
gitRef
|
|
101
|
-
commitSha
|
|
102
|
-
requestedRef
|
|
103
|
-
filePath
|
|
104
|
-
repositoryFilePath
|
|
105
|
-
startLine
|
|
106
|
-
endLine
|
|
107
|
-
evidenceRange {
|
|
108
|
-
startLine
|
|
109
|
-
endLine
|
|
110
|
-
matchLine
|
|
111
|
-
rangeKind
|
|
112
|
-
matchSpansTruncated
|
|
113
|
-
}
|
|
114
|
-
indexedRange {
|
|
115
|
-
startLine
|
|
116
|
-
endLine
|
|
117
|
-
}
|
|
118
|
-
symbolContext {
|
|
119
|
-
name
|
|
120
|
-
qualifiedPath
|
|
121
|
-
kind
|
|
122
|
-
relation
|
|
123
|
-
definitionRange {
|
|
124
|
-
filePath
|
|
125
|
-
repositoryFilePath
|
|
126
|
-
startLine
|
|
127
|
-
endLine
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
fileContentHash
|
|
131
|
-
symbolRef
|
|
132
|
-
qualifiedPath
|
|
133
|
-
kind
|
|
134
|
-
category
|
|
135
|
-
language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
|
|
136
|
-
repositoryEvidence {
|
|
137
|
-
bm25MatchFields
|
|
138
|
-
semanticContext {
|
|
139
|
-
scopes {
|
|
1
|
+
import{version2}from"./chunk-w8790ap4.js";import{createHash,randomBytes}from"node:crypto";function generateCodeVerifier(){return randomBytes(32).toString("base64url")}function generateCodeChallenge(verifier){return createHash("sha256").update(verifier).digest("base64url")}function generateState(){return randomBytes(32).toString("hex")}import{z as z4}from"zod";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 TermsAcceptanceRequiredError 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 TermsAcceptanceRequiredError({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}var DEFAULT_MCP_URL="https://mcp.githits.com";var DEFAULT_API_URL="https://api.githits.com";var DEFAULT_CODE_NAV_URL="https://pkgseer.dev";class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getMcpUrl(){return resolveServiceUrl("GITHITS_MCP_URL",DEFAULT_MCP_URL)}function getMcpStorageKeyUrl(){return process.env.GITHITS_MCP_URL??DEFAULT_MCP_URL}function getApiUrl(){return resolveServiceUrl("GITHITS_API_URL",DEFAULT_API_URL)}function getCodeNavigationUrl(){if(process.env.GITHITS_CODE_NAV_URL!==undefined){return validateServiceUrl(process.env.GITHITS_CODE_NAV_URL,"GITHITS_CODE_NAV_URL")}if(process.env.PKGSEER_URL!==undefined){return validateServiceUrl(process.env.PKGSEER_URL,"PKGSEER_URL")}return DEFAULT_CODE_NAV_URL}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){const override=process.env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken(){return process.env.GITHITS_API_TOKEN}import{z}from"zod";var DEFAULT_FETCH_TIMEOUT_MS=120000;class FetchTimeoutError 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={}){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 FetchTimeoutError(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}),timeout])}catch(cause){if(cause instanceof FetchTimeoutError)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError}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 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 AuthenticationError extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}class ApiRateLimitError 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 AuthenticationError||error instanceof TermsAcceptanceRequiredError}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}var LANGUAGE_SCHEMA=z.object({id:z.string(),name:z.string(),display_name:z.string(),aliases:z.array(z.string()),search_priority:z.number().optional()});var LANGUAGES_SCHEMA=z.array(LANGUAGE_SCHEMA);class GitHitsServiceImpl{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=await this.request("/search",{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,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 await this.createError(response)}return response.text()})}async getLanguages(){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.request",async()=>{const response=await this.request("/languages",{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async searchLanguages(query,limit=5){return withServiceDiagnostics(this.runtime.diagnostics,"githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await this.request(`/languages?${params.toString()}`,{headers:this.headers()});if(!response.ok){throw await this.createError(response)}return this.parseLanguages(response)})}async submitFeedback(params){return withServiceDiagnostics(this.runtime.diagnostics,"githits.feedback.request",async()=>{const response=await this.request("/feedbacks",{method:"POST",headers:this.headers(),body:JSON.stringify({...params.exampleId!==undefined&&{example_id:params.exampleId},...params.solutionId!==undefined&&{solution_id:params.solutionId},accepted:params.accepted,feedback_text:params.feedbackText??null,...params.toolName!==undefined&&{tool_name:params.toolName}})});if(!response.ok){throw await this.createError(response)}return{success:true,message:"Feedback submitted successfully"}})}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)}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}}async parseLanguages(response){let data;try{data=await response.json()}catch(cause){throw new Error("GitHits returned an invalid languages response.",{cause})}const parsed=LANGUAGES_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("GitHits returned an invalid languages response.",{cause:parsed.error})}return parsed.data}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,["detail"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:return new AuthenticationError(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 ApiRateLimitError(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 FetchTimeoutError{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 token=await options.getToken();if(!token){throw new AuthenticationError(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(token.startsWith("ghi-")||!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}import{z as z3}from"zod";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");let response;try{response=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",headers:{...request.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})}catch(cause){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 response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");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}}import{z as z2}from"zod";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)}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;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;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 PackageIntelligenceVersionNotFoundError extends Error{packageName;requestedVersion;availableVersions;constructor(message,packageName,requestedVersion,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.availableVersions=availableVersions;this.name="PackageIntelligenceVersionNotFoundError"}}class MalformedPackageIntelligenceResponseError extends Error{constructor(message){super(message);this.name="MalformedPackageIntelligenceResponseError"}}class PackageIntelligenceChangelogSourceNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceChangelogSourceNotFoundError"}}var githubRepositorySchema=z2.object({stargazersCount:z2.number().int().nullable().optional(),forksCount:z2.number().int().nullable().optional(),openIssuesCount:z2.number().int().nullable().optional(),archived:z2.boolean().nullable().optional(),language:z2.string().nullable().optional(),topics:z2.array(z2.string()).nullable().optional(),pushedAt:z2.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),description:z2.string().nullable().optional(),latestVersion:z2.string().nullable().optional(),latestVersionPublishedAt:z2.string().nullable().optional(),versionCount:z2.number().int().nullable().optional(),downloadsRefreshedAt:z2.string().nullable().optional(),homepage:z2.string().nullable().optional(),repositoryUrl:z2.string().nullable().optional(),license:z2.string().nullable().optional(),downloadsLastMonth:z2.number().int().nullable().optional(),downloadsTotal:z2.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z2.object({osvId:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),publishedAt:z2.string().nullable().optional()});var packageSecurityOverviewSchema=z2.object({vulnerabilityCount:z2.number().int().nullable().optional(),allVulnerabilityCount:z2.number().int(),hasCurrentVulnerabilities:z2.boolean().nullable().optional(),recentVulnerabilities:z2.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z2.object({version:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),body:z2.string().nullable().optional()});var packageSummaryResponseSchema=z2.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z2.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema=z2.object({message:z2.string(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var graphQLResponseSchema=z2.object({data:z2.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var PACKAGE_SUMMARY_QUERY=`
|
|
2
|
+
query PackageSummary(
|
|
3
|
+
$registry: Registry!
|
|
4
|
+
$name: String!
|
|
5
|
+
$includeVerboseFields: Boolean! = true
|
|
6
|
+
) {
|
|
7
|
+
packageSummary(registry: $registry, name: $name) {
|
|
8
|
+
package {
|
|
140
9
|
name
|
|
141
|
-
qualifiedPath
|
|
142
|
-
kind
|
|
143
|
-
parentQualifiedPath
|
|
144
|
-
declarationStartLine
|
|
145
|
-
declarationEndLine
|
|
146
|
-
parameterNames
|
|
147
|
-
returnType
|
|
148
|
-
symbolRef
|
|
149
|
-
}
|
|
150
|
-
scopeChainTruncated
|
|
151
|
-
preferredRead {
|
|
152
|
-
targetLabel
|
|
153
10
|
registry
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
11
|
+
description
|
|
12
|
+
latestVersion
|
|
13
|
+
latestVersionPublishedAt
|
|
14
|
+
homepage
|
|
15
|
+
repositoryUrl
|
|
16
|
+
license
|
|
17
|
+
downloadsLastMonth
|
|
18
|
+
downloadsTotal
|
|
19
|
+
versionCount @include(if: $includeVerboseFields)
|
|
20
|
+
downloadsRefreshedAt @include(if: $includeVerboseFields)
|
|
21
|
+
githubRepository {
|
|
22
|
+
stargazersCount
|
|
23
|
+
forksCount
|
|
24
|
+
openIssuesCount
|
|
25
|
+
archived
|
|
26
|
+
language @include(if: $includeVerboseFields)
|
|
27
|
+
topics @include(if: $includeVerboseFields)
|
|
28
|
+
pushedAt @include(if: $includeVerboseFields)
|
|
29
|
+
}
|
|
164
30
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
lineNumber
|
|
176
|
-
text
|
|
177
|
-
highlights
|
|
178
|
-
prefixTruncated
|
|
179
|
-
suffixTruncated
|
|
31
|
+
security {
|
|
32
|
+
vulnerabilityCount
|
|
33
|
+
allVulnerabilityCount
|
|
34
|
+
hasCurrentVulnerabilities
|
|
35
|
+
recentVulnerabilities @include(if: $includeVerboseFields) {
|
|
36
|
+
osvId
|
|
37
|
+
summary
|
|
38
|
+
severityScore
|
|
39
|
+
publishedAt
|
|
40
|
+
}
|
|
180
41
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
matchLine
|
|
186
|
-
rangeKind
|
|
187
|
-
matchSpansTruncated
|
|
188
|
-
linesOmittedBefore
|
|
189
|
-
linesOmittedAfter
|
|
190
|
-
lines {
|
|
191
|
-
lineNumber
|
|
192
|
-
text
|
|
193
|
-
highlights
|
|
194
|
-
prefixTruncated
|
|
195
|
-
suffixTruncated
|
|
42
|
+
latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
|
|
43
|
+
version
|
|
44
|
+
publishedAt
|
|
45
|
+
body
|
|
196
46
|
}
|
|
197
47
|
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
$
|
|
205
|
-
$
|
|
206
|
-
$
|
|
207
|
-
$filters: DiscoverySearchFiltersInput
|
|
208
|
-
$allowPartialResults: Boolean
|
|
209
|
-
$limit: Int
|
|
210
|
-
$offset: Int
|
|
211
|
-
$waitTimeoutMs: Int
|
|
212
|
-
$includeFocusedSource: Boolean!
|
|
48
|
+
}`;var packageVersionIdentitySchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),version:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),deprecated:z2.boolean().nullable().optional(),deprecationReason:z2.string().nullable().optional()});var vulnerabilityDetailSchema=z2.object({osvId:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),severityType:z2.string().nullable().optional(),affectedVersionRanges:z2.array(z2.string()).nullable().optional(),affectedVersionRangesCount:z2.number().int(),affectedVersionRangesTruncated:z2.boolean(),fixedInVersions:z2.array(z2.string()).nullable().optional(),publishedAt:z2.string().nullable().optional(),modifiedAt:z2.string().nullable().optional(),withdrawnAt:z2.string().nullable().optional(),aliases:z2.array(z2.string()).nullable().optional(),isMalicious:z2.boolean().nullable().optional(),affectsInspectedVersion:z2.boolean(),matchedAffectedVersionRanges:z2.array(z2.string()),duplicateIds:z2.array(z2.string())});var pageInfoSchema=z2.object({hasNextPage:z2.boolean(),endCursor:z2.string().nullable().optional(),totalCount:z2.number().int()});var vulnerabilityAdvisoryPageSchema=z2.object({entries:z2.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z2.object({affectedVulnerabilityCount:z2.number().int(),nonAffectingVulnerabilityCount:z2.number().int(),allVulnerabilityCount:z2.number().int(),currentVersionAffected:z2.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z2.array(z2.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z2.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z2.object({data:z2.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var transitiveAuditAdvisorySchema=z2.object({osvId:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),affectedVersionRanges:z2.array(z2.string()).nullable().optional(),fixedInVersions:z2.array(z2.string()).nullable().optional(),publishedAt:z2.string().nullable().optional(),modifiedAt:z2.string().nullable().optional(),aliases:z2.array(z2.string()).nullable().optional(),isMalicious:z2.boolean().nullable().optional()});var transitiveAuditOccurrenceSchema=z2.object({version:z2.string(),affectsResolvedVersion:z2.boolean(),matchedAffectedVersionRanges:z2.array(z2.string()),fixVersionsAboveResolved:z2.array(z2.string()),nearestFixedVersion:z2.string().nullable().optional(),advisory:transitiveAuditAdvisorySchema});var transitiveAuditPackageSchema=z2.object({registry:z2.string(),name:z2.string(),selectedCount:z2.number().int().nonnegative(),advisoryOccurrences:z2.array(transitiveAuditOccurrenceSchema).nullable().optional()});var transitiveAuditSummarySchema=z2.object({selected:z2.object({totalVulnerabilities:z2.number().int().nonnegative()}),totalPackagesAnalyzed:z2.number().int().nonnegative(),packages:z2.array(transitiveAuditPackageSchema),calculatedAt:z2.string().nullable().optional()});var transitiveAuditResponseSchema=z2.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:z2.object({transitive:z2.object({vulnerabilitySummary:transitiveAuditSummarySchema.nullable().optional()}).nullable().optional()}).nullable().optional()});var transitiveAuditGraphQLResponseSchema=z2.object({data:z2.object({packageDependencies:transitiveAuditResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
|
|
49
|
+
query PackageVulnerabilities(
|
|
50
|
+
$registry: Registry!
|
|
51
|
+
$name: String!
|
|
52
|
+
$version: String
|
|
53
|
+
$minSeverity: Float
|
|
54
|
+
$includeWithdrawn: Boolean
|
|
55
|
+
$scope: VulnerabilityScope = AFFECTED
|
|
56
|
+
$after: String
|
|
213
57
|
) {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
limit: $limit
|
|
221
|
-
offset: $offset
|
|
222
|
-
waitTimeoutMs: $waitTimeoutMs
|
|
58
|
+
packageVulnerabilities(
|
|
59
|
+
registry: $registry
|
|
60
|
+
name: $name
|
|
61
|
+
version: $version
|
|
62
|
+
minSeverity: $minSeverity
|
|
63
|
+
includeWithdrawn: $includeWithdrawn
|
|
223
64
|
) {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
title
|
|
239
|
-
summary
|
|
240
|
-
score
|
|
241
|
-
highlights {
|
|
242
|
-
title
|
|
65
|
+
package {
|
|
66
|
+
name
|
|
67
|
+
registry
|
|
68
|
+
version
|
|
69
|
+
}
|
|
70
|
+
security {
|
|
71
|
+
affectedVulnerabilityCount
|
|
72
|
+
nonAffectingVulnerabilityCount
|
|
73
|
+
allVulnerabilityCount
|
|
74
|
+
currentVersionAffected
|
|
75
|
+
upgradePaths
|
|
76
|
+
advisories(scope: $scope, first: 100, after: $after) {
|
|
77
|
+
entries {
|
|
78
|
+
osvId
|
|
243
79
|
summary
|
|
80
|
+
severityScore
|
|
81
|
+
severityType
|
|
82
|
+
affectedVersionRanges
|
|
83
|
+
affectedVersionRangesCount
|
|
84
|
+
affectedVersionRangesTruncated
|
|
85
|
+
fixedInVersions
|
|
86
|
+
publishedAt
|
|
87
|
+
modifiedAt
|
|
88
|
+
withdrawnAt
|
|
89
|
+
aliases
|
|
90
|
+
isMalicious
|
|
91
|
+
affectsInspectedVersion
|
|
92
|
+
matchedAffectedVersionRanges
|
|
93
|
+
duplicateIds
|
|
244
94
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
|
|
250
|
-
locator {
|
|
251
|
-
${UNIFIED_SEARCH_LOCATOR_SELECTION}
|
|
95
|
+
pageInfo {
|
|
96
|
+
hasNextPage
|
|
97
|
+
endCursor
|
|
98
|
+
totalCount
|
|
252
99
|
}
|
|
253
100
|
}
|
|
254
|
-
page {
|
|
255
|
-
offset
|
|
256
|
-
limit
|
|
257
|
-
returned
|
|
258
|
-
hasMore
|
|
259
|
-
}
|
|
260
|
-
partialResults
|
|
261
|
-
evidenceNotice
|
|
262
|
-
sourceStatus {
|
|
263
|
-
source
|
|
264
|
-
targetLabel
|
|
265
|
-
requestedTargetLabel
|
|
266
|
-
freshTargetLabel
|
|
267
|
-
servedTargetLabel
|
|
268
|
-
${TARGET_RESOLUTION_SELECTION}
|
|
269
|
-
indexingStatus
|
|
270
|
-
codeIndexState
|
|
271
|
-
resultCount
|
|
272
|
-
appliedFilters
|
|
273
|
-
ignoredFilters
|
|
274
|
-
incompatibleFilters
|
|
275
|
-
appliedQueryFeatures
|
|
276
|
-
ignoredQueryFeatures
|
|
277
|
-
incompatibleQueryFeatures
|
|
278
|
-
suggestedSiteTargets
|
|
279
|
-
suggestedSiteTargetsTruncated
|
|
280
|
-
note
|
|
281
|
-
${DOC_COVERAGE_SELECTION}
|
|
282
|
-
${DOCUMENTATION_CONTRIBUTORS_SELECTION}
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
progress {
|
|
286
|
-
searchRef
|
|
287
|
-
status
|
|
288
|
-
targetsTotal
|
|
289
|
-
targetsReady
|
|
290
|
-
elapsedMs
|
|
291
|
-
query
|
|
292
|
-
queryWarnings
|
|
293
|
-
sources
|
|
294
|
-
requestedSources
|
|
295
|
-
targetMode
|
|
296
|
-
requestedTargets {
|
|
297
|
-
registry
|
|
298
|
-
name
|
|
299
|
-
version
|
|
300
|
-
repoUrl
|
|
301
|
-
gitRef
|
|
302
|
-
site
|
|
303
|
-
}
|
|
304
|
-
filters {
|
|
305
|
-
fileIntent
|
|
306
|
-
kind
|
|
307
|
-
category
|
|
308
|
-
publicOnly
|
|
309
|
-
pathPrefix
|
|
310
|
-
}
|
|
311
|
-
limit
|
|
312
|
-
offset
|
|
313
|
-
targets {
|
|
314
|
-
requested
|
|
315
|
-
resolvedRequested
|
|
316
|
-
served
|
|
317
|
-
freshness
|
|
318
|
-
indexingRef
|
|
319
|
-
requestedRefKind
|
|
320
|
-
${TARGET_RESOLUTION_SELECTION}
|
|
321
|
-
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
322
|
-
${DOC_COVERAGE_SELECTION}
|
|
323
|
-
}
|
|
324
|
-
expiresAt
|
|
325
101
|
}
|
|
326
102
|
}
|
|
327
|
-
}`;var
|
|
328
|
-
query
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
103
|
+
}`;var TRANSITIVE_AUDIT_SCOPE_FIELDS={AFFECTED:{summary:"affected",packageCount:"affectedCount"},NON_AFFECTING:{summary:"nonAffecting",packageCount:"nonAffectingCount"},ALL:{summary:"combined",packageCount:"totalCount"}};function buildPackageTransitiveVulnerabilityAuditQuery(scope){const fields=TRANSITIVE_AUDIT_SCOPE_FIELDS[scope];return`
|
|
104
|
+
query PackageTransitiveVulnerabilityAudit(
|
|
105
|
+
$registry: Registry!
|
|
106
|
+
$name: String!
|
|
107
|
+
$version: String!
|
|
108
|
+
$minSeverity: Float
|
|
109
|
+
$scope: VulnerabilityScope!
|
|
110
|
+
$includeTransitiveAdvisoryDetails: Boolean! = false
|
|
111
|
+
) {
|
|
112
|
+
packageDependencies(
|
|
113
|
+
registry: $registry
|
|
114
|
+
name: $name
|
|
115
|
+
version: $version
|
|
116
|
+
includeTransitive: true
|
|
117
|
+
) {
|
|
118
|
+
package {
|
|
342
119
|
name
|
|
120
|
+
registry
|
|
343
121
|
version
|
|
344
|
-
repoUrl
|
|
345
|
-
gitRef
|
|
346
|
-
site
|
|
347
|
-
}
|
|
348
|
-
filters {
|
|
349
|
-
fileIntent
|
|
350
|
-
kind
|
|
351
|
-
category
|
|
352
|
-
publicOnly
|
|
353
|
-
pathPrefix
|
|
354
|
-
}
|
|
355
|
-
limit
|
|
356
|
-
offset
|
|
357
|
-
targets {
|
|
358
|
-
requested
|
|
359
|
-
resolvedRequested
|
|
360
|
-
served
|
|
361
|
-
freshness
|
|
362
|
-
indexingRef
|
|
363
|
-
requestedRefKind
|
|
364
|
-
${TARGET_RESOLUTION_SELECTION}
|
|
365
|
-
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
366
|
-
${DOC_COVERAGE_SELECTION}
|
|
367
122
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
123
|
+
dependencies {
|
|
124
|
+
transitive {
|
|
125
|
+
vulnerabilitySummary(minSeverity: $minSeverity) {
|
|
126
|
+
selected: ${fields.summary} {
|
|
127
|
+
totalVulnerabilities
|
|
128
|
+
}
|
|
129
|
+
totalPackagesAnalyzed
|
|
130
|
+
calculatedAt
|
|
131
|
+
packages {
|
|
132
|
+
registry
|
|
133
|
+
name
|
|
134
|
+
selectedCount: ${fields.packageCount}
|
|
135
|
+
advisoryOccurrences(scope: $scope, minSeverity: $minSeverity) {
|
|
136
|
+
version
|
|
137
|
+
affectsResolvedVersion
|
|
138
|
+
matchedAffectedVersionRanges
|
|
139
|
+
fixVersionsAboveResolved
|
|
140
|
+
nearestFixedVersion
|
|
141
|
+
advisory {
|
|
142
|
+
osvId
|
|
143
|
+
summary
|
|
144
|
+
severityScore
|
|
145
|
+
affectedVersionRanges @include(if: $includeTransitiveAdvisoryDetails)
|
|
146
|
+
fixedInVersions @include(if: $includeTransitiveAdvisoryDetails)
|
|
147
|
+
publishedAt
|
|
148
|
+
modifiedAt
|
|
149
|
+
aliases
|
|
150
|
+
isMalicious
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
395
154
|
}
|
|
396
155
|
}
|
|
397
|
-
page {
|
|
398
|
-
offset
|
|
399
|
-
limit
|
|
400
|
-
returned
|
|
401
|
-
hasMore
|
|
402
|
-
}
|
|
403
|
-
partialResults
|
|
404
|
-
evidenceNotice
|
|
405
|
-
sourceStatus {
|
|
406
|
-
source
|
|
407
|
-
targetLabel
|
|
408
|
-
requestedTargetLabel
|
|
409
|
-
freshTargetLabel
|
|
410
|
-
servedTargetLabel
|
|
411
|
-
${TARGET_RESOLUTION_SELECTION}
|
|
412
|
-
indexingStatus
|
|
413
|
-
codeIndexState
|
|
414
|
-
resultCount
|
|
415
|
-
appliedFilters
|
|
416
|
-
ignoredFilters
|
|
417
|
-
incompatibleFilters
|
|
418
|
-
appliedQueryFeatures
|
|
419
|
-
ignoredQueryFeatures
|
|
420
|
-
incompatibleQueryFeatures
|
|
421
|
-
suggestedSiteTargets
|
|
422
|
-
suggestedSiteTargetsTruncated
|
|
423
|
-
note
|
|
424
|
-
${DOC_COVERAGE_SELECTION}
|
|
425
|
-
${DOCUMENTATION_CONTRIBUTORS_SELECTION}
|
|
426
|
-
}
|
|
427
156
|
}
|
|
428
157
|
}
|
|
429
|
-
}`;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=z3.object({version:z3.string().nullable().optional(),ref:z3.string()});var indexingDurationEstimateSchema=z3.object({lowerSeconds:z3.number().int().nullable().optional(),upperSeconds:z3.number().int().nullable().optional(),elapsedSeconds:z3.number().int().nullable().optional(),sampleCount:z3.number().int().nullable().optional(),source:z3.string().nullable().optional()}).nullable().optional();var targetResolutionIdentitySchema=z3.object({kind:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),site:z3.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z3.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z3.string().nullable().optional(),freshnessReason:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z3.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z3.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLineRangeSchema=z3.object({startLine:z3.number().int().positive(),endLine:z3.number().int().positive()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchEvidenceRangeSchema=unifiedSearchLineRangeSchema.extend({matchLine:z3.number().int().positive().nullable().optional(),rangeKind:z3.string().nullable().optional(),matchSpansTruncated:z3.boolean()});var unifiedSearchDefinitionRangeSchema=unifiedSearchLineRangeSchema.extend({filePath:z3.string(),repositoryFilePath:z3.string()});var unifiedSearchSymbolContextBaseSchema=z3.object({name:z3.string(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional()});var unifiedSearchSymbolContextSchema=z3.discriminatedUnion("relation",[unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ENCLOSES_MATCH"),definitionRange:unifiedSearchDefinitionRangeSchema}),unifiedSearchSymbolContextBaseSchema.extend({relation:z3.literal("ASSOCIATED_WITH_INDEXED_CHUNK"),definitionRange:unifiedSearchDefinitionRangeSchema.nullable().optional()})]);var unifiedSearchLocatorSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),pageId:z3.string().nullable().optional(),docsReadTarget:z3.string().nullable().optional(),sourceKind:z3.string().nullable().optional(),sourceUrl:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),repositoryFilePath:z3.string().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),evidenceRange:unifiedSearchEvidenceRangeSchema.nullable().optional(),indexedRange:unifiedSearchLineRangeSchema.nullable().optional(),symbolContext:unifiedSearchSymbolContextSchema.nullable().optional(),fileContentHash:z3.string().nullable().optional(),symbolRef:z3.string().nullable().optional(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),language:z3.string().nullable().optional()});var unifiedSearchSemanticPreferredReadSchema=z3.object({targetLabel:z3.string(),registry:z3.string().nullable(),packageName:z3.string().nullable(),version:z3.string().nullable(),repoUrl:z3.string(),gitRef:z3.string(),commitSha:z3.string(),requestedRef:z3.string().nullable(),filePath:z3.string(),repositoryFilePath:z3.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=z3.object({name:z3.string(),qualifiedPath:z3.string(),kind:z3.string(),parentQualifiedPath:z3.string().nullable(),declarationStartLine:z3.number().int().positive(),declarationEndLine:z3.number().int().positive(),parameterNames:z3.array(z3.string()),returnType:z3.string().nullable(),symbolRef:z3.string()}).refine((range)=>range.declarationStartLine<=range.declarationEndLine,{message:"declarationStartLine must be less than or equal to declarationEndLine"});var unifiedSearchSemanticContextSchema=z3.object({scopes:z3.array(unifiedSearchSemanticScopeSchema),scopeChainTruncated:z3.boolean(),preferredRead:unifiedSearchSemanticPreferredReadSchema});var unifiedSearchHighlightSchema=z3.tuple([z3.number().int().nonnegative(),z3.number().int().nonnegative()]).refine(([start,end])=>start<=end,{message:"highlight start must be less than or equal to end"});var unifiedSearchFocusedSourceLineSchema=z3.object({lineNumber:z3.number().int().positive(),text:z3.string(),highlights:z3.array(unifiedSearchHighlightSchema),prefixTruncated:z3.boolean(),suffixTruncated:z3.boolean()});var unifiedSearchFocusedSourceSchema=z3.object({startLine:z3.number().int().positive(),endLine:z3.number().int().positive(),matchLine:z3.number().int().positive().nullable(),rangeKind:z3.string().nullable(),matchSpansTruncated:z3.boolean(),lines:z3.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z3.boolean(),linesOmittedAfter:z3.boolean()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchBm25MatchFieldSchema=z3.enum(["SYMBOL_NAME","FILE_PATH","DOCUMENTATION","SOURCE_IDENTIFIER"]);var unifiedSearchMatchedSourceSchema=unifiedSearchLineRangeSchema.extend({matchLine:z3.number().int().positive().nullable(),rangeKind:z3.string(),matchSpansTruncated:z3.boolean(),lines:z3.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z3.boolean(),linesOmittedAfter:z3.boolean()});var unifiedSearchDocumentationPreviewSchema=z3.object({text:z3.string().min(1),highlights:z3.array(unifiedSearchHighlightSchema)});var unifiedSearchRepositoryEvidenceSchema=z3.object({focusedSource:unifiedSearchFocusedSourceSchema.nullable().optional(),semanticContext:unifiedSearchSemanticContextSchema.nullable(),bm25MatchFields:z3.array(unifiedSearchBm25MatchFieldSchema).min(1).nullable().optional(),matchedSource:unifiedSearchMatchedSourceSchema.nullable().optional()});var contentSafetySchema=z3.object({filtered:z3.boolean(),modifications:z3.array(z3.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var unifiedSearchHitSchema=z3.object({id:z3.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),title:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),score:z3.number().nullable().optional(),highlights:z3.object({title:z3.array(z3.tuple([z3.number().int(),z3.number().int()])).nullable().optional(),summary:z3.array(z3.tuple([z3.number().int(),z3.number().int()])).nullable().optional()}).nullable().optional(),repositoryEvidence:unifiedSearchRepositoryEvidenceSchema.nullable().optional(),documentationPreview:unifiedSearchDocumentationPreviewSchema.nullable().optional(),contentSafety:contentSafetySchema.optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z3.object({offset:z3.number().int(),limit:z3.number().int(),returned:z3.number().int(),hasMore:z3.boolean()});var docCoverageSchema=z3.object({coverageState:z3.string(),coverageReason:z3.string().nullable().optional(),pagesCrawled:z3.number().int().nullable().optional(),frontierRemaining:z3.number().int().nullable().optional(),artifactOverflowPageCount:z3.number().int().nullable().optional(),estimatedTotalPages:z3.number().int().nullable().optional(),note:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z3.object({kind:z3.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z3.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z3.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z3.number().int().nonnegative(),repositoryUrl:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional(),siteKey:z3.string().nullable().optional(),siteUrl:z3.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z3.object({source:unifiedSearchSourceSchema,targetLabel:z3.string(),requestedTargetLabel:z3.string().nullable().optional(),freshTargetLabel:z3.string().nullable().optional(),servedTargetLabel:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z3.string().nullable().optional(),codeIndexState:z3.string().nullable().optional(),resultCount:z3.number().int().nullable().optional(),appliedFilters:z3.array(z3.string()),ignoredFilters:z3.array(z3.string()),incompatibleFilters:z3.array(z3.string()),appliedQueryFeatures:z3.array(z3.string()),ignoredQueryFeatures:z3.array(z3.string()),incompatibleQueryFeatures:z3.array(z3.string()),suggestedSiteTargets:z3.array(z3.string()),suggestedSiteTargetsTruncated:z3.boolean(),note:z3.string().nullable().optional(),coverage:docCoverageSchema,contributors:z3.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z3.object({query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),results:z3.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z3.boolean(),sourceStatus:z3.array(unifiedSearchSourceStatusSchema),evidenceNotice:z3.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z3.string().min(1);var unifiedSearchFiltersSchema=z3.object({fileIntent:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),publicOnly:z3.boolean().nullable().optional(),pathPrefix:z3.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z3.object({requested:z3.string().nullable().optional(),resolvedRequested:z3.string().nullable().optional(),served:z3.string().nullable().optional(),freshness:z3.string().nullable().optional(),indexingRef:z3.string().nullable().optional(),requestedRefKind:z3.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z3.array(availableVersionSchema).nullable().optional(),availableRefs:z3.array(availableVersionSchema).nullable().optional(),suggestedRefs:z3.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string().nullable().optional(),version:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),site:z3.string().nullable().optional()});var unifiedSearchProgressSchema=z3.object({searchRef:z3.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z3.number().int(),targetsReady:z3.number().int(),elapsedMs:z3.number().int(),query:z3.string(),queryWarnings:z3.array(z3.string()),sources:z3.array(unifiedSearchSourceSchema),requestedSources:z3.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z3.string().nullable().optional(),requestedTargets:z3.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z3.number().int().nullable().optional(),offset:z3.number().int().nullable().optional(),targets:z3.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z3.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z3.object({completed:z3.boolean(),searchRef:z3.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffGraphQLErrorSchema=z3.object({message:z3.string(),path:z3.array(z3.union([z3.string(),z3.number().int()])).nullable().optional(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var codeDiffRegistrySchema=z3.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z3.object({registry:codeDiffRegistrySchema,name:z3.string(),repoUrl:z3.string()});var codeDiffRefResolutionSchema=z3.object({requested:z3.string(),resolvedVersion:z3.string().nullable().optional(),ref:z3.string(),commitSha:z3.string(),refKind:z3.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z3.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z3.object({filesChanged:z3.number().int(),added:z3.number().int(),deleted:z3.number().int(),modified:z3.number().int(),modeChanged:z3.number().int(),typeChanged:z3.number().int(),inventoryComplete:z3.boolean(),unprojectableFiles:z3.number().int()});var rawCodeDiffScopeSchema=z3.object({status:z3.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z3.string().nullable().optional(),toSubpath:z3.string().nullable().optional(),pathPrefix:z3.string().nullable().optional(),pathGlob:z3.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z3.object({code:z3.string(),retryable:z3.boolean(),retryAfterMs:z3.number().int().nullable().optional(),stage:z3.string().nullable().optional(),limitKind:z3.string().nullable().optional()});var rawCodeDiffFileSchema=z3.object({path:z3.string(),pathEncoding:z3.enum(["UTF8","BYTE_ESCAPED"]),status:z3.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z3.boolean(),typeChanged:z3.boolean(),additions:z3.number().int().nullable().optional(),deletions:z3.number().int().nullable().optional(),patch:z3.string().nullable().optional(),contentStatus:z3.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z3.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z3.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z3.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z3.array(rawCodeDiffFileSchema),hasMoreFiles:z3.boolean()});var codeDiffResultSchema=z3.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z3.object({data:z3.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
|
|
430
|
-
|
|
158
|
+
}`}var directDependencySchema=z2.object({name:z2.string().nullable().optional(),versionConstraint:z2.string().nullable().optional(),type:z2.string().nullable().optional()});var dependencyGraphNodeSchema=z2.object({registry:z2.string(),name:z2.string(),version:z2.string().nullable().optional()});var dependencyGraphEdgeSchema=z2.object({fromIndex:z2.number().int().nullable().optional(),toIndex:z2.number().int(),constraint:z2.string().nullable().optional(),dependencyType:z2.string().nullable().optional()});var dependencyGraphSchema=z2.object({formatVersion:z2.number().int(),nodes:z2.array(dependencyGraphNodeSchema),edges:z2.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z2.object({totalVulnerabilities:z2.number().int(),critical:z2.number().int(),high:z2.number().int(),medium:z2.number().int(),low:z2.number().int(),unknown:z2.number().int()});var vulnerabilitySummaryDetailSchema=z2.object({osvId:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),severityType:z2.string().nullable().optional(),affectedVersionRanges:z2.array(z2.string()).nullable().optional(),fixedInVersions:z2.array(z2.string()).nullable().optional(),publishedAt:z2.string().nullable().optional(),modifiedAt:z2.string().nullable().optional(),withdrawnAt:z2.string().nullable().optional(),aliases:z2.array(z2.string()).nullable().optional(),isMalicious:z2.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z2.object({version:z2.string(),affectsResolvedVersion:z2.boolean(),matchedAffectedVersionRanges:z2.array(z2.string()),fixVersionsAboveResolved:z2.array(z2.string()),nearestFixedVersion:z2.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z2.object({registry:z2.string(),name:z2.string(),versions:z2.array(z2.string()),affectedCount:z2.number().int(),nonAffectingCount:z2.number().int(),totalCount:z2.number().int(),maxSeverityScore:z2.number().nullable().optional(),maxSeverityLabel:z2.string().nullable().optional(),advisoryIds:z2.array(z2.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z2.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z2.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z2.number().int(),affectedPackageCount:z2.number().int(),packages:z2.array(transitiveVulnerablePackageSchema),calculatedAt:z2.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z2.object({version:z2.string(),reason:z2.string().nullable().optional()});var deprecatedDependencySchema=z2.object({registry:z2.string(),name:z2.string(),versions:z2.array(z2.string()),reasons:z2.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z2.object({version:z2.string(),severity:z2.string()});var outdatedDependencySchema=z2.object({registry:z2.string(),name:z2.string(),latestVersion:z2.string().nullable().optional(),severity:z2.string(),versions:z2.array(outdatedDependencyVersionSchema),repositoryUrl:z2.string().nullable().optional()});var duplicateDependencySchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string(),versions:z2.array(z2.string())});var dependencyConflictEdgeSchema=z2.object({fromIndex:z2.number().int().nullable().optional(),toIndex:z2.number().int(),versionConstraint:z2.string(),dependencyType:z2.string()});var dependencyConflictSchema=z2.object({packageName:z2.string(),requiredVersions:z2.array(z2.string()),conflictingEdges:z2.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string(),versions:z2.array(z2.string()),requiredVersions:z2.array(z2.string()),conflictingEdges:z2.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z2.object({totalCount:z2.number().int(),deprecatedCount:z2.number().int(),outdatedCount:z2.number().int(),duplicateCount:z2.number().int(),conflictCount:z2.number().int(),deprecatedPackages:z2.array(deprecatedDependencySchema),outdatedPackages:z2.array(outdatedDependencySchema),duplicatePackages:z2.array(duplicateDependencySchema),conflicts:z2.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z2.object({cycleStart:z2.string(),circularPath:z2.array(z2.string()),displayChain:z2.string()});var environmentMarkerSchema=z2.object({type:z2.string().nullable().optional(),value:z2.string().nullable().optional(),raw:z2.string().nullable().optional()});var transitiveDependencySchema=z2.object({totalEdges:z2.number().int().nullable().optional(),uniquePackagesCount:z2.number().int().nullable().optional(),uniqueDependencies:z2.array(z2.string()).nullable().optional(),dependencyConflicts:z2.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z2.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z2.object({direct:z2.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z2.object({name:z2.string(),constraint:z2.string().nullable().optional()});var dependencyGroupSchema=z2.object({name:z2.string(),lifecycle:z2.string(),conditionType:z2.string(),conditionValue:z2.string().nullable().optional(),selectionMode:z2.string(),exclusiveGroup:z2.string().nullable().optional(),fallbackPriority:z2.number().int().nullable().optional(),compatibleWith:z2.array(z2.string()).nullable().optional(),defaultEnabled:z2.boolean().nullable().optional(),dependencies:z2.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z2.object({primaryGroup:z2.string().nullable().optional(),environmentMarkers:z2.array(environmentMarkerSchema).nullable().optional(),groups:z2.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z2.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z2.object({data:z2.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
|
|
159
|
+
query PackageDependencies(
|
|
160
|
+
$registry: Registry!
|
|
161
|
+
$name: String!
|
|
162
|
+
$version: String
|
|
163
|
+
$includeTransitive: Boolean
|
|
164
|
+
$includeTransitiveDetails: Boolean! = true
|
|
165
|
+
$includeDependencyGraph: Boolean! = true
|
|
166
|
+
$includeGroups: Boolean! = true
|
|
167
|
+
$includeDependencyIssues: Boolean! = false
|
|
168
|
+
$maxDepth: Int
|
|
169
|
+
$lifecycle: [String!]
|
|
170
|
+
) {
|
|
171
|
+
packageDependencies(
|
|
172
|
+
registry: $registry
|
|
173
|
+
name: $name
|
|
174
|
+
version: $version
|
|
175
|
+
includeTransitive: $includeTransitive
|
|
176
|
+
maxDepth: $maxDepth
|
|
177
|
+
lifecycle: $lifecycle
|
|
178
|
+
) {
|
|
179
|
+
package {
|
|
431
180
|
name
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
fromResolution {
|
|
435
|
-
requested
|
|
436
|
-
resolvedVersion
|
|
437
|
-
ref
|
|
438
|
-
commitSha
|
|
439
|
-
refKind
|
|
440
|
-
versionSource
|
|
441
|
-
}
|
|
442
|
-
toResolution {
|
|
443
|
-
requested
|
|
444
|
-
resolvedVersion
|
|
445
|
-
ref
|
|
446
|
-
commitSha
|
|
447
|
-
refKind
|
|
448
|
-
versionSource
|
|
181
|
+
registry
|
|
182
|
+
version
|
|
449
183
|
}
|
|
450
|
-
|
|
451
|
-
summary
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
unprojectableFiles
|
|
184
|
+
dependencies {
|
|
185
|
+
# Backend-side summary block intentionally not selected — our
|
|
186
|
+
# envelope computes runtime.count client-side from direct[].length
|
|
187
|
+
# so the invariant runtime.count === runtime.items.length always
|
|
188
|
+
# holds regardless of backend-side drift.
|
|
189
|
+
direct {
|
|
190
|
+
name
|
|
191
|
+
versionConstraint
|
|
192
|
+
type
|
|
460
193
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
194
|
+
transitive {
|
|
195
|
+
totalEdges @include(if: $includeTransitiveDetails)
|
|
196
|
+
uniquePackagesCount @include(if: $includeTransitiveDetails)
|
|
197
|
+
uniqueDependencies @include(if: $includeTransitiveDetails)
|
|
198
|
+
dependencyConflicts @include(if: $includeTransitiveDetails) {
|
|
199
|
+
packageName
|
|
200
|
+
requiredVersions
|
|
201
|
+
conflictingEdges {
|
|
202
|
+
fromIndex
|
|
203
|
+
toIndex
|
|
204
|
+
versionConstraint
|
|
205
|
+
dependencyType
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
circularDependencyCycles @include(if: $includeTransitiveDetails) {
|
|
209
|
+
cycleStart
|
|
210
|
+
circularPath
|
|
211
|
+
displayChain
|
|
212
|
+
}
|
|
213
|
+
dependencyGraph @include(if: $includeDependencyGraph) {
|
|
214
|
+
formatVersion
|
|
215
|
+
nodes {
|
|
216
|
+
registry
|
|
217
|
+
name
|
|
218
|
+
version
|
|
219
|
+
}
|
|
220
|
+
edges {
|
|
221
|
+
fromIndex
|
|
222
|
+
toIndex
|
|
223
|
+
constraint
|
|
224
|
+
dependencyType
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
dependencyIssues @include(if: $includeDependencyIssues) {
|
|
228
|
+
totalCount
|
|
229
|
+
deprecatedCount
|
|
230
|
+
outdatedCount
|
|
231
|
+
duplicateCount
|
|
232
|
+
conflictCount
|
|
233
|
+
deprecatedPackages {
|
|
234
|
+
registry
|
|
235
|
+
name
|
|
236
|
+
versions
|
|
237
|
+
reasons {
|
|
238
|
+
version
|
|
239
|
+
reason
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
outdatedPackages {
|
|
243
|
+
registry
|
|
244
|
+
name
|
|
245
|
+
latestVersion
|
|
246
|
+
severity
|
|
247
|
+
versions {
|
|
248
|
+
version
|
|
249
|
+
severity
|
|
250
|
+
}
|
|
251
|
+
repositoryUrl
|
|
252
|
+
}
|
|
253
|
+
duplicatePackages {
|
|
254
|
+
registry
|
|
255
|
+
name
|
|
256
|
+
versions
|
|
257
|
+
}
|
|
258
|
+
conflicts {
|
|
259
|
+
registry
|
|
260
|
+
name
|
|
261
|
+
versions
|
|
262
|
+
requiredVersions
|
|
263
|
+
conflictingEdges {
|
|
264
|
+
fromIndex
|
|
265
|
+
toIndex
|
|
266
|
+
versionConstraint
|
|
267
|
+
dependencyType
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
467
271
|
}
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
272
|
+
}
|
|
273
|
+
dependencyGroups @include(if: $includeGroups) {
|
|
274
|
+
primaryGroup
|
|
275
|
+
environmentMarkers {
|
|
276
|
+
type
|
|
277
|
+
value
|
|
278
|
+
raw
|
|
475
279
|
}
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
$
|
|
496
|
-
$
|
|
497
|
-
$
|
|
498
|
-
$
|
|
499
|
-
$
|
|
500
|
-
$
|
|
501
|
-
$
|
|
280
|
+
groups {
|
|
281
|
+
name
|
|
282
|
+
lifecycle
|
|
283
|
+
conditionType
|
|
284
|
+
conditionValue
|
|
285
|
+
selectionMode
|
|
286
|
+
exclusiveGroup
|
|
287
|
+
fallbackPriority
|
|
288
|
+
compatibleWith
|
|
289
|
+
defaultEnabled
|
|
290
|
+
dependencies {
|
|
291
|
+
name
|
|
292
|
+
constraint
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
|
|
298
|
+
query PackageUpgradeDependencyProbe(
|
|
299
|
+
$registry: Registry!
|
|
300
|
+
$name: String!
|
|
301
|
+
$version: String!
|
|
302
|
+
$includeTransitiveRisk: Boolean!
|
|
303
|
+
$includeTransitiveSecurity: Boolean!
|
|
304
|
+
$includeDependencyIssues: Boolean!
|
|
305
|
+
$includeDependencyChanges: Boolean!
|
|
306
|
+
$includeGroups: Boolean!
|
|
307
|
+
$lifecycle: [String!]
|
|
308
|
+
$minSeverity: Float
|
|
502
309
|
) {
|
|
503
|
-
|
|
310
|
+
packageDependencies(
|
|
504
311
|
registry: $registry
|
|
505
312
|
name: $name
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
fromRef: $fromRef
|
|
510
|
-
toRef: $toRef
|
|
511
|
-
rawOptions: $rawOptions
|
|
313
|
+
version: $version
|
|
314
|
+
includeTransitive: $includeTransitiveRisk
|
|
315
|
+
lifecycle: $lifecycle
|
|
512
316
|
) {
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
317
|
+
package {
|
|
318
|
+
name
|
|
319
|
+
registry
|
|
320
|
+
version
|
|
321
|
+
publishedAt
|
|
322
|
+
deprecated
|
|
323
|
+
deprecationReason
|
|
324
|
+
}
|
|
325
|
+
dependencies {
|
|
326
|
+
direct {
|
|
327
|
+
name
|
|
328
|
+
versionConstraint
|
|
329
|
+
type
|
|
330
|
+
}
|
|
331
|
+
transitive @include(if: $includeTransitiveRisk) {
|
|
332
|
+
dependencyGraph @include(if: $includeDependencyChanges) {
|
|
333
|
+
formatVersion
|
|
334
|
+
nodes {
|
|
335
|
+
registry
|
|
336
|
+
name
|
|
337
|
+
version
|
|
338
|
+
}
|
|
339
|
+
edges {
|
|
340
|
+
fromIndex
|
|
341
|
+
toIndex
|
|
342
|
+
constraint
|
|
343
|
+
dependencyType
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
|
|
347
|
+
affected {
|
|
348
|
+
totalVulnerabilities
|
|
349
|
+
critical
|
|
350
|
+
high
|
|
351
|
+
medium
|
|
352
|
+
low
|
|
353
|
+
unknown
|
|
354
|
+
}
|
|
355
|
+
nonAffecting {
|
|
356
|
+
totalVulnerabilities
|
|
357
|
+
critical
|
|
358
|
+
high
|
|
359
|
+
medium
|
|
360
|
+
low
|
|
361
|
+
unknown
|
|
362
|
+
}
|
|
363
|
+
combined {
|
|
364
|
+
totalVulnerabilities
|
|
365
|
+
critical
|
|
366
|
+
high
|
|
367
|
+
medium
|
|
368
|
+
low
|
|
369
|
+
unknown
|
|
370
|
+
}
|
|
371
|
+
totalPackagesAnalyzed
|
|
372
|
+
affectedPackageCount
|
|
373
|
+
calculatedAt
|
|
374
|
+
packages {
|
|
375
|
+
registry
|
|
376
|
+
name
|
|
377
|
+
versions
|
|
378
|
+
affectedCount
|
|
379
|
+
nonAffectingCount
|
|
380
|
+
totalCount
|
|
381
|
+
maxSeverityScore
|
|
382
|
+
maxSeverityLabel
|
|
383
|
+
advisoryIds(scope: AFFECTED)
|
|
384
|
+
mostCritical {
|
|
385
|
+
osvId
|
|
386
|
+
registry
|
|
387
|
+
packageName
|
|
388
|
+
summary
|
|
389
|
+
severityScore
|
|
390
|
+
severityType
|
|
391
|
+
affectedVersionRanges
|
|
392
|
+
fixedInVersions
|
|
393
|
+
publishedAt
|
|
394
|
+
modifiedAt
|
|
395
|
+
withdrawnAt
|
|
396
|
+
aliases
|
|
397
|
+
isMalicious
|
|
398
|
+
}
|
|
399
|
+
advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
|
|
400
|
+
version
|
|
401
|
+
affectsResolvedVersion
|
|
402
|
+
matchedAffectedVersionRanges
|
|
403
|
+
fixVersionsAboveResolved
|
|
404
|
+
nearestFixedVersion
|
|
405
|
+
advisory {
|
|
406
|
+
osvId
|
|
407
|
+
registry
|
|
408
|
+
packageName
|
|
409
|
+
summary
|
|
410
|
+
severityScore
|
|
411
|
+
severityType
|
|
412
|
+
affectedVersionRanges
|
|
413
|
+
fixedInVersions
|
|
414
|
+
publishedAt
|
|
415
|
+
modifiedAt
|
|
416
|
+
withdrawnAt
|
|
417
|
+
aliases
|
|
418
|
+
isMalicious
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
dependencyIssues @include(if: $includeDependencyIssues) {
|
|
424
|
+
totalCount
|
|
425
|
+
deprecatedCount
|
|
426
|
+
outdatedCount
|
|
427
|
+
duplicateCount
|
|
428
|
+
conflictCount
|
|
429
|
+
deprecatedPackages {
|
|
430
|
+
registry
|
|
431
|
+
name
|
|
432
|
+
versions
|
|
433
|
+
reasons {
|
|
434
|
+
version
|
|
435
|
+
reason
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
outdatedPackages {
|
|
439
|
+
registry
|
|
440
|
+
name
|
|
441
|
+
latestVersion
|
|
442
|
+
severity
|
|
443
|
+
versions {
|
|
444
|
+
version
|
|
445
|
+
severity
|
|
446
|
+
}
|
|
447
|
+
repositoryUrl
|
|
448
|
+
}
|
|
449
|
+
duplicatePackages {
|
|
450
|
+
registry
|
|
451
|
+
name
|
|
452
|
+
versions
|
|
453
|
+
}
|
|
454
|
+
conflicts {
|
|
455
|
+
registry
|
|
456
|
+
name
|
|
457
|
+
versions
|
|
458
|
+
requiredVersions
|
|
459
|
+
conflictingEdges {
|
|
460
|
+
fromIndex
|
|
461
|
+
toIndex
|
|
462
|
+
versionConstraint
|
|
463
|
+
dependencyType
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
dependencyGroups @include(if: $includeGroups) {
|
|
470
|
+
primaryGroup
|
|
471
|
+
environmentMarkers {
|
|
472
|
+
type
|
|
473
|
+
value
|
|
474
|
+
raw
|
|
475
|
+
}
|
|
476
|
+
groups {
|
|
477
|
+
name
|
|
478
|
+
lifecycle
|
|
479
|
+
conditionType
|
|
480
|
+
conditionValue
|
|
481
|
+
selectionMode
|
|
482
|
+
exclusiveGroup
|
|
483
|
+
fallbackPriority
|
|
484
|
+
compatibleWith
|
|
485
|
+
defaultEnabled
|
|
486
|
+
dependencies {
|
|
487
|
+
name
|
|
488
|
+
constraint
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}`;var packageUpgradeAdvisorySchema=z2.object({id:z2.string().nullable().optional(),aliases:z2.array(z2.string()),summary:z2.string().nullable().optional(),severity:z2.number().nullable().optional(),severityLabel:z2.string().nullable().optional(),fixedIn:z2.array(z2.string()),isMalicious:z2.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z2.object({version:z2.string(),publishedAt:z2.string().nullable().optional(),deprecated:z2.boolean().nullable().optional(),deprecationReason:z2.string().nullable().optional(),affectedCount:z2.number().int(),nonAffectingCount:z2.number().int(),allCount:z2.number().int(),lastModifiedAt:z2.string().nullable().optional(),advisories:z2.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z2.object({entries:z2.array(z2.object({id:z2.string(),registry:z2.string(),name:z2.string(),versions:z2.array(z2.string()),affectedCount:z2.number().int(),maxSeverityScore:z2.number().nullable().optional(),maxSeverityLabel:z2.string().nullable().optional(),advisoryIds:z2.array(z2.string())})),totalCount:z2.number().int(),truncated:z2.boolean()});var packageUpgradeTransitiveSecuritySchema=z2.object({currentAffected:z2.number().int(),targetAffected:z2.number().int(),introducedPackages:z2.array(z2.string()),fixedPackages:z2.array(z2.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z2.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z2.array(packageUpgradeAdvisorySchema),removed:z2.array(packageUpgradeAdvisorySchema),notAddressed:z2.array(packageUpgradeAdvisorySchema),fixed:z2.array(packageUpgradeAdvisorySchema),introduced:z2.array(packageUpgradeAdvisorySchema),unchanged:z2.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z2.object({version:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),htmlUrl:z2.string().nullable().optional(),body:z2.string().nullable().optional(),bodyPreview:z2.string().nullable().optional(),headline:z2.string().nullable().optional(),signals:z2.array(z2.string())});var packageUpgradeChangelogSchema=z2.object({source:z2.string().nullable().optional(),fallback:z2.string().nullable().optional(),entries:z2.array(packageUpgradeChangelogEntrySchema),sampledEntries:z2.array(packageUpgradeChangelogEntrySchema),keywordEntries:z2.array(packageUpgradeChangelogEntrySchema),totalKeywordEntries:z2.number().int(),totalEntries:z2.number().int(),totalEntriesWithBodies:z2.number().int(),truncated:z2.boolean(),hasReleaseNoteBodies:z2.boolean(),breakingSignals:z2.array(z2.string()),migrationSignals:z2.array(z2.string())});var packageUpgradeCompatibilitySchema=z2.object({peerDependencyChanges:z2.array(z2.string()),notes:z2.array(z2.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z2.object({name:z2.string(),registry:z2.string().nullable().optional(),version:z2.string().nullable().optional(),fromVersions:z2.array(z2.string()),toVersions:z2.array(z2.string()),constraint:z2.string().nullable().optional(),type:z2.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z2.object({added:z2.array(packageUpgradeDependencyChangeItemSchema),removed:z2.array(packageUpgradeDependencyChangeItemSchema),changed:z2.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z2.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z2.object({currentTotal:z2.number().int(),targetTotal:z2.number().int(),introducedDeprecated:z2.array(z2.string()),introducedDuplicates:z2.array(z2.string()),introducedConflicts:z2.array(z2.string()),introducedOutdated:z2.array(z2.string())}).nullable().optional();var packageUpgradeReviewSchema=z2.object({registry:z2.string(),name:z2.string(),currentVersion:z2.string(),targetVersion:z2.string(),latestVersion:z2.string().nullable().optional(),versionDelta:z2.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknowns:z2.array(z2.string())});var packageUpgradeReviewResponseSchema=z2.object({summary:z2.object({total:z2.number().int(),withUnknowns:z2.number().int(),withAddedAdvisories:z2.number().int(),withBreakingSignals:z2.number().int(),withDirectDependencyChanges:z2.number().int(),withTransitiveVulnerabilityAdditions:z2.number().int()}),reviews:z2.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z2.object({data:z2.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var PACKAGE_UPGRADE_REVIEW_QUERY=`
|
|
494
|
+
query PackageUpgradeReview(
|
|
495
|
+
$packages: [PackageUpgradeReviewPackageInput!]!
|
|
496
|
+
$includeTransitiveSecurity: Boolean!
|
|
497
|
+
$includeDependencyIssues: Boolean!
|
|
498
|
+
$minSeverity: Float
|
|
499
|
+
$changelogLimit: Int!
|
|
500
|
+
) {
|
|
501
|
+
packageUpgradeReview(
|
|
502
|
+
packages: $packages
|
|
503
|
+
includeTransitiveSecurity: $includeTransitiveSecurity
|
|
504
|
+
minSeverity: $minSeverity
|
|
505
|
+
changelogLimit: $changelogLimit
|
|
506
|
+
) {
|
|
507
|
+
summary {
|
|
508
|
+
total
|
|
509
|
+
withUnknowns
|
|
510
|
+
withAddedAdvisories
|
|
511
|
+
withBreakingSignals
|
|
512
|
+
withDirectDependencyChanges
|
|
513
|
+
withTransitiveVulnerabilityAdditions
|
|
514
|
+
}
|
|
515
|
+
reviews {
|
|
516
|
+
registry
|
|
517
|
+
name
|
|
518
|
+
currentVersion
|
|
519
|
+
targetVersion
|
|
520
|
+
latestVersion
|
|
521
|
+
versionDelta
|
|
522
|
+
security {
|
|
523
|
+
current {
|
|
524
|
+
version
|
|
525
|
+
publishedAt
|
|
526
|
+
deprecated
|
|
527
|
+
deprecationReason
|
|
528
|
+
affectedCount
|
|
529
|
+
nonAffectingCount
|
|
530
|
+
allCount
|
|
531
|
+
lastModifiedAt
|
|
532
|
+
advisories {
|
|
533
|
+
...PackageUpgradeAdvisoryFields
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
target {
|
|
537
|
+
version
|
|
538
|
+
publishedAt
|
|
539
|
+
deprecated
|
|
540
|
+
deprecationReason
|
|
541
|
+
affectedCount
|
|
542
|
+
nonAffectingCount
|
|
543
|
+
allCount
|
|
544
|
+
lastModifiedAt
|
|
545
|
+
advisories {
|
|
546
|
+
...PackageUpgradeAdvisoryFields
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
added {
|
|
550
|
+
...PackageUpgradeAdvisoryFields
|
|
551
|
+
}
|
|
552
|
+
removed {
|
|
553
|
+
...PackageUpgradeAdvisoryFields
|
|
554
|
+
}
|
|
555
|
+
notAddressed {
|
|
556
|
+
...PackageUpgradeAdvisoryFields
|
|
557
|
+
}
|
|
558
|
+
fixed {
|
|
559
|
+
...PackageUpgradeAdvisoryFields
|
|
560
|
+
}
|
|
561
|
+
introduced {
|
|
562
|
+
...PackageUpgradeAdvisoryFields
|
|
563
|
+
}
|
|
564
|
+
unchanged {
|
|
565
|
+
...PackageUpgradeAdvisoryFields
|
|
566
|
+
}
|
|
567
|
+
transitive @include(if: $includeTransitiveSecurity) {
|
|
568
|
+
currentAffected
|
|
569
|
+
targetAffected
|
|
570
|
+
introducedPackages
|
|
571
|
+
fixedPackages
|
|
572
|
+
introducedPackageDetails(first: 50) {
|
|
573
|
+
...PackageUpgradeTransitivePackagePageFields
|
|
574
|
+
}
|
|
575
|
+
fixedPackageDetails(first: 50) {
|
|
576
|
+
...PackageUpgradeTransitivePackagePageFields
|
|
577
|
+
}
|
|
578
|
+
stillAffectedPackageDetails(first: 50) {
|
|
579
|
+
...PackageUpgradeTransitivePackagePageFields
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
changelog {
|
|
584
|
+
source
|
|
585
|
+
fallback
|
|
586
|
+
entries {
|
|
587
|
+
...PackageUpgradeChangelogEntryFields
|
|
588
|
+
}
|
|
589
|
+
sampledEntries {
|
|
590
|
+
...PackageUpgradeChangelogEntryFields
|
|
591
|
+
}
|
|
592
|
+
keywordEntries {
|
|
593
|
+
...PackageUpgradeChangelogEntryFields
|
|
594
|
+
}
|
|
595
|
+
totalKeywordEntries
|
|
596
|
+
totalEntries
|
|
597
|
+
totalEntriesWithBodies
|
|
598
|
+
truncated
|
|
599
|
+
hasReleaseNoteBodies
|
|
600
|
+
breakingSignals
|
|
601
|
+
migrationSignals
|
|
602
|
+
}
|
|
603
|
+
compatibility {
|
|
604
|
+
peerDependencyChanges
|
|
605
|
+
notes
|
|
606
|
+
}
|
|
607
|
+
dependencyChanges {
|
|
608
|
+
direct {
|
|
609
|
+
...PackageUpgradeDependencyChangeGroupFields
|
|
610
|
+
}
|
|
611
|
+
transitive {
|
|
612
|
+
...PackageUpgradeDependencyChangeGroupFields
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
dependencyIssues @include(if: $includeDependencyIssues) {
|
|
616
|
+
currentTotal
|
|
617
|
+
targetTotal
|
|
618
|
+
introducedDeprecated
|
|
619
|
+
introducedDuplicates
|
|
620
|
+
introducedConflicts
|
|
621
|
+
introducedOutdated
|
|
622
|
+
}
|
|
623
|
+
unknowns
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
|
|
629
|
+
id
|
|
630
|
+
aliases
|
|
631
|
+
summary
|
|
632
|
+
severity
|
|
633
|
+
severityLabel
|
|
634
|
+
fixedIn
|
|
635
|
+
isMalicious
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
|
|
639
|
+
entries {
|
|
640
|
+
id
|
|
641
|
+
registry
|
|
642
|
+
name
|
|
643
|
+
versions
|
|
644
|
+
affectedCount
|
|
645
|
+
maxSeverityScore
|
|
646
|
+
maxSeverityLabel
|
|
647
|
+
advisoryIds
|
|
648
|
+
}
|
|
649
|
+
totalCount
|
|
650
|
+
truncated
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
|
|
654
|
+
version
|
|
655
|
+
publishedAt
|
|
656
|
+
htmlUrl
|
|
657
|
+
body
|
|
658
|
+
bodyPreview
|
|
659
|
+
headline
|
|
660
|
+
signals
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
|
|
664
|
+
added {
|
|
665
|
+
name
|
|
666
|
+
registry
|
|
667
|
+
version
|
|
668
|
+
fromVersions
|
|
669
|
+
toVersions
|
|
670
|
+
constraint
|
|
671
|
+
type
|
|
672
|
+
}
|
|
673
|
+
removed {
|
|
674
|
+
name
|
|
675
|
+
registry
|
|
676
|
+
version
|
|
677
|
+
fromVersions
|
|
678
|
+
toVersions
|
|
679
|
+
constraint
|
|
680
|
+
type
|
|
681
|
+
}
|
|
682
|
+
changed {
|
|
683
|
+
name
|
|
684
|
+
registry
|
|
685
|
+
version
|
|
686
|
+
fromVersions
|
|
687
|
+
toVersions
|
|
688
|
+
constraint
|
|
689
|
+
type
|
|
690
|
+
}
|
|
691
|
+
}`;var changelogPackageInfoSchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),fromVersion:z2.string().nullable().optional(),toVersion:z2.string().nullable().optional(),limit:z2.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z2.object({version:z2.string().nullable().optional(),normalizedVersion:z2.string().nullable().optional(),body:z2.string().nullable().optional(),htmlUrl:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional()});var changelogReportResponseSchema=z2.object({package:changelogPackageInfoSchema,source:z2.string().nullable().optional(),entries:z2.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z2.object({data:z2.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var PACKAGE_CHANGELOG_QUERY=`
|
|
692
|
+
query PackageChangelog(
|
|
520
693
|
$registry: Registry
|
|
521
|
-
$
|
|
694
|
+
$name: String
|
|
522
695
|
$repoUrl: String
|
|
523
696
|
$gitRef: String
|
|
524
|
-
$
|
|
525
|
-
$
|
|
526
|
-
$pathSelectors: [FilePathSelectorInput!]
|
|
527
|
-
$extensions: [String!]
|
|
528
|
-
$fileTypes: [String!]
|
|
529
|
-
$languages: [String!]
|
|
530
|
-
$fileIntent: FileIntent
|
|
531
|
-
$fileIntents: [FileIntent!]
|
|
532
|
-
$excludeFileIntents: [FileIntent!]
|
|
533
|
-
$excludeDocFiles: Boolean
|
|
534
|
-
$excludeTestFiles: Boolean
|
|
535
|
-
$includeHidden: Boolean
|
|
697
|
+
$fromVersion: String
|
|
698
|
+
$toVersion: String
|
|
536
699
|
$limit: Int
|
|
537
|
-
$
|
|
700
|
+
$includeBodies: Boolean! = true
|
|
538
701
|
) {
|
|
539
|
-
|
|
702
|
+
packageChangelog(
|
|
540
703
|
registry: $registry
|
|
541
|
-
|
|
704
|
+
name: $name
|
|
542
705
|
repoUrl: $repoUrl
|
|
543
706
|
gitRef: $gitRef
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
pathSelectors: $pathSelectors
|
|
547
|
-
extensions: $extensions
|
|
548
|
-
fileTypes: $fileTypes
|
|
549
|
-
languages: $languages
|
|
550
|
-
fileIntent: $fileIntent
|
|
551
|
-
fileIntents: $fileIntents
|
|
552
|
-
excludeFileIntents: $excludeFileIntents
|
|
553
|
-
excludeDocFiles: $excludeDocFiles
|
|
554
|
-
excludeTestFiles: $excludeTestFiles
|
|
555
|
-
includeHidden: $includeHidden
|
|
707
|
+
fromVersion: $fromVersion
|
|
708
|
+
toVersion: $toVersion
|
|
556
709
|
limit: $limit
|
|
557
|
-
waitTimeoutMs: $waitTimeoutMs
|
|
558
710
|
) {
|
|
559
|
-
|
|
560
|
-
path
|
|
711
|
+
package {
|
|
561
712
|
name
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
hasMore
|
|
568
|
-
indexedVersion
|
|
569
|
-
resolution {
|
|
570
|
-
requestedVersion
|
|
571
|
-
requestedRef
|
|
572
|
-
resolvedRef
|
|
573
|
-
commitSha
|
|
574
|
-
}
|
|
575
|
-
${TARGET_RESOLUTION_SELECTION}
|
|
576
|
-
diagnostics {
|
|
577
|
-
hint
|
|
713
|
+
registry
|
|
714
|
+
repoUrl
|
|
715
|
+
fromVersion
|
|
716
|
+
toVersion
|
|
717
|
+
limit
|
|
578
718
|
}
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
availableVersions {
|
|
719
|
+
source
|
|
720
|
+
entries {
|
|
582
721
|
version
|
|
583
|
-
|
|
722
|
+
normalizedVersion
|
|
723
|
+
body @include(if: $includeBodies)
|
|
724
|
+
htmlUrl
|
|
725
|
+
publishedAt
|
|
584
726
|
}
|
|
585
|
-
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
586
727
|
}
|
|
587
|
-
}`;var
|
|
588
|
-
query
|
|
589
|
-
$registry: Registry
|
|
590
|
-
$packageName: String
|
|
591
|
-
$repoUrl: String
|
|
592
|
-
$gitRef: String
|
|
728
|
+
}`;var packageDocSourceKindSchema=z2.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z2.object({id:z2.string().nullable().optional(),docsReadTarget:z2.string(),title:z2.string().nullable().optional(),slug:z2.string().nullable().optional(),order:z2.number().int().nullable().optional(),linkName:z2.string().nullable().optional(),lastUpdatedAt:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional()});var packageDocsPageInfoSchema=z2.object({hasNextPage:z2.boolean(),endCursor:z2.string().nullable().optional(),totalCount:z2.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),stale:z2.boolean().nullable().optional(),codeIndexState:z2.string().nullable().optional(),pages:z2.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z2.object({url:z2.string().nullable().optional(),label:z2.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z2.object({id:z2.string().nullable().optional(),docsReadTarget:z2.string(),title:z2.string().nullable().optional(),content:z2.string().nullable().optional(),contentFormat:z2.string().nullable().optional(),breadcrumbs:z2.array(z2.string()).nullable().optional(),linkName:z2.string().nullable().optional(),lastUpdatedAt:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),baseUrl:z2.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z2.object({data:z2.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var packageDocReadGraphQLResponseSchema=z2.object({data:z2.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var LIST_PACKAGE_DOCS_QUERY=`
|
|
729
|
+
query ListPackageDocs(
|
|
730
|
+
$registry: Registry!
|
|
731
|
+
$packageName: String!
|
|
593
732
|
$version: String
|
|
594
|
-
$
|
|
595
|
-
$
|
|
596
|
-
$endLine: Int
|
|
597
|
-
$waitTimeoutMs: Int
|
|
733
|
+
$limit: Int
|
|
734
|
+
$after: String
|
|
598
735
|
) {
|
|
599
|
-
|
|
736
|
+
listPackageDocs(
|
|
600
737
|
registry: $registry
|
|
601
738
|
packageName: $packageName
|
|
602
|
-
repoUrl: $repoUrl
|
|
603
|
-
gitRef: $gitRef
|
|
604
739
|
version: $version
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
endLine: $endLine
|
|
608
|
-
waitTimeoutMs: $waitTimeoutMs
|
|
740
|
+
limit: $limit
|
|
741
|
+
after: $after
|
|
609
742
|
) {
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
startLine
|
|
615
|
-
endLine
|
|
616
|
-
repoUrl
|
|
617
|
-
gitRef
|
|
618
|
-
isBinary
|
|
743
|
+
registry
|
|
744
|
+
packageName
|
|
745
|
+
version
|
|
746
|
+
stale
|
|
619
747
|
codeIndexState
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
$packageName: String
|
|
633
|
-
$repoUrl: String
|
|
634
|
-
$gitRef: String
|
|
635
|
-
$version: String
|
|
636
|
-
$waitTimeoutMs: Int
|
|
637
|
-
$pattern: String!
|
|
638
|
-
$patternType: GrepPatternType
|
|
639
|
-
$caseSensitive: Boolean
|
|
640
|
-
$pathSelectors: [GrepPathSelectorInput!]
|
|
641
|
-
$extensions: [String!]
|
|
642
|
-
$excludeDocFiles: Boolean
|
|
643
|
-
$excludeTestFiles: Boolean
|
|
644
|
-
$allowUnscoped: Boolean
|
|
645
|
-
$contextLinesBefore: Int
|
|
646
|
-
$contextLinesAfter: Int
|
|
647
|
-
$maxMatches: Int
|
|
648
|
-
$maxMatchesPerFile: Int
|
|
649
|
-
$cursor: String
|
|
650
|
-
$symbolFields: [String!]
|
|
651
|
-
) {
|
|
652
|
-
grepRepo(
|
|
653
|
-
registry: $registry
|
|
654
|
-
packageName: $packageName
|
|
655
|
-
repoUrl: $repoUrl
|
|
656
|
-
gitRef: $gitRef
|
|
657
|
-
version: $version
|
|
658
|
-
waitTimeoutMs: $waitTimeoutMs
|
|
659
|
-
pattern: $pattern
|
|
660
|
-
patternType: $patternType
|
|
661
|
-
caseSensitive: $caseSensitive
|
|
662
|
-
pathSelectors: $pathSelectors
|
|
663
|
-
extensions: $extensions
|
|
664
|
-
excludeDocFiles: $excludeDocFiles
|
|
665
|
-
excludeTestFiles: $excludeTestFiles
|
|
666
|
-
allowUnscoped: $allowUnscoped
|
|
667
|
-
contextLinesBefore: $contextLinesBefore
|
|
668
|
-
contextLinesAfter: $contextLinesAfter
|
|
669
|
-
maxMatches: $maxMatches
|
|
670
|
-
maxMatchesPerFile: $maxMatchesPerFile
|
|
671
|
-
cursor: $cursor
|
|
672
|
-
symbolFields: $symbolFields
|
|
673
|
-
) {
|
|
674
|
-
matches {
|
|
675
|
-
filePath
|
|
676
|
-
line
|
|
677
|
-
matchStartByte
|
|
678
|
-
matchEndByte
|
|
679
|
-
lineContent
|
|
680
|
-
contextBefore
|
|
681
|
-
contextAfter
|
|
682
|
-
fileContentHash
|
|
683
|
-
fileIntent
|
|
684
|
-
symbolRowId${symbolBlock}
|
|
685
|
-
}
|
|
686
|
-
nextCursor
|
|
687
|
-
totalMatches
|
|
688
|
-
hasMore
|
|
689
|
-
truncatedReason
|
|
690
|
-
routeTaken
|
|
691
|
-
filesScanned
|
|
692
|
-
filesInScope
|
|
693
|
-
binaryFilesSkipped
|
|
694
|
-
filesTooLargeSkipped
|
|
695
|
-
uniqueFilesMatched
|
|
696
|
-
indexedVersion
|
|
697
|
-
resolution {
|
|
698
|
-
requestedVersion
|
|
748
|
+
pages {
|
|
749
|
+
id
|
|
750
|
+
docsReadTarget
|
|
751
|
+
title
|
|
752
|
+
slug
|
|
753
|
+
order
|
|
754
|
+
linkName
|
|
755
|
+
lastUpdatedAt
|
|
756
|
+
sourceKind
|
|
757
|
+
sourceUrl
|
|
758
|
+
repoUrl
|
|
759
|
+
gitRef
|
|
699
760
|
requestedRef
|
|
700
|
-
|
|
701
|
-
commitSha
|
|
702
|
-
}
|
|
703
|
-
${TARGET_RESOLUTION_SELECTION}
|
|
704
|
-
codeIndexState
|
|
705
|
-
indexingRef
|
|
706
|
-
availableVersions {
|
|
707
|
-
version
|
|
708
|
-
ref
|
|
709
|
-
}
|
|
710
|
-
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
711
|
-
}
|
|
712
|
-
}`}var unifiedSearchGraphQLResponseSchema=z3.object({data:z3.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z3.object({data:z3.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl{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,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,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,executeWithToken:(token)=>this.executeUnifiedSearch(token,params,options)})}async searchStatus(searchRef,waitTimeoutMs=0,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options)})}async codeDiff(params){validateCodeDiffParams(params);return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeCodeDiff(token,params)})}async executeCodeDiff(token,params){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})}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 CodeDiffError(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 AuthenticationError(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 CodeDiffError(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??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs,includeFocusedSource:options?.omitFocusedSource!==true};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})}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,variables:{searchRef,includeResults:true,waitTimeoutMs,includeFocusedSource:options?.omitFocusedSource!==true}})}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){const status=response.status;const detail=parseDetail(response.responseBody);if(status===401){return new AuthenticationError(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)}createTransportError(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})}createGraphQLError(errors){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,this.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(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(this.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,appendIndexingWaitHint(message,typeof extensions?.hint==="string"?extensions.hint:undefined));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,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions),errorMetadata);case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions),errorMetadata);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 AuthenticationError(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)}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)=>({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,summary:entry.summary??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined,summary:entry.highlights.summary??undefined}:undefined,repositoryEvidence:entry.repositoryEvidence,documentationPreview:entry.documentationPreview,contentSafety:entry.contentSafety,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)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError(`Target is indexing. ${INDEXING_WAIT_HINT}`,data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate)}}async listFiles(params){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({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}}async readFile(params){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({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{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)}}async grepRepo(params){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({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)}}}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"&¶msRecord.mode!=="stats"&¶msRecord.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 parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}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 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}}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}function appendIndexingWaitHint(message,backendHint){const hintAlreadyInMessage=Boolean(backendHint&&message.includes(backendHint));const existingGuidance=`${message} ${backendHint??""}`;if(/(?:--wait\b|wait_timeout_ms|waitTimeoutMs)/i.test(existingGuidance)){return hintAlreadyInMessage?undefined:backendHint}return backendHint&&!hintAlreadyInMessage?`${backendHint} ${INDEXING_WAIT_HINT}`:INDEXING_WAIT_HINT}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}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.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 z4}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;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;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 PackageIntelligenceVersionNotFoundError extends Error{packageName;requestedVersion;availableVersions;constructor(message,packageName,requestedVersion,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.availableVersions=availableVersions;this.name="PackageIntelligenceVersionNotFoundError"}}class MalformedPackageIntelligenceResponseError extends Error{constructor(message){super(message);this.name="MalformedPackageIntelligenceResponseError"}}class PackageIntelligenceChangelogSourceNotFoundError extends Error{constructor(message){super(message);this.name="PackageIntelligenceChangelogSourceNotFoundError"}}var githubRepositorySchema=z4.object({stargazersCount:z4.number().int().nullable().optional(),forksCount:z4.number().int().nullable().optional(),openIssuesCount:z4.number().int().nullable().optional(),archived:z4.boolean().nullable().optional(),language:z4.string().nullable().optional(),topics:z4.array(z4.string()).nullable().optional(),pushedAt:z4.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),description:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),latestVersionPublishedAt:z4.string().nullable().optional(),versionCount:z4.number().int().nullable().optional(),downloadsRefreshedAt:z4.string().nullable().optional(),homepage:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),license:z4.string().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),publishedAt:z4.string().nullable().optional()});var packageSecurityOverviewSchema=z4.object({vulnerabilityCount:z4.number().int().nullable().optional(),allVulnerabilityCount:z4.number().int(),hasCurrentVulnerabilities:z4.boolean().nullable().optional(),recentVulnerabilities:z4.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z4.object({version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),body:z4.string().nullable().optional()});var packageSummaryResponseSchema=z4.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z4.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});var graphQLResponseSchema=z4.object({data:z4.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
|
|
713
|
-
query PackageSummary(
|
|
714
|
-
$registry: Registry!
|
|
715
|
-
$name: String!
|
|
716
|
-
$includeVerboseFields: Boolean! = true
|
|
717
|
-
) {
|
|
718
|
-
packageSummary(registry: $registry, name: $name) {
|
|
719
|
-
package {
|
|
720
|
-
name
|
|
721
|
-
registry
|
|
722
|
-
description
|
|
723
|
-
latestVersion
|
|
724
|
-
latestVersionPublishedAt
|
|
725
|
-
homepage
|
|
726
|
-
repositoryUrl
|
|
727
|
-
license
|
|
728
|
-
downloadsLastMonth
|
|
729
|
-
downloadsTotal
|
|
730
|
-
versionCount @include(if: $includeVerboseFields)
|
|
731
|
-
downloadsRefreshedAt @include(if: $includeVerboseFields)
|
|
732
|
-
githubRepository {
|
|
733
|
-
stargazersCount
|
|
734
|
-
forksCount
|
|
735
|
-
openIssuesCount
|
|
736
|
-
archived
|
|
737
|
-
language @include(if: $includeVerboseFields)
|
|
738
|
-
topics @include(if: $includeVerboseFields)
|
|
739
|
-
pushedAt @include(if: $includeVerboseFields)
|
|
740
|
-
}
|
|
761
|
+
filePath
|
|
741
762
|
}
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
recentVulnerabilities @include(if: $includeVerboseFields) {
|
|
747
|
-
osvId
|
|
748
|
-
summary
|
|
749
|
-
severityScore
|
|
750
|
-
publishedAt
|
|
751
|
-
}
|
|
763
|
+
pageInfo {
|
|
764
|
+
hasNextPage
|
|
765
|
+
endCursor
|
|
766
|
+
totalCount
|
|
752
767
|
}
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
768
|
+
}
|
|
769
|
+
}`;var READ_PACKAGE_DOC_QUERY=`
|
|
770
|
+
query ReadPackageDoc($pageId: String!) {
|
|
771
|
+
getDocPage(pageId: $pageId) {
|
|
772
|
+
registry
|
|
773
|
+
packageName
|
|
774
|
+
version
|
|
775
|
+
sourceKind
|
|
776
|
+
page {
|
|
777
|
+
id
|
|
778
|
+
docsReadTarget
|
|
779
|
+
title
|
|
780
|
+
content
|
|
781
|
+
contentFormat
|
|
782
|
+
breadcrumbs
|
|
783
|
+
linkName
|
|
784
|
+
lastUpdatedAt
|
|
785
|
+
sourceKind
|
|
786
|
+
source {
|
|
787
|
+
url
|
|
788
|
+
label
|
|
789
|
+
}
|
|
790
|
+
repoUrl
|
|
791
|
+
gitRef
|
|
792
|
+
requestedRef
|
|
793
|
+
filePath
|
|
794
|
+
baseUrl
|
|
757
795
|
}
|
|
758
796
|
}
|
|
759
|
-
}`;var packageVersionIdentitySchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),deprecated:z4.boolean().nullable().optional(),deprecationReason:z4.string().nullable().optional()});var vulnerabilityDetailSchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),severityType:z4.string().nullable().optional(),affectedVersionRanges:z4.array(z4.string()).nullable().optional(),affectedVersionRangesCount:z4.number().int(),affectedVersionRangesTruncated:z4.boolean(),fixedInVersions:z4.array(z4.string()).nullable().optional(),publishedAt:z4.string().nullable().optional(),modifiedAt:z4.string().nullable().optional(),withdrawnAt:z4.string().nullable().optional(),aliases:z4.array(z4.string()).nullable().optional(),isMalicious:z4.boolean().nullable().optional(),affectsInspectedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),duplicateIds:z4.array(z4.string())});var pageInfoSchema=z4.object({hasNextPage:z4.boolean(),endCursor:z4.string().nullable().optional(),totalCount:z4.number().int()});var vulnerabilityAdvisoryPageSchema=z4.object({entries:z4.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z4.object({affectedVulnerabilityCount:z4.number().int(),nonAffectingVulnerabilityCount:z4.number().int(),allVulnerabilityCount:z4.number().int(),currentVersionAffected:z4.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z4.array(z4.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z4.object({data:z4.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var transitiveAuditAdvisorySchema=z4.object({osvId:z4.string().nullable().optional(),summary:z4.string().nullable().optional(),severityScore:z4.number().nullable().optional(),affectedVersionRanges:z4.array(z4.string()).nullable().optional(),fixedInVersions:z4.array(z4.string()).nullable().optional(),publishedAt:z4.string().nullable().optional(),modifiedAt:z4.string().nullable().optional(),aliases:z4.array(z4.string()).nullable().optional(),isMalicious:z4.boolean().nullable().optional()});var transitiveAuditOccurrenceSchema=z4.object({version:z4.string(),affectsResolvedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),fixVersionsAboveResolved:z4.array(z4.string()),nearestFixedVersion:z4.string().nullable().optional(),advisory:transitiveAuditAdvisorySchema});var transitiveAuditPackageSchema=z4.object({registry:z4.string(),name:z4.string(),selectedCount:z4.number().int().nonnegative(),advisoryOccurrences:z4.array(transitiveAuditOccurrenceSchema).nullable().optional()});var transitiveAuditSummarySchema=z4.object({selected:z4.object({totalVulnerabilities:z4.number().int().nonnegative()}),totalPackagesAnalyzed:z4.number().int().nonnegative(),packages:z4.array(transitiveAuditPackageSchema),calculatedAt:z4.string().nullable().optional()});var transitiveAuditResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:z4.object({transitive:z4.object({vulnerabilitySummary:transitiveAuditSummarySchema.nullable().optional()}).nullable().optional()}).nullable().optional()});var transitiveAuditGraphQLResponseSchema=z4.object({data:z4.object({packageDependencies:transitiveAuditResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
|
|
760
|
-
query
|
|
761
|
-
$registry: Registry!
|
|
797
|
+
}`;class PackageIntelligenceServiceImpl{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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){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},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.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);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)}return report}async fetchPackageVulnerabilitiesPage(token,params,after){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},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};const security=data.security?{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,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async fetchTransitiveVulnerabilityAudit(token,directIdentity,minSeverity,advisoryScope,params){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},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 packages=summary.packages.filter((pkg)=>pkg.selectedCount>0).map((pkg)=>{const occurrences=pkg.advisoryOccurrences??[];if(occurrences.length!==pkg.selectedCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit package occurrence count differs from selected count.")}return{registry:pkg.registry,name:pkg.name,occurrenceCount:pkg.selectedCount,occurrences:occurrences.map((occurrence)=>{const isAffected=occurrence.affectsResolvedVersion;if(advisoryScope==="AFFECTED"&&!isAffected||advisoryScope==="NON_AFFECTING"&&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,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.selected.totalVulnerabilities;if(normalisedOccurrenceCount!==occurrenceCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence count differs from selected total.")}return{advisoryScope,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,packageCount:packages.length,occurrenceCount,calculatedAt:summary.calculatedAt??undefined,packages}}async packageDependencies(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},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.")}return stripNullProperties(data)}async executePackageUpgradeDependencyProbe(token,params){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},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){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&¶ms.lifecycle.length>0?params.lifecycle:undefined},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};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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},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=changelogGraphQLResponseSchema.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?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&¶ms.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){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},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,pages:data.pages?.map((page)=>({id:page.id??undefined,docsReadTarget:page.docsReadTarget,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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},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 this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??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 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=parseDetail(response.responseBody);if(status===401){return new AuthenticationError(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=getPrimaryExtensions(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":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError(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 parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function getPrimaryExtensions(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function parseVersionList(raw){if(!Array.isArray(raw))return;const versions=[];for(const item of raw){if(typeof item==="string"&&item.length>0){versions.push(item)}}return versions.length>0?versions:undefined}var latestVersionMaliciousEvidenceSchema=z3.object({advisories:z3.array(z3.object({osvId:z3.string(),classificationReasons:z3.array(z3.string())})).max(5),totalCount:z3.number().int().nonnegative(),truncated:z3.boolean()}).nullable();var compactMatchSchema=z3.object({confidence:z3.string()});var candidateEvidenceSchema=z3.object({canonicalKey:z3.string(),nameSimilarity:z3.number().nullable()});var detailedMatchSchema=compactMatchSchema.extend({matchedAliases:z3.array(z3.string()),matchTier:z3.number().int(),score:z3.number()});var listTargetSchema=z3.object({kind:z3.string(),canonicalKey:z3.string(),latestVersionMaliciousStatus:z3.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z3.string().nullable().optional(),repositoryUrl:z3.string().nullable().optional(),stars:z3.number().int().nullable().optional(),downloadsLastMonth:z3.number().int().nullable().optional(),downloadsTotal:z3.number().int().nullable().optional(),docsAvailable:z3.boolean(),codeAvailable:z3.boolean(),groupKey:z3.string().nullable(),match:compactMatchSchema.nullable(),docsPageCount:z3.number().int().nullable(),codeFileCount:z3.number().int().nullable(),license:z3.string().nullable()});var targetReferenceSchema=z3.object({kind:z3.string(),canonicalKey:z3.string(),confidence:z3.string()});var detailedTargetSchema=listTargetSchema.omit({match:true}).extend({match:detailedMatchSchema.nullable(),displayName:z3.string(),registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),latestVersion:z3.string().nullable().optional(),repositoryOwner:z3.string().nullable().optional(),repositoryName:z3.string().nullable().optional(),documentationUrl:z3.string().nullable().optional()});var graphQLErrorSchema2=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});function responseSchema(targetSchema,includeNameSimilarity){const resultSchema=z3.object({best:targetReferenceSchema.nullable(),protectedMatches:z3.array(targetReferenceSchema),candidates:includeNameSimilarity?z3.array(candidateEvidenceSchema):z3.array(candidateEvidenceSchema).optional(),targets:z3.array(targetSchema),targetsTruncated:z3.boolean(),ambiguous:z3.boolean(),ambiguousReason:z3.string()});return z3.object({data:z3.object({resolveTarget:resultSchema.nullable()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()})}var RESOLVE_TARGET_QUERY=`
|
|
798
|
+
query ResolveTarget(
|
|
762
799
|
$name: String!
|
|
763
|
-
$
|
|
764
|
-
$
|
|
765
|
-
$
|
|
766
|
-
$
|
|
767
|
-
$
|
|
800
|
+
$query: String
|
|
801
|
+
$registries: [Registry!]
|
|
802
|
+
$preferredKinds: [TargetResolutionKind!]
|
|
803
|
+
$intentHints: [String!]
|
|
804
|
+
$limit: Int!
|
|
805
|
+
$includeDetailedFields: Boolean!
|
|
806
|
+
$includeNameSimilarity: Boolean!
|
|
768
807
|
) {
|
|
769
|
-
|
|
770
|
-
registry: $registry
|
|
808
|
+
resolveTarget(
|
|
771
809
|
name: $name
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
810
|
+
query: $query
|
|
811
|
+
registries: $registries
|
|
812
|
+
preferredKinds: $preferredKinds
|
|
813
|
+
intentHints: $intentHints
|
|
814
|
+
limit: $limit
|
|
775
815
|
) {
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
registry
|
|
779
|
-
version
|
|
816
|
+
best {
|
|
817
|
+
...ResolveTargetReferenceFields
|
|
780
818
|
}
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
affectedVersionRangesTruncated
|
|
796
|
-
fixedInVersions
|
|
797
|
-
publishedAt
|
|
798
|
-
modifiedAt
|
|
799
|
-
withdrawnAt
|
|
800
|
-
aliases
|
|
801
|
-
isMalicious
|
|
802
|
-
affectsInspectedVersion
|
|
803
|
-
matchedAffectedVersionRanges
|
|
804
|
-
duplicateIds
|
|
805
|
-
}
|
|
806
|
-
pageInfo {
|
|
807
|
-
hasNextPage
|
|
808
|
-
endCursor
|
|
809
|
-
totalCount
|
|
810
|
-
}
|
|
819
|
+
protectedMatches {
|
|
820
|
+
...ResolveTargetReferenceFields
|
|
821
|
+
}
|
|
822
|
+
candidates @include(if: $includeNameSimilarity) {
|
|
823
|
+
canonicalKey
|
|
824
|
+
nameSimilarity
|
|
825
|
+
}
|
|
826
|
+
targetsTruncated
|
|
827
|
+
targets {
|
|
828
|
+
...ResolveTargetListFields
|
|
829
|
+
...ResolveTargetJsonFields @include(if: $includeDetailedFields)
|
|
830
|
+
match {
|
|
831
|
+
confidence
|
|
832
|
+
...ResolveTargetMatchJsonFields @include(if: $includeDetailedFields)
|
|
811
833
|
}
|
|
812
834
|
}
|
|
835
|
+
ambiguous
|
|
836
|
+
ambiguousReason
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
fragment ResolveTargetReferenceFields on TargetResolutionCandidate {
|
|
841
|
+
kind
|
|
842
|
+
canonicalKey
|
|
843
|
+
confidence
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
fragment ResolveTargetListFields on TargetResolutionTarget {
|
|
847
|
+
kind
|
|
848
|
+
canonicalKey
|
|
849
|
+
latestVersionMaliciousStatus
|
|
850
|
+
latestVersionMaliciousEvidence {
|
|
851
|
+
advisories {
|
|
852
|
+
osvId
|
|
853
|
+
classificationReasons
|
|
854
|
+
}
|
|
855
|
+
totalCount
|
|
856
|
+
truncated
|
|
857
|
+
}
|
|
858
|
+
description
|
|
859
|
+
repositoryUrl
|
|
860
|
+
stars
|
|
861
|
+
downloadsLastMonth
|
|
862
|
+
downloadsTotal
|
|
863
|
+
docsAvailable
|
|
864
|
+
codeAvailable
|
|
865
|
+
groupKey
|
|
866
|
+
docsPageCount
|
|
867
|
+
codeFileCount
|
|
868
|
+
license
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
fragment ResolveTargetJsonFields on TargetResolutionTarget {
|
|
872
|
+
displayName
|
|
873
|
+
registry
|
|
874
|
+
packageName
|
|
875
|
+
latestVersion
|
|
876
|
+
repositoryOwner
|
|
877
|
+
repositoryName
|
|
878
|
+
documentationUrl
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
fragment ResolveTargetMatchJsonFields on TargetResolutionMatch {
|
|
882
|
+
matchedAliases
|
|
883
|
+
matchTier
|
|
884
|
+
score
|
|
885
|
+
}`;class ResolveTargetServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async resolveTarget(params){return withServiceDiagnostics(this.runtime.diagnostics,"resolve-target.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeResolveTarget(token,params)}))}async executeResolveTarget(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:RESOLVE_TARGET_QUERY,variables:buildVariables(params),fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw createPackageIntelligenceTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw createPackageIntelligenceHttpError(response)}const parsed=(params.includeDetailedFields?responseSchema(detailedTargetSchema,params.includeNameSimilarity):responseSchema(listTargetSchema,params.includeNameSimilarity)).safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the target-resolution service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw createPackageIntelligenceGraphQLError(parsed.data.errors,this.runtime.clientVersion,this.runtime.diagnostics)}const result=parsed.data.data?.resolveTarget;if(!result){throw new MalformedPackageIntelligenceResponseError("Empty response from the target-resolution service.")}const nameSimilarityByCanonicalKey=new Map((result.candidates??[]).map((candidate)=>[candidate.canonicalKey,candidate.nameSimilarity]));return{best:result.best?normaliseReference(result.best):undefined,protectedMatches:result.protectedMatches.map(normaliseReference),targets:result.targets.map((target)=>normaliseTarget(target,nameSimilarityByCanonicalKey.get(target.canonicalKey))),targetsTruncated:result.targetsTruncated,ambiguous:result.ambiguous,ambiguousReason:result.ambiguousReason}}}function parseCompactResolveTargetResult(value){const parsed=responseSchema(listTargetSchema,false).safeParse({data:{resolveTarget:value}});if(!parsed.success||!parsed.data.data?.resolveTarget)return;const result=parsed.data.data.resolveTarget;return{best:result.best?normaliseReference(result.best):undefined,protectedMatches:result.protectedMatches.map(normaliseReference),targets:result.targets.map((target)=>normaliseTarget(target,undefined)),targetsTruncated:result.targetsTruncated,ambiguous:result.ambiguous,ambiguousReason:result.ambiguousReason}}function normaliseReference(target){return{kind:target.kind,canonicalKey:target.canonicalKey,confidence:target.confidence}}function buildVariables(params){const variables={name:params.name,limit:params.limit,includeDetailedFields:params.includeDetailedFields,includeNameSimilarity:params.includeNameSimilarity};if(params.query!==undefined)variables.query=params.query;if(params.registries!==undefined)variables.registries=params.registries;if(params.preferredKinds!==undefined){variables.preferredKinds=params.preferredKinds}if(params.intentHints!==undefined)variables.intentHints=params.intentHints;return variables}function normaliseTarget(target,nameSimilarity){const result={kind:target.kind,canonicalKey:target.canonicalKey,latestVersionMaliciousStatus:target.latestVersionMaliciousStatus,docsAvailable:target.docsAvailable,codeAvailable:target.codeAvailable};assignDefined(result,"description",target.description);assignDefined(result,"latestVersionMaliciousEvidence",target.latestVersionMaliciousEvidence);assignDefined(result,"repositoryUrl",target.repositoryUrl);assignDefined(result,"stars",target.stars);assignDefined(result,"downloadsLastMonth",target.downloadsLastMonth);assignDefined(result,"downloadsTotal",target.downloadsTotal);assignDefined(result,"groupKey",target.groupKey);assignDefined(result,"docsPageCount",target.docsPageCount);assignDefined(result,"codeFileCount",target.codeFileCount);assignDefined(result,"license",target.license);if(target.match){const match={confidence:target.match.confidence};assignDefined(match,"nameSimilarity",nameSimilarity);if("matchedAliases"in target.match){assignDefined(match,"matchedAliases",target.match.matchedAliases);assignDefined(match,"matchTier",target.match.matchTier);assignDefined(match,"score",target.match.score)}result.match=match}if("displayName"in target){assignDefined(result,"displayName",target.displayName);assignDefined(result,"registry",target.registry);assignDefined(result,"packageName",target.packageName);assignDefined(result,"latestVersion",target.latestVersion);assignDefined(result,"repositoryOwner",target.repositoryOwner);assignDefined(result,"repositoryName",target.repositoryName);assignDefined(result,"documentationUrl",target.documentationUrl)}return result}function assignDefined(target,key,value){if(value!==null&&value!==undefined)target[key]=value}var AGENTIC_ASK_REQUEST_TIMEOUT_MS=210000;var AGENTIC_ASK_MAX_RESPONSE_BYTES=4*1024*1024;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;var sourceLineRangeSchema=z4.string().regex(/^\d+-\d+$/);var cliSourceArgumentsSchema=z4.union([z4.tuple([z4.literal("githits@latest"),z4.literal("code"),z4.literal("read"),z4.literal("--lines"),sourceLineRangeSchema,z4.literal("--"),z4.string().min(1),z4.string().min(1)]),z4.tuple([z4.literal("githits@latest"),z4.literal("docs"),z4.literal("read"),z4.literal("--lines"),sourceLineRangeSchema,z4.literal("--"),z4.string().min(1)])]);var cliSourceCallSchema=z4.object({command:z4.literal("npx"),arguments:cliSourceArgumentsSchema});var cliResponseSchema=z4.object({source_format:z4.literal("cli"),tool_call_id:z4.string().regex(UUID_V7_PATTERN),thread_id:z4.string().regex(UUID_V7_PATTERN),answer_markdown:z4.string().min(1),sources:z4.array(cliSourceCallSchema)});var needsTargetResponseSchema=z4.object({outcome:z4.literal("needs_target"),message:z4.string().min(1),resolution:z4.unknown()});var mcpCodeReadSourceCallSchema=z4.object({name:z4.literal("code_read"),arguments:z4.object({target:z4.string().min(1),path:z4.string().min(1),start_line:z4.number().int().min(1),end_line:z4.number().int().min(1)})});var mcpDocumentationReadSourceCallSchema=z4.object({name:z4.literal("docs_read"),arguments:z4.object({page_id:z4.string().min(1),start_line:z4.number().int().min(1),end_line:z4.number().int().min(1)})});var mcpResponseSchema=z4.object({source_format:z4.literal("mcp"),tool_call_id:z4.string().regex(UUID_V7_PATTERN),thread_id:z4.string().regex(UUID_V7_PATTERN),answer_markdown:z4.string().min(1),sources:z4.array(z4.discriminatedUnion("name",[mcpCodeReadSourceCallSchema,mcpDocumentationReadSourceCallSchema]))});var upstreamUrlSchema=z4.string().refine((value)=>value===value.trim()&&!hasControlCharacters(value)).pipe(z4.string().url()).refine((value)=>{if(!URL.canParse(value))return false;const protocol=new URL(value).protocol;return protocol==="http:"||protocol==="https:"});var urlResponseSchema=z4.object({source_format:z4.literal("url"),tool_call_id:z4.string().regex(UUID_V7_PATTERN),thread_id:z4.string().regex(UUID_V7_PATTERN),answer_markdown:z4.string().min(1),sources:z4.array(z4.object({url:upstreamUrlSchema}))});class AgenticAskHttpError extends Error{code;status;toolCallId;retryAfterSeconds;threadId;retryable;constructor(code,message,status,toolCallId,retryAfterSeconds,retryable=false,threadId){super(message);this.code=code;this.status=status;this.toolCallId=toolCallId;this.retryAfterSeconds=retryAfterSeconds;this.threadId=threadId;this.name="AgenticAskHttpError";this.retryable=retryable}}class AgenticAskRequestTimeoutError extends Error{timeoutMs;constructor(timeoutMs){super("Agentic Ask 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 Agentic Ask response.",{cause:options?.cause});this.name="MalformedAgenticAskResponseError"}}class AgenticAskResponseTooLargeError extends Error{maxBytes;constructor(maxBytes=AGENTIC_ASK_MAX_RESPONSE_BYTES){super("GitHits returned an Agentic Ask response that was too large.");this.maxBytes=maxBytes;this.name="AgenticAskResponseTooLargeError"}}class AgenticAskServiceImpl{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_MS))}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=parseAgenticAskToolCallId(response.headers.get("X-GitHits-Tool-Call-Id"));const threadId=normalizeAgenticAskThreadId(response.headers.get("X-GitHits-Thread-Id"));if(!response.ok){if(response.status===403){let body="";try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted)throw signal.reason??cause}throwIfTermsAcceptanceRequired(body)}else{await response.body?.cancel().catch(()=>{return})}throw createHttpError(response,toolCallId,threadId,request)}let body;try{body=await readBoundedResponseBody(response)}catch(cause){if(signal.aborted||cause instanceof AgenticAskResponseTooLargeError){throw cause}throw new AgenticAskConnectionError({cause})}let raw;try{raw=JSON.parse(body)}catch(cause){throw new MalformedAgenticAskResponseError({cause})}const clarification=needsTargetResponseSchema.safeParse(raw);if(clarification.success){const resolution=parseCompactResolveTargetResult(clarification.data.resolution);if(!resolution||request.target!==undefined||request.threadId!==undefined){throw new MalformedAgenticAskResponseError}return{outcome:"needs_target",message:clarification.data.message,resolution}}const responseSchema=request.sourceFormat==="mcp"?mcpResponseSchema:request.sourceFormat==="url"?urlResponseSchema:cliResponseSchema;const parsed=responseSchema.safeParse(raw);if(!parsed.success){throw new MalformedAgenticAskResponseError({cause:parsed.error})}return parsed.data}}function parseAgenticAskToolCallId(value){return normalizeUuidV7(value)}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){const declaredLength=response.headers.get("Content-Length");if(isDeclaredBodyTooLarge(declaredLength)){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>AGENTIC_ASK_MAX_RESPONSE_BYTES){await reader.cancel().catch(()=>{return});throw new AgenticAskResponseTooLargeError}text+=decoder.decode(value,{stream:true})}return text+decoder.decode()}finally{reader.releaseLock()}}function isDeclaredBodyTooLarge(value){if(!value||!/^\d+$/.test(value))return false;try{return BigInt(value)>BigInt(AGENTIC_ASK_MAX_RESPONSE_BYTES)}catch{return false}}function createHttpError(response,toolCallId,threadId,request){const status=response.status;switch(status){case 400:return new AgenticAskHttpError("INVALID_TARGET",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 rejected the Agentic Ask target.",status,toolCallId,undefined,false,threadId);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 Agentic Ask is denied.",status,toolCallId,undefined,false,threadId);case 404:return new AgenticAskHttpError("THREAD_NOT_FOUND","Agentic Ask thread was not found.",status,toolCallId,undefined,false,threadId);case 409:return new AgenticAskHttpError("INVALID_REQUEST","This Agentic Ask thread cannot accept another follow-up.",status,toolCallId,undefined,false,threadId);case 422:return new AgenticAskHttpError("INVALID_REQUEST","GitHits rejected the Agentic Ask request.",status,toolCallId,undefined,false,threadId);case 429:return new AgenticAskHttpError("RATE_LIMITED","Agentic Ask is rate limited.",status,toolCallId,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()),true,threadId);case 500:return new AgenticAskHttpError("EXECUTION_FAILED","Agentic Ask failed.",status,toolCallId,undefined,false,threadId);case 503:return new AgenticAskHttpError("SERVICE_UNAVAILABLE","Agentic Ask is temporarily unavailable.",status,toolCallId,undefined,true,threadId);case 504:return new AgenticAskHttpError("TIMEOUT","Agentic Ask timed out.",status,toolCallId,undefined,true,threadId);default:return new AgenticAskHttpError("HTTP_ERROR",`Agentic Ask 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"}import{z as z5}from"zod";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_LIST=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry(registry){return registryMap[registry]}function toPkgseerRegistryLowercase(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)}var INDEXING_WAIT_HINT="Wait until ready with CLI `--wait 60000` or MCP `wait_timeout_ms: 60000`.";var GREP_REPO_SYMBOL_FIELDS=["symbol_ref","name","qualified_path","kind","category","arity","is_public","file_path","start_line","end_line","content_hash","parent_path"];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;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;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 CodeDiffError 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{packageName;requestedVersion;latestIndexed;availableVersions;metadata;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions,metadata=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.metadata=metadata;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;metadata;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs,metadata=undefined){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;this.metadata=metadata;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=`
|
|
886
|
+
availableRefs {
|
|
887
|
+
version
|
|
888
|
+
ref
|
|
889
|
+
}`;var TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION=`
|
|
890
|
+
suggestedRefs {
|
|
891
|
+
version
|
|
892
|
+
ref
|
|
893
|
+
}`;var DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION=`
|
|
894
|
+
suggestedRefs {
|
|
895
|
+
version
|
|
896
|
+
ref
|
|
897
|
+
}`;var DOC_COVERAGE_SELECTION=`
|
|
898
|
+
coverage {
|
|
899
|
+
coverageState
|
|
900
|
+
coverageReason
|
|
901
|
+
pagesCrawled
|
|
902
|
+
frontierRemaining
|
|
903
|
+
artifactOverflowPageCount
|
|
904
|
+
estimatedTotalPages
|
|
905
|
+
note
|
|
906
|
+
}`;var DOCUMENTATION_CONTRIBUTORS_SELECTION=`
|
|
907
|
+
contributors {
|
|
908
|
+
kind
|
|
909
|
+
state
|
|
910
|
+
freshness
|
|
911
|
+
resultCount
|
|
912
|
+
repositoryUrl
|
|
913
|
+
commitSha
|
|
914
|
+
siteKey
|
|
915
|
+
siteUrl
|
|
916
|
+
${DOC_COVERAGE_SELECTION}
|
|
917
|
+
}`;var TARGET_RESOLUTION_SELECTION=`
|
|
918
|
+
targetResolution {
|
|
919
|
+
requested {
|
|
920
|
+
kind
|
|
921
|
+
registry
|
|
922
|
+
packageName
|
|
923
|
+
version
|
|
924
|
+
repoUrl
|
|
925
|
+
gitRef
|
|
926
|
+
commitSha
|
|
927
|
+
}
|
|
928
|
+
resolvedRequested {
|
|
929
|
+
kind
|
|
930
|
+
registry
|
|
931
|
+
packageName
|
|
932
|
+
version
|
|
933
|
+
repoUrl
|
|
934
|
+
gitRef
|
|
935
|
+
commitSha
|
|
936
|
+
}
|
|
937
|
+
served {
|
|
938
|
+
kind
|
|
939
|
+
registry
|
|
940
|
+
packageName
|
|
941
|
+
version
|
|
942
|
+
repoUrl
|
|
943
|
+
gitRef
|
|
944
|
+
commitSha
|
|
945
|
+
}
|
|
946
|
+
freshness
|
|
947
|
+
freshnessReason
|
|
948
|
+
indexingRef
|
|
949
|
+
availableVersions {
|
|
950
|
+
version
|
|
951
|
+
ref
|
|
952
|
+
}
|
|
953
|
+
${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
|
|
954
|
+
${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
|
|
955
|
+
}`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
|
|
956
|
+
availableVersions {
|
|
957
|
+
version
|
|
958
|
+
ref
|
|
959
|
+
}`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
|
|
960
|
+
availableVersions {
|
|
961
|
+
version
|
|
962
|
+
ref
|
|
963
|
+
}
|
|
964
|
+
availableRefs {
|
|
965
|
+
version
|
|
966
|
+
ref
|
|
967
|
+
}
|
|
968
|
+
${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
|
|
969
|
+
indexingEstimate {
|
|
970
|
+
lowerSeconds
|
|
971
|
+
upperSeconds
|
|
972
|
+
elapsedSeconds
|
|
973
|
+
sampleCount
|
|
974
|
+
source
|
|
975
|
+
}`;var UNIFIED_SEARCH_LOCATOR_SELECTION=`
|
|
976
|
+
registry
|
|
977
|
+
packageName
|
|
978
|
+
version
|
|
979
|
+
pageId
|
|
980
|
+
docsReadTarget
|
|
981
|
+
sourceKind
|
|
982
|
+
sourceUrl
|
|
983
|
+
repoUrl
|
|
984
|
+
gitRef
|
|
985
|
+
commitSha
|
|
986
|
+
requestedRef
|
|
987
|
+
filePath
|
|
988
|
+
repositoryFilePath
|
|
989
|
+
startLine
|
|
990
|
+
endLine
|
|
991
|
+
evidenceRange {
|
|
992
|
+
startLine
|
|
993
|
+
endLine
|
|
994
|
+
matchLine
|
|
995
|
+
rangeKind
|
|
996
|
+
matchSpansTruncated
|
|
997
|
+
}
|
|
998
|
+
indexedRange {
|
|
999
|
+
startLine
|
|
1000
|
+
endLine
|
|
1001
|
+
}
|
|
1002
|
+
symbolContext {
|
|
1003
|
+
name
|
|
1004
|
+
qualifiedPath
|
|
1005
|
+
kind
|
|
1006
|
+
relation
|
|
1007
|
+
definitionRange {
|
|
1008
|
+
filePath
|
|
1009
|
+
repositoryFilePath
|
|
1010
|
+
startLine
|
|
1011
|
+
endLine
|
|
813
1012
|
}
|
|
814
|
-
}
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
name: $name
|
|
826
|
-
version: $version
|
|
827
|
-
includeTransitive: true
|
|
828
|
-
) {
|
|
829
|
-
package {
|
|
1013
|
+
}
|
|
1014
|
+
fileContentHash
|
|
1015
|
+
symbolRef
|
|
1016
|
+
qualifiedPath
|
|
1017
|
+
kind
|
|
1018
|
+
category
|
|
1019
|
+
language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
|
|
1020
|
+
repositoryEvidence {
|
|
1021
|
+
bm25MatchFields
|
|
1022
|
+
semanticContext {
|
|
1023
|
+
scopes {
|
|
830
1024
|
name
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
}
|
|
840
|
-
totalPackagesAnalyzed
|
|
841
|
-
calculatedAt
|
|
842
|
-
packages {
|
|
843
|
-
registry
|
|
844
|
-
name
|
|
845
|
-
selectedCount: ${fields.packageCount}
|
|
846
|
-
advisoryOccurrences(scope: $scope, minSeverity: $minSeverity) {
|
|
847
|
-
version
|
|
848
|
-
affectsResolvedVersion
|
|
849
|
-
matchedAffectedVersionRanges
|
|
850
|
-
fixVersionsAboveResolved
|
|
851
|
-
nearestFixedVersion
|
|
852
|
-
advisory {
|
|
853
|
-
osvId
|
|
854
|
-
summary
|
|
855
|
-
severityScore
|
|
856
|
-
affectedVersionRanges @include(if: $includeTransitiveAdvisoryDetails)
|
|
857
|
-
fixedInVersions @include(if: $includeTransitiveAdvisoryDetails)
|
|
858
|
-
publishedAt
|
|
859
|
-
modifiedAt
|
|
860
|
-
aliases
|
|
861
|
-
isMalicious
|
|
862
|
-
}
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
1025
|
+
qualifiedPath
|
|
1026
|
+
kind
|
|
1027
|
+
parentQualifiedPath
|
|
1028
|
+
declarationStartLine
|
|
1029
|
+
declarationEndLine
|
|
1030
|
+
parameterNames
|
|
1031
|
+
returnType
|
|
1032
|
+
symbolRef
|
|
867
1033
|
}
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
$registry: Registry!
|
|
872
|
-
$name: String!
|
|
873
|
-
$version: String
|
|
874
|
-
$includeTransitive: Boolean
|
|
875
|
-
$includeTransitiveDetails: Boolean! = true
|
|
876
|
-
$includeDependencyGraph: Boolean! = true
|
|
877
|
-
$includeGroups: Boolean! = true
|
|
878
|
-
$includeDependencyIssues: Boolean! = false
|
|
879
|
-
$maxDepth: Int
|
|
880
|
-
$lifecycle: [String!]
|
|
881
|
-
) {
|
|
882
|
-
packageDependencies(
|
|
883
|
-
registry: $registry
|
|
884
|
-
name: $name
|
|
885
|
-
version: $version
|
|
886
|
-
includeTransitive: $includeTransitive
|
|
887
|
-
maxDepth: $maxDepth
|
|
888
|
-
lifecycle: $lifecycle
|
|
889
|
-
) {
|
|
890
|
-
package {
|
|
891
|
-
name
|
|
1034
|
+
scopeChainTruncated
|
|
1035
|
+
preferredRead {
|
|
1036
|
+
targetLabel
|
|
892
1037
|
registry
|
|
1038
|
+
packageName
|
|
893
1039
|
version
|
|
1040
|
+
repoUrl
|
|
1041
|
+
gitRef
|
|
1042
|
+
commitSha
|
|
1043
|
+
requestedRef
|
|
1044
|
+
filePath
|
|
1045
|
+
repositoryFilePath
|
|
1046
|
+
startLine
|
|
1047
|
+
endLine
|
|
894
1048
|
}
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
packageName
|
|
911
|
-
requiredVersions
|
|
912
|
-
conflictingEdges {
|
|
913
|
-
fromIndex
|
|
914
|
-
toIndex
|
|
915
|
-
versionConstraint
|
|
916
|
-
dependencyType
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
circularDependencyCycles @include(if: $includeTransitiveDetails) {
|
|
920
|
-
cycleStart
|
|
921
|
-
circularPath
|
|
922
|
-
displayChain
|
|
923
|
-
}
|
|
924
|
-
dependencyGraph @include(if: $includeDependencyGraph) {
|
|
925
|
-
formatVersion
|
|
926
|
-
nodes {
|
|
927
|
-
registry
|
|
928
|
-
name
|
|
929
|
-
version
|
|
930
|
-
}
|
|
931
|
-
edges {
|
|
932
|
-
fromIndex
|
|
933
|
-
toIndex
|
|
934
|
-
constraint
|
|
935
|
-
dependencyType
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
dependencyIssues @include(if: $includeDependencyIssues) {
|
|
939
|
-
totalCount
|
|
940
|
-
deprecatedCount
|
|
941
|
-
outdatedCount
|
|
942
|
-
duplicateCount
|
|
943
|
-
conflictCount
|
|
944
|
-
deprecatedPackages {
|
|
945
|
-
registry
|
|
946
|
-
name
|
|
947
|
-
versions
|
|
948
|
-
reasons {
|
|
949
|
-
version
|
|
950
|
-
reason
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
outdatedPackages {
|
|
954
|
-
registry
|
|
955
|
-
name
|
|
956
|
-
latestVersion
|
|
957
|
-
severity
|
|
958
|
-
versions {
|
|
959
|
-
version
|
|
960
|
-
severity
|
|
961
|
-
}
|
|
962
|
-
repositoryUrl
|
|
963
|
-
}
|
|
964
|
-
duplicatePackages {
|
|
965
|
-
registry
|
|
966
|
-
name
|
|
967
|
-
versions
|
|
968
|
-
}
|
|
969
|
-
conflicts {
|
|
970
|
-
registry
|
|
971
|
-
name
|
|
972
|
-
versions
|
|
973
|
-
requiredVersions
|
|
974
|
-
conflictingEdges {
|
|
975
|
-
fromIndex
|
|
976
|
-
toIndex
|
|
977
|
-
versionConstraint
|
|
978
|
-
dependencyType
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
dependencyGroups @include(if: $includeGroups) {
|
|
985
|
-
primaryGroup
|
|
986
|
-
environmentMarkers {
|
|
987
|
-
type
|
|
988
|
-
value
|
|
989
|
-
raw
|
|
990
|
-
}
|
|
991
|
-
groups {
|
|
992
|
-
name
|
|
993
|
-
lifecycle
|
|
994
|
-
conditionType
|
|
995
|
-
conditionValue
|
|
996
|
-
selectionMode
|
|
997
|
-
exclusiveGroup
|
|
998
|
-
fallbackPriority
|
|
999
|
-
compatibleWith
|
|
1000
|
-
defaultEnabled
|
|
1001
|
-
dependencies {
|
|
1002
|
-
name
|
|
1003
|
-
constraint
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1049
|
+
}
|
|
1050
|
+
focusedSource @include(if: $includeFocusedSource) {
|
|
1051
|
+
startLine
|
|
1052
|
+
endLine
|
|
1053
|
+
matchLine
|
|
1054
|
+
rangeKind
|
|
1055
|
+
matchSpansTruncated
|
|
1056
|
+
linesOmittedBefore
|
|
1057
|
+
linesOmittedAfter
|
|
1058
|
+
lines {
|
|
1059
|
+
lineNumber
|
|
1060
|
+
text
|
|
1061
|
+
highlights
|
|
1062
|
+
prefixTruncated
|
|
1063
|
+
suffixTruncated
|
|
1006
1064
|
}
|
|
1007
1065
|
}
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1066
|
+
matchedSource {
|
|
1067
|
+
startLine
|
|
1068
|
+
endLine
|
|
1069
|
+
matchLine
|
|
1070
|
+
rangeKind
|
|
1071
|
+
matchSpansTruncated
|
|
1072
|
+
linesOmittedBefore
|
|
1073
|
+
linesOmittedAfter
|
|
1074
|
+
lines {
|
|
1075
|
+
lineNumber
|
|
1076
|
+
text
|
|
1077
|
+
highlights
|
|
1078
|
+
prefixTruncated
|
|
1079
|
+
suffixTruncated
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
contentSafety {
|
|
1084
|
+
filtered
|
|
1085
|
+
modifications
|
|
1086
|
+
}`;var UNIFIED_SEARCH_QUERY=`
|
|
1087
|
+
query UnifiedSearch(
|
|
1088
|
+
$targets: [SearchPackageInput!]!
|
|
1089
|
+
$query: String!
|
|
1090
|
+
$sources: [DiscoverySearchSource!]
|
|
1091
|
+
$filters: DiscoverySearchFiltersInput
|
|
1092
|
+
$allowPartialResults: Boolean
|
|
1093
|
+
$limit: Int
|
|
1094
|
+
$offset: Int
|
|
1095
|
+
$waitTimeoutMs: Int
|
|
1096
|
+
$includeFocusedSource: Boolean!
|
|
1020
1097
|
) {
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1098
|
+
search(
|
|
1099
|
+
targets: $targets
|
|
1100
|
+
query: $query
|
|
1101
|
+
sources: $sources
|
|
1102
|
+
filters: $filters
|
|
1103
|
+
allowPartialResults: $allowPartialResults
|
|
1104
|
+
limit: $limit
|
|
1105
|
+
offset: $offset
|
|
1106
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
1027
1107
|
) {
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
version
|
|
1049
|
-
}
|
|
1050
|
-
edges {
|
|
1051
|
-
fromIndex
|
|
1052
|
-
toIndex
|
|
1053
|
-
constraint
|
|
1054
|
-
dependencyType
|
|
1055
|
-
}
|
|
1108
|
+
completed
|
|
1109
|
+
searchRef
|
|
1110
|
+
result {
|
|
1111
|
+
query
|
|
1112
|
+
queryWarnings
|
|
1113
|
+
sources
|
|
1114
|
+
results {
|
|
1115
|
+
id
|
|
1116
|
+
resultType
|
|
1117
|
+
targetLabel
|
|
1118
|
+
requestedTargetLabel
|
|
1119
|
+
freshTargetLabel
|
|
1120
|
+
servedTargetLabel
|
|
1121
|
+
freshness
|
|
1122
|
+
title
|
|
1123
|
+
summary
|
|
1124
|
+
score
|
|
1125
|
+
highlights {
|
|
1126
|
+
title
|
|
1127
|
+
summary
|
|
1056
1128
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
critical
|
|
1061
|
-
high
|
|
1062
|
-
medium
|
|
1063
|
-
low
|
|
1064
|
-
unknown
|
|
1065
|
-
}
|
|
1066
|
-
nonAffecting {
|
|
1067
|
-
totalVulnerabilities
|
|
1068
|
-
critical
|
|
1069
|
-
high
|
|
1070
|
-
medium
|
|
1071
|
-
low
|
|
1072
|
-
unknown
|
|
1073
|
-
}
|
|
1074
|
-
combined {
|
|
1075
|
-
totalVulnerabilities
|
|
1076
|
-
critical
|
|
1077
|
-
high
|
|
1078
|
-
medium
|
|
1079
|
-
low
|
|
1080
|
-
unknown
|
|
1081
|
-
}
|
|
1082
|
-
totalPackagesAnalyzed
|
|
1083
|
-
affectedPackageCount
|
|
1084
|
-
calculatedAt
|
|
1085
|
-
packages {
|
|
1086
|
-
registry
|
|
1087
|
-
name
|
|
1088
|
-
versions
|
|
1089
|
-
affectedCount
|
|
1090
|
-
nonAffectingCount
|
|
1091
|
-
totalCount
|
|
1092
|
-
maxSeverityScore
|
|
1093
|
-
maxSeverityLabel
|
|
1094
|
-
advisoryIds(scope: AFFECTED)
|
|
1095
|
-
mostCritical {
|
|
1096
|
-
osvId
|
|
1097
|
-
registry
|
|
1098
|
-
packageName
|
|
1099
|
-
summary
|
|
1100
|
-
severityScore
|
|
1101
|
-
severityType
|
|
1102
|
-
affectedVersionRanges
|
|
1103
|
-
fixedInVersions
|
|
1104
|
-
publishedAt
|
|
1105
|
-
modifiedAt
|
|
1106
|
-
withdrawnAt
|
|
1107
|
-
aliases
|
|
1108
|
-
isMalicious
|
|
1109
|
-
}
|
|
1110
|
-
advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
|
|
1111
|
-
version
|
|
1112
|
-
affectsResolvedVersion
|
|
1113
|
-
matchedAffectedVersionRanges
|
|
1114
|
-
fixVersionsAboveResolved
|
|
1115
|
-
nearestFixedVersion
|
|
1116
|
-
advisory {
|
|
1117
|
-
osvId
|
|
1118
|
-
registry
|
|
1119
|
-
packageName
|
|
1120
|
-
summary
|
|
1121
|
-
severityScore
|
|
1122
|
-
severityType
|
|
1123
|
-
affectedVersionRanges
|
|
1124
|
-
fixedInVersions
|
|
1125
|
-
publishedAt
|
|
1126
|
-
modifiedAt
|
|
1127
|
-
withdrawnAt
|
|
1128
|
-
aliases
|
|
1129
|
-
isMalicious
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1129
|
+
documentationPreview {
|
|
1130
|
+
text
|
|
1131
|
+
highlights
|
|
1133
1132
|
}
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
outdatedCount
|
|
1138
|
-
duplicateCount
|
|
1139
|
-
conflictCount
|
|
1140
|
-
deprecatedPackages {
|
|
1141
|
-
registry
|
|
1142
|
-
name
|
|
1143
|
-
versions
|
|
1144
|
-
reasons {
|
|
1145
|
-
version
|
|
1146
|
-
reason
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
outdatedPackages {
|
|
1150
|
-
registry
|
|
1151
|
-
name
|
|
1152
|
-
latestVersion
|
|
1153
|
-
severity
|
|
1154
|
-
versions {
|
|
1155
|
-
version
|
|
1156
|
-
severity
|
|
1157
|
-
}
|
|
1158
|
-
repositoryUrl
|
|
1159
|
-
}
|
|
1160
|
-
duplicatePackages {
|
|
1161
|
-
registry
|
|
1162
|
-
name
|
|
1163
|
-
versions
|
|
1164
|
-
}
|
|
1165
|
-
conflicts {
|
|
1166
|
-
registry
|
|
1167
|
-
name
|
|
1168
|
-
versions
|
|
1169
|
-
requiredVersions
|
|
1170
|
-
conflictingEdges {
|
|
1171
|
-
fromIndex
|
|
1172
|
-
toIndex
|
|
1173
|
-
versionConstraint
|
|
1174
|
-
dependencyType
|
|
1175
|
-
}
|
|
1176
|
-
}
|
|
1133
|
+
${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
|
|
1134
|
+
locator {
|
|
1135
|
+
${UNIFIED_SEARCH_LOCATOR_SELECTION}
|
|
1177
1136
|
}
|
|
1178
1137
|
}
|
|
1138
|
+
page {
|
|
1139
|
+
offset
|
|
1140
|
+
limit
|
|
1141
|
+
returned
|
|
1142
|
+
hasMore
|
|
1143
|
+
}
|
|
1144
|
+
partialResults
|
|
1145
|
+
evidenceNotice
|
|
1146
|
+
sourceStatus {
|
|
1147
|
+
source
|
|
1148
|
+
targetLabel
|
|
1149
|
+
requestedTargetLabel
|
|
1150
|
+
freshTargetLabel
|
|
1151
|
+
servedTargetLabel
|
|
1152
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
1153
|
+
indexingStatus
|
|
1154
|
+
codeIndexState
|
|
1155
|
+
resultCount
|
|
1156
|
+
appliedFilters
|
|
1157
|
+
ignoredFilters
|
|
1158
|
+
incompatibleFilters
|
|
1159
|
+
appliedQueryFeatures
|
|
1160
|
+
ignoredQueryFeatures
|
|
1161
|
+
incompatibleQueryFeatures
|
|
1162
|
+
suggestedSiteTargets
|
|
1163
|
+
suggestedSiteTargetsTruncated
|
|
1164
|
+
note
|
|
1165
|
+
${DOC_COVERAGE_SELECTION}
|
|
1166
|
+
${DOCUMENTATION_CONTRIBUTORS_SELECTION}
|
|
1167
|
+
}
|
|
1179
1168
|
}
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1169
|
+
progress {
|
|
1170
|
+
searchRef
|
|
1171
|
+
status
|
|
1172
|
+
targetsTotal
|
|
1173
|
+
targetsReady
|
|
1174
|
+
elapsedMs
|
|
1175
|
+
query
|
|
1176
|
+
queryWarnings
|
|
1177
|
+
sources
|
|
1178
|
+
requestedSources
|
|
1179
|
+
targetMode
|
|
1180
|
+
requestedTargets {
|
|
1181
|
+
registry
|
|
1188
1182
|
name
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1183
|
+
version
|
|
1184
|
+
repoUrl
|
|
1185
|
+
gitRef
|
|
1186
|
+
site
|
|
1187
|
+
}
|
|
1188
|
+
filters {
|
|
1189
|
+
fileIntent
|
|
1190
|
+
kind
|
|
1191
|
+
category
|
|
1192
|
+
publicOnly
|
|
1193
|
+
pathPrefix
|
|
1194
|
+
}
|
|
1195
|
+
limit
|
|
1196
|
+
offset
|
|
1197
|
+
targets {
|
|
1198
|
+
requested
|
|
1199
|
+
resolvedRequested
|
|
1200
|
+
served
|
|
1201
|
+
freshness
|
|
1202
|
+
indexingRef
|
|
1203
|
+
requestedRefKind
|
|
1204
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
1205
|
+
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
1206
|
+
${DOC_COVERAGE_SELECTION}
|
|
1201
1207
|
}
|
|
1208
|
+
expiresAt
|
|
1202
1209
|
}
|
|
1203
1210
|
}
|
|
1204
|
-
}`;var
|
|
1205
|
-
query
|
|
1206
|
-
$
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
summary {
|
|
1219
|
-
total
|
|
1220
|
-
withUnknowns
|
|
1221
|
-
withAddedAdvisories
|
|
1222
|
-
withBreakingSignals
|
|
1223
|
-
withDirectDependencyChanges
|
|
1224
|
-
withTransitiveVulnerabilityAdditions
|
|
1225
|
-
}
|
|
1226
|
-
reviews {
|
|
1211
|
+
}`;var UNIFIED_SEARCH_STATUS_QUERY=`
|
|
1212
|
+
query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int, $includeFocusedSource: Boolean!) {
|
|
1213
|
+
discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
|
|
1214
|
+
searchRef
|
|
1215
|
+
status
|
|
1216
|
+
targetsTotal
|
|
1217
|
+
targetsReady
|
|
1218
|
+
elapsedMs
|
|
1219
|
+
query
|
|
1220
|
+
queryWarnings
|
|
1221
|
+
sources
|
|
1222
|
+
requestedSources
|
|
1223
|
+
targetMode
|
|
1224
|
+
requestedTargets {
|
|
1227
1225
|
registry
|
|
1228
1226
|
name
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
...PackageUpgradeAdvisoryFields
|
|
1227
|
+
version
|
|
1228
|
+
repoUrl
|
|
1229
|
+
gitRef
|
|
1230
|
+
site
|
|
1231
|
+
}
|
|
1232
|
+
filters {
|
|
1233
|
+
fileIntent
|
|
1234
|
+
kind
|
|
1235
|
+
category
|
|
1236
|
+
publicOnly
|
|
1237
|
+
pathPrefix
|
|
1238
|
+
}
|
|
1239
|
+
limit
|
|
1240
|
+
offset
|
|
1241
|
+
targets {
|
|
1242
|
+
requested
|
|
1243
|
+
resolvedRequested
|
|
1244
|
+
served
|
|
1245
|
+
freshness
|
|
1246
|
+
indexingRef
|
|
1247
|
+
requestedRefKind
|
|
1248
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
1249
|
+
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
1250
|
+
${DOC_COVERAGE_SELECTION}
|
|
1251
|
+
}
|
|
1252
|
+
expiresAt
|
|
1253
|
+
results {
|
|
1254
|
+
query
|
|
1255
|
+
queryWarnings
|
|
1256
|
+
sources
|
|
1257
|
+
results {
|
|
1258
|
+
id
|
|
1259
|
+
resultType
|
|
1260
|
+
targetLabel
|
|
1261
|
+
requestedTargetLabel
|
|
1262
|
+
freshTargetLabel
|
|
1263
|
+
servedTargetLabel
|
|
1264
|
+
freshness
|
|
1265
|
+
title
|
|
1266
|
+
summary
|
|
1267
|
+
score
|
|
1268
|
+
highlights {
|
|
1269
|
+
title
|
|
1270
|
+
summary
|
|
1274
1271
|
}
|
|
1275
|
-
|
|
1276
|
-
|
|
1272
|
+
documentationPreview {
|
|
1273
|
+
text
|
|
1274
|
+
highlights
|
|
1277
1275
|
}
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
introducedPackages
|
|
1282
|
-
fixedPackages
|
|
1283
|
-
introducedPackageDetails(first: 50) {
|
|
1284
|
-
...PackageUpgradeTransitivePackagePageFields
|
|
1285
|
-
}
|
|
1286
|
-
fixedPackageDetails(first: 50) {
|
|
1287
|
-
...PackageUpgradeTransitivePackagePageFields
|
|
1288
|
-
}
|
|
1289
|
-
stillAffectedPackageDetails(first: 50) {
|
|
1290
|
-
...PackageUpgradeTransitivePackagePageFields
|
|
1291
|
-
}
|
|
1276
|
+
${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
|
|
1277
|
+
locator {
|
|
1278
|
+
${UNIFIED_SEARCH_LOCATOR_SELECTION}
|
|
1292
1279
|
}
|
|
1293
1280
|
}
|
|
1294
|
-
|
|
1281
|
+
page {
|
|
1282
|
+
offset
|
|
1283
|
+
limit
|
|
1284
|
+
returned
|
|
1285
|
+
hasMore
|
|
1286
|
+
}
|
|
1287
|
+
partialResults
|
|
1288
|
+
evidenceNotice
|
|
1289
|
+
sourceStatus {
|
|
1295
1290
|
source
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1291
|
+
targetLabel
|
|
1292
|
+
requestedTargetLabel
|
|
1293
|
+
freshTargetLabel
|
|
1294
|
+
servedTargetLabel
|
|
1295
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
1296
|
+
indexingStatus
|
|
1297
|
+
codeIndexState
|
|
1298
|
+
resultCount
|
|
1299
|
+
appliedFilters
|
|
1300
|
+
ignoredFilters
|
|
1301
|
+
incompatibleFilters
|
|
1302
|
+
appliedQueryFeatures
|
|
1303
|
+
ignoredQueryFeatures
|
|
1304
|
+
incompatibleQueryFeatures
|
|
1305
|
+
suggestedSiteTargets
|
|
1306
|
+
suggestedSiteTargetsTruncated
|
|
1307
|
+
note
|
|
1308
|
+
${DOC_COVERAGE_SELECTION}
|
|
1309
|
+
${DOCUMENTATION_CONTRIBUTORS_SELECTION}
|
|
1313
1310
|
}
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
notes
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
}`;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 indexingDurationEstimateSchema=z5.object({lowerSeconds:z5.number().int().nullable().optional(),upperSeconds:z5.number().int().nullable().optional(),elapsedSeconds:z5.number().int().nullable().optional(),sampleCount:z5.number().int().nullable().optional(),source:z5.string().nullable().optional()}).nullable().optional();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(),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 unifiedSearchFocusedSourceSchema=z5.object({startLine:z5.number().int().positive(),endLine:z5.number().int().positive(),matchLine:z5.number().int().positive().nullable(),rangeKind:z5.string().nullable(),matchSpansTruncated:z5.boolean(),lines:z5.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z5.boolean(),linesOmittedAfter:z5.boolean()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});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({focusedSource:unifiedSearchFocusedSourceSchema.nullable().optional(),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({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(),summary: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(),summary:z5.array(z5.tuple([z5.number().int(),z5.number().int()])).nullable().optional()}).nullable().optional(),repositoryEvidence:unifiedSearchRepositoryEvidenceSchema.nullable().optional(),documentationPreview:unifiedSearchDocumentationPreviewSchema.nullable().optional(),contentSafety:contentSafetySchema.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(),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 graphQLErrorSchema3=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 {
|
|
1314
|
+
registry
|
|
1315
|
+
name
|
|
1316
|
+
repoUrl
|
|
1317
|
+
}
|
|
1318
|
+
fromResolution {
|
|
1319
|
+
requested
|
|
1320
|
+
resolvedVersion
|
|
1321
|
+
ref
|
|
1322
|
+
commitSha
|
|
1323
|
+
refKind
|
|
1324
|
+
versionSource
|
|
1325
|
+
}
|
|
1326
|
+
toResolution {
|
|
1327
|
+
requested
|
|
1328
|
+
resolvedVersion
|
|
1329
|
+
ref
|
|
1330
|
+
commitSha
|
|
1331
|
+
refKind
|
|
1332
|
+
versionSource
|
|
1333
|
+
}
|
|
1334
|
+
raw {
|
|
1335
|
+
summary {
|
|
1336
|
+
filesChanged
|
|
1337
|
+
added
|
|
1338
|
+
deleted
|
|
1339
|
+
modified
|
|
1340
|
+
modeChanged
|
|
1341
|
+
typeChanged
|
|
1342
|
+
inventoryComplete
|
|
1343
|
+
unprojectableFiles
|
|
1317
1344
|
}
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
}
|
|
1345
|
+
scope {
|
|
1346
|
+
status
|
|
1347
|
+
fromSubpath
|
|
1348
|
+
toSubpath
|
|
1349
|
+
pathPrefix
|
|
1350
|
+
pathGlob
|
|
1325
1351
|
}
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1352
|
+
contentCoverage
|
|
1353
|
+
contentFailure {
|
|
1354
|
+
code
|
|
1355
|
+
retryable
|
|
1356
|
+
retryAfterMs
|
|
1357
|
+
stage
|
|
1358
|
+
limitKind
|
|
1333
1359
|
}
|
|
1334
|
-
|
|
1360
|
+
files {
|
|
1361
|
+
path
|
|
1362
|
+
pathEncoding
|
|
1363
|
+
status
|
|
1364
|
+
modeChanged
|
|
1365
|
+
typeChanged
|
|
1366
|
+
contentStatus
|
|
1367
|
+
contentSafety {
|
|
1368
|
+
filtered
|
|
1369
|
+
modifications
|
|
1370
|
+
}`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
|
|
1371
|
+
additions
|
|
1372
|
+
deletions`:`
|
|
1373
|
+
additions
|
|
1374
|
+
deletions
|
|
1375
|
+
patch
|
|
1376
|
+
contentOmissionReason`;return`
|
|
1377
|
+
query CodeDiff(
|
|
1378
|
+
$registry: Registry
|
|
1379
|
+
$name: String
|
|
1380
|
+
$fromVersion: String
|
|
1381
|
+
$toVersion: String
|
|
1382
|
+
$repoUrl: String
|
|
1383
|
+
$fromRef: String
|
|
1384
|
+
$toRef: String
|
|
1385
|
+
$rawOptions: RawCodeDiffOptions
|
|
1386
|
+
) {
|
|
1387
|
+
codeDiff(
|
|
1388
|
+
registry: $registry
|
|
1389
|
+
name: $name
|
|
1390
|
+
fromVersion: $fromVersion
|
|
1391
|
+
toVersion: $toVersion
|
|
1392
|
+
repoUrl: $repoUrl
|
|
1393
|
+
fromRef: $fromRef
|
|
1394
|
+
toRef: $toRef
|
|
1395
|
+
rawOptions: $rawOptions
|
|
1396
|
+
) {
|
|
1397
|
+
${CODE_DIFF_COMMON_SELECTION}${contentFields}
|
|
1398
|
+
}
|
|
1399
|
+
hasMoreFiles
|
|
1335
1400
|
}
|
|
1336
1401
|
}
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
|
|
1340
|
-
id
|
|
1341
|
-
aliases
|
|
1342
|
-
summary
|
|
1343
|
-
severity
|
|
1344
|
-
severityLabel
|
|
1345
|
-
fixedIn
|
|
1346
|
-
isMalicious
|
|
1347
|
-
}
|
|
1348
|
-
|
|
1349
|
-
fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
|
|
1350
|
-
entries {
|
|
1351
|
-
id
|
|
1352
|
-
registry
|
|
1353
|
-
name
|
|
1354
|
-
versions
|
|
1355
|
-
affectedCount
|
|
1356
|
-
maxSeverityScore
|
|
1357
|
-
maxSeverityLabel
|
|
1358
|
-
advisoryIds
|
|
1359
|
-
}
|
|
1360
|
-
totalCount
|
|
1361
|
-
truncated
|
|
1362
|
-
}
|
|
1363
|
-
|
|
1364
|
-
fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
|
|
1365
|
-
version
|
|
1366
|
-
publishedAt
|
|
1367
|
-
htmlUrl
|
|
1368
|
-
body
|
|
1369
|
-
bodyPreview
|
|
1370
|
-
headline
|
|
1371
|
-
signals
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
|
-
fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
|
|
1375
|
-
added {
|
|
1376
|
-
name
|
|
1377
|
-
registry
|
|
1378
|
-
version
|
|
1379
|
-
fromVersions
|
|
1380
|
-
toVersions
|
|
1381
|
-
constraint
|
|
1382
|
-
type
|
|
1383
|
-
}
|
|
1384
|
-
removed {
|
|
1385
|
-
name
|
|
1386
|
-
registry
|
|
1387
|
-
version
|
|
1388
|
-
fromVersions
|
|
1389
|
-
toVersions
|
|
1390
|
-
constraint
|
|
1391
|
-
type
|
|
1392
|
-
}
|
|
1393
|
-
changed {
|
|
1394
|
-
name
|
|
1395
|
-
registry
|
|
1396
|
-
version
|
|
1397
|
-
fromVersions
|
|
1398
|
-
toVersions
|
|
1399
|
-
constraint
|
|
1400
|
-
type
|
|
1401
|
-
}
|
|
1402
|
-
}`;var changelogPackageInfoSchema=z4.object({name:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),repoUrl:z4.string().nullable().optional(),fromVersion:z4.string().nullable().optional(),toVersion:z4.string().nullable().optional(),limit:z4.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z4.object({version:z4.string().nullable().optional(),normalizedVersion:z4.string().nullable().optional(),body:z4.string().nullable().optional(),htmlUrl:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional()});var changelogReportResponseSchema=z4.object({package:changelogPackageInfoSchema,source:z4.string().nullable().optional(),entries:z4.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z4.object({data:z4.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_CHANGELOG_QUERY=`
|
|
1403
|
-
query PackageChangelog(
|
|
1402
|
+
}`}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});var listRepoFilesGraphQLResponseSchema=z5.object({data:z5.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).optional()});var LIST_REPO_FILES_QUERY=`
|
|
1403
|
+
query ListRepoFiles(
|
|
1404
1404
|
$registry: Registry
|
|
1405
|
-
$
|
|
1405
|
+
$packageName: String
|
|
1406
1406
|
$repoUrl: String
|
|
1407
1407
|
$gitRef: String
|
|
1408
|
-
$
|
|
1409
|
-
$
|
|
1408
|
+
$version: String
|
|
1409
|
+
$pathPrefix: String
|
|
1410
|
+
$pathSelectors: [FilePathSelectorInput!]
|
|
1411
|
+
$extensions: [String!]
|
|
1412
|
+
$fileTypes: [String!]
|
|
1413
|
+
$languages: [String!]
|
|
1414
|
+
$fileIntent: FileIntent
|
|
1415
|
+
$fileIntents: [FileIntent!]
|
|
1416
|
+
$excludeFileIntents: [FileIntent!]
|
|
1417
|
+
$excludeDocFiles: Boolean
|
|
1418
|
+
$excludeTestFiles: Boolean
|
|
1419
|
+
$includeHidden: Boolean
|
|
1410
1420
|
$limit: Int
|
|
1411
|
-
$
|
|
1421
|
+
$waitTimeoutMs: Int
|
|
1412
1422
|
) {
|
|
1413
|
-
|
|
1423
|
+
listRepoFiles(
|
|
1424
|
+
registry: $registry
|
|
1425
|
+
packageName: $packageName
|
|
1426
|
+
repoUrl: $repoUrl
|
|
1427
|
+
gitRef: $gitRef
|
|
1428
|
+
version: $version
|
|
1429
|
+
pathPrefix: $pathPrefix
|
|
1430
|
+
pathSelectors: $pathSelectors
|
|
1431
|
+
extensions: $extensions
|
|
1432
|
+
fileTypes: $fileTypes
|
|
1433
|
+
languages: $languages
|
|
1434
|
+
fileIntent: $fileIntent
|
|
1435
|
+
fileIntents: $fileIntents
|
|
1436
|
+
excludeFileIntents: $excludeFileIntents
|
|
1437
|
+
excludeDocFiles: $excludeDocFiles
|
|
1438
|
+
excludeTestFiles: $excludeTestFiles
|
|
1439
|
+
includeHidden: $includeHidden
|
|
1440
|
+
limit: $limit
|
|
1441
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
1442
|
+
) {
|
|
1443
|
+
files {
|
|
1444
|
+
path
|
|
1445
|
+
name
|
|
1446
|
+
language
|
|
1447
|
+
fileType
|
|
1448
|
+
byteSize
|
|
1449
|
+
}
|
|
1450
|
+
total
|
|
1451
|
+
hasMore
|
|
1452
|
+
indexedVersion
|
|
1453
|
+
resolution {
|
|
1454
|
+
requestedVersion
|
|
1455
|
+
requestedRef
|
|
1456
|
+
resolvedRef
|
|
1457
|
+
commitSha
|
|
1458
|
+
}
|
|
1459
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
1460
|
+
diagnostics {
|
|
1461
|
+
hint
|
|
1462
|
+
}
|
|
1463
|
+
codeIndexState
|
|
1464
|
+
indexingRef
|
|
1465
|
+
availableVersions {
|
|
1466
|
+
version
|
|
1467
|
+
ref
|
|
1468
|
+
}
|
|
1469
|
+
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
1470
|
+
}
|
|
1471
|
+
}`;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,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z5.object({data:z5.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).optional()});var FETCH_CODE_CONTEXT_QUERY=`
|
|
1472
|
+
query FetchCodeContext(
|
|
1473
|
+
$registry: Registry
|
|
1474
|
+
$packageName: String
|
|
1475
|
+
$repoUrl: String
|
|
1476
|
+
$gitRef: String
|
|
1477
|
+
$version: String
|
|
1478
|
+
$filePath: String!
|
|
1479
|
+
$startLine: Int
|
|
1480
|
+
$endLine: Int
|
|
1481
|
+
$waitTimeoutMs: Int
|
|
1482
|
+
) {
|
|
1483
|
+
fetchCodeContext(
|
|
1414
1484
|
registry: $registry
|
|
1415
|
-
|
|
1485
|
+
packageName: $packageName
|
|
1416
1486
|
repoUrl: $repoUrl
|
|
1417
1487
|
gitRef: $gitRef
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1488
|
+
version: $version
|
|
1489
|
+
filePath: $filePath
|
|
1490
|
+
startLine: $startLine
|
|
1491
|
+
endLine: $endLine
|
|
1492
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
1421
1493
|
) {
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
publishedAt
|
|
1437
|
-
}
|
|
1494
|
+
content
|
|
1495
|
+
filePath
|
|
1496
|
+
language
|
|
1497
|
+
totalLines
|
|
1498
|
+
startLine
|
|
1499
|
+
endLine
|
|
1500
|
+
repoUrl
|
|
1501
|
+
gitRef
|
|
1502
|
+
isBinary
|
|
1503
|
+
codeIndexState
|
|
1504
|
+
indexingRef
|
|
1505
|
+
${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
|
|
1506
|
+
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
1507
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
1438
1508
|
}
|
|
1439
|
-
}`;var
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1509
|
+
}`;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});var grepRepoGraphQLResponseSchema=z5.object({data:z5.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).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(`
|
|
1510
|
+
`);const symbolBlock=symbolSelection.length>0?`
|
|
1511
|
+
symbol {
|
|
1512
|
+
${symbolSelection}
|
|
1513
|
+
}`:"";return`
|
|
1514
|
+
query GrepRepo(
|
|
1515
|
+
$registry: Registry
|
|
1516
|
+
$packageName: String
|
|
1517
|
+
$repoUrl: String
|
|
1518
|
+
$gitRef: String
|
|
1443
1519
|
$version: String
|
|
1444
|
-
$
|
|
1445
|
-
$
|
|
1520
|
+
$waitTimeoutMs: Int
|
|
1521
|
+
$pattern: String!
|
|
1522
|
+
$patternType: GrepPatternType
|
|
1523
|
+
$caseSensitive: Boolean
|
|
1524
|
+
$pathSelectors: [GrepPathSelectorInput!]
|
|
1525
|
+
$extensions: [String!]
|
|
1526
|
+
$excludeDocFiles: Boolean
|
|
1527
|
+
$excludeTestFiles: Boolean
|
|
1528
|
+
$allowUnscoped: Boolean
|
|
1529
|
+
$contextLinesBefore: Int
|
|
1530
|
+
$contextLinesAfter: Int
|
|
1531
|
+
$maxMatches: Int
|
|
1532
|
+
$maxMatchesPerFile: Int
|
|
1533
|
+
$cursor: String
|
|
1534
|
+
$symbolFields: [String!]
|
|
1446
1535
|
) {
|
|
1447
|
-
|
|
1536
|
+
grepRepo(
|
|
1448
1537
|
registry: $registry
|
|
1449
1538
|
packageName: $packageName
|
|
1539
|
+
repoUrl: $repoUrl
|
|
1540
|
+
gitRef: $gitRef
|
|
1450
1541
|
version: $version
|
|
1451
|
-
|
|
1452
|
-
|
|
1542
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
1543
|
+
pattern: $pattern
|
|
1544
|
+
patternType: $patternType
|
|
1545
|
+
caseSensitive: $caseSensitive
|
|
1546
|
+
pathSelectors: $pathSelectors
|
|
1547
|
+
extensions: $extensions
|
|
1548
|
+
excludeDocFiles: $excludeDocFiles
|
|
1549
|
+
excludeTestFiles: $excludeTestFiles
|
|
1550
|
+
allowUnscoped: $allowUnscoped
|
|
1551
|
+
contextLinesBefore: $contextLinesBefore
|
|
1552
|
+
contextLinesAfter: $contextLinesAfter
|
|
1553
|
+
maxMatches: $maxMatches
|
|
1554
|
+
maxMatchesPerFile: $maxMatchesPerFile
|
|
1555
|
+
cursor: $cursor
|
|
1556
|
+
symbolFields: $symbolFields
|
|
1453
1557
|
) {
|
|
1454
|
-
|
|
1455
|
-
packageName
|
|
1456
|
-
version
|
|
1457
|
-
stale
|
|
1458
|
-
pages {
|
|
1459
|
-
id
|
|
1460
|
-
docsReadTarget
|
|
1461
|
-
title
|
|
1462
|
-
slug
|
|
1463
|
-
order
|
|
1464
|
-
linkName
|
|
1465
|
-
lastUpdatedAt
|
|
1466
|
-
sourceKind
|
|
1467
|
-
sourceUrl
|
|
1468
|
-
repoUrl
|
|
1469
|
-
gitRef
|
|
1470
|
-
requestedRef
|
|
1558
|
+
matches {
|
|
1471
1559
|
filePath
|
|
1560
|
+
line
|
|
1561
|
+
matchStartByte
|
|
1562
|
+
matchEndByte
|
|
1563
|
+
lineContent
|
|
1564
|
+
contextBefore
|
|
1565
|
+
contextAfter
|
|
1566
|
+
fileContentHash
|
|
1567
|
+
fileIntent
|
|
1568
|
+
symbolRowId${symbolBlock}
|
|
1472
1569
|
}
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
page {
|
|
1487
|
-
id
|
|
1488
|
-
docsReadTarget
|
|
1489
|
-
title
|
|
1490
|
-
content
|
|
1491
|
-
contentFormat
|
|
1492
|
-
breadcrumbs
|
|
1493
|
-
linkName
|
|
1494
|
-
lastUpdatedAt
|
|
1495
|
-
sourceKind
|
|
1496
|
-
source {
|
|
1497
|
-
url
|
|
1498
|
-
label
|
|
1499
|
-
}
|
|
1500
|
-
repoUrl
|
|
1501
|
-
gitRef
|
|
1570
|
+
nextCursor
|
|
1571
|
+
totalMatches
|
|
1572
|
+
hasMore
|
|
1573
|
+
truncatedReason
|
|
1574
|
+
routeTaken
|
|
1575
|
+
filesScanned
|
|
1576
|
+
filesInScope
|
|
1577
|
+
binaryFilesSkipped
|
|
1578
|
+
filesTooLargeSkipped
|
|
1579
|
+
uniqueFilesMatched
|
|
1580
|
+
indexedVersion
|
|
1581
|
+
resolution {
|
|
1582
|
+
requestedVersion
|
|
1502
1583
|
requestedRef
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
}`;class PackageIntelligenceServiceImpl{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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){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},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.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);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)}return report}async fetchPackageVulnerabilitiesPage(token,params,after){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},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};const security=data.security?{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,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async fetchTransitiveVulnerabilityAudit(token,directIdentity,minSeverity,advisoryScope,params){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},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 packages=summary.packages.filter((pkg)=>pkg.selectedCount>0).map((pkg)=>{const occurrences=pkg.advisoryOccurrences??[];if(occurrences.length!==pkg.selectedCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit package occurrence count differs from selected count.")}return{registry:pkg.registry,name:pkg.name,occurrenceCount:pkg.selectedCount,occurrences:occurrences.map((occurrence)=>{const isAffected=occurrence.affectsResolvedVersion;if(advisoryScope==="AFFECTED"&&!isAffected||advisoryScope==="NON_AFFECTING"&&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,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.selected.totalVulnerabilities;if(normalisedOccurrenceCount!==occurrenceCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence count differs from selected total.")}return{advisoryScope,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,packageCount:packages.length,occurrenceCount,calculatedAt:summary.calculatedAt??undefined,packages}}async packageDependencies(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},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.")}return stripNullProperties(data)}async executePackageUpgradeDependencyProbe(token,params){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},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){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&¶ms.lifecycle.length>0?params.lifecycle:undefined},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};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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},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=changelogGraphQLResponseSchema.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?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&¶ms.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){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},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,pages:data.pages?.map((page)=>({id:page.id??undefined,docsReadTarget:page.docsReadTarget,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){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId},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 this.normalisePackageDocResult(data)}normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??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 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=parseDetail2(response.responseBody);if(status===401){return new AuthenticationError(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":return new PackageIntelligenceVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,parseVersionList(extensions?.available_versions??extensions?.availableVersions));case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new PackageIntelligenceValidationError(message);case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError(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 parseDetail2(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function parseVersionList(raw){if(!Array.isArray(raw))return;const versions=[];for(const item of raw){if(typeof item==="string"&&item.length>0){versions.push(item)}}return versions.length>0?versions:undefined}class RefreshingGitHitsService{apiUrl;tokenProvider;serviceFactory;runtime;constructor(apiUrl,tokenProvider,serviceFactory=undefined,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params,options){return this.withTokenRefresh(options?(service)=>service.search(params,options):(service)=>service.search(params),options)}async getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}async withTokenRefresh(operation,options){return executeWithTokenRefresh({getToken:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.getToken()},forceRefresh:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.forceRefresh()},shouldRefresh:isTokenRefreshableError,executeWithToken:async(token)=>{options?.signal?.throwIfAborted();const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}import{z as z5}from"zod";var latestVersionMaliciousEvidenceSchema=z5.object({advisories:z5.array(z5.object({osvId:z5.string(),classificationReasons:z5.array(z5.string())})).max(5),totalCount:z5.number().int().nonnegative(),truncated:z5.boolean()}).nullable();var compactMatchSchema=z5.object({confidence:z5.string()});var candidateEvidenceSchema=z5.object({canonicalKey:z5.string(),nameSimilarity:z5.number().nullable()});var detailedMatchSchema=compactMatchSchema.extend({matchedAliases:z5.array(z5.string()),matchTier:z5.number().int(),score:z5.number()});var listTargetSchema=z5.object({kind:z5.string(),canonicalKey:z5.string(),latestVersionMaliciousStatus:z5.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z5.string().nullable().optional(),repositoryUrl:z5.string().nullable().optional(),stars:z5.number().int().nullable().optional(),downloadsLastMonth:z5.number().int().nullable().optional(),downloadsTotal:z5.number().int().nullable().optional(),docsAvailable:z5.boolean(),codeAvailable:z5.boolean(),groupKey:z5.string().nullable(),match:compactMatchSchema.nullable(),docsPageCount:z5.number().int().nullable(),codeFileCount:z5.number().int().nullable(),license:z5.string().nullable()});var targetReferenceSchema=z5.object({kind:z5.string(),canonicalKey:z5.string(),confidence:z5.string()});var detailedTargetSchema=listTargetSchema.omit({match:true}).extend({match:detailedMatchSchema.nullable(),displayName:z5.string(),registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),latestVersion:z5.string().nullable().optional(),repositoryOwner:z5.string().nullable().optional(),repositoryName:z5.string().nullable().optional(),documentationUrl:z5.string().nullable().optional()});var graphQLErrorSchema3=z5.object({message:z5.string(),extensions:z5.record(z5.string(),z5.unknown()).optional()});function responseSchema(targetSchema,includeNameSimilarity){const resultSchema=z5.object({best:targetReferenceSchema.nullable(),protectedMatches:z5.array(targetReferenceSchema),candidates:includeNameSimilarity?z5.array(candidateEvidenceSchema):z5.array(candidateEvidenceSchema).optional(),targets:z5.array(targetSchema),targetsTruncated:z5.boolean(),ambiguous:z5.boolean(),ambiguousReason:z5.string()});return z5.object({data:z5.object({resolveTarget:resultSchema.nullable()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).optional()})}var RESOLVE_TARGET_QUERY=`
|
|
1508
|
-
query ResolveTarget(
|
|
1509
|
-
$name: String!
|
|
1510
|
-
$query: String
|
|
1511
|
-
$registries: [Registry!]
|
|
1512
|
-
$preferredKinds: [TargetResolutionKind!]
|
|
1513
|
-
$intentHints: [String!]
|
|
1514
|
-
$limit: Int!
|
|
1515
|
-
$includeDetailedFields: Boolean!
|
|
1516
|
-
$includeNameSimilarity: Boolean!
|
|
1517
|
-
) {
|
|
1518
|
-
resolveTarget(
|
|
1519
|
-
name: $name
|
|
1520
|
-
query: $query
|
|
1521
|
-
registries: $registries
|
|
1522
|
-
preferredKinds: $preferredKinds
|
|
1523
|
-
intentHints: $intentHints
|
|
1524
|
-
limit: $limit
|
|
1525
|
-
) {
|
|
1526
|
-
best {
|
|
1527
|
-
...ResolveTargetReferenceFields
|
|
1528
|
-
}
|
|
1529
|
-
protectedMatches {
|
|
1530
|
-
...ResolveTargetReferenceFields
|
|
1531
|
-
}
|
|
1532
|
-
candidates @include(if: $includeNameSimilarity) {
|
|
1533
|
-
canonicalKey
|
|
1534
|
-
nameSimilarity
|
|
1535
|
-
}
|
|
1536
|
-
targetsTruncated
|
|
1537
|
-
targets {
|
|
1538
|
-
...ResolveTargetListFields
|
|
1539
|
-
...ResolveTargetJsonFields @include(if: $includeDetailedFields)
|
|
1540
|
-
match {
|
|
1541
|
-
confidence
|
|
1542
|
-
...ResolveTargetMatchJsonFields @include(if: $includeDetailedFields)
|
|
1543
|
-
}
|
|
1584
|
+
resolvedRef
|
|
1585
|
+
commitSha
|
|
1544
1586
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
kind
|
|
1552
|
-
canonicalKey
|
|
1553
|
-
confidence
|
|
1554
|
-
}
|
|
1555
|
-
|
|
1556
|
-
fragment ResolveTargetListFields on TargetResolutionTarget {
|
|
1557
|
-
kind
|
|
1558
|
-
canonicalKey
|
|
1559
|
-
latestVersionMaliciousStatus
|
|
1560
|
-
latestVersionMaliciousEvidence {
|
|
1561
|
-
advisories {
|
|
1562
|
-
osvId
|
|
1563
|
-
classificationReasons
|
|
1587
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
1588
|
+
codeIndexState
|
|
1589
|
+
indexingRef
|
|
1590
|
+
availableVersions {
|
|
1591
|
+
version
|
|
1592
|
+
ref
|
|
1564
1593
|
}
|
|
1565
|
-
|
|
1566
|
-
truncated
|
|
1594
|
+
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
1567
1595
|
}
|
|
1568
|
-
description
|
|
1569
|
-
repositoryUrl
|
|
1570
|
-
stars
|
|
1571
|
-
downloadsLastMonth
|
|
1572
|
-
downloadsTotal
|
|
1573
|
-
docsAvailable
|
|
1574
|
-
codeAvailable
|
|
1575
|
-
groupKey
|
|
1576
|
-
docsPageCount
|
|
1577
|
-
codeFileCount
|
|
1578
|
-
license
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
fragment ResolveTargetJsonFields on TargetResolutionTarget {
|
|
1582
|
-
displayName
|
|
1583
|
-
registry
|
|
1584
|
-
packageName
|
|
1585
|
-
latestVersion
|
|
1586
|
-
repositoryOwner
|
|
1587
|
-
repositoryName
|
|
1588
|
-
documentationUrl
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
fragment ResolveTargetMatchJsonFields on TargetResolutionMatch {
|
|
1592
|
-
matchedAliases
|
|
1593
|
-
matchTier
|
|
1594
|
-
score
|
|
1595
|
-
}`;class ResolveTargetServiceImpl{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async resolveTarget(params){return withServiceDiagnostics(this.runtime.diagnostics,"resolve-target.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeResolveTarget(token,params)}))}async executeResolveTarget(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:RESOLVE_TARGET_QUERY,variables:buildVariables(params),fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw createPackageIntelligenceTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw createPackageIntelligenceHttpError(response)}const parsed=(params.includeDetailedFields?responseSchema(detailedTargetSchema,params.includeNameSimilarity):responseSchema(listTargetSchema,params.includeNameSimilarity)).safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the target-resolution service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw createPackageIntelligenceGraphQLError(parsed.data.errors,this.runtime.clientVersion,this.runtime.diagnostics)}const result=parsed.data.data?.resolveTarget;if(!result){throw new MalformedPackageIntelligenceResponseError("Empty response from the target-resolution service.")}const nameSimilarityByCanonicalKey=new Map((result.candidates??[]).map((candidate)=>[candidate.canonicalKey,candidate.nameSimilarity]));return{best:result.best?normaliseReference(result.best):undefined,protectedMatches:result.protectedMatches.map(normaliseReference),targets:result.targets.map((target)=>normaliseTarget(target,nameSimilarityByCanonicalKey.get(target.canonicalKey))),targetsTruncated:result.targetsTruncated,ambiguous:result.ambiguous,ambiguousReason:result.ambiguousReason}}}function normaliseReference(target){return{kind:target.kind,canonicalKey:target.canonicalKey,confidence:target.confidence}}function buildVariables(params){const variables={name:params.name,limit:params.limit,includeDetailedFields:params.includeDetailedFields,includeNameSimilarity:params.includeNameSimilarity};if(params.query!==undefined)variables.query=params.query;if(params.registries!==undefined)variables.registries=params.registries;if(params.preferredKinds!==undefined){variables.preferredKinds=params.preferredKinds}if(params.intentHints!==undefined)variables.intentHints=params.intentHints;return variables}function normaliseTarget(target,nameSimilarity){const result={kind:target.kind,canonicalKey:target.canonicalKey,latestVersionMaliciousStatus:target.latestVersionMaliciousStatus,docsAvailable:target.docsAvailable,codeAvailable:target.codeAvailable};assignDefined(result,"description",target.description);assignDefined(result,"latestVersionMaliciousEvidence",target.latestVersionMaliciousEvidence);assignDefined(result,"repositoryUrl",target.repositoryUrl);assignDefined(result,"stars",target.stars);assignDefined(result,"downloadsLastMonth",target.downloadsLastMonth);assignDefined(result,"downloadsTotal",target.downloadsTotal);assignDefined(result,"groupKey",target.groupKey);assignDefined(result,"docsPageCount",target.docsPageCount);assignDefined(result,"codeFileCount",target.codeFileCount);assignDefined(result,"license",target.license);if(target.match){const match={confidence:target.match.confidence};assignDefined(match,"nameSimilarity",nameSimilarity);if("matchedAliases"in target.match){assignDefined(match,"matchedAliases",target.match.matchedAliases);assignDefined(match,"matchTier",target.match.matchTier);assignDefined(match,"score",target.match.score)}result.match=match}if("displayName"in target){assignDefined(result,"displayName",target.displayName);assignDefined(result,"registry",target.registry);assignDefined(result,"packageName",target.packageName);assignDefined(result,"latestVersion",target.latestVersion);assignDefined(result,"repositoryOwner",target.repositoryOwner);assignDefined(result,"repositoryName",target.repositoryName);assignDefined(result,"documentationUrl",target.documentationUrl)}return result}function assignDefined(target,key,value){if(value!==null&&value!==undefined)target[key]=value}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash as createHash2,randomUUID}from"node:crypto";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;function resolveRawSessionId(env=process.env,ppid=process.ppid){for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}function hashValue(input){return createHash2("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}var APP_DIR="githits";var USER_AUTH_STATE_DIR=".githits";function getAppConfigDir(fs){return getAppConfigDirForEnv(fs,process.env,process.platform,fs.getHomeDir())}function getAppConfigDirForEnv(fs,env,platform,home=getHomeDirForEnv(fs,env,platform)){if(platform==="win32"){return fs.joinPath(env.APPDATA??fs.joinPath(home,"AppData","Roaming"),APP_DIR)}return fs.joinPath(env.XDG_CONFIG_HOME??fs.joinPath(home,".config"),APP_DIR)}function getAuthConfigPath(fs){return fs.joinPath(getAppConfigDir(fs),"config.toml")}function getAuthConfigPathForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"config.toml")}function getAuthFileStorageDir(fs){return fs.joinPath(getAppConfigDir(fs),"auth")}function getAuthFileStorageDirForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"auth")}function getHomeDirForEnv(fs,env,platform){if(platform==="win32"&&env.USERPROFILE)return env.USERPROFILE;if(platform!=="win32"&&env.HOME)return env.HOME;return fs.getHomeDir()}function getLegacyAuthStorageDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyAuthStorageDirForEnv(fs,env,platform){return fs.joinPath(getHomeDirForEnv(fs,env,platform),USER_AUTH_STATE_DIR)}function getAuthLockDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyMacAppConfigDir(fs){return fs.joinPath(fs.getHomeDir(),"Library","Application Support",APP_DIR)}function getLegacyMacAppConfigDirForEnv(fs,env){return fs.joinPath(getHomeDirForEnv(fs,env,"darwin"),"Library","Application Support",APP_DIR)}function getLegacyMacAuthConfigPath(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"config.toml")}function getLegacyMacAuthConfigPathForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"config.toml")}function getLegacyMacAuthFileStorageDir(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"auth")}function getLegacyMacAuthFileStorageDirForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"auth")}import{z as z6}from"zod";import{parse as parseToml}from"smol-toml";class AppConfigError extends Error{constructor(message){super(message);this.name="AppConfigError"}}async function readAppConfig(fs){let configPath=getAuthConfigPath(fs);if(!await fs.exists(configPath)){const legacyMacConfigPath=getLegacyMacAuthConfigPath(fs);if(process.platform==="darwin"&&await fs.exists(legacyMacConfigPath)){configPath=legacyMacConfigPath}else{return{configPath,data:{}}}}try{return{configPath,data:parseToml(await fs.readFile(configPath))}}catch(error){const message=error instanceof Error?error.message:String(error);throw new AppConfigError(`Cannot parse GitHits config at ${configPath}: ${message}`)}}var AUTH_STORAGE_MODES=["keychain","file"];var AUTH_STORAGE_MODE_VALUES=new Set(AUTH_STORAGE_MODES);var CONFIG_SCHEMA=z6.object({auth:z6.object({storage:z6.string().optional()}).optional()}).passthrough();class AuthConfigError extends Error{constructor(message){super(message);this.name="AuthConfigError"}}function parseAuthStorageMode(value){const normalized=value.trim().toLowerCase();if(AUTH_STORAGE_MODE_VALUES.has(normalized)){return normalized}throw new AuthConfigError(`Invalid auth storage mode "${value}". Use "keychain" or "file". File mode stores OAuth credentials unencrypted on disk.`)}async function loadAuthConfig(fs){const envMode=process.env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{storage:parseAuthStorageMode(envMode),configPath:getAuthConfigPath(fs)}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GITHITS_AUTH_STORAGE: ${error.message}`)}throw error}}let document;try{document=await readAppConfig(fs)}catch(error){if(error instanceof AppConfigError){throw new AuthConfigError(error.message)}throw error}const parsed=CONFIG_SCHEMA.safeParse(document.data);if(!parsed.success){throw new AuthConfigError(`Invalid GitHits config at ${document.configPath}: ${z6.prettifyError(parsed.error)}`)}const configuredMode=parsed.data.auth?.storage;if(configuredMode===undefined||configuredMode.trim()===""){return{storage:"keychain",configPath:document.configPath}}try{return{storage:parseAuthStorageMode(configuredMode),configPath:document.configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GitHits config at ${document.configPath}: ${error.message}`)}throw error}}var AUTH_FILE="auth.json";var CLIENT_FILE="client.json";var DIR_MODE=448;var FILE_MODE=384;class AuthStorageImpl{fs;configDir;authPath;clientPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.authPath=fs.joinPath(this.configDir,AUTH_FILE);this.clientPath=fs.joinPath(this.configDir,CLIENT_FILE)}getStorageLocation(){return this.configDir}async loadTokens(baseUrl){const stored=await this.loadAuthFile();if(!stored)return null;return stored.tokens[normalizeBaseUrl(baseUrl)]??null}async saveTokens(baseUrl,data){const stored=await this.loadAuthFile()??{version:1,tokens:{}};stored.tokens[normalizeBaseUrl(baseUrl)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2),FILE_MODE)}async saveTokensIfUnchanged(baseUrl,expected,data){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl,data);return true}async clearTokens(baseUrl){const stored=await this.loadAuthFile();if(!stored)return;delete stored.tokens[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.tokens).length===0){await this.fs.deleteFile(this.authPath)}else{await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2),FILE_MODE)}}async clearTokensIfUnchanged(baseUrl,expected){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl);return true}clearActiveTokensIfUnchanged(baseUrl,expected){return this.clearTokensIfUnchanged(baseUrl,expected)}async loadClient(baseUrl){const stored=await this.loadClientFile();if(!stored)return null;return stored.clients[normalizeBaseUrl(baseUrl)]??null}async clearClient(baseUrl){const stored=await this.loadClientFile();if(!stored)return;delete stored.clients[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.clients).length===0){await this.fs.deleteFile(this.clientPath)}else{await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2),FILE_MODE)}}async saveClient(baseUrl,data){const stored=await this.loadClientFile()??{version:1,clients:{}};stored.clients[normalizeBaseUrl(baseUrl)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2),FILE_MODE)}clearActiveClient(baseUrl){return this.clearClient(baseUrl)}async saveAuthSession(baseUrl,client,tokens){await this.saveClient(baseUrl,client);await this.saveTokens(baseUrl,tokens)}async clearAuthSession(baseUrl){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl),()=>this.clearClient(baseUrl))}async loadAuthFile(){if(!await this.fs.exists(this.authPath))return null;try{const content=await this.fs.readFile(this.authPath);const data=JSON.parse(content);if(data.version!==1||!data.tokens)return null;return data}catch{return null}}async loadClientFile(){if(!await this.fs.exists(this.clientPath))return null;try{const content=await this.fs.readFile(this.clientPath);const data=JSON.parse(content);if(data.version!==1||!data.clients)return null;return data}catch{return null}}}function normalizeBaseUrl(url){return url.replace(/\/+$/,"")}function sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}async function clearAuthSessionBestEffort(clearTokens,clearClient){let firstError;try{await clearTokens()}catch(error){firstError=error}try{await clearClient()}catch(error){firstError??=error}if(firstError)throw firstError}var DIAGNOSTICS_FILE="diagnostics.json";var DIR_MODE2=448;var FILE_MODE2=384;var CLEAR_REASONS=new Set(["logout","terminal_invalid_refresh_token","terminal_invalid_client"]);class AuthDiagnosticsStorage{fs;configDir;diagnosticsPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.diagnosticsPath=fs.joinPath(this.configDir,DIAGNOSTICS_FILE)}async recordClear(baseUrl,reason){try{const stored=await this.loadFile()??{version:1,events:{}};stored.events[normalizeBaseUrl(baseUrl)]={reason,at:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE2);await this.fs.atomicWriteFile(this.diagnosticsPath,JSON.stringify(stored,null,2),FILE_MODE2)}catch{}}async load(baseUrl){const stored=await this.loadFile();if(!stored)return null;const event=stored.events[normalizeBaseUrl(baseUrl)]??null;return isAuthClearEvent(event)?event:null}async loadFile(){if(!await this.fs.exists(this.diagnosticsPath))return null;try{const content=await this.fs.readFile(this.diagnosticsPath);const data=JSON.parse(content);if(!isRecord2(data)||data.version!==1||!isRecord2(data.events)){return null}return data}catch{return null}}}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isAuthClearReason(value){return typeof value==="string"&&CLEAR_REASONS.has(value)}function isAuthClearEvent(value){if(value===null||typeof value!=="object")return false;return isAuthClearReason(value.reason)&&typeof value.at==="string"&&value.at.length>0}import{createServer}from"node:http";import{z as z7}from"zod";class TokenRefreshError extends Error{status;body;oauthError;oauthErrorDescription;constructor(status,body){const details=parseOAuthErrorBody(body);const description=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);super(description?`Token refresh failed with HTTP ${status}: ${description}`:`Token refresh failed with HTTP ${status}`);this.name="TokenRefreshError";this.status=status;this.body=body;this.oauthError=details.oauthError;this.oauthErrorDescription=details.oauthErrorDescription}}class AuthServiceImpl{fetchFn;fetchTimeoutMs;constructor(fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs}async discoverEndpoints(mcpBaseUrl){const validatedBaseUrl=validateServiceUrl(mcpBaseUrl,"GITHITS_MCP_URL");const url=`${validatedBaseUrl.replace(/\/+$/,"")}/.well-known/oauth-authorization-server`;const response=await fetchWithTimeout(url,{},this.fetchOptions());if(!response.ok){throw new Error(`Failed to discover OAuth endpoints: ${response.status} ${response.statusText}`)}const data=await readJsonResponse(response,"OAuth metadata response was not valid JSON.");const parsed=OAUTH_METADATA_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("OAuth metadata missing required endpoints")}return{authorizationEndpoint:validateServiceUrl(parsed.data.authorization_endpoint,"OAuth authorization endpoint"),tokenEndpoint:validateServiceUrl(parsed.data.token_endpoint,"OAuth token endpoint"),registrationEndpoint:validateServiceUrl(parsed.data.registration_endpoint,"OAuth registration endpoint")}}async registerClient(params){const registrationEndpoint=validateServiceUrl(params.registrationEndpoint,"OAuth registration endpoint");const response=await fetchWithTimeout(registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"GitHits CLI",redirect_uris:params.redirectUris,grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"})},this.fetchOptions());if(!response.ok){const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);throw new Error(`Client registration failed with HTTP ${response.status}.${detail?` ${detail}`:""}`)}const data=await readJsonResponse(response,"Client registration response was not valid JSON.");const parsed=CLIENT_REGISTRATION_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Client registration response missing required fields")}return{clientId:parsed.data.client_id,clientSecret:parsed.data.client_secret}}generatePkceParams(){const verifier=generateCodeVerifier();return{verifier,challenge:generateCodeChallenge(verifier),state:generateState()}}buildAuthUrl(params){const url=new URL(params.authorizationEndpoint);url.searchParams.set("response_type","code");url.searchParams.set("client_id",params.clientId);url.searchParams.set("redirect_uri",params.redirectUri);url.searchParams.set("state",params.state);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method","S256");return url.toString()}startCallbackServer(port,expectedState){const server=createServer();const connections=new Set;let callbackHandled=false;let resolved=false;server.on("connection",(socket)=>{connections.add(socket);socket.once("close",()=>connections.delete(socket))});const result=new Promise((resolve)=>{server.on("request",(req,res)=>{const address=server.address();const actualPort=typeof address==="object"&&address!==null?address.port:port;const url=new URL(req.url??"",`http://127.0.0.1:${actualPort}`);if(url.pathname==="/favicon.ico"){res.writeHead(204);res.end();return}if(url.pathname!=="/callback"){if(callbackHandled){sendHtmlResponse(res,200,successHtml("You're already signed in."));return}sendHtmlResponse(res,404,errorHtml("Invalid callback path.","Run `githits login` to start authentication."));return}const code=url.searchParams.get("code");const state=url.searchParams.get("state");const error=url.searchParams.get("error");const errorDescription=url.searchParams.get("error_description");const evaluation=evaluateCallback({code,state,error,errorDescription,expectedState});callbackHandled=true;const settle=()=>{if(!resolved){resolved=true;resolve(evaluation.result)}};res.once("finish",settle);res.once("close",settle);sendHtmlResponse(res,evaluation.statusCode,evaluation.html)})});return new Promise((resolve,reject)=>{const onError=(err)=>{reject(new Error(`Failed to start callback server: ${err.message}`))};server.once("error",onError);server.listen(port,"127.0.0.1",()=>{server.off("error",onError);server.on("error",()=>{});resolve({result,close:()=>closeCallbackServerConnections(server,connections)})})})}async exchangeCodeForTokens(params){const body=new URLSearchParams({grant_type:"authorization_code",client_id:params.clientId,client_secret:params.clientSecret,code:params.code,code_verifier:params.codeVerifier,redirect_uri:params.redirectUri});const tokenEndpoint=validateServiceUrl(params.tokenEndpoint,"OAuth token endpoint");const response=await fetchWithTimeout(tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);throw new Error(`Token exchange failed with HTTP ${response.status}.${detail?` ${detail}`:""}`)}return parseTokenResponse(await readJsonResponse(response,"Token exchange response was not valid JSON."))}async refreshAccessToken(params){const body=new URLSearchParams({grant_type:"refresh_token",client_id:params.clientId,client_secret:params.clientSecret,refresh_token:params.refreshToken});const tokenEndpoint=validateServiceUrl(params.tokenEndpoint,"OAuth token endpoint");const response=await fetchWithTimeout(tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const error=await response.text();throw new TokenRefreshError(response.status,error)}return parseRefreshTokenResponse(await readJsonResponse(response,"Token refresh response was not valid JSON."))}fetchOptions(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}}function classifyTerminalRefreshError(error){if(!(error instanceof TokenRefreshError)||error.status<400||error.status>=500){return}const oauthError=error.oauthError?.toLowerCase();switch(oauthError){case"invalid_grant":case"refresh_token_not_found":case"refresh_token_already_used":case"session_not_found":case"session_expired":return"invalid_refresh_token"}const text=[error.oauthError,error.oauthErrorDescription,error.body,error.message].filter((part)=>typeof part==="string").join(" ").toLowerCase();if(oauthError==="invalid_client"||text.includes("client not found")||text.includes("client id not found")||text.includes("client_id not found")||text.includes("oauth client not found")||text.includes("client does not match")||text.includes("client authentication required")||text.includes("invalid client credentials")){return"invalid_client"}return}function parseOAuthErrorBody(body){try{const parsed=JSON.parse(body);return{oauthError:stringField2(parsed.error)??stringField2(parsed.error_code)??stringField2(parsed.code),oauthErrorDescription:stringField2(parsed.error_description)??stringField2(parsed.errorDescription)??stringField2(parsed.message)??stringField2(parsed.msg)}}catch{return{oauthError:undefined,oauthErrorDescription:undefined}}}function stringField2(value){return typeof value==="string"&&value.trim()?value:undefined}var OAUTH_ERROR_DETAIL_FIELDS=["detail","error_description","message","msg","error"];var OAUTH_METADATA_SCHEMA=z7.object({authorization_endpoint:z7.string().min(1),token_endpoint:z7.string().min(1),registration_endpoint:z7.string().min(1)});var CLIENT_REGISTRATION_SCHEMA=z7.object({client_id:z7.string().min(1),client_secret:z7.string().min(1)});var EXPIRES_IN_SCHEMA=z7.union([z7.number(),z7.string().trim().regex(/^\d+(?:\.\d+)?$/).transform(Number)]).pipe(z7.number().positive());var TOKEN_RESPONSE_SCHEMA=z7.object({access_token:z7.string().min(1),refresh_token:z7.string().min(1),expires_in:EXPIRES_IN_SCHEMA.optional()});var REFRESH_TOKEN_RESPONSE_SCHEMA=z7.object({access_token:z7.string().min(1),refresh_token:z7.string().min(1).optional(),expires_in:EXPIRES_IN_SCHEMA.optional()});async function readJsonResponse(response,message){try{return await response.json()}catch(cause){throw new Error(message,{cause})}}function parseTokenResponse(data){const parsed=TOKEN_RESPONSE_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Token response missing required fields")}return{accessToken:parsed.data.access_token,refreshToken:parsed.data.refresh_token,expiresIn:parsed.data.expires_in??3600}}function parseRefreshTokenResponse(data){const parsed=REFRESH_TOKEN_RESPONSE_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Token response missing required fields")}return{accessToken:parsed.data.access_token,refreshToken:parsed.data.refresh_token,expiresIn:parsed.data.expires_in??3600}}function successHtml(title="You're signed in"){return`<!DOCTYPE html>
|
|
1596
|
+
}`}var unifiedSearchGraphQLResponseSchema=z5.object({data:z5.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).optional()});var unifiedSearchStatusGraphQLResponseSchema=z5.object({data:z5.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema3).optional()});class CodeNavigationServiceImpl{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,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,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,executeWithToken:(token)=>this.executeUnifiedSearch(token,params,options)})}async searchStatus(searchRef,waitTimeoutMs=0,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options)})}async codeDiff(params){validateCodeDiffParams(params);return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeCodeDiff(token,params)})}async executeCodeDiff(token,params){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})}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 CodeDiffError(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=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new AuthenticationError(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 CodeDiffError(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??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs,includeFocusedSource:options?.omitFocusedSource!==true};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})}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,variables:{searchRef,includeResults:true,waitTimeoutMs,includeFocusedSource:options?.omitFocusedSource!==true}})}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){const status=response.status;const detail=parseDetail2(response.responseBody);if(status===401){return new AuthenticationError(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)}createTransportError(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})}createGraphQLError(errors){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;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);const errorMetadata=parseGraphQLErrorMetadata(extensions,indexingEstimate);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,this.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(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(this.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,appendIndexingWaitHint(message,typeof extensions?.hint==="string"?extensions.hint:undefined));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,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions),errorMetadata);case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions),errorMetadata);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 AuthenticationError(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)}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)=>({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,summary:entry.summary??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined,summary:entry.highlights.summary??undefined}:undefined,repositoryEvidence:entry.repositoryEvidence,documentationPreview:entry.documentationPreview,contentSafety:entry.contentSafety,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)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError(`Target is indexing. ${INDEXING_WAIT_HINT}`,data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate)}}async listFiles(params){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({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}}async readFile(params){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({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{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)}}async grepRepo(params){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({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)}}}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"&¶msRecord.mode!=="stats"&¶msRecord.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=getPrimaryExtensions2(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 parseDetail2(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}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 getPrimaryExtensions2(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 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}}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}function appendIndexingWaitHint(message,backendHint){const hintAlreadyInMessage=Boolean(backendHint&&message.includes(backendHint));const existingGuidance=`${message} ${backendHint??""}`;if(/(?:--wait\b|wait_timeout_ms|waitTimeoutMs)/i.test(existingGuidance)){return hintAlreadyInMessage?undefined:backendHint}return backendHint&&!hintAlreadyInMessage?`${backendHint} ${INDEXING_WAIT_HINT}`:INDEXING_WAIT_HINT}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}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.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")}class RefreshingGitHitsService{apiUrl;tokenProvider;serviceFactory;runtime;constructor(apiUrl,tokenProvider,serviceFactory=undefined,runtime={}){this.apiUrl=apiUrl;this.tokenProvider=tokenProvider;this.serviceFactory=serviceFactory;this.runtime=runtime}async search(params,options){return this.withTokenRefresh(options?(service)=>service.search(params,options):(service)=>service.search(params),options)}async getLanguages(){return this.withTokenRefresh((service)=>service.getLanguages())}async searchLanguages(query,limit){return this.withTokenRefresh((service)=>service.searchLanguages(query,limit))}async submitFeedback(params){return this.withTokenRefresh((service)=>service.submitFeedback(params))}async withTokenRefresh(operation,options){return executeWithTokenRefresh({getToken:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.getToken()},forceRefresh:()=>{options?.signal?.throwIfAborted();return this.tokenProvider.forceRefresh()},shouldRefresh:isTokenRefreshableError,executeWithToken:async(token)=>{options?.signal?.throwIfAborted();const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}import{createHash as createHash2,randomUUID}from"node:crypto";var MAX_HEADER_BYTES=256;var SESSION_ENV_VARS=["TERM_SESSION_ID","ITERM_SESSION_ID","WEZTERM_PANE","KITTY_PID","ALACRITTY_SOCKET","WT_SESSION","VSCODE_PID","SUPERSET_PANE_ID","SUPERSET_WORKSPACE_ID","STARSHIP_SESSION_KEY","SSH_CONNECTION"];var cachedSessionId;function resolveRawSessionId(env=process.env,ppid=process.ppid){for(const key of SESSION_ENV_VARS){const value=env[key];if(value&&value.trim().length>0){return value.trim()}}if(typeof ppid==="number"&&!Number.isNaN(ppid)&&ppid>0){return String(ppid)}return randomUUID()}function getSessionId(env,ppid){if(cachedSessionId!==undefined&&env===undefined&&ppid===undefined){return cachedSessionId}const raw=resolveRawSessionId(env,ppid);const hashed=hashValue(raw);if(env===undefined&&ppid===undefined){cachedSessionId=hashed}return hashed}function hashValue(input){return createHash2("sha256").update(input).digest("hex").slice(0,16)}var AGENT_PROBES=[{envVar:"OPENCODE",name:"opencode"},{envVar:"CLAUDECODE",name:"claude-code"},{envVar:"CURSOR_TRACE_ID",name:"cursor"},{envVar:"WINDSURF_CONFIG_DIR",name:"windsurf"},{envVar:"ZED_TERM",name:"zed"},{envVar:"VSCODE_PID",name:"vscode"}];function parseAgentString(raw){const trimmed=raw.trim();if(trimmed.length===0)return;const slashIndex=trimmed.indexOf("/");if(slashIndex===-1)return{name:trimmed};const name=trimmed.slice(0,slashIndex);const ver=trimmed.slice(slashIndex+1);if(name.length===0)return;return{name,version:ver||undefined}}function formatAgentInfo(info){return info.version?`${info.name}/${info.version}`:info.name}function resolveAgentInfo(env=process.env){const explicit=env.GITHITS_AGENT;if(explicit&&explicit.trim().length>0){return parseAgentString(explicit)}for(const probe of AGENT_PROBES){const value=env[probe.envVar];if(value&&value.trim().length>0){return{name:probe.name}}}return}var CONTROL_CHARS=/[\x00-\x1f\x7f-\x9f]/g;function sanitizeHeaderValue(value){if(value===undefined||value===null||typeof value!=="string"){return}const cleaned=value.replace(CONTROL_CHARS,"").trim();if(cleaned.length===0)return;if(Buffer.byteLength(cleaned,"utf8")>MAX_HEADER_BYTES)return;return cleaned}function createClientHeaderBuilder(options){return()=>buildClientHeadersWithContext({clientName:options.clientName,clientVersion:options.clientVersion,agentProvider:options.agentProvider,env:options.env,ppid:options.ppid})}function buildClientHeadersWithContext(context){try{const headers={};const name=sanitizeHeaderValue(context.clientName);if(name){headers["x-githits-client-name"]=name}const safeClientVersion=sanitizeHeaderValue(context.clientVersion);if(safeClientVersion){headers["x-githits-client-version"]=safeClientVersion}const agentInfo=context.agentProvider?.()??resolveAgentInfo(context.env);if(agentInfo){const agentValue=sanitizeHeaderValue(formatAgentInfo(agentInfo));if(agentValue){headers["x-githits-agent"]=agentValue}}const sessionId=sanitizeHeaderValue(getSessionId(context.env,context.ppid));if(sessionId){headers["x-githits-session-id"]=sessionId}return headers}catch{return{}}}var APP_DIR="githits";var USER_AUTH_STATE_DIR=".githits";function getAppConfigDir(fs){return getAppConfigDirForEnv(fs,process.env,process.platform,fs.getHomeDir())}function getAppConfigDirForEnv(fs,env,platform,home=getHomeDirForEnv(fs,env,platform)){if(platform==="win32"){return fs.joinPath(env.APPDATA??fs.joinPath(home,"AppData","Roaming"),APP_DIR)}return fs.joinPath(env.XDG_CONFIG_HOME??fs.joinPath(home,".config"),APP_DIR)}function getAuthConfigPath(fs){return fs.joinPath(getAppConfigDir(fs),"config.toml")}function getAuthConfigPathForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"config.toml")}function getAuthFileStorageDir(fs){return fs.joinPath(getAppConfigDir(fs),"auth")}function getAuthFileStorageDirForEnv(fs,env,platform){return fs.joinPath(getAppConfigDirForEnv(fs,env,platform),"auth")}function getHomeDirForEnv(fs,env,platform){if(platform==="win32"&&env.USERPROFILE)return env.USERPROFILE;if(platform!=="win32"&&env.HOME)return env.HOME;return fs.getHomeDir()}function getLegacyAuthStorageDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyAuthStorageDirForEnv(fs,env,platform){return fs.joinPath(getHomeDirForEnv(fs,env,platform),USER_AUTH_STATE_DIR)}function getAuthLockDir(fs){return fs.joinPath(fs.getHomeDir(),USER_AUTH_STATE_DIR)}function getLegacyMacAppConfigDir(fs){return fs.joinPath(fs.getHomeDir(),"Library","Application Support",APP_DIR)}function getLegacyMacAppConfigDirForEnv(fs,env){return fs.joinPath(getHomeDirForEnv(fs,env,"darwin"),"Library","Application Support",APP_DIR)}function getLegacyMacAuthConfigPath(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"config.toml")}function getLegacyMacAuthConfigPathForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"config.toml")}function getLegacyMacAuthFileStorageDir(fs){return fs.joinPath(getLegacyMacAppConfigDir(fs),"auth")}function getLegacyMacAuthFileStorageDirForEnv(fs,env){return fs.joinPath(getLegacyMacAppConfigDirForEnv(fs,env),"auth")}import{z as z6}from"zod";import{parse as parseToml}from"smol-toml";class AppConfigError extends Error{constructor(message){super(message);this.name="AppConfigError"}}async function readAppConfig(fs){let configPath=getAuthConfigPath(fs);if(!await fs.exists(configPath)){const legacyMacConfigPath=getLegacyMacAuthConfigPath(fs);if(process.platform==="darwin"&&await fs.exists(legacyMacConfigPath)){configPath=legacyMacConfigPath}else{return{configPath,data:{}}}}try{return{configPath,data:parseToml(await fs.readFile(configPath))}}catch(error){const message=error instanceof Error?error.message:String(error);throw new AppConfigError(`Cannot parse GitHits config at ${configPath}: ${message}`)}}var AUTH_STORAGE_MODES=["keychain","file"];var AUTH_STORAGE_MODE_VALUES=new Set(AUTH_STORAGE_MODES);var CONFIG_SCHEMA=z6.object({auth:z6.object({storage:z6.string().optional()}).optional()}).passthrough();class AuthConfigError extends Error{constructor(message){super(message);this.name="AuthConfigError"}}function parseAuthStorageMode(value){const normalized=value.trim().toLowerCase();if(AUTH_STORAGE_MODE_VALUES.has(normalized)){return normalized}throw new AuthConfigError(`Invalid auth storage mode "${value}". Use "keychain" or "file". File mode stores OAuth credentials unencrypted on disk.`)}async function loadAuthConfig(fs){const envMode=process.env.GITHITS_AUTH_STORAGE;if(envMode!==undefined&&envMode.trim()!==""){try{return{storage:parseAuthStorageMode(envMode),configPath:getAuthConfigPath(fs)}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GITHITS_AUTH_STORAGE: ${error.message}`)}throw error}}let document;try{document=await readAppConfig(fs)}catch(error){if(error instanceof AppConfigError){throw new AuthConfigError(error.message)}throw error}const parsed=CONFIG_SCHEMA.safeParse(document.data);if(!parsed.success){throw new AuthConfigError(`Invalid GitHits config at ${document.configPath}: ${z6.prettifyError(parsed.error)}`)}const configuredMode=parsed.data.auth?.storage;if(configuredMode===undefined||configuredMode.trim()===""){return{storage:"keychain",configPath:document.configPath}}try{return{storage:parseAuthStorageMode(configuredMode),configPath:document.configPath}}catch(error){if(error instanceof AuthConfigError){throw new AuthConfigError(`Invalid GitHits config at ${document.configPath}: ${error.message}`)}throw error}}var AUTH_FILE="auth.json";var CLIENT_FILE="client.json";var DIR_MODE=448;var FILE_MODE=384;class AuthStorageImpl{fs;configDir;authPath;clientPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.authPath=fs.joinPath(this.configDir,AUTH_FILE);this.clientPath=fs.joinPath(this.configDir,CLIENT_FILE)}getStorageLocation(){return this.configDir}async loadTokens(baseUrl){const stored=await this.loadAuthFile();if(!stored)return null;return stored.tokens[normalizeBaseUrl(baseUrl)]??null}async saveTokens(baseUrl,data){const stored=await this.loadAuthFile()??{version:1,tokens:{}};stored.tokens[normalizeBaseUrl(baseUrl)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2),FILE_MODE)}async saveTokensIfUnchanged(baseUrl,expected,data){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl,data);return true}async clearTokens(baseUrl){const stored=await this.loadAuthFile();if(!stored)return;delete stored.tokens[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.tokens).length===0){await this.fs.deleteFile(this.authPath)}else{await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2),FILE_MODE)}}async clearTokensIfUnchanged(baseUrl,expected){const current=await this.loadTokens(baseUrl);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl);return true}clearActiveTokensIfUnchanged(baseUrl,expected){return this.clearTokensIfUnchanged(baseUrl,expected)}async loadClient(baseUrl){const stored=await this.loadClientFile();if(!stored)return null;return stored.clients[normalizeBaseUrl(baseUrl)]??null}async clearClient(baseUrl){const stored=await this.loadClientFile();if(!stored)return;delete stored.clients[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.clients).length===0){await this.fs.deleteFile(this.clientPath)}else{await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2),FILE_MODE)}}async saveClient(baseUrl,data){const stored=await this.loadClientFile()??{version:1,clients:{}};stored.clients[normalizeBaseUrl(baseUrl)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2),FILE_MODE)}clearActiveClient(baseUrl){return this.clearClient(baseUrl)}async saveAuthSession(baseUrl,client,tokens){await this.saveClient(baseUrl,client);await this.saveTokens(baseUrl,tokens)}async clearAuthSession(baseUrl){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl),()=>this.clearClient(baseUrl))}async loadAuthFile(){if(!await this.fs.exists(this.authPath))return null;try{const content=await this.fs.readFile(this.authPath);const data=JSON.parse(content);if(data.version!==1||!data.tokens)return null;return data}catch{return null}}async loadClientFile(){if(!await this.fs.exists(this.clientPath))return null;try{const content=await this.fs.readFile(this.clientPath);const data=JSON.parse(content);if(data.version!==1||!data.clients)return null;return data}catch{return null}}}function normalizeBaseUrl(url){return url.replace(/\/+$/,"")}function sameTokenData(a,b){if(a===null||b===null)return a===b;return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}async function clearAuthSessionBestEffort(clearTokens,clearClient){let firstError;try{await clearTokens()}catch(error){firstError=error}try{await clearClient()}catch(error){firstError??=error}if(firstError)throw firstError}var DIAGNOSTICS_FILE="diagnostics.json";var DIR_MODE2=448;var FILE_MODE2=384;var CLEAR_REASONS=new Set(["logout","terminal_invalid_refresh_token","terminal_invalid_client"]);class AuthDiagnosticsStorage{fs;configDir;diagnosticsPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.diagnosticsPath=fs.joinPath(this.configDir,DIAGNOSTICS_FILE)}async recordClear(baseUrl,reason){try{const stored=await this.loadFile()??{version:1,events:{}};stored.events[normalizeBaseUrl(baseUrl)]={reason,at:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE2);await this.fs.atomicWriteFile(this.diagnosticsPath,JSON.stringify(stored,null,2),FILE_MODE2)}catch{}}async load(baseUrl){const stored=await this.loadFile();if(!stored)return null;const event=stored.events[normalizeBaseUrl(baseUrl)]??null;return isAuthClearEvent(event)?event:null}async loadFile(){if(!await this.fs.exists(this.diagnosticsPath))return null;try{const content=await this.fs.readFile(this.diagnosticsPath);const data=JSON.parse(content);if(!isRecord2(data)||data.version!==1||!isRecord2(data.events)){return null}return data}catch{return null}}}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function isAuthClearReason(value){return typeof value==="string"&&CLEAR_REASONS.has(value)}function isAuthClearEvent(value){if(value===null||typeof value!=="object")return false;return isAuthClearReason(value.reason)&&typeof value.at==="string"&&value.at.length>0}import{createServer}from"node:http";import{z as z7}from"zod";class TokenRefreshError extends Error{status;body;oauthError;oauthErrorDescription;constructor(status,body){const details=parseOAuthErrorBody(body);const description=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);super(description?`Token refresh failed with HTTP ${status}: ${description}`:`Token refresh failed with HTTP ${status}`);this.name="TokenRefreshError";this.status=status;this.body=body;this.oauthError=details.oauthError;this.oauthErrorDescription=details.oauthErrorDescription}}class AuthServiceImpl{fetchFn;fetchTimeoutMs;constructor(fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs}async discoverEndpoints(mcpBaseUrl){const validatedBaseUrl=validateServiceUrl(mcpBaseUrl,"GITHITS_MCP_URL");const url=`${validatedBaseUrl.replace(/\/+$/,"")}/.well-known/oauth-authorization-server`;const response=await fetchWithTimeout(url,{},this.fetchOptions());if(!response.ok){throw new Error(`Failed to discover OAuth endpoints: ${response.status} ${response.statusText}`)}const data=await readJsonResponse(response,"OAuth metadata response was not valid JSON.");const parsed=OAUTH_METADATA_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("OAuth metadata missing required endpoints")}return{authorizationEndpoint:validateServiceUrl(parsed.data.authorization_endpoint,"OAuth authorization endpoint"),tokenEndpoint:validateServiceUrl(parsed.data.token_endpoint,"OAuth token endpoint"),registrationEndpoint:validateServiceUrl(parsed.data.registration_endpoint,"OAuth registration endpoint")}}async registerClient(params){const registrationEndpoint=validateServiceUrl(params.registrationEndpoint,"OAuth registration endpoint");const response=await fetchWithTimeout(registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"GitHits CLI",redirect_uris:params.redirectUris,grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"client_secret_post"})},this.fetchOptions());if(!response.ok){const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);throw new Error(`Client registration failed with HTTP ${response.status}.${detail?` ${detail}`:""}`)}const data=await readJsonResponse(response,"Client registration response was not valid JSON.");const parsed=CLIENT_REGISTRATION_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Client registration response missing required fields")}return{clientId:parsed.data.client_id,clientSecret:parsed.data.client_secret}}generatePkceParams(){const verifier=generateCodeVerifier();return{verifier,challenge:generateCodeChallenge(verifier),state:generateState()}}buildAuthUrl(params){const url=new URL(params.authorizationEndpoint);url.searchParams.set("response_type","code");url.searchParams.set("client_id",params.clientId);url.searchParams.set("redirect_uri",params.redirectUri);url.searchParams.set("state",params.state);url.searchParams.set("code_challenge",params.codeChallenge);url.searchParams.set("code_challenge_method","S256");return url.toString()}startCallbackServer(port,expectedState){const server=createServer();const connections=new Set;let callbackHandled=false;let resolved=false;server.on("connection",(socket)=>{connections.add(socket);socket.once("close",()=>connections.delete(socket))});const result=new Promise((resolve)=>{server.on("request",(req,res)=>{const address=server.address();const actualPort=typeof address==="object"&&address!==null?address.port:port;const url=new URL(req.url??"",`http://127.0.0.1:${actualPort}`);if(url.pathname==="/favicon.ico"){res.writeHead(204);res.end();return}if(url.pathname!=="/callback"){if(callbackHandled){sendHtmlResponse(res,200,successHtml("You're already signed in."));return}sendHtmlResponse(res,404,errorHtml("Invalid callback path.","Run `githits login` to start authentication."));return}const code=url.searchParams.get("code");const state=url.searchParams.get("state");const error=url.searchParams.get("error");const errorDescription=url.searchParams.get("error_description");const evaluation=evaluateCallback({code,state,error,errorDescription,expectedState});callbackHandled=true;const settle=()=>{if(!resolved){resolved=true;resolve(evaluation.result)}};res.once("finish",settle);res.once("close",settle);sendHtmlResponse(res,evaluation.statusCode,evaluation.html)})});return new Promise((resolve,reject)=>{const onError=(err)=>{reject(new Error(`Failed to start callback server: ${err.message}`))};server.once("error",onError);server.listen(port,"127.0.0.1",()=>{server.off("error",onError);server.on("error",()=>{});resolve({result,close:()=>closeCallbackServerConnections(server,connections)})})})}async exchangeCodeForTokens(params){const body=new URLSearchParams({grant_type:"authorization_code",client_id:params.clientId,client_secret:params.clientSecret,code:params.code,code_verifier:params.codeVerifier,redirect_uri:params.redirectUri});const tokenEndpoint=validateServiceUrl(params.tokenEndpoint,"OAuth token endpoint");const response=await fetchWithTimeout(tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,OAUTH_ERROR_DETAIL_FIELDS);throw new Error(`Token exchange failed with HTTP ${response.status}.${detail?` ${detail}`:""}`)}return parseTokenResponse(await readJsonResponse(response,"Token exchange response was not valid JSON."))}async refreshAccessToken(params){const body=new URLSearchParams({grant_type:"refresh_token",client_id:params.clientId,client_secret:params.clientSecret,refresh_token:params.refreshToken});const tokenEndpoint=validateServiceUrl(params.tokenEndpoint,"OAuth token endpoint");const response=await fetchWithTimeout(tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:body.toString()},this.fetchOptions());if(!response.ok){const error=await response.text();throw new TokenRefreshError(response.status,error)}return parseRefreshTokenResponse(await readJsonResponse(response,"Token refresh response was not valid JSON."))}fetchOptions(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}}function classifyTerminalRefreshError(error){if(!(error instanceof TokenRefreshError)||error.status<400||error.status>=500){return}const oauthError=error.oauthError?.toLowerCase();switch(oauthError){case"invalid_grant":case"refresh_token_not_found":case"refresh_token_already_used":case"session_not_found":case"session_expired":return"invalid_refresh_token"}const text=[error.oauthError,error.oauthErrorDescription,error.body,error.message].filter((part)=>typeof part==="string").join(" ").toLowerCase();if(oauthError==="invalid_client"||text.includes("client not found")||text.includes("client id not found")||text.includes("client_id not found")||text.includes("oauth client not found")||text.includes("client does not match")||text.includes("client authentication required")||text.includes("invalid client credentials")){return"invalid_client"}return}function parseOAuthErrorBody(body){try{const parsed=JSON.parse(body);return{oauthError:stringField2(parsed.error)??stringField2(parsed.error_code)??stringField2(parsed.code),oauthErrorDescription:stringField2(parsed.error_description)??stringField2(parsed.errorDescription)??stringField2(parsed.message)??stringField2(parsed.msg)}}catch{return{oauthError:undefined,oauthErrorDescription:undefined}}}function stringField2(value){return typeof value==="string"&&value.trim()?value:undefined}var OAUTH_ERROR_DETAIL_FIELDS=["detail","error_description","message","msg","error"];var OAUTH_METADATA_SCHEMA=z7.object({authorization_endpoint:z7.string().min(1),token_endpoint:z7.string().min(1),registration_endpoint:z7.string().min(1)});var CLIENT_REGISTRATION_SCHEMA=z7.object({client_id:z7.string().min(1),client_secret:z7.string().min(1)});var EXPIRES_IN_SCHEMA=z7.union([z7.number(),z7.string().trim().regex(/^\d+(?:\.\d+)?$/).transform(Number)]).pipe(z7.number().positive());var TOKEN_RESPONSE_SCHEMA=z7.object({access_token:z7.string().min(1),refresh_token:z7.string().min(1),expires_in:EXPIRES_IN_SCHEMA.optional()});var REFRESH_TOKEN_RESPONSE_SCHEMA=z7.object({access_token:z7.string().min(1),refresh_token:z7.string().min(1).optional(),expires_in:EXPIRES_IN_SCHEMA.optional()});async function readJsonResponse(response,message){try{return await response.json()}catch(cause){throw new Error(message,{cause})}}function parseTokenResponse(data){const parsed=TOKEN_RESPONSE_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Token response missing required fields")}return{accessToken:parsed.data.access_token,refreshToken:parsed.data.refresh_token,expiresIn:parsed.data.expires_in??3600}}function parseRefreshTokenResponse(data){const parsed=REFRESH_TOKEN_RESPONSE_SCHEMA.safeParse(data);if(!parsed.success){throw new Error("Token response missing required fields")}return{accessToken:parsed.data.access_token,refreshToken:parsed.data.refresh_token,expiresIn:parsed.data.expires_in??3600}}function successHtml(title="You're signed in"){return`<!DOCTYPE html>
|
|
1596
1597
|
<html><head>
|
|
1597
1598
|
<title>GitHits CLI</title>
|
|
1598
1599
|
<meta charset="utf-8">
|
|
@@ -1930,4 +1931,4 @@ Warning: file storage is plaintext. Use it only on machines where local file acc
|
|
|
1930
1931
|
`)}
|
|
1931
1932
|
`}function formatAttributes(attributes){if(!attributes)return"";return Object.entries(attributes).map(([key,value])=>`${key}=${String(value)}`).join(" ")}function formatMs(value){return`${value.toFixed(1)}ms`}var PROACTIVE_REFRESH_RATIO=0.9;function shouldRefreshToken(token,ratio,now){if(!token.expiresAt){return{expired:false,shouldRefresh:false}}const expiresAt=new Date(token.expiresAt).getTime();const nowMs=now.getTime();if(nowMs>=expiresAt){return{expired:true,shouldRefresh:true}}const createdAt=new Date(token.createdAt).getTime();const lifetime=expiresAt-createdAt;if(lifetime<=0){return{expired:false,shouldRefresh:false}}const threshold=createdAt+lifetime*ratio;return{expired:false,shouldRefresh:nowMs>=threshold}}async function refreshExpiredToken(authService,authStorage,mcpUrl){const manager=new TokenManager({authService,authStorage,mcpUrl,refreshFailureMode:"return-undefined"});return manager.forceRefresh()}class TokenManager{authService;authStorage;mcpUrl;refreshFailureMode;authDiagnostics;cachedToken=null;softRefreshPromise=null;forceRefreshPromise=null;constructor(deps){this.authService=deps.authService;this.authStorage=deps.authStorage;this.mcpUrl=deps.mcpUrl;this.refreshFailureMode=deps.refreshFailureMode??"throw";this.authDiagnostics=deps.authDiagnostics}async getToken(){return withTelemetrySpan("token-manager.get-token",async()=>{const activeForceRefresh=this.forceRefreshPromise;if(activeForceRefresh){return(await activeForceRefresh).accessToken}if(!this.cachedToken){const storedToken=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));const startedForceRefresh=this.forceRefreshPromise;if(startedForceRefresh){return(await startedForceRefresh).accessToken}if(!this.cachedToken){this.cachedToken=storedToken}if(!this.cachedToken)return}const currentToken=this.cachedToken.accessToken;const{expired,shouldRefresh}=shouldRefreshToken(this.cachedToken,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh){return currentToken}let refresh;try{refresh=await this.refreshFromGetToken()}catch(error){if(!expired)return currentToken;throw error}if(refresh.accessToken){return refresh.accessToken}if(refresh.invalidatedCurrentToken){return}if(!expired){return currentToken}return})}async forceRefresh(){return withTelemetrySpan("token-manager.force-refresh",()=>this.refreshAfterAuthFailure())}refreshFromGetToken(){return this.softRefresh()}async softRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;if(this.softRefreshPromise)return this.softRefreshPromise;this.softRefreshPromise=this.executeRefresh();try{return await this.softRefreshPromise}finally{this.softRefreshPromise=null}}async refreshAfterAuthFailure(){const result=await this.forceEndpointRefresh();return result.accessToken}async forceEndpointRefresh(){if(this.forceRefreshPromise)return this.forceRefreshPromise;this.forceRefreshPromise=(async()=>{const softResult=await this.softRefreshPromise?.catch(()=>{return});if(softResult?.accessToken&&softResult.refreshedViaEndpoint){return softResult}return this.executeRefresh()})();try{return await this.forceRefreshPromise}finally{this.forceRefreshPromise=null}}async executeRefresh(){return withAuthStorageLock(this.authStorage,()=>withTelemetrySpan("token-manager.refresh",async()=>{const candidate=await this.loadRefreshCandidate();if(!candidate)return refreshResult(undefined,false);if(candidate.externallyUpdated){const{shouldRefresh}=shouldRefreshToken(candidate.tokens,PROACTIVE_REFRESH_RATIO,new Date);if(!shouldRefresh)return refreshResult(candidate.tokens.accessToken,false)}const tokens=candidate.tokens;const client=await withTelemetrySpan("token-manager.load-client",()=>this.authStorage.loadClient(this.mcpUrl));if(!client){if(this.refreshFailureMode==="return-undefined"){return refreshResult(undefined,false)}throw new AuthenticationError("Stored GitHits credentials cannot be refreshed because the OAuth client registration is missing or unreadable.","local")}let response;try{const metadata=await withTelemetrySpan("token-manager.discover-endpoints",()=>this.authService.discoverEndpoints(this.mcpUrl));response=await withTelemetrySpan("token-manager.refresh-access-token",()=>this.authService.refreshAccessToken({tokenEndpoint:metadata.tokenEndpoint,clientId:client.clientId,clientSecret:client.clientSecret,refreshToken:tokens.refreshToken}))}catch(error){const terminalFailure=classifyTerminalRefreshError(error);const reloadedToken=await this.loadExternallyUpdatedToken(tokens);if(reloadedToken)return refreshResult(reloadedToken.accessToken,false);const isExpired=tokens.expiresAt?new Date>=new Date(tokens.expiresAt):false;if(terminalFailure){return this.clearTerminalRefreshFailure(tokens,terminalFailure)}if(candidate.externallyUpdated&&!isExpired){return refreshResult(tokens.accessToken,false)}if(isExpired){const currentStoredTokens=await this.loadExternallyUpdatedToken(tokens);if(currentStoredTokens){return refreshResult(currentStoredTokens.accessToken,false)}}if(this.refreshFailureMode==="return-undefined"){return refreshResult(undefined,false)}throw error}const newTokenData={accessToken:response.accessToken,refreshToken:response.refreshToken??tokens.refreshToken,expiresAt:new Date(Date.now()+response.expiresIn*1000).toISOString(),createdAt:new Date().toISOString()};const saved=await withTelemetrySpan("token-manager.save-tokens",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,tokens,newTokenData));if(!saved){return this.resolveSuccessfulRefreshConflict(tokens,response,newTokenData)}this.cachedToken=newTokenData;return refreshResult(response.accessToken,true)}))}async resolveSuccessfulRefreshConflict(refreshedFrom,response,newTokenData){const currentToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!currentToken){this.cachedToken=null;return refreshResult(undefined,false)}if(!response.refreshToken||currentToken.refreshToken!==refreshedFrom.refreshToken){this.cachedToken=currentToken;return refreshResult(currentToken.accessToken,false)}const saved=await withTelemetrySpan("token-manager.save-rotated-tokens-after-conflict",()=>this.authStorage.saveTokensIfUnchanged(this.mcpUrl,currentToken,newTokenData));if(saved){this.cachedToken=newTokenData;return refreshResult(newTokenData.accessToken,true)}const latestToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));this.cachedToken=latestToken;return refreshResult(latestToken?.accessToken,false)}async clearTerminalRefreshFailure(failedTokens,reason){const cleared=await withTelemetrySpan("token-manager.clear-terminal-refresh-failure",()=>this.authStorage.clearActiveTokensIfUnchanged(this.mcpUrl,failedTokens),{reason:`terminal_${reason}`});if(!cleared){const latestToken=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));this.cachedToken=latestToken;return refreshResult(latestToken?.accessToken,false,!latestToken)}if(reason==="invalid_client"){await withTelemetrySpan("token-manager.clear-invalid-client",()=>this.authStorage.clearActiveClient(this.mcpUrl),{reason:"terminal_invalid_client"}).catch(()=>{return})}await this.authDiagnostics?.recordClear(this.mcpUrl,`terminal_${reason}`);this.cachedToken=null;return refreshResult(undefined,false,true)}async loadRefreshCandidate(){const storedTokens=await withTelemetrySpan("token-manager.load-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!this.cachedToken){this.cachedToken=storedTokens;return storedTokens?{tokens:storedTokens,externallyUpdated:false}:null}if(!storedTokens){this.cachedToken=null;return null}if(!areSameTokenData(storedTokens,this.cachedToken)){this.cachedToken=storedTokens;return{tokens:storedTokens,externallyUpdated:true}}return{tokens:this.cachedToken,externallyUpdated:false}}async loadExternallyUpdatedToken(failedTokens){const storedTokens=await withTelemetrySpan("token-manager.reload-tokens",()=>this.authStorage.loadTokens(this.mcpUrl));if(!storedTokens)return;if(areSameTokenData(storedTokens,failedTokens))return;this.cachedToken=storedTokens;return storedTokens}}function areSameTokenData(a,b){return a.accessToken===b.accessToken&&a.refreshToken===b.refreshToken&&a.expiresAt===b.expiresAt&&a.createdAt===b.createdAt}function refreshResult(accessToken,refreshedViaEndpoint,invalidatedCurrentToken=false){return{accessToken,refreshedViaEndpoint,invalidatedCurrentToken}}function debugLog(area,payload){if(!isAreaEnabled(area))return;const line={ts:new Date().toISOString(),area,...payload};let text;try{text=JSON.stringify(line)}catch{text=JSON.stringify({ts:line.ts,area,error:"debug-log payload not serialisable"})}process.stderr.write(`${text}
|
|
1932
1933
|
`)}function isDebugAreaEnabled(area){return isAreaEnabled(area)}function isAreaEnabled(area){const raw=process.env.GITHITS_DEBUG;if(!raw||raw==="")return false;const scopes=raw.split(",").map((s)=>s.trim()).filter(Boolean);if(scopes.includes(area))return true;if(isExplicitOnlyArea(area))return false;return scopes.includes("*")}function isExplicitOnlyArea(area){return area==="code-nav-wire"}var BASE_CLIENT_NAME="githits-cli";var USER_AGENT=`${BASE_CLIENT_NAME}/${version2}`;async function createAuthStorage(fileSystemService){return withTelemetrySpan("container.create-auth-storage",async()=>{const authConfig=await loadAuthConfig(fileSystemService);recordAuthFingerprint(authConfig.storage);return createAuthStorageForMode(fileSystemService,authConfig.storage,authConfig.configPath)})}function recordAuthFingerprint(mode,env=process.env){const handle=startTelemetrySpan("auth.fingerprint",{mode,platform:process.platform,homeSet:Boolean(env.HOME),xdgConfigHomeSet:Boolean(env.XDG_CONFIG_HOME),appDataSet:Boolean(env.APPDATA),userProfileSet:Boolean(env.USERPROFILE)});endTelemetrySpan(handle)}function createAuthStorageForMode(fileSystemService,mode,configPath="your GitHits config.toml"){const fileStorage=new ModeAwareFileAuthStorage(new AuthStorageImpl(fileSystemService,getAuthFileStorageDir(fileSystemService)),mode,configPath);const legacyStorage=new AuthStorageImpl(fileSystemService,getLegacyAuthStorageDir(fileSystemService));const additionalLegacyStores=process.platform==="darwin"?[new AuthStorageImpl(fileSystemService,getLegacyMacAuthFileStorageDir(fileSystemService))]:[];const rawKeyring=new KeyringServiceImpl;const keyring=process.platform==="win32"?new ChunkingKeyringService(rawKeyring,WINDOWS_MAX_ENTRY_SIZE):rawKeyring;const keychainStorage=new KeychainAuthStorage(keyring);const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return new LockedAuthStorage(new MigratingAuthStorage(keychainStorage,fileStorage,legacyStorage,mode,configPath,(message)=>console.error(message),metadataStorage,additionalLegacyStores),fileSystemService)}async function loadAutoLoginAuthSessionMetadata2(){const envToken=getEnvApiToken();if(envToken){const now=new Date().toISOString();return{createdAt:now,expiresAt:null,updatedAt:now}}const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);return metadataStorage.load(getMcpStorageKeyUrl())}async function clearAutoLoginAuthSessionMetadata2(){const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);await metadataStorage.clear(getMcpStorageKeyUrl())}async function createAuthCommandDependencies2(){return withTelemetrySpan("container.create-auth-command",async()=>{const fileSystemService=new FileSystemServiceImpl;return{authStorage:await createAuthStorage(fileSystemService),authService:new AuthServiceImpl(createLazyCliFetch()),browserService:new BrowserServiceImpl,fileSystemService,authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpStorageKeyUrl(),envApiToken:getEnvApiToken()}})}async function createLogoutCommandDependencies2(){return withTelemetrySpan("container.create-logout-command",async()=>{const fileSystemService=new FileSystemServiceImpl;return{authStorage:createAuthStorageForMode(fileSystemService,"keychain",getAuthConfigPath(fileSystemService)),authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpStorageKeyUrl()}})}async function createAuthStatusDependencies2(){return withTelemetrySpan("container.create-auth-status",async()=>{const fileSystemService=new FileSystemServiceImpl;const envApiToken=getEnvApiToken();return{authStorage:envApiToken?createAuthStorageForMode(fileSystemService,"keychain"):await createAuthStorage(fileSystemService),authService:new AuthServiceImpl(createLazyCliFetch()),browserService:new BrowserServiceImpl,fileSystemService,authDiagnostics:new AuthDiagnosticsStorage(fileSystemService),mcpUrl:getMcpStorageKeyUrl(),envApiToken}})}async function createContainer2(options={}){return withTelemetrySpan("container.create",async()=>{const resolveStoredToken=options.resolveStoredToken??true;const mcpUrl=getMcpUrl();const apiUrl=getApiUrl();const codeNavigationUrl=getCodeNavigationUrl();const fileSystemService=new FileSystemServiceImpl;const fetchFn=createCliFetch();const authService=new AuthServiceImpl(fetchFn);const browserService=new BrowserServiceImpl;const clientHeaders=createClientHeaderBuilder({clientName:options.clientName??BASE_CLIENT_NAME,clientVersion:version2,agentProvider:options.agentProvider});const diagnostics={withOperation:withTelemetrySpan,isEnabled:isDebugAreaEnabled,debug:debugLog};const serviceRuntime={clientHeaders,userAgent:USER_AGENT,clientVersion:version2,diagnostics};const envToken=getEnvApiToken();if(envToken){const authStorage=createAuthStorageForMode(fileSystemService,"keychain");const tokenProvider=createStaticTokenProvider(envToken);const codeNavigationService=new CodeNavigationServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const packageIntelligenceService=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const resolveTargetService=new ResolveTargetServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const agenticAskService=new AgenticAskServiceImpl(apiUrl,tokenProvider,fetchFn,{...serviceRuntime,timeoutMs:AGENTIC_ASK_REQUEST_TIMEOUT_MS});return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken:envToken,hasValidToken:true,envApiToken:envToken,codeNavigationUrl,codeNavigationService,packageIntelligenceService,resolveTargetService,agenticAskService,githitsService:new GitHitsServiceImpl(apiUrl,envToken,fetchFn,undefined,serviceRuntime),tokenProvider}}const authStorage=await createAuthStorage(fileSystemService);const tokenManager=new TokenManager({authService,authStorage,mcpUrl,...options.refreshFailureMode!==undefined?{refreshFailureMode:options.refreshFailureMode}:{},authDiagnostics:new AuthDiagnosticsStorage(fileSystemService)});const apiToken=resolveStoredToken?await withTelemetrySpan("container.token.get",()=>tokenManager.getToken()):undefined;if(resolveStoredToken&&apiToken===undefined){await new AuthSessionMetadataStorage(fileSystemService).clear(mcpUrl)}const codeNavigationService=new CodeNavigationServiceImpl(codeNavigationUrl,tokenManager,fetchFn,serviceRuntime);const packageIntelligenceService=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenManager,fetchFn,serviceRuntime);const resolveTargetService=new ResolveTargetServiceImpl(codeNavigationUrl,tokenManager,fetchFn,serviceRuntime);const agenticAskService=new AgenticAskServiceImpl(apiUrl,tokenManager,fetchFn,{...serviceRuntime,timeoutMs:AGENTIC_ASK_REQUEST_TIMEOUT_MS});return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken,hasValidToken:apiToken!==undefined,envApiToken:undefined,codeNavigationUrl,codeNavigationService,packageIntelligenceService,resolveTargetService,agenticAskService,githitsService:new RefreshingGitHitsService(apiUrl,tokenManager,(innerApiUrl,token)=>new GitHitsServiceImpl(innerApiUrl,token,fetchFn,undefined,serviceRuntime),serviceRuntime),tokenProvider:tokenManager}})}
|
|
1933
|
-
export{LOCAL_AUTHENTICATION_MISSING_MESSAGE,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError,ApiRateLimitError,FetchTimeoutError,fetchWithTimeout,isFetchTimeoutError,TERMS_URL,TermsAcceptanceRequiredError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,validateServiceUrl,normalizeSingleLineText,AgenticAskHttpError,AgenticAskRequestTimeoutError,AgenticAskConnectionError,MalformedAgenticAskResponseError,AgenticAskResponseTooLargeError,normalizeAgenticAskThreadId,
|
|
1934
|
+
export{LOCAL_AUTHENTICATION_MISSING_MESSAGE,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError,ApiRateLimitError,FetchTimeoutError,fetchWithTimeout,isFetchTimeoutError,TERMS_URL,TermsAcceptanceRequiredError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,validateServiceUrl,normalizeSingleLineText,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,AgenticAskHttpError,AgenticAskRequestTimeoutError,AgenticAskConnectionError,MalformedAgenticAskResponseError,AgenticAskResponseTooLargeError,normalizeAgenticAskThreadId,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,GREP_REPO_SYMBOL_FIELDS,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,getAppConfigDirForEnv,getAuthConfigPath,getAuthConfigPathForEnv,getAuthFileStorageDirForEnv,getLegacyAuthStorageDirForEnv,getLegacyMacAuthConfigPathForEnv,getLegacyMacAuthFileStorageDirForEnv,AppConfigError,readAppConfig,AuthConfigError,parseAuthStorageMode,AuthStorageLockTimeoutError,AuthStoragePolicyError,debugLog,isDebugAreaEnabled,normalizeBaseUrl,isAuthClearReason,FileSystemServiceImpl,createCliFetch,createLazyCliFetch,isTelemetryEnabled,withTelemetrySpan,startTelemetrySpan,endTelemetrySpan,flushTelemetry,refreshExpiredToken,loadAutoLoginAuthSessionMetadata2,clearAutoLoginAuthSessionMetadata2,createAuthCommandDependencies2,createLogoutCommandDependencies2,createAuthStatusDependencies2,createContainer2};
|