githits 0.12.0 → 0.12.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.
@@ -0,0 +1,1797 @@
1
+ import{version2}from"./chunk-19g34jxs.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)}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){const status=response.status;switch(status){case 400:return new AgenticAskHttpError("INVALID_TARGET","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
+ availableRefs {
3
+ version
4
+ ref
5
+ }`;var TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION=`
6
+ suggestedRefs {
7
+ version
8
+ ref
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
+ sourceKind
97
+ sourceUrl
98
+ repoUrl
99
+ gitRef
100
+ commitSha
101
+ requestedRef
102
+ filePath
103
+ repositoryFilePath
104
+ startLine
105
+ endLine
106
+ evidenceRange {
107
+ startLine
108
+ endLine
109
+ matchLine
110
+ rangeKind
111
+ matchSpansTruncated
112
+ }
113
+ indexedRange {
114
+ startLine
115
+ endLine
116
+ }
117
+ symbolContext {
118
+ name
119
+ qualifiedPath
120
+ kind
121
+ relation
122
+ definitionRange {
123
+ filePath
124
+ repositoryFilePath
125
+ startLine
126
+ endLine
127
+ }
128
+ }
129
+ fileContentHash
130
+ symbolRef
131
+ qualifiedPath
132
+ kind
133
+ category
134
+ language`;var UNIFIED_SEARCH_QUERY=`
135
+ query UnifiedSearch(
136
+ $targets: [SearchPackageInput!]!
137
+ $query: String!
138
+ $sources: [DiscoverySearchSource!]
139
+ $filters: DiscoverySearchFiltersInput
140
+ $allowPartialResults: Boolean
141
+ $limit: Int
142
+ $offset: Int
143
+ $waitTimeoutMs: Int
144
+ ) {
145
+ search(
146
+ targets: $targets
147
+ query: $query
148
+ sources: $sources
149
+ filters: $filters
150
+ allowPartialResults: $allowPartialResults
151
+ limit: $limit
152
+ offset: $offset
153
+ waitTimeoutMs: $waitTimeoutMs
154
+ ) {
155
+ completed
156
+ searchRef
157
+ result {
158
+ query
159
+ queryWarnings
160
+ sources
161
+ results {
162
+ id
163
+ resultType
164
+ targetLabel
165
+ requestedTargetLabel
166
+ freshTargetLabel
167
+ servedTargetLabel
168
+ freshness
169
+ title
170
+ summary
171
+ score
172
+ highlights {
173
+ title
174
+ summary
175
+ }
176
+ locator {
177
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
178
+ }
179
+ }
180
+ page {
181
+ offset
182
+ limit
183
+ returned
184
+ hasMore
185
+ }
186
+ partialResults
187
+ evidenceNotice
188
+ sourceStatus {
189
+ source
190
+ targetLabel
191
+ requestedTargetLabel
192
+ freshTargetLabel
193
+ servedTargetLabel
194
+ ${TARGET_RESOLUTION_SELECTION}
195
+ indexingStatus
196
+ codeIndexState
197
+ resultCount
198
+ appliedFilters
199
+ ignoredFilters
200
+ incompatibleFilters
201
+ appliedQueryFeatures
202
+ ignoredQueryFeatures
203
+ incompatibleQueryFeatures
204
+ suggestedSiteTargets
205
+ suggestedSiteTargetsTruncated
206
+ note
207
+ ${DOC_COVERAGE_SELECTION}
208
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
209
+ }
210
+ }
211
+ progress {
212
+ searchRef
213
+ status
214
+ targetsTotal
215
+ targetsReady
216
+ elapsedMs
217
+ query
218
+ queryWarnings
219
+ sources
220
+ requestedSources
221
+ targetMode
222
+ requestedTargets {
223
+ registry
224
+ name
225
+ version
226
+ repoUrl
227
+ gitRef
228
+ site
229
+ }
230
+ filters {
231
+ fileIntent
232
+ kind
233
+ category
234
+ publicOnly
235
+ pathPrefix
236
+ }
237
+ limit
238
+ offset
239
+ targets {
240
+ requested
241
+ resolvedRequested
242
+ served
243
+ freshness
244
+ indexingRef
245
+ requestedRefKind
246
+ ${TARGET_RESOLUTION_SELECTION}
247
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
248
+ ${DOC_COVERAGE_SELECTION}
249
+ }
250
+ expiresAt
251
+ }
252
+ }
253
+ }`;var UNIFIED_SEARCH_STATUS_QUERY=`
254
+ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
255
+ discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
256
+ searchRef
257
+ status
258
+ targetsTotal
259
+ targetsReady
260
+ elapsedMs
261
+ query
262
+ queryWarnings
263
+ sources
264
+ requestedSources
265
+ targetMode
266
+ requestedTargets {
267
+ registry
268
+ name
269
+ version
270
+ repoUrl
271
+ gitRef
272
+ site
273
+ }
274
+ filters {
275
+ fileIntent
276
+ kind
277
+ category
278
+ publicOnly
279
+ pathPrefix
280
+ }
281
+ limit
282
+ offset
283
+ targets {
284
+ requested
285
+ resolvedRequested
286
+ served
287
+ freshness
288
+ indexingRef
289
+ requestedRefKind
290
+ ${TARGET_RESOLUTION_SELECTION}
291
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
292
+ ${DOC_COVERAGE_SELECTION}
293
+ }
294
+ expiresAt
295
+ results {
296
+ query
297
+ queryWarnings
298
+ sources
299
+ results {
300
+ id
301
+ resultType
302
+ targetLabel
303
+ requestedTargetLabel
304
+ freshTargetLabel
305
+ servedTargetLabel
306
+ freshness
307
+ title
308
+ summary
309
+ score
310
+ highlights {
311
+ title
312
+ summary
313
+ }
314
+ locator {
315
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
316
+ }
317
+ }
318
+ page {
319
+ offset
320
+ limit
321
+ returned
322
+ hasMore
323
+ }
324
+ partialResults
325
+ evidenceNotice
326
+ sourceStatus {
327
+ source
328
+ targetLabel
329
+ requestedTargetLabel
330
+ freshTargetLabel
331
+ servedTargetLabel
332
+ ${TARGET_RESOLUTION_SELECTION}
333
+ indexingStatus
334
+ codeIndexState
335
+ resultCount
336
+ appliedFilters
337
+ ignoredFilters
338
+ incompatibleFilters
339
+ appliedQueryFeatures
340
+ ignoredQueryFeatures
341
+ incompatibleQueryFeatures
342
+ suggestedSiteTargets
343
+ suggestedSiteTargetsTruncated
344
+ note
345
+ ${DOC_COVERAGE_SELECTION}
346
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
347
+ }
348
+ }
349
+ }
350
+ }`;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(),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 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(),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 contentSafetySchema=z3.object({filtered:z3.boolean(),modifications:z3.array(z3.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});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 {
351
+ registry
352
+ name
353
+ repoUrl
354
+ }
355
+ fromResolution {
356
+ requested
357
+ resolvedVersion
358
+ ref
359
+ commitSha
360
+ refKind
361
+ versionSource
362
+ }
363
+ toResolution {
364
+ requested
365
+ resolvedVersion
366
+ ref
367
+ commitSha
368
+ refKind
369
+ versionSource
370
+ }
371
+ raw {
372
+ summary {
373
+ filesChanged
374
+ added
375
+ deleted
376
+ modified
377
+ modeChanged
378
+ typeChanged
379
+ inventoryComplete
380
+ unprojectableFiles
381
+ }
382
+ scope {
383
+ status
384
+ fromSubpath
385
+ toSubpath
386
+ pathPrefix
387
+ pathGlob
388
+ }
389
+ contentCoverage
390
+ contentFailure {
391
+ code
392
+ retryable
393
+ retryAfterMs
394
+ stage
395
+ limitKind
396
+ }
397
+ files {
398
+ path
399
+ pathEncoding
400
+ status
401
+ modeChanged
402
+ typeChanged
403
+ contentStatus
404
+ contentSafety {
405
+ filtered
406
+ modifications
407
+ }`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
408
+ additions
409
+ deletions`:`
410
+ additions
411
+ deletions
412
+ patch
413
+ contentOmissionReason`;return`
414
+ query CodeDiff(
415
+ $registry: Registry
416
+ $name: String
417
+ $fromVersion: String
418
+ $toVersion: String
419
+ $repoUrl: String
420
+ $fromRef: String
421
+ $toRef: String
422
+ $rawOptions: RawCodeDiffOptions
423
+ ) {
424
+ codeDiff(
425
+ registry: $registry
426
+ name: $name
427
+ fromVersion: $fromVersion
428
+ toVersion: $toVersion
429
+ repoUrl: $repoUrl
430
+ fromRef: $fromRef
431
+ toRef: $toRef
432
+ rawOptions: $rawOptions
433
+ ) {
434
+ ${CODE_DIFF_COMMON_SELECTION}${contentFields}
435
+ }
436
+ hasMoreFiles
437
+ }
438
+ }
439
+ }`}var navigationResolutionSchema=z3.object({requestedVersion:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),resolvedRef:z3.string().nullable().optional(),commitSha:z3.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z3.object({hint:z3.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z3.object({path:z3.string(),name:z3.string().nullable().optional(),language:z3.string().nullable().optional(),fileType:z3.string().nullable().optional(),byteSize:z3.number().int().nullable().optional()});var listRepoFilesResponseSchema=z3.object({files:z3.array(repoFileEntrySchema),total:z3.number().int(),hasMore:z3.boolean(),indexedVersion:z3.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var listRepoFilesGraphQLResponseSchema=z3.object({data:z3.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
440
+ query ListRepoFiles(
441
+ $registry: Registry
442
+ $packageName: String
443
+ $repoUrl: String
444
+ $gitRef: String
445
+ $version: String
446
+ $pathPrefix: String
447
+ $pathSelectors: [FilePathSelectorInput!]
448
+ $extensions: [String!]
449
+ $fileTypes: [String!]
450
+ $languages: [String!]
451
+ $fileIntent: FileIntent
452
+ $fileIntents: [FileIntent!]
453
+ $excludeFileIntents: [FileIntent!]
454
+ $excludeDocFiles: Boolean
455
+ $excludeTestFiles: Boolean
456
+ $includeHidden: Boolean
457
+ $limit: Int
458
+ $waitTimeoutMs: Int
459
+ ) {
460
+ listRepoFiles(
461
+ registry: $registry
462
+ packageName: $packageName
463
+ repoUrl: $repoUrl
464
+ gitRef: $gitRef
465
+ version: $version
466
+ pathPrefix: $pathPrefix
467
+ pathSelectors: $pathSelectors
468
+ extensions: $extensions
469
+ fileTypes: $fileTypes
470
+ languages: $languages
471
+ fileIntent: $fileIntent
472
+ fileIntents: $fileIntents
473
+ excludeFileIntents: $excludeFileIntents
474
+ excludeDocFiles: $excludeDocFiles
475
+ excludeTestFiles: $excludeTestFiles
476
+ includeHidden: $includeHidden
477
+ limit: $limit
478
+ waitTimeoutMs: $waitTimeoutMs
479
+ ) {
480
+ files {
481
+ path
482
+ name
483
+ language
484
+ fileType
485
+ byteSize
486
+ }
487
+ total
488
+ hasMore
489
+ indexedVersion
490
+ resolution {
491
+ requestedVersion
492
+ requestedRef
493
+ resolvedRef
494
+ commitSha
495
+ }
496
+ ${TARGET_RESOLUTION_SELECTION}
497
+ diagnostics {
498
+ hint
499
+ }
500
+ codeIndexState
501
+ indexingRef
502
+ availableVersions {
503
+ version
504
+ ref
505
+ }
506
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
507
+ }
508
+ }`;var codeContextResponseSchema=z3.object({content:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),language:z3.string().nullable().optional(),totalLines:z3.number().int().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),isBinary:z3.boolean().nullable().optional(),codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z3.object({data:z3.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
509
+ query FetchCodeContext(
510
+ $registry: Registry
511
+ $packageName: String
512
+ $repoUrl: String
513
+ $gitRef: String
514
+ $version: String
515
+ $filePath: String!
516
+ $startLine: Int
517
+ $endLine: Int
518
+ $waitTimeoutMs: Int
519
+ ) {
520
+ fetchCodeContext(
521
+ registry: $registry
522
+ packageName: $packageName
523
+ repoUrl: $repoUrl
524
+ gitRef: $gitRef
525
+ version: $version
526
+ filePath: $filePath
527
+ startLine: $startLine
528
+ endLine: $endLine
529
+ waitTimeoutMs: $waitTimeoutMs
530
+ ) {
531
+ content
532
+ filePath
533
+ language
534
+ totalLines
535
+ startLine
536
+ endLine
537
+ repoUrl
538
+ gitRef
539
+ isBinary
540
+ codeIndexState
541
+ indexingRef
542
+ ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
543
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
544
+ ${TARGET_RESOLUTION_SELECTION}
545
+ }
546
+ }`;var grepRepoMatchSchema=z3.object({filePath:z3.string(),line:z3.number().int(),matchStartByte:z3.number().int(),matchEndByte:z3.number().int(),lineContent:z3.string(),contextBefore:z3.array(z3.string()).nullable().optional(),contextAfter:z3.array(z3.string()).nullable().optional(),fileContentHash:z3.string().nullable().optional(),fileIntent:z3.string().nullable().optional(),symbolRowId:z3.string().nullable().optional(),symbol:z3.object({symbolRef:z3.string().optional(),name:z3.string().optional(),qualifiedPath:z3.string().nullable().optional(),kind:z3.string().nullable().optional(),category:z3.string().nullable().optional(),arity:z3.number().int().nullable().optional(),isPublic:z3.boolean().nullable().optional(),filePath:z3.string().nullable().optional(),startLine:z3.number().int().nullable().optional(),endLine:z3.number().int().nullable().optional(),contentHash:z3.string().nullable().optional(),parentPath:z3.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z3.object({matches:z3.array(grepRepoMatchSchema),nextCursor:z3.string().nullable().optional(),hasMore:z3.boolean(),truncatedReason:z3.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z3.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z3.number().int(),filesInScope:z3.number().int(),binaryFilesSkipped:z3.number().int(),filesTooLargeSkipped:z3.number().int(),totalMatches:z3.number().int(),uniqueFilesMatched:z3.number().int(),indexedVersion:z3.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z3.string(),indexingRef:z3.string().nullable().optional(),availableVersions:z3.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var grepRepoGraphQLResponseSchema=z3.object({data:z3.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema).optional()});var GREP_REPO_SYMBOL_SELECTIONS={symbol_ref:"symbolRef",name:"name",qualified_path:"qualifiedPath",kind:"kind",category:"category",arity:"arity",is_public:"isPublic",file_path:"filePath",start_line:"startLine",end_line:"endLine",content_hash:"contentHash",parent_path:"parentPath"};function buildGrepRepoQuery(symbolFields){const symbolSelection=(symbolFields??[]).map((field)=>GREP_REPO_SYMBOL_SELECTIONS[field]).filter((field)=>Boolean(field)).filter((field,index,fields)=>fields.indexOf(field)===index).join(`
547
+ `);const symbolBlock=symbolSelection.length>0?`
548
+ symbol {
549
+ ${symbolSelection}
550
+ }`:"";return`
551
+ query GrepRepo(
552
+ $registry: Registry
553
+ $packageName: String
554
+ $repoUrl: String
555
+ $gitRef: String
556
+ $version: String
557
+ $waitTimeoutMs: Int
558
+ $pattern: String!
559
+ $patternType: GrepPatternType
560
+ $caseSensitive: Boolean
561
+ $pathSelectors: [GrepPathSelectorInput!]
562
+ $extensions: [String!]
563
+ $excludeDocFiles: Boolean
564
+ $excludeTestFiles: Boolean
565
+ $allowUnscoped: Boolean
566
+ $contextLinesBefore: Int
567
+ $contextLinesAfter: Int
568
+ $maxMatches: Int
569
+ $maxMatchesPerFile: Int
570
+ $cursor: String
571
+ $symbolFields: [String!]
572
+ ) {
573
+ grepRepo(
574
+ registry: $registry
575
+ packageName: $packageName
576
+ repoUrl: $repoUrl
577
+ gitRef: $gitRef
578
+ version: $version
579
+ waitTimeoutMs: $waitTimeoutMs
580
+ pattern: $pattern
581
+ patternType: $patternType
582
+ caseSensitive: $caseSensitive
583
+ pathSelectors: $pathSelectors
584
+ extensions: $extensions
585
+ excludeDocFiles: $excludeDocFiles
586
+ excludeTestFiles: $excludeTestFiles
587
+ allowUnscoped: $allowUnscoped
588
+ contextLinesBefore: $contextLinesBefore
589
+ contextLinesAfter: $contextLinesAfter
590
+ maxMatches: $maxMatches
591
+ maxMatchesPerFile: $maxMatchesPerFile
592
+ cursor: $cursor
593
+ symbolFields: $symbolFields
594
+ ) {
595
+ matches {
596
+ filePath
597
+ line
598
+ matchStartByte
599
+ matchEndByte
600
+ lineContent
601
+ contextBefore
602
+ contextAfter
603
+ fileContentHash
604
+ fileIntent
605
+ symbolRowId${symbolBlock}
606
+ }
607
+ nextCursor
608
+ totalMatches
609
+ hasMore
610
+ truncatedReason
611
+ routeTaken
612
+ filesScanned
613
+ filesInScope
614
+ binaryFilesSkipped
615
+ filesTooLargeSkipped
616
+ uniqueFilesMatched
617
+ indexedVersion
618
+ resolution {
619
+ requestedVersion
620
+ requestedRef
621
+ resolvedRef
622
+ commitSha
623
+ }
624
+ ${TARGET_RESOLUTION_SELECTION}
625
+ codeIndexState
626
+ indexingRef
627
+ availableVersions {
628
+ version
629
+ ref
630
+ }
631
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
632
+ }
633
+ }`}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){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef,waitTimeoutMs=0){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs)})}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){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};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){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true,waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){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"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,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,sourceKind:value.sourceKind??undefined,sourceUrl:value.sourceUrl??undefined,repoUrl:value.repoUrl??undefined,gitRef:value.gitRef??undefined,commitSha:value.commitSha??undefined,requestedRef:value.requestedRef??undefined,filePath:value.filePath??undefined,repositoryFilePath:value.repositoryFilePath??undefined,startLine:value.startLine??undefined,endLine:value.endLine??undefined,evidenceRange:value.evidenceRange?{startLine:value.evidenceRange.startLine,endLine:value.evidenceRange.endLine,matchLine:value.evidenceRange.matchLine??undefined,rangeKind:value.evidenceRange.rangeKind??undefined,matchSpansTruncated:value.evidenceRange.matchSpansTruncated}:undefined,indexedRange:value.indexedRange?{startLine:value.indexedRange.startLine,endLine:value.indexedRange.endLine}:undefined,symbolContext:value.symbolContext?normaliseUnifiedSearchSymbolContext(value.symbolContext):undefined,fileContentHash:value.fileContentHash??undefined,symbolRef:value.symbolRef??undefined,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined,category:value.category??undefined,language:value.language??undefined}}function normaliseUnifiedSearchSymbolContext(value){const identity={name:value.name,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined};if(value.relation==="ENCLOSES_MATCH"){return{...identity,relation:"encloses_match",definitionRange:normaliseUnifiedSearchDefinitionRange(value.definitionRange)}}return{...identity,relation:"associated_with_indexed_chunk",definitionRange:value.definitionRange?normaliseUnifiedSearchDefinitionRange(value.definitionRange):undefined}}function normaliseUnifiedSearchDefinitionRange(value){return{filePath:value.filePath,repositoryFilePath:value.repositoryFilePath,startLine:value.startLine,endLine:value.endLine}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}const availableVersions=parseCodeDiffErrorRefs(extensions.available_versions);if(availableVersions)details.availableVersions=availableVersions;if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function 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=`
634
+ query PackageSummary(
635
+ $registry: Registry!
636
+ $name: String!
637
+ $includeVerboseFields: Boolean! = true
638
+ ) {
639
+ packageSummary(registry: $registry, name: $name) {
640
+ package {
641
+ name
642
+ registry
643
+ description
644
+ latestVersion
645
+ latestVersionPublishedAt
646
+ homepage
647
+ repositoryUrl
648
+ license
649
+ downloadsLastMonth
650
+ downloadsTotal
651
+ versionCount @include(if: $includeVerboseFields)
652
+ downloadsRefreshedAt @include(if: $includeVerboseFields)
653
+ githubRepository {
654
+ stargazersCount
655
+ forksCount
656
+ openIssuesCount
657
+ archived
658
+ language @include(if: $includeVerboseFields)
659
+ topics @include(if: $includeVerboseFields)
660
+ pushedAt @include(if: $includeVerboseFields)
661
+ }
662
+ }
663
+ security {
664
+ vulnerabilityCount
665
+ allVulnerabilityCount
666
+ hasCurrentVulnerabilities
667
+ recentVulnerabilities @include(if: $includeVerboseFields) {
668
+ osvId
669
+ summary
670
+ severityScore
671
+ publishedAt
672
+ }
673
+ }
674
+ latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
675
+ version
676
+ publishedAt
677
+ body
678
+ }
679
+ }
680
+ }`;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 PACKAGE_VULNERABILITIES_QUERY=`
681
+ query PackageVulnerabilities(
682
+ $registry: Registry!
683
+ $name: String!
684
+ $version: String
685
+ $minSeverity: Float
686
+ $includeWithdrawn: Boolean
687
+ $scope: VulnerabilityScope = AFFECTED
688
+ $after: String
689
+ ) {
690
+ packageVulnerabilities(
691
+ registry: $registry
692
+ name: $name
693
+ version: $version
694
+ minSeverity: $minSeverity
695
+ includeWithdrawn: $includeWithdrawn
696
+ ) {
697
+ package {
698
+ name
699
+ registry
700
+ version
701
+ }
702
+ security {
703
+ affectedVulnerabilityCount
704
+ nonAffectingVulnerabilityCount
705
+ allVulnerabilityCount
706
+ currentVersionAffected
707
+ upgradePaths
708
+ advisories(scope: $scope, first: 100, after: $after) {
709
+ entries {
710
+ osvId
711
+ summary
712
+ severityScore
713
+ severityType
714
+ affectedVersionRanges
715
+ affectedVersionRangesCount
716
+ affectedVersionRangesTruncated
717
+ fixedInVersions
718
+ publishedAt
719
+ modifiedAt
720
+ withdrawnAt
721
+ aliases
722
+ isMalicious
723
+ affectsInspectedVersion
724
+ matchedAffectedVersionRanges
725
+ duplicateIds
726
+ }
727
+ pageInfo {
728
+ hasNextPage
729
+ endCursor
730
+ totalCount
731
+ }
732
+ }
733
+ }
734
+ }
735
+ }`;var directDependencySchema=z4.object({name:z4.string().nullable().optional(),versionConstraint:z4.string().nullable().optional(),type:z4.string().nullable().optional()});var dependencyGraphNodeSchema=z4.object({registry:z4.string(),name:z4.string(),version:z4.string().nullable().optional()});var dependencyGraphEdgeSchema=z4.object({fromIndex:z4.number().int().nullable().optional(),toIndex:z4.number().int(),constraint:z4.string().nullable().optional(),dependencyType:z4.string().nullable().optional()});var dependencyGraphSchema=z4.object({formatVersion:z4.number().int(),nodes:z4.array(dependencyGraphNodeSchema),edges:z4.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z4.object({totalVulnerabilities:z4.number().int(),critical:z4.number().int(),high:z4.number().int(),medium:z4.number().int(),low:z4.number().int(),unknown:z4.number().int()});var vulnerabilitySummaryDetailSchema=z4.object({osvId:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),packageName: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(),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()});var transitiveDependencyVulnerabilitySchema=z4.object({version:z4.string(),affectsResolvedVersion:z4.boolean(),matchedAffectedVersionRanges:z4.array(z4.string()),fixVersionsAboveResolved:z4.array(z4.string()),nearestFixedVersion:z4.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z4.object({registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),affectedCount:z4.number().int(),nonAffectingCount:z4.number().int(),totalCount:z4.number().int(),maxSeverityScore:z4.number().nullable().optional(),maxSeverityLabel:z4.string().nullable().optional(),advisoryIds:z4.array(z4.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z4.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z4.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z4.number().int(),affectedPackageCount:z4.number().int(),packages:z4.array(transitiveVulnerablePackageSchema),calculatedAt:z4.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z4.object({version:z4.string(),reason:z4.string().nullable().optional()});var deprecatedDependencySchema=z4.object({registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),reasons:z4.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z4.object({version:z4.string(),severity:z4.string()});var outdatedDependencySchema=z4.object({registry:z4.string(),name:z4.string(),latestVersion:z4.string().nullable().optional(),severity:z4.string(),versions:z4.array(outdatedDependencyVersionSchema),repositoryUrl:z4.string().nullable().optional()});var duplicateDependencySchema=z4.object({registry:z4.string().nullable().optional(),name:z4.string(),versions:z4.array(z4.string())});var dependencyConflictEdgeSchema=z4.object({fromIndex:z4.number().int().nullable().optional(),toIndex:z4.number().int(),versionConstraint:z4.string(),dependencyType:z4.string()});var dependencyConflictSchema=z4.object({packageName:z4.string(),requiredVersions:z4.array(z4.string()),conflictingEdges:z4.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z4.object({registry:z4.string().nullable().optional(),name:z4.string(),versions:z4.array(z4.string()),requiredVersions:z4.array(z4.string()),conflictingEdges:z4.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z4.object({totalCount:z4.number().int(),deprecatedCount:z4.number().int(),outdatedCount:z4.number().int(),duplicateCount:z4.number().int(),conflictCount:z4.number().int(),deprecatedPackages:z4.array(deprecatedDependencySchema),outdatedPackages:z4.array(outdatedDependencySchema),duplicatePackages:z4.array(duplicateDependencySchema),conflicts:z4.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z4.object({cycleStart:z4.string(),circularPath:z4.array(z4.string()),displayChain:z4.string()});var environmentMarkerSchema=z4.object({type:z4.string().nullable().optional(),value:z4.string().nullable().optional(),raw:z4.string().nullable().optional()});var transitiveDependencySchema=z4.object({totalEdges:z4.number().int().nullable().optional(),uniquePackagesCount:z4.number().int().nullable().optional(),uniqueDependencies:z4.array(z4.string()).nullable().optional(),dependencyConflicts:z4.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z4.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z4.object({direct:z4.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z4.object({name:z4.string(),constraint:z4.string().nullable().optional()});var dependencyGroupSchema=z4.object({name:z4.string(),lifecycle:z4.string(),conditionType:z4.string(),conditionValue:z4.string().nullable().optional(),selectionMode:z4.string(),exclusiveGroup:z4.string().nullable().optional(),fallbackPriority:z4.number().int().nullable().optional(),compatibleWith:z4.array(z4.string()).nullable().optional(),defaultEnabled:z4.boolean().nullable().optional(),dependencies:z4.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z4.object({primaryGroup:z4.string().nullable().optional(),environmentMarkers:z4.array(environmentMarkerSchema).nullable().optional(),groups:z4.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z4.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z4.object({data:z4.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
736
+ query PackageDependencies(
737
+ $registry: Registry!
738
+ $name: String!
739
+ $version: String
740
+ $includeTransitive: Boolean
741
+ $includeTransitiveDetails: Boolean! = true
742
+ $includeDependencyGraph: Boolean! = true
743
+ $includeGroups: Boolean! = true
744
+ $includeDependencyIssues: Boolean! = false
745
+ $maxDepth: Int
746
+ $lifecycle: [String!]
747
+ ) {
748
+ packageDependencies(
749
+ registry: $registry
750
+ name: $name
751
+ version: $version
752
+ includeTransitive: $includeTransitive
753
+ maxDepth: $maxDepth
754
+ lifecycle: $lifecycle
755
+ ) {
756
+ package {
757
+ name
758
+ registry
759
+ version
760
+ }
761
+ dependencies {
762
+ # Backend-side summary block intentionally not selected — our
763
+ # envelope computes runtime.count client-side from direct[].length
764
+ # so the invariant runtime.count === runtime.items.length always
765
+ # holds regardless of backend-side drift.
766
+ direct {
767
+ name
768
+ versionConstraint
769
+ type
770
+ }
771
+ transitive {
772
+ totalEdges @include(if: $includeTransitiveDetails)
773
+ uniquePackagesCount @include(if: $includeTransitiveDetails)
774
+ uniqueDependencies @include(if: $includeTransitiveDetails)
775
+ dependencyConflicts @include(if: $includeTransitiveDetails) {
776
+ packageName
777
+ requiredVersions
778
+ conflictingEdges {
779
+ fromIndex
780
+ toIndex
781
+ versionConstraint
782
+ dependencyType
783
+ }
784
+ }
785
+ circularDependencyCycles @include(if: $includeTransitiveDetails) {
786
+ cycleStart
787
+ circularPath
788
+ displayChain
789
+ }
790
+ dependencyGraph @include(if: $includeDependencyGraph) {
791
+ formatVersion
792
+ nodes {
793
+ registry
794
+ name
795
+ version
796
+ }
797
+ edges {
798
+ fromIndex
799
+ toIndex
800
+ constraint
801
+ dependencyType
802
+ }
803
+ }
804
+ dependencyIssues @include(if: $includeDependencyIssues) {
805
+ totalCount
806
+ deprecatedCount
807
+ outdatedCount
808
+ duplicateCount
809
+ conflictCount
810
+ deprecatedPackages {
811
+ registry
812
+ name
813
+ versions
814
+ reasons {
815
+ version
816
+ reason
817
+ }
818
+ }
819
+ outdatedPackages {
820
+ registry
821
+ name
822
+ latestVersion
823
+ severity
824
+ versions {
825
+ version
826
+ severity
827
+ }
828
+ repositoryUrl
829
+ }
830
+ duplicatePackages {
831
+ registry
832
+ name
833
+ versions
834
+ }
835
+ conflicts {
836
+ registry
837
+ name
838
+ versions
839
+ requiredVersions
840
+ conflictingEdges {
841
+ fromIndex
842
+ toIndex
843
+ versionConstraint
844
+ dependencyType
845
+ }
846
+ }
847
+ }
848
+ }
849
+ }
850
+ dependencyGroups @include(if: $includeGroups) {
851
+ primaryGroup
852
+ environmentMarkers {
853
+ type
854
+ value
855
+ raw
856
+ }
857
+ groups {
858
+ name
859
+ lifecycle
860
+ conditionType
861
+ conditionValue
862
+ selectionMode
863
+ exclusiveGroup
864
+ fallbackPriority
865
+ compatibleWith
866
+ defaultEnabled
867
+ dependencies {
868
+ name
869
+ constraint
870
+ }
871
+ }
872
+ }
873
+ }
874
+ }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
875
+ query PackageUpgradeDependencyProbe(
876
+ $registry: Registry!
877
+ $name: String!
878
+ $version: String!
879
+ $includeTransitiveRisk: Boolean!
880
+ $includeTransitiveSecurity: Boolean!
881
+ $includeDependencyIssues: Boolean!
882
+ $includeDependencyChanges: Boolean!
883
+ $includeGroups: Boolean!
884
+ $lifecycle: [String!]
885
+ $minSeverity: Float
886
+ ) {
887
+ packageDependencies(
888
+ registry: $registry
889
+ name: $name
890
+ version: $version
891
+ includeTransitive: $includeTransitiveRisk
892
+ lifecycle: $lifecycle
893
+ ) {
894
+ package {
895
+ name
896
+ registry
897
+ version
898
+ publishedAt
899
+ deprecated
900
+ deprecationReason
901
+ }
902
+ dependencies {
903
+ direct {
904
+ name
905
+ versionConstraint
906
+ type
907
+ }
908
+ transitive @include(if: $includeTransitiveRisk) {
909
+ dependencyGraph @include(if: $includeDependencyChanges) {
910
+ formatVersion
911
+ nodes {
912
+ registry
913
+ name
914
+ version
915
+ }
916
+ edges {
917
+ fromIndex
918
+ toIndex
919
+ constraint
920
+ dependencyType
921
+ }
922
+ }
923
+ vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
924
+ affected {
925
+ totalVulnerabilities
926
+ critical
927
+ high
928
+ medium
929
+ low
930
+ unknown
931
+ }
932
+ nonAffecting {
933
+ totalVulnerabilities
934
+ critical
935
+ high
936
+ medium
937
+ low
938
+ unknown
939
+ }
940
+ combined {
941
+ totalVulnerabilities
942
+ critical
943
+ high
944
+ medium
945
+ low
946
+ unknown
947
+ }
948
+ totalPackagesAnalyzed
949
+ affectedPackageCount
950
+ calculatedAt
951
+ packages {
952
+ registry
953
+ name
954
+ versions
955
+ affectedCount
956
+ nonAffectingCount
957
+ totalCount
958
+ maxSeverityScore
959
+ maxSeverityLabel
960
+ advisoryIds(scope: AFFECTED)
961
+ mostCritical {
962
+ osvId
963
+ registry
964
+ packageName
965
+ summary
966
+ severityScore
967
+ severityType
968
+ affectedVersionRanges
969
+ fixedInVersions
970
+ publishedAt
971
+ modifiedAt
972
+ withdrawnAt
973
+ aliases
974
+ isMalicious
975
+ }
976
+ advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
977
+ version
978
+ affectsResolvedVersion
979
+ matchedAffectedVersionRanges
980
+ fixVersionsAboveResolved
981
+ nearestFixedVersion
982
+ advisory {
983
+ osvId
984
+ registry
985
+ packageName
986
+ summary
987
+ severityScore
988
+ severityType
989
+ affectedVersionRanges
990
+ fixedInVersions
991
+ publishedAt
992
+ modifiedAt
993
+ withdrawnAt
994
+ aliases
995
+ isMalicious
996
+ }
997
+ }
998
+ }
999
+ }
1000
+ dependencyIssues @include(if: $includeDependencyIssues) {
1001
+ totalCount
1002
+ deprecatedCount
1003
+ outdatedCount
1004
+ duplicateCount
1005
+ conflictCount
1006
+ deprecatedPackages {
1007
+ registry
1008
+ name
1009
+ versions
1010
+ reasons {
1011
+ version
1012
+ reason
1013
+ }
1014
+ }
1015
+ outdatedPackages {
1016
+ registry
1017
+ name
1018
+ latestVersion
1019
+ severity
1020
+ versions {
1021
+ version
1022
+ severity
1023
+ }
1024
+ repositoryUrl
1025
+ }
1026
+ duplicatePackages {
1027
+ registry
1028
+ name
1029
+ versions
1030
+ }
1031
+ conflicts {
1032
+ registry
1033
+ name
1034
+ versions
1035
+ requiredVersions
1036
+ conflictingEdges {
1037
+ fromIndex
1038
+ toIndex
1039
+ versionConstraint
1040
+ dependencyType
1041
+ }
1042
+ }
1043
+ }
1044
+ }
1045
+ }
1046
+ dependencyGroups @include(if: $includeGroups) {
1047
+ primaryGroup
1048
+ environmentMarkers {
1049
+ type
1050
+ value
1051
+ raw
1052
+ }
1053
+ groups {
1054
+ name
1055
+ lifecycle
1056
+ conditionType
1057
+ conditionValue
1058
+ selectionMode
1059
+ exclusiveGroup
1060
+ fallbackPriority
1061
+ compatibleWith
1062
+ defaultEnabled
1063
+ dependencies {
1064
+ name
1065
+ constraint
1066
+ }
1067
+ }
1068
+ }
1069
+ }
1070
+ }`;var packageUpgradeAdvisorySchema=z4.object({id:z4.string().nullable().optional(),aliases:z4.array(z4.string()),summary:z4.string().nullable().optional(),severity:z4.number().nullable().optional(),severityLabel:z4.string().nullable().optional(),fixedIn:z4.array(z4.string()),isMalicious:z4.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z4.object({version:z4.string(),publishedAt:z4.string().nullable().optional(),deprecated:z4.boolean().nullable().optional(),deprecationReason:z4.string().nullable().optional(),affectedCount:z4.number().int(),nonAffectingCount:z4.number().int(),allCount:z4.number().int(),lastModifiedAt:z4.string().nullable().optional(),advisories:z4.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z4.object({entries:z4.array(z4.object({id:z4.string(),registry:z4.string(),name:z4.string(),versions:z4.array(z4.string()),affectedCount:z4.number().int(),maxSeverityScore:z4.number().nullable().optional(),maxSeverityLabel:z4.string().nullable().optional(),advisoryIds:z4.array(z4.string())})),totalCount:z4.number().int(),truncated:z4.boolean()});var packageUpgradeTransitiveSecuritySchema=z4.object({currentAffected:z4.number().int(),targetAffected:z4.number().int(),introducedPackages:z4.array(z4.string()),fixedPackages:z4.array(z4.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z4.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z4.array(packageUpgradeAdvisorySchema),removed:z4.array(packageUpgradeAdvisorySchema),notAddressed:z4.array(packageUpgradeAdvisorySchema),fixed:z4.array(packageUpgradeAdvisorySchema),introduced:z4.array(packageUpgradeAdvisorySchema),unchanged:z4.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z4.object({version:z4.string().nullable().optional(),publishedAt:z4.string().nullable().optional(),htmlUrl:z4.string().nullable().optional(),body:z4.string().nullable().optional(),bodyPreview:z4.string().nullable().optional(),headline:z4.string().nullable().optional(),signals:z4.array(z4.string())});var packageUpgradeChangelogSchema=z4.object({source:z4.string().nullable().optional(),fallback:z4.string().nullable().optional(),entries:z4.array(packageUpgradeChangelogEntrySchema),sampledEntries:z4.array(packageUpgradeChangelogEntrySchema),keywordEntries:z4.array(packageUpgradeChangelogEntrySchema),totalKeywordEntries:z4.number().int(),totalEntries:z4.number().int(),totalEntriesWithBodies:z4.number().int(),truncated:z4.boolean(),hasReleaseNoteBodies:z4.boolean(),breakingSignals:z4.array(z4.string()),migrationSignals:z4.array(z4.string())});var packageUpgradeCompatibilitySchema=z4.object({peerDependencyChanges:z4.array(z4.string()),notes:z4.array(z4.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z4.object({name:z4.string(),registry:z4.string().nullable().optional(),version:z4.string().nullable().optional(),fromVersions:z4.array(z4.string()),toVersions:z4.array(z4.string()),constraint:z4.string().nullable().optional(),type:z4.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z4.object({added:z4.array(packageUpgradeDependencyChangeItemSchema),removed:z4.array(packageUpgradeDependencyChangeItemSchema),changed:z4.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z4.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z4.object({currentTotal:z4.number().int(),targetTotal:z4.number().int(),introducedDeprecated:z4.array(z4.string()),introducedDuplicates:z4.array(z4.string()),introducedConflicts:z4.array(z4.string()),introducedOutdated:z4.array(z4.string())}).nullable().optional();var packageUpgradeReviewSchema=z4.object({registry:z4.string(),name:z4.string(),currentVersion:z4.string(),targetVersion:z4.string(),latestVersion:z4.string().nullable().optional(),versionDelta:z4.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknowns:z4.array(z4.string())});var packageUpgradeReviewResponseSchema=z4.object({summary:z4.object({total:z4.number().int(),withUnknowns:z4.number().int(),withAddedAdvisories:z4.number().int(),withBreakingSignals:z4.number().int(),withDirectDependencyChanges:z4.number().int(),withTransitiveVulnerabilityAdditions:z4.number().int()}),reviews:z4.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z4.object({data:z4.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var PACKAGE_UPGRADE_REVIEW_QUERY=`
1071
+ query PackageUpgradeReview(
1072
+ $packages: [PackageUpgradeReviewPackageInput!]!
1073
+ $includeTransitiveSecurity: Boolean!
1074
+ $includeDependencyIssues: Boolean!
1075
+ $minSeverity: Float
1076
+ $changelogLimit: Int!
1077
+ ) {
1078
+ packageUpgradeReview(
1079
+ packages: $packages
1080
+ includeTransitiveSecurity: $includeTransitiveSecurity
1081
+ minSeverity: $minSeverity
1082
+ changelogLimit: $changelogLimit
1083
+ ) {
1084
+ summary {
1085
+ total
1086
+ withUnknowns
1087
+ withAddedAdvisories
1088
+ withBreakingSignals
1089
+ withDirectDependencyChanges
1090
+ withTransitiveVulnerabilityAdditions
1091
+ }
1092
+ reviews {
1093
+ registry
1094
+ name
1095
+ currentVersion
1096
+ targetVersion
1097
+ latestVersion
1098
+ versionDelta
1099
+ security {
1100
+ current {
1101
+ version
1102
+ publishedAt
1103
+ deprecated
1104
+ deprecationReason
1105
+ affectedCount
1106
+ nonAffectingCount
1107
+ allCount
1108
+ lastModifiedAt
1109
+ advisories {
1110
+ ...PackageUpgradeAdvisoryFields
1111
+ }
1112
+ }
1113
+ target {
1114
+ version
1115
+ publishedAt
1116
+ deprecated
1117
+ deprecationReason
1118
+ affectedCount
1119
+ nonAffectingCount
1120
+ allCount
1121
+ lastModifiedAt
1122
+ advisories {
1123
+ ...PackageUpgradeAdvisoryFields
1124
+ }
1125
+ }
1126
+ added {
1127
+ ...PackageUpgradeAdvisoryFields
1128
+ }
1129
+ removed {
1130
+ ...PackageUpgradeAdvisoryFields
1131
+ }
1132
+ notAddressed {
1133
+ ...PackageUpgradeAdvisoryFields
1134
+ }
1135
+ fixed {
1136
+ ...PackageUpgradeAdvisoryFields
1137
+ }
1138
+ introduced {
1139
+ ...PackageUpgradeAdvisoryFields
1140
+ }
1141
+ unchanged {
1142
+ ...PackageUpgradeAdvisoryFields
1143
+ }
1144
+ transitive @include(if: $includeTransitiveSecurity) {
1145
+ currentAffected
1146
+ targetAffected
1147
+ introducedPackages
1148
+ fixedPackages
1149
+ introducedPackageDetails(first: 50) {
1150
+ ...PackageUpgradeTransitivePackagePageFields
1151
+ }
1152
+ fixedPackageDetails(first: 50) {
1153
+ ...PackageUpgradeTransitivePackagePageFields
1154
+ }
1155
+ stillAffectedPackageDetails(first: 50) {
1156
+ ...PackageUpgradeTransitivePackagePageFields
1157
+ }
1158
+ }
1159
+ }
1160
+ changelog {
1161
+ source
1162
+ fallback
1163
+ entries {
1164
+ ...PackageUpgradeChangelogEntryFields
1165
+ }
1166
+ sampledEntries {
1167
+ ...PackageUpgradeChangelogEntryFields
1168
+ }
1169
+ keywordEntries {
1170
+ ...PackageUpgradeChangelogEntryFields
1171
+ }
1172
+ totalKeywordEntries
1173
+ totalEntries
1174
+ totalEntriesWithBodies
1175
+ truncated
1176
+ hasReleaseNoteBodies
1177
+ breakingSignals
1178
+ migrationSignals
1179
+ }
1180
+ compatibility {
1181
+ peerDependencyChanges
1182
+ notes
1183
+ }
1184
+ dependencyChanges {
1185
+ direct {
1186
+ ...PackageUpgradeDependencyChangeGroupFields
1187
+ }
1188
+ transitive {
1189
+ ...PackageUpgradeDependencyChangeGroupFields
1190
+ }
1191
+ }
1192
+ dependencyIssues @include(if: $includeDependencyIssues) {
1193
+ currentTotal
1194
+ targetTotal
1195
+ introducedDeprecated
1196
+ introducedDuplicates
1197
+ introducedConflicts
1198
+ introducedOutdated
1199
+ }
1200
+ unknowns
1201
+ }
1202
+ }
1203
+ }
1204
+
1205
+ fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1206
+ id
1207
+ aliases
1208
+ summary
1209
+ severity
1210
+ severityLabel
1211
+ fixedIn
1212
+ isMalicious
1213
+ }
1214
+
1215
+ fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1216
+ entries {
1217
+ id
1218
+ registry
1219
+ name
1220
+ versions
1221
+ affectedCount
1222
+ maxSeverityScore
1223
+ maxSeverityLabel
1224
+ advisoryIds
1225
+ }
1226
+ totalCount
1227
+ truncated
1228
+ }
1229
+
1230
+ fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
1231
+ version
1232
+ publishedAt
1233
+ htmlUrl
1234
+ body
1235
+ bodyPreview
1236
+ headline
1237
+ signals
1238
+ }
1239
+
1240
+ fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1241
+ added {
1242
+ name
1243
+ registry
1244
+ version
1245
+ fromVersions
1246
+ toVersions
1247
+ constraint
1248
+ type
1249
+ }
1250
+ removed {
1251
+ name
1252
+ registry
1253
+ version
1254
+ fromVersions
1255
+ toVersions
1256
+ constraint
1257
+ type
1258
+ }
1259
+ changed {
1260
+ name
1261
+ registry
1262
+ version
1263
+ fromVersions
1264
+ toVersions
1265
+ constraint
1266
+ type
1267
+ }
1268
+ }`;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=`
1269
+ query PackageChangelog(
1270
+ $registry: Registry
1271
+ $name: String
1272
+ $repoUrl: String
1273
+ $gitRef: String
1274
+ $fromVersion: String
1275
+ $toVersion: String
1276
+ $limit: Int
1277
+ $includeBodies: Boolean! = true
1278
+ ) {
1279
+ packageChangelog(
1280
+ registry: $registry
1281
+ name: $name
1282
+ repoUrl: $repoUrl
1283
+ gitRef: $gitRef
1284
+ fromVersion: $fromVersion
1285
+ toVersion: $toVersion
1286
+ limit: $limit
1287
+ ) {
1288
+ package {
1289
+ name
1290
+ registry
1291
+ repoUrl
1292
+ fromVersion
1293
+ toVersion
1294
+ limit
1295
+ }
1296
+ source
1297
+ entries {
1298
+ version
1299
+ normalizedVersion
1300
+ body @include(if: $includeBodies)
1301
+ htmlUrl
1302
+ publishedAt
1303
+ }
1304
+ }
1305
+ }`;var packageDocSourceKindSchema=z4.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z4.object({id:z4.string().nullable().optional(),title:z4.string().nullable().optional(),slug:z4.string().nullable().optional(),order:z4.number().int().nullable().optional(),linkName:z4.string().nullable().optional(),lastUpdatedAt:z4.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z4.string().nullable().optional(),repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),requestedRef:z4.string().nullable().optional(),filePath:z4.string().nullable().optional()});var packageDocsPageInfoSchema=z4.object({hasNextPage:z4.boolean(),endCursor:z4.string().nullable().optional(),totalCount:z4.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z4.object({registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),version:z4.string().nullable().optional(),stale:z4.boolean().nullable().optional(),pages:z4.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z4.object({url:z4.string().nullable().optional(),label:z4.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z4.object({id:z4.string().nullable().optional(),title:z4.string().nullable().optional(),content:z4.string().nullable().optional(),contentFormat:z4.string().nullable().optional(),breadcrumbs:z4.array(z4.string()).nullable().optional(),linkName:z4.string().nullable().optional(),lastUpdatedAt:z4.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),requestedRef:z4.string().nullable().optional(),filePath:z4.string().nullable().optional(),baseUrl:z4.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z4.object({registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),version:z4.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z4.object({data:z4.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z4.object({data:z4.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
1306
+ query ListPackageDocs(
1307
+ $registry: Registry!
1308
+ $packageName: String!
1309
+ $version: String
1310
+ $limit: Int
1311
+ $after: String
1312
+ ) {
1313
+ listPackageDocs(
1314
+ registry: $registry
1315
+ packageName: $packageName
1316
+ version: $version
1317
+ limit: $limit
1318
+ after: $after
1319
+ ) {
1320
+ registry
1321
+ packageName
1322
+ version
1323
+ stale
1324
+ pages {
1325
+ id
1326
+ title
1327
+ slug
1328
+ order
1329
+ linkName
1330
+ lastUpdatedAt
1331
+ sourceKind
1332
+ sourceUrl
1333
+ repoUrl
1334
+ gitRef
1335
+ requestedRef
1336
+ filePath
1337
+ }
1338
+ pageInfo {
1339
+ hasNextPage
1340
+ endCursor
1341
+ totalCount
1342
+ }
1343
+ }
1344
+ }`;var READ_PACKAGE_DOC_QUERY=`
1345
+ query ReadPackageDoc($pageId: String!) {
1346
+ getDocPage(pageId: $pageId) {
1347
+ registry
1348
+ packageName
1349
+ version
1350
+ sourceKind
1351
+ page {
1352
+ id
1353
+ title
1354
+ content
1355
+ contentFormat
1356
+ breadcrumbs
1357
+ linkName
1358
+ lastUpdatedAt
1359
+ sourceKind
1360
+ source {
1361
+ url
1362
+ label
1363
+ }
1364
+ repoUrl
1365
+ gitRef
1366
+ requestedRef
1367
+ filePath
1368
+ baseUrl
1369
+ }
1370
+ }
1371
+ }`;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;return this.normaliseVulnerabilityReport(data)}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 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&&params.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}}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&&params.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,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,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=`
1372
+ query ResolveTarget(
1373
+ $name: String!
1374
+ $query: String
1375
+ $registries: [Registry!]
1376
+ $preferredKinds: [TargetResolutionKind!]
1377
+ $intentHints: [String!]
1378
+ $limit: Int!
1379
+ $includeDetailedFields: Boolean!
1380
+ $includeNameSimilarity: Boolean!
1381
+ ) {
1382
+ resolveTarget(
1383
+ name: $name
1384
+ query: $query
1385
+ registries: $registries
1386
+ preferredKinds: $preferredKinds
1387
+ intentHints: $intentHints
1388
+ limit: $limit
1389
+ ) {
1390
+ best {
1391
+ ...ResolveTargetReferenceFields
1392
+ }
1393
+ protectedMatches {
1394
+ ...ResolveTargetReferenceFields
1395
+ }
1396
+ candidates @include(if: $includeNameSimilarity) {
1397
+ canonicalKey
1398
+ nameSimilarity
1399
+ }
1400
+ targetsTruncated
1401
+ targets {
1402
+ ...ResolveTargetListFields
1403
+ ...ResolveTargetJsonFields @include(if: $includeDetailedFields)
1404
+ match {
1405
+ confidence
1406
+ ...ResolveTargetMatchJsonFields @include(if: $includeDetailedFields)
1407
+ }
1408
+ }
1409
+ ambiguous
1410
+ ambiguousReason
1411
+ }
1412
+ }
1413
+
1414
+ fragment ResolveTargetReferenceFields on TargetResolutionCandidate {
1415
+ kind
1416
+ canonicalKey
1417
+ confidence
1418
+ }
1419
+
1420
+ fragment ResolveTargetListFields on TargetResolutionTarget {
1421
+ kind
1422
+ canonicalKey
1423
+ latestVersionMaliciousStatus
1424
+ latestVersionMaliciousEvidence {
1425
+ advisories {
1426
+ osvId
1427
+ classificationReasons
1428
+ }
1429
+ totalCount
1430
+ truncated
1431
+ }
1432
+ description
1433
+ repositoryUrl
1434
+ stars
1435
+ downloadsLastMonth
1436
+ downloadsTotal
1437
+ docsAvailable
1438
+ codeAvailable
1439
+ groupKey
1440
+ docsPageCount
1441
+ codeFileCount
1442
+ license
1443
+ }
1444
+
1445
+ fragment ResolveTargetJsonFields on TargetResolutionTarget {
1446
+ displayName
1447
+ registry
1448
+ packageName
1449
+ latestVersion
1450
+ repositoryOwner
1451
+ repositoryName
1452
+ documentationUrl
1453
+ }
1454
+
1455
+ fragment ResolveTargetMatchJsonFields on TargetResolutionMatch {
1456
+ matchedAliases
1457
+ matchTier
1458
+ score
1459
+ }`;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();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"}if(oauthError==="invalid_grant"&&(text.includes("invalid refresh token")||text.includes("refresh token already used")||text.includes("already used")||text.includes("session expired")||text.includes("session not found"))){return"invalid_refresh_token"}return}function parseOAuthErrorBody(body){try{const parsed=JSON.parse(body);return{oauthError:stringField2(parsed.error),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","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>
1460
+ <html><head>
1461
+ <title>GitHits CLI</title>
1462
+ <meta charset="utf-8">
1463
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1464
+ <link rel="preconnect" href="https://fonts.googleapis.com">
1465
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
1466
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
1467
+ <style>
1468
+ *, *::before, *::after { box-sizing: border-box; }
1469
+ body {
1470
+ margin: 0;
1471
+ min-height: 100vh;
1472
+ width: 100%;
1473
+ padding: 16px;
1474
+ background: #21262d;
1475
+ color: #ffffff;
1476
+ font-family: 'Inter', sans-serif;
1477
+ display: flex;
1478
+ align-items: center;
1479
+ justify-content: center;
1480
+ }
1481
+ .content {
1482
+ display: flex;
1483
+ flex-direction: column;
1484
+ align-items: center;
1485
+ gap: 20px;
1486
+ padding: 0 16px;
1487
+ }
1488
+ .message {
1489
+ display: flex;
1490
+ flex-direction: column;
1491
+ align-items: center;
1492
+ gap: 8px;
1493
+ }
1494
+ .success-icon {
1495
+ width: 48px;
1496
+ height: 48px;
1497
+ border-radius: 50%;
1498
+ border: 2px solid #57fec9;
1499
+ background: transparent;
1500
+ display: flex;
1501
+ align-items: center;
1502
+ justify-content: center;
1503
+ }
1504
+ .heading {
1505
+ font-family: 'Lexend', sans-serif;
1506
+ font-weight: 600;
1507
+ font-size: 32px;
1508
+ line-height: 40px;
1509
+ color: #ffffff;
1510
+ margin: 0;
1511
+ text-align: center;
1512
+ text-wrap: pretty;
1513
+ }
1514
+ .text {
1515
+ font-family: 'Inter', sans-serif;
1516
+ font-weight: 400;
1517
+ font-size: 16px;
1518
+ line-height: 24px;
1519
+ margin: 0;
1520
+ text-align: center;
1521
+ text-wrap: pretty;
1522
+ }
1523
+ .text-muted {
1524
+ color: #abb2bf;
1525
+ }${COPY_BTN_CSS}
1526
+ </style>
1527
+ </head>
1528
+ <body>
1529
+ <div class="content">
1530
+ <div class="success-icon" aria-hidden="true">
1531
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#57fec9" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
1532
+ <polyline points="20 6 9 17 4 12" />
1533
+ </svg>
1534
+ </div>
1535
+ <div class="message">
1536
+ <h1 class="heading">${escapeHtml(title)}</h1>
1537
+ <p class="text text-muted">You can close this window and return to your terminal.</p>
1538
+ </div>
1539
+
1540
+ <svg class="wordmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 554 129.3" width="103" height="24" role="img" aria-label="GitHits">
1541
+ <title>GitHits</title>
1542
+ <defs>
1543
+ <linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
1544
+ <stop offset="0" style="stop-color: #ff4fae" />
1545
+ <stop offset="1" style="stop-color: #ff872f" />
1546
+ </linearGradient>
1547
+ </defs>
1548
+ <path d="M148.6,29.1c7.9,0,14.4-6.4,14.4-14.4S156.6.3,148.6.3s-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4Z" fill="#ff4fae" />
1549
+ <path d="M383.9,29.1c7.9,0,14.4-6.4,14.4-14.4s-6.4-14.4-14.4-14.4-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4ZM396.4,40.8h-25v86.6h25V40.8ZM454.3,8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8v-24h-18.8V8.5ZM553.1,92.2c-.9-2.6-2.2-4.9-4.1-6.9-2.2-2.4-5.1-4.4-8.8-6.2-3.7-1.8-8.2-3.4-13.4-4.9-4.1-1.1-7.3-2.1-9.6-3-2.4-.9-4.1-1.7-5.3-2.4-1.1-.8-1.9-1.7-2.5-2.9-.6-1.1-.9-2.3-.9-3.5s.2-2.4.7-3.4,1.2-1.9,2.2-2.6c1-.7,2.2-1.3,3.7-1.6s3.2-.5,5-.5,4.5.4,7.1,1.3c2.6.9,5.2,2.1,7.7,3.7,2.5,1.6,4.7,3.3,6.7,5.2l12.5-14.2c-2.8-2.8-6-5.2-9.6-7.3-3.7-2.1-7.7-3.7-11.9-4.8-4.3-1.1-8.7-1.7-13.2-1.7s-8.8.7-12.9,1.9c-4.1,1.3-7.7,3.1-10.8,5.5s-5.6,5.2-7.3,8.5c-1.8,3.3-2.6,7-2.6,11s.5,6.4,1.6,9.2c1,2.8,2.5,5.3,4.5,7.7,2.3,2.5,5.4,4.7,9.3,6.7s8.6,3.7,14.2,5.1c3.6,1,6.6,1.9,8.9,2.8,2.3.8,4,1.6,5.1,2.3,2,1.4,3,3.3,3,5.7s-.2,2.4-.7,3.5-1.2,2-2.2,2.7-2.2,1.3-3.5,1.7c-1.4.4-2.9.6-4.5.6-4.2,0-8.4-.8-12.5-2.5-4.2-1.6-7.9-4.3-11.2-8l-14.7,12.8c3.8,4.8,8.9,8.6,15.2,11.4,6.3,2.8,13.5,4.1,21.7,4.1s12.5-1.2,17.8-3.7,9.4-5.8,12.4-10.1c3-4.3,4.5-9.2,4.5-14.7s-.4-6-1.3-8.6h-.3ZM327.2,60.5h-50.2V6h-25v121.4h25v-42.8h50.2v42.8h25V6h-25v54.5Z" fill="url(#wm-grad)" />
1550
+ <path d="M239.1,64.8v-24h-18.8V8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8ZM161.1,40.8h-25v86.6h25V40.8ZM91.6,84.6h-26.8v-24h54s1.2,4.3,1.1,12.1c-.3,30.6-25.3,55.5-55.9,55.7h-.5C27.4,128.4-1.6,98.3,0,61.8,1.5,29.6,27.4,3.4,59.6,1.4c21-1.2,40,7.7,52.4,22.4l-17.2,17.2c-7.7-10.1-20.3-16.4-34.3-15.4-19.4,1.4-35,17.1-36.4,36.5-1.6,23,16.6,42.2,39.3,42.2s28-19.7,28-19.7h.2Z" fill="#ff4fae" />
1551
+ </svg>
1552
+
1553
+ ${HELP_CTA}
1554
+ </div>
1555
+ ${COPY_SCRIPT_HTML}
1556
+ </body></html>`}var KNOWN_OAUTH_ERROR_MESSAGES={access_denied:"Access was denied."};function describeOauthError(code,description){const mapped=KNOWN_OAUTH_ERROR_MESSAGES[code];if(mapped)return mapped;if(description){return/[.!?]$/.test(description)?description:`${description}.`}return"Something went wrong while signing in."}function evaluateCallback(input){if(input.error){const message=input.errorDescription?`${input.error}: ${input.errorDescription}`:input.error;const browserMessage=describeOauthError(input.error,input.errorDescription);return{statusCode:200,html:errorHtml(browserMessage,input.error,RETRY_CTA),result:{type:"oauth_error",message}}}if(input.code&&input.state){if(input.state!==input.expectedState){return{statusCode:400,html:errorHtml("Sign-in could not be verified for security reasons.",undefined,RETRY_CTA),result:{type:"state_mismatch",message:"Security validation failed (state mismatch)"}}}return{statusCode:200,html:successHtml(),result:{type:"success",code:input.code,state:input.state}}}return{statusCode:400,html:errorHtml("Sign-in did not complete correctly.",undefined,RETRY_CTA),result:{type:"invalid_callback",message:"Authentication callback missing required parameters"}}}function errorHtml(error,errorCode,ctaHtml){const errorCodeHtml=errorCode?`<p class="error-code">Error code: <code>${escapeHtml(errorCode)}</code></p>`:"";return`<!DOCTYPE html>
1557
+ <html><head>
1558
+ <title>GitHits CLI</title>
1559
+ <meta charset="utf-8">
1560
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1561
+ <link rel="preconnect" href="https://fonts.googleapis.com">
1562
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
1563
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
1564
+ <style>
1565
+ *, *::before, *::after { box-sizing: border-box; }
1566
+ body {
1567
+ margin: 0;
1568
+ min-height: 100vh;
1569
+ width: 100%;
1570
+ padding: 16px;
1571
+ background: #21262d;
1572
+ color: #ffffff;
1573
+ font-family: 'Inter', sans-serif;
1574
+ display: flex;
1575
+ align-items: center;
1576
+ justify-content: center;
1577
+ }
1578
+ .content {
1579
+ display: flex;
1580
+ flex-direction: column;
1581
+ align-items: center;
1582
+ gap: 20px;
1583
+ padding: 0 16px;
1584
+ }
1585
+ .message {
1586
+ display: flex;
1587
+ flex-direction: column;
1588
+ align-items: center;
1589
+ gap: 8px;
1590
+ }
1591
+ .error-icon {
1592
+ width: 48px;
1593
+ height: 48px;
1594
+ border-radius: 50%;
1595
+ border: 2px solid #ff5a6a;
1596
+ background: transparent;
1597
+ display: flex;
1598
+ align-items: center;
1599
+ justify-content: center;
1600
+ }
1601
+ .heading {
1602
+ font-family: 'Lexend', sans-serif;
1603
+ font-weight: 600;
1604
+ font-size: 32px;
1605
+ line-height: 40px;
1606
+ color: #ffffff;
1607
+ margin: 0;
1608
+ text-align: center;
1609
+ text-wrap: pretty;
1610
+ }
1611
+ .text {
1612
+ font-family: 'Inter', sans-serif;
1613
+ font-weight: 400;
1614
+ font-size: 16px;
1615
+ line-height: 24px;
1616
+ margin: 0;
1617
+ text-align: center;
1618
+ text-wrap: pretty;
1619
+ }
1620
+ .text-muted {
1621
+ color: #abb2bf;
1622
+ }
1623
+ .footer-text {
1624
+ font-family: 'Inter', sans-serif;
1625
+ font-weight: 400;
1626
+ font-size: 12px;
1627
+ line-height: 16px;
1628
+ color: #abb2bf;
1629
+ margin: 0;
1630
+ text-align: center;
1631
+ text-wrap: pretty;
1632
+ }
1633
+ .footer-link {
1634
+ color: inherit;
1635
+ text-decoration: underline;
1636
+ text-underline-offset: 2px;
1637
+ }
1638
+ .error-code {
1639
+ font-family: 'Inter', sans-serif;
1640
+ font-weight: 400;
1641
+ font-size: 12px;
1642
+ line-height: 16px;
1643
+ color: #abb2bf;
1644
+ opacity: 0.7;
1645
+ margin: 4px 0 0;
1646
+ text-align: center;
1647
+ }
1648
+ .error-code code {
1649
+ font-size: 11px;
1650
+ padding: 0 5px;
1651
+ }
1652
+ code {
1653
+ font-family: 'Consolas', monospace;
1654
+ font-size: 13px;
1655
+ background: rgba(255, 255, 255, 0.08);
1656
+ padding: 1px 6px;
1657
+ border-radius: 4px;
1658
+ color: #ffffff;
1659
+ }${COPY_BTN_CSS}
1660
+ </style>
1661
+ </head>
1662
+ <body>
1663
+ <div class="content">
1664
+ <div class="error-icon" aria-hidden="true">
1665
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#ff5a6a" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
1666
+ <line x1="18" y1="6" x2="6" y2="18"/>
1667
+ <line x1="6" y1="6" x2="18" y2="18"/>
1668
+ </svg>
1669
+ </div>
1670
+
1671
+ <div class="message">
1672
+ <h1 class="heading">Sign-in failed</h1>
1673
+ <p class="text text-muted">${escapeHtml(error)}</p>
1674
+ ${errorCodeHtml}
1675
+ </div>
1676
+
1677
+ ${ctaHtml??""}
1678
+
1679
+ <svg class="wordmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 554 129.3" width="103" height="24" role="img" aria-label="GitHits">
1680
+ <title>GitHits</title>
1681
+ <defs>
1682
+ <linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
1683
+ <stop offset="0" style="stop-color: #ff4fae" />
1684
+ <stop offset="1" style="stop-color: #ff872f" />
1685
+ </linearGradient>
1686
+ </defs>
1687
+ <path d="M148.6,29.1c7.9,0,14.4-6.4,14.4-14.4S156.6.3,148.6.3s-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4Z" fill="#ff4fae" />
1688
+ <path d="M383.9,29.1c7.9,0,14.4-6.4,14.4-14.4s-6.4-14.4-14.4-14.4-14.4,6.4-14.4,14.4,6.4,14.4,14.4,14.4ZM396.4,40.8h-25v86.6h25V40.8ZM454.3,8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8v-24h-18.8V8.5ZM553.1,92.2c-.9-2.6-2.2-4.9-4.1-6.9-2.2-2.4-5.1-4.4-8.8-6.2-3.7-1.8-8.2-3.4-13.4-4.9-4.1-1.1-7.3-2.1-9.6-3-2.4-.9-4.1-1.7-5.3-2.4-1.1-.8-1.9-1.7-2.5-2.9-.6-1.1-.9-2.3-.9-3.5s.2-2.4.7-3.4,1.2-1.9,2.2-2.6c1-.7,2.2-1.3,3.7-1.6s3.2-.5,5-.5,4.5.4,7.1,1.3c2.6.9,5.2,2.1,7.7,3.7,2.5,1.6,4.7,3.3,6.7,5.2l12.5-14.2c-2.8-2.8-6-5.2-9.6-7.3-3.7-2.1-7.7-3.7-11.9-4.8-4.3-1.1-8.7-1.7-13.2-1.7s-8.8.7-12.9,1.9c-4.1,1.3-7.7,3.1-10.8,5.5s-5.6,5.2-7.3,8.5c-1.8,3.3-2.6,7-2.6,11s.5,6.4,1.6,9.2c1,2.8,2.5,5.3,4.5,7.7,2.3,2.5,5.4,4.7,9.3,6.7s8.6,3.7,14.2,5.1c3.6,1,6.6,1.9,8.9,2.8,2.3.8,4,1.6,5.1,2.3,2,1.4,3,3.3,3,5.7s-.2,2.4-.7,3.5-1.2,2-2.2,2.7-2.2,1.3-3.5,1.7c-1.4.4-2.9.6-4.5.6-4.2,0-8.4-.8-12.5-2.5-4.2-1.6-7.9-4.3-11.2-8l-14.7,12.8c3.8,4.8,8.9,8.6,15.2,11.4,6.3,2.8,13.5,4.1,21.7,4.1s12.5-1.2,17.8-3.7,9.4-5.8,12.4-10.1c3-4.3,4.5-9.2,4.5-14.7s-.4-6-1.3-8.6h-.3ZM327.2,60.5h-50.2V6h-25v121.4h25v-42.8h50.2v42.8h25V6h-25v54.5Z" fill="url(#wm-grad)" />
1689
+ <path d="M239.1,64.8v-24h-18.8V8.5h-25v32.3h-18.8v24h18.8v62.6h25v-62.6h18.8ZM161.1,40.8h-25v86.6h25V40.8ZM91.6,84.6h-26.8v-24h54s1.2,4.3,1.1,12.1c-.3,30.6-25.3,55.5-55.9,55.7h-.5C27.4,128.4-1.6,98.3,0,61.8,1.5,29.6,27.4,3.4,59.6,1.4c21-1.2,40,7.7,52.4,22.4l-17.2,17.2c-7.7-10.1-20.3-16.4-34.3-15.4-19.4,1.4-35,17.1-36.4,36.5-1.6,23,16.6,42.2,39.3,42.2s28-19.7,28-19.7h.2Z" fill="#ff4fae" />
1690
+ </svg>
1691
+
1692
+ <p class="footer-text">Having trouble? Check our <a class="footer-link" href="https://app.githits.com/docs/" target="_blank" rel="noopener noreferrer">documentation</a> or contact <a class="footer-link" href="mailto:support@githits.com">support</a>.</p>
1693
+ </div>
1694
+ ${COPY_SCRIPT_HTML}
1695
+ </body></html>`}function sendHtmlResponse(res,statusCode,html){res.writeHead(statusCode,{"Content-Type":"text/html; charset=utf-8"});res.end(html)}function closeCallbackServerConnections(server,connections){return new Promise((resolve,reject)=>{const destroyConnections=()=>{for(const socket of connections)socket.destroy()};if(!server.listening){destroyConnections();resolve();return}server.close((error)=>{if(error)reject(error);else resolve()});destroyConnections()})}var COPY_ICON_SVG=`<svg class="githits-cli-icon githits-cli-icon-copy" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`;var CHECK_ICON_SVG=`<svg class="githits-cli-icon githits-cli-icon-check" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg>`;function commandButton(cmd){const escaped=escapeHtml(cmd);return`<button type="button" class="githits-cli-btn" data-copy="${escaped}" aria-label="Copy command: ${escaped}"><span class="githits-cli-cmd">${escaped}</span>${COPY_ICON_SVG}${CHECK_ICON_SVG}</button>`}function ctaBlock(introHtml,commands){const buttons=commands.map(commandButton).join(`
1696
+ `);return`<div class="cli-cta">
1697
+ <p class="tip">${introHtml}</p>
1698
+ ${buttons}
1699
+ </div>`}var COPY_BTN_CSS=`
1700
+ .wordmark {
1701
+ margin: 16px 0;
1702
+ }
1703
+ .cli-cta {
1704
+ display: flex;
1705
+ flex-direction: column;
1706
+ align-items: center;
1707
+ gap: 12px;
1708
+ margin: 16px 0 0;
1709
+ }
1710
+ .wordmark + .cli-cta {
1711
+ margin-top: 0;
1712
+ }
1713
+ .tip {
1714
+ font-family: 'Inter', sans-serif;
1715
+ font-weight: 400;
1716
+ font-size: 14px;
1717
+ line-height: 20px;
1718
+ color: #d5d9df;
1719
+ margin: 0;
1720
+ text-align: center;
1721
+ text-wrap: pretty;
1722
+ }
1723
+ .githits-cli-btn {
1724
+ display: inline-flex;
1725
+ align-items: center;
1726
+ gap: 0.5rem;
1727
+ background-color: rgba(255, 255, 255, 0.08);
1728
+ border: none;
1729
+ border-radius: 0.5rem;
1730
+ padding: 1rem 1.25rem;
1731
+ font-family: Consolas, ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
1732
+ font-size: 14px;
1733
+ font-weight: 500;
1734
+ color: #abb2bf;
1735
+ cursor: pointer;
1736
+ line-height: 1;
1737
+ transition: background-color 0.2s ease, transform 0.1s ease, color 0.2s ease;
1738
+ }
1739
+ .githits-cli-btn:hover {
1740
+ color: #d5d9df;
1741
+ }
1742
+ .githits-cli-btn:active {
1743
+ transform: scale(0.98);
1744
+ }
1745
+ .githits-cli-btn:focus-visible {
1746
+ outline: 2px solid #abb2bf;
1747
+ outline-offset: 2px;
1748
+ }
1749
+ .githits-cli-cmd {
1750
+ white-space: nowrap;
1751
+ }
1752
+ .githits-cli-icon {
1753
+ width: 14px;
1754
+ height: 14px;
1755
+ color: #abb2bf;
1756
+ flex-shrink: 0;
1757
+ }
1758
+ .githits-cli-btn.copied .githits-cli-icon-copy { display: none; }
1759
+ .githits-cli-btn:not(.copied) .githits-cli-icon-check { display: none; }
1760
+ .githits-cli-btn.copied .githits-cli-icon { color: #abb2bf; }`;var COPY_SCRIPT_HTML=`<script>
1761
+ (function() {
1762
+ var timers = new WeakMap();
1763
+ var buttons = document.querySelectorAll('.githits-cli-btn');
1764
+ for (var i = 0; i < buttons.length; i++) {
1765
+ buttons[i].addEventListener('click', function(e) {
1766
+ var target = e.currentTarget;
1767
+ var text = target.getAttribute('data-copy');
1768
+ if (!text || !navigator.clipboard) return;
1769
+ navigator.clipboard.writeText(text).then(function() {
1770
+ target.classList.add('copied');
1771
+ var existing = timers.get(target);
1772
+ if (existing) clearTimeout(existing);
1773
+ timers.set(target, setTimeout(function() {
1774
+ target.classList.remove('copied');
1775
+ timers.delete(target);
1776
+ }, 1500));
1777
+ });
1778
+ });
1779
+ }
1780
+ })();
1781
+ </script>`;var RETRY_CTA=ctaBlock("To try again, run these commands in your terminal:",["npx githits@latest logout","npx githits@latest login"]);var HELP_CTA=ctaBlock("Explore available commands with:",["npx githits@latest --help"]);function escapeHtml(text){return text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var METADATA_FILE="metadata.json";var DIR_MODE3=448;var FILE_MODE3=384;class AuthSessionMetadataStorage{fs;configDir;metadataPath;constructor(fs,configDir){this.fs=fs;this.configDir=configDir??getAuthFileStorageDir(fs);this.metadataPath=fs.joinPath(this.configDir,METADATA_FILE)}async load(baseUrl){const stored=await this.loadFile();if(!stored)return null;const metadata=stored.sessions[normalizeBaseUrl(baseUrl)]??null;return isAuthSessionMetadata(metadata)?metadata:null}async saveFromTokens(baseUrl,tokens){const stored=await this.loadFile()??{version:1,sessions:{}};stored.sessions[normalizeBaseUrl(baseUrl)]={createdAt:tokens.createdAt,expiresAt:tokens.expiresAt,updatedAt:new Date().toISOString()};await this.fs.ensureDir(this.configDir,DIR_MODE3);await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2),FILE_MODE3)}async clear(baseUrl){const stored=await this.loadFile();if(!stored)return;delete stored.sessions[normalizeBaseUrl(baseUrl)];if(Object.keys(stored.sessions).length===0){await this.fs.deleteFile(this.metadataPath);return}await this.fs.atomicWriteFile(this.metadataPath,JSON.stringify(stored,null,2),FILE_MODE3)}async loadFile(){if(!await this.fs.exists(this.metadataPath))return null;try{const content=await this.fs.readFile(this.metadataPath);const data=JSON.parse(content);if(data.version!==1||!data.sessions)return null;return data}catch{return null}}}function isAuthSessionMetadata(value){if(value===null||typeof value!=="object")return false;return typeof value.createdAt==="string"&&value.createdAt.length>0&&typeof value.updatedAt==="string"&&value.updatedAt.length>0&&(value.expiresAt===null||typeof value.expiresAt==="string"&&value.expiresAt.length>0)}import open from"open";class BrowserServiceImpl{async open(url){await open(url)}}var WINDOWS_MAX_ENTRY_SIZE=1200;var CHUNKED_PREFIX="CHUNKED:";var MAX_CHUNK_COUNT=100;function chunkKey(account,writeId,index){return`${account}:chunk:${writeId}:${index}`}function parseChunkedSentinel(value){if(!value.startsWith(CHUNKED_PREFIX))return null;const rest=value.slice(CHUNKED_PREFIX.length);const colonIndex=rest.indexOf(":");if(colonIndex===-1)return null;const writeId=rest.slice(0,colonIndex);if(writeId.length===0)return null;const countStr=rest.slice(colonIndex+1);const count=Number(countStr);if(!Number.isInteger(count)||count<=0)return null;return{writeId,count}}function splitIntoChunks(value,maxSize){if(value.length===0)return[""];const chunks=[];for(let offset=0;offset<value.length;offset+=maxSize){chunks.push(value.slice(offset,offset+maxSize))}return chunks}function generateWriteId(){let id;do{id=Math.random().toString(36).slice(2,8)}while(id.length<6);return id}class ChunkingKeyringService{inner;maxEntrySize;constructor(inner,maxEntrySize=WINDOWS_MAX_ENTRY_SIZE){this.inner=inner;this.maxEntrySize=maxEntrySize}getPassword(service,account){const value=this.inner.getPassword(service,account);if(value===null)return null;if(!value.startsWith(CHUNKED_PREFIX))return value;const sentinel=parseChunkedSentinel(value);if(sentinel===null)return null;const chunks=[];for(let i=0;i<sentinel.count;i++){const chunk=this.inner.getPassword(service,chunkKey(account,sentinel.writeId,i));if(chunk===null){console.error(`Warning: Incomplete chunked keychain entry for "${account}" (missing chunk ${i} of ${sentinel.count}). Treating as missing.`);return null}chunks.push(chunk)}return chunks.join("")}setPassword(service,account,password){const oldValue=this.readOldSentinel(service,account);if(password.length<=this.maxEntrySize){this.inner.setPassword(service,account,password)}else{const chunks=splitIntoChunks(password,this.maxEntrySize);if(chunks.length>MAX_CHUNK_COUNT){throw new Error(`Value requires ${chunks.length} chunks, exceeding maximum of ${MAX_CHUNK_COUNT}. `+`This likely indicates a bug — credential data should not be this large.`)}const writeId=generateWriteId();for(const[i,chunk]of chunks.entries()){this.inner.setPassword(service,chunkKey(account,writeId,i),chunk)}this.inner.setPassword(service,account,`${CHUNKED_PREFIX}${writeId}:${chunks.length}`)}if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}}deletePassword(service,account){const oldValue=this.readOldSentinel(service,account);if(oldValue!==null){this.deleteChunkEntries(service,account,oldValue)}return this.inner.deletePassword(service,account)}readOldSentinel(service,account){try{const value=this.inner.getPassword(service,account);if(value===null)return null;return parseChunkedSentinel(value)}catch{return null}}deleteChunkEntries(service,account,sentinel){for(let i=0;i<sentinel.count;i++){try{this.inner.deletePassword(service,chunkKey(account,sentinel.writeId,i))}catch{}}}}import{randomUUID as randomUUID2}from"node:crypto";import{mkdir,mkdtemp,readdir,readFile,rename as renamePath,rmdir,stat,unlink,writeFile}from"node:fs/promises";import{homedir,tmpdir}from"node:os";import{dirname,join}from"node:path";class FileSystemServiceImpl{async readFile(path){return readFile(path,"utf-8")}async writeFile(path,contents,mode){await writeFile(path,contents,{mode})}async writeFileExclusive(path,contents,mode){await writeFile(path,contents,{mode,flag:"wx"})}async deleteFile(path){try{await unlink(path)}catch(error){if(error.code!=="ENOENT"){throw error}}}async deleteDirIfEmpty(path){try{await rmdir(path)}catch(error){const code=error.code;if(code!=="ENOENT"&&code!=="ENOTEMPTY"&&code!=="EEXIST"&&code!=="ENOTDIR"){throw error}}}async rename(source,destination){await renamePath(source,destination)}async exists(path){try{await stat(path);return true}catch{return false}}async ensureDir(path,mode){await mkdir(path,{recursive:true,mode})}async createTempDir(prefix){return mkdtemp(join(tmpdir(),prefix))}getHomeDir(){return homedir()}joinPath(...segments){return join(...segments)}getCwd(){return process.cwd()}getDirname(path){return dirname(path)}async readdir(path){return readdir(path)}async isDirectory(path){try{const stats=await stat(path);return stats.isDirectory()}catch{return false}}async atomicWriteFile(path,contents,maximumMode){const tmpPath=`${path}.${process.pid}.${randomUUID2()}.tmp`;const normalizedMaximum=maximumMode===undefined?undefined:maximumMode&511;let mode=normalizedMaximum??384;try{const existing=await stat(path);const existingMode=existing.mode&511;mode=normalizedMaximum===undefined?existingMode:existingMode&normalizedMaximum}catch{}try{await writeFile(tmpPath,contents,{mode});await renamePath(tmpPath,path)}catch(error){try{await unlink(tmpPath)}catch{}throw error}}}var SERVICE_NAME="githits";var TOKEN_PREFIX="v1:tokens:";var CLIENT_PREFIX="v1:client:";function parseJsonOrNull2(json){if(json===null)return null;try{const parsed=JSON.parse(json);if(typeof parsed!=="object"||parsed===null)return null;return parsed}catch{return null}}function isValidTokenData(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.accessToken==="string"&&d.accessToken.length>0&&typeof d.refreshToken==="string"&&d.refreshToken.length>0&&typeof d.createdAt==="string"&&d.createdAt.length>0&&(d.expiresAt===null||typeof d.expiresAt==="string"&&d.expiresAt.length>0)}function isValidClientRegistration(data){if(typeof data!=="object"||data===null)return false;const d=data;return typeof d.clientId==="string"&&d.clientId.length>0&&typeof d.clientSecret==="string"&&d.clientSecret.length>0&&typeof d.redirectUri==="string"&&d.redirectUri.length>0&&typeof d.registeredAt==="string"&&d.registeredAt.length>0}class KeychainAuthStorage{keyring;constructor(keyring){this.keyring=keyring}async loadTokens(baseUrl){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidTokenData(data))return null;return data}async saveTokens(baseUrl,data){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}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 key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.deletePassword(SERVICE_NAME,key)}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 key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidClientRegistration(data))return null;return data}async saveClient(baseUrl,data){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async clearClient(baseUrl){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl)}`;this.keyring.deletePassword(SERVICE_NAME,key)}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))}getStorageLocation(){switch(process.platform){case"darwin":return"macOS Keychain (githits)";case"win32":return"Windows Credential Manager (githits)";default:return"System keychain (githits)"}}}import{Entry}from"@napi-rs/keyring";class KeychainUnavailableError extends Error{constructor(message,cause){super(message);this.name="KeychainUnavailableError";this.cause=cause}}function wrapKeyringError(error){const message=error instanceof Error?error.message:String(error);throw new KeychainUnavailableError(`System keychain unavailable: ${message}`,error)}class KeyringServiceImpl{getPassword(service,account){try{return new Entry(service,account).getPassword()}catch(error){wrapKeyringError(error)}}setPassword(service,account,password){try{new Entry(service,account).setPassword(password)}catch(error){wrapKeyringError(error)}}deletePassword(service,account){try{return new Entry(service,account).deleteCredential()}catch(error){wrapKeyringError(error)}}}import{AsyncLocalStorage}from"node:async_hooks";import{execFile}from"node:child_process";import{createHash as createHash3,randomUUID as randomUUID3}from"node:crypto";import{mkdir as mkdir2}from"node:fs/promises";import{dirname as dirname2}from"node:path";import{promisify}from"node:util";var LOCK_DIR="auth.lock";var LOCK_TIMEOUT_MS=DEFAULT_FETCH_TIMEOUT_MS*2+1e4;var LOCK_RETRY_MS=25;var LOCK_OWNER_RECHECK_MS=1000;var ORPHANED_LOCK_MS=5000;var OWNER_FILE="owner.json";var RECLAIM_FILE_PREFIX="reclaim-";var RELEASE_DIR_PREFIX=`${LOCK_DIR}.release-`;var RECLAIM_OWNER_HASH_PATTERN=/^[0-9a-f]{64}$/;var MAX_NODE_PROCESS_ID=2147483647;var PROCESS_IDENTITY_LOOKUP_TIMEOUT_MS=5000;var RELEASE_OWNER_READ_ATTEMPTS=3;var CLEANUP_FILE_DELETE_ATTEMPTS=3;var execFileAsync=promisify(execFile);class AuthStorageLockTimeoutError extends Error{constructor(message){super(message);this.name="AuthStorageLockTimeoutError"}}function withAuthStorageLock(storage,fn){return storage.withAuthStorageLock(fn)}class LockedAuthStorage{storage;fileSystemService;lockPath;lockTimeoutMs;isOwnerAlive;processStartedAtLookup;currentProcessStartedAtPromise;lockContext=new AsyncLocalStorage;currentOwner=null;lockLoads;constructor(storage,fileSystemService,options={}){this.storage=storage;this.fileSystemService=fileSystemService;this.lockTimeoutMs=options.lockTimeoutMs??LOCK_TIMEOUT_MS;this.processStartedAtLookup=options.getProcessStartedAt??getProcessStartedAt;this.isOwnerAlive=options.isOwnerAlive??((pid,processStartedAt)=>isOriginalProcessAlive(pid,processStartedAt,pid===process.pid?()=>this.getCurrentProcessStartedAt():this.processStartedAtLookup));this.lockLoads=storage.requiresLoadLock===true;this.lockPath=fileSystemService.joinPath(getAuthLockDir(fileSystemService),LOCK_DIR)}loadTokens(baseUrl){return this.lockLoads?this.withAuthStorageLock(()=>this.storage.loadTokens(baseUrl)):this.storage.loadTokens(baseUrl)}saveTokens(baseUrl,data){return this.withAuthStorageLock(()=>this.storage.saveTokens(baseUrl,data))}saveTokensIfUnchanged(baseUrl,expected,data){return this.withAuthStorageLock(()=>this.storage.saveTokensIfUnchanged(baseUrl,expected,data))}clearTokens(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearTokens(baseUrl))}clearTokensIfUnchanged(baseUrl,expected){return this.withAuthStorageLock(()=>this.storage.clearTokensIfUnchanged(baseUrl,expected))}clearActiveTokensIfUnchanged(baseUrl,expected){return this.withAuthStorageLock(()=>this.storage.clearActiveTokensIfUnchanged(baseUrl,expected))}loadClient(baseUrl){return this.lockLoads?this.withAuthStorageLock(()=>this.storage.loadClient(baseUrl)):this.storage.loadClient(baseUrl)}saveClient(baseUrl,data){return this.withAuthStorageLock(()=>this.storage.saveClient(baseUrl,data))}clearClient(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearClient(baseUrl))}clearActiveClient(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearActiveClient(baseUrl))}saveAuthSession(baseUrl,client,tokens){return this.withAuthStorageLock(()=>this.storage.saveAuthSession(baseUrl,client,tokens))}clearAuthSession(baseUrl){return this.withAuthStorageLock(()=>this.storage.clearAuthSession(baseUrl))}getStorageLocation(){return this.storage.getStorageLocation()}async withAuthStorageLock(fn){const ownerId=this.lockContext.getStore();if(ownerId&&this.currentOwner?.id===ownerId){return fn()}const acquiredOwner=await this.acquireLock();try{return await this.lockContext.run(acquiredOwner.id,fn)}finally{await this.releaseLock(acquiredOwner)}}async acquireLock(){const processStartedAt=await this.getCurrentProcessStartedAt();const startedAt=Date.now();let nextOwnerCheckAt=0;await mkdir2(dirname2(this.lockPath),{recursive:true,mode:448});while(true){try{await mkdir2(this.lockPath,{recursive:false,mode:448});try{const owner=await this.writeOwner(processStartedAt);return owner}catch(error){const code=error.code;if(code==="EEXIST"||code==="ENOENT"){if(Date.now()-startedAt>=this.lockTimeoutMs){throw this.createLockTimeoutError()}await sleep(LOCK_RETRY_MS);continue}await this.fileSystemService.deleteDirIfEmpty(this.lockPath).catch(()=>{return});throw error}}catch(error){if(error.code!=="EEXIST")throw error;const now=Date.now();if(now>=nextOwnerCheckAt){await this.reclaimStaleLock();nextOwnerCheckAt=Date.now()+LOCK_OWNER_RECHECK_MS}if(Date.now()-startedAt>=this.lockTimeoutMs){throw this.createLockTimeoutError()}await sleep(LOCK_RETRY_MS)}}}createLockTimeoutError(){return new AuthStorageLockTimeoutError(`Timed out waiting for GitHits auth storage lock at ${this.lockPath}. After stopping all GitHits CLI and MCP processes, remove this directory and retry.`)}getCurrentProcessStartedAt(){if(!this.currentProcessStartedAtPromise){const lookup=this.processStartedAtLookup(process.pid);this.currentProcessStartedAtPromise=lookup;lookup.then((startedAt)=>{if(startedAt===null&&this.currentProcessStartedAtPromise===lookup){this.currentProcessStartedAtPromise=undefined}},()=>{if(this.currentProcessStartedAtPromise===lookup){this.currentProcessStartedAtPromise=undefined}})}return this.currentProcessStartedAtPromise}async writeOwner(processStartedAt){const owner={id:randomUUID3(),pid:process.pid,createdAt:new Date().toISOString(),processStartedAt};await this.fileSystemService.writeFileExclusive(this.ownerPath(),JSON.stringify(owner),384);this.currentOwner=owner;return owner}async reclaimStaleLock(){const ownerResult=await this.readOwner();if(ownerResult.state==="missing"){await this.reclaimOldOwnerlessLock();return}if(ownerResult.state==="unknown")return;const owner=ownerResult.owner;const ownerDead=!await this.isOwnerAlive(owner.pid,owner.processStartedAt);if(!ownerDead)return;await this.reclaimProvenDeadOwner(owner)}async reclaimProvenDeadOwner(owner){const claimPath=this.reclaimPath(owner.id);try{await this.fileSystemService.writeFileExclusive(claimPath,"",384)}catch{return}const currentOwner=await this.readOwner();let removedExpectedOwner=false;if(currentOwner.state==="present"&&currentOwner.owner.id===owner.id){removedExpectedOwner=await this.deleteFileForCleanup(this.ownerPath())}if(!await this.deleteFileForCleanup(claimPath)){return}if(!removedExpectedOwner)return;await this.fileSystemService.deleteDirIfEmpty(this.lockPath).catch(()=>{return})}async reclaimOldOwnerlessLock(){const createdAtMs=await lockCreatedAtMs(this.lockPath);if(Date.now()-createdAtMs<ORPHANED_LOCK_MS)return;let entries;try{entries=await this.fileSystemService.readdir(this.lockPath)}catch{return}if(entries.some((entry)=>!isReclaimFileName(entry)))return;for(const entry of entries){const claimPath=this.fileSystemService.joinPath(this.lockPath,entry);if(!await this.deleteFileForCleanup(claimPath))return}await this.fileSystemService.deleteDirIfEmpty(this.lockPath).catch(()=>{return})}async readOwner(){let raw;try{raw=await this.fileSystemService.readFile(this.ownerPath())}catch(error){return error.code==="ENOENT"?{state:"missing"}:{state:"unknown"}}try{const parsed=JSON.parse(raw);if(typeof parsed.id!=="string"||typeof parsed.pid!=="number"||!Number.isSafeInteger(parsed.pid)||parsed.pid<=0||parsed.pid>MAX_NODE_PROCESS_ID||typeof parsed.createdAt!=="string"||!(typeof parsed.processStartedAt==="string"||parsed.processStartedAt===null)){return{state:"unknown"}}const owner={id:parsed.id,pid:parsed.pid,createdAt:parsed.createdAt,processStartedAt:parsed.processStartedAt};return{state:"present",owner}}catch{return{state:"unknown"}}}async releaseLock(owner){if(this.currentOwner?.id===owner.id)this.currentOwner=null;const currentOwner=await this.readOwnerForRelease();if(currentOwner.state!=="present"||currentOwner.owner.id!==owner.id)return;if(!await this.deleteFileForCleanup(this.ownerPath()))return;const releasePath=this.releasePath(owner.id);try{await this.fileSystemService.rename(this.lockPath,releasePath)}catch{return}await this.fileSystemService.deleteDirIfEmpty(releasePath).catch(()=>{return})}ownerPath(){return this.fileSystemService.joinPath(this.lockPath,OWNER_FILE)}reclaimPath(ownerId){const ownerHash=createHash3("sha256").update(ownerId).digest("hex");return this.fileSystemService.joinPath(this.lockPath,`${RECLAIM_FILE_PREFIX}${ownerHash}`)}releasePath(ownerId){const ownerHash=createHash3("sha256").update(ownerId).digest("hex");return this.fileSystemService.joinPath(this.fileSystemService.getDirname(this.lockPath),`${RELEASE_DIR_PREFIX}${ownerHash}`)}async readOwnerForRelease(){let result=await this.readOwner();for(let attempt=1;result.state==="unknown"&&attempt<RELEASE_OWNER_READ_ATTEMPTS;attempt+=1){await sleep(LOCK_RETRY_MS);result=await this.readOwner()}return result}async deleteFileForCleanup(path){for(let attempt=1;attempt<=CLEANUP_FILE_DELETE_ATTEMPTS;attempt+=1){try{await this.fileSystemService.deleteFile(path);return true}catch(error){const code=error.code;const retryable=code==="EACCES"||code==="EBUSY"||code==="EPERM";if(!retryable||attempt===CLEANUP_FILE_DELETE_ATTEMPTS)return false;await sleep(LOCK_RETRY_MS)}}return false}}function sleep(ms){return new Promise((resolve)=>setTimeout(resolve,ms))}function isReclaimFileName(entry){return entry.startsWith(RECLAIM_FILE_PREFIX)&&RECLAIM_OWNER_HASH_PATTERN.test(entry.slice(RECLAIM_FILE_PREFIX.length))}async function isOriginalProcessAlive(pid,processStartedAt,getStartedAt){if(!isProcessAlive(pid))return false;if(!processStartedAt)return true;let observedStartedAt;try{observedStartedAt=await getStartedAt(pid)}catch{return true}if(!observedStartedAt)return true;return observedStartedAt===processStartedAt}function isProcessAlive(pid){if(pid<=0)return false;try{process.kill(pid,0);return true}catch(error){const code=error.code;return code!=="ESRCH"}}async function getProcessStartedAt(pid){try{if(process.platform==="win32"){const{stdout}=await execFileAsync("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`],{timeout:PROCESS_IDENTITY_LOOKUP_TIMEOUT_MS,killSignal:"SIGKILL",windowsHide:true});return stdout.trim()||null}const{stdout}=await execFileAsync("ps",["-p",String(pid),"-o","lstart="],{timeout:PROCESS_IDENTITY_LOOKUP_TIMEOUT_MS,killSignal:"SIGKILL"});const parsed=Date.parse(stdout.trim());return Number.isNaN(parsed)?null:new Date(parsed).toISOString()}catch{return null}}async function lockCreatedAtMs(path){try{const{stat}=await import("node:fs/promises");return(await stat(path)).mtimeMs}catch{return 0}}class AuthStoragePolicyError extends Error{constructor(message){super(message);this.name="AuthStoragePolicyError"}}function createFileAuthStorageGuidance(configPath){return`OAuth credentials were not saved to plaintext file storage.
1782
+
1783
+ Options:
1784
+ 1. Unlock or fix your system keychain.
1785
+ 2. Use GITHITS_API_TOKEN for CI/automation.
1786
+ 3. If you accept storing OAuth credentials unencrypted on disk, set:
1787
+
1788
+ [auth]
1789
+ storage = "file"
1790
+
1791
+ in ${configPath}, or run with GITHITS_AUTH_STORAGE=file.
1792
+
1793
+ Warning: file storage is plaintext. Use it only on machines where local file access is trusted.`}class ModeAwareFileAuthStorage{storage;mode;configPath;constructor(storage,mode,configPath="your GitHits config.toml"){this.storage=storage;this.mode=mode;this.configPath=configPath}loadTokens(baseUrl){return this.storage.loadTokens(baseUrl)}async saveTokens(baseUrl,data){this.assertFileMode();await this.storage.saveTokens(baseUrl,data)}async saveTokensIfUnchanged(baseUrl,expected,data){this.assertFileMode();return this.storage.saveTokensIfUnchanged(baseUrl,expected,data)}clearTokens(baseUrl){return this.storage.clearTokens(baseUrl)}clearTokensIfUnchanged(baseUrl,expected){return this.storage.clearTokensIfUnchanged(baseUrl,expected)}clearActiveTokensIfUnchanged(baseUrl,expected){return this.storage.clearActiveTokensIfUnchanged(baseUrl,expected)}loadClient(baseUrl){return this.storage.loadClient(baseUrl)}async saveClient(baseUrl,data){this.assertFileMode();await this.storage.saveClient(baseUrl,data)}clearClient(baseUrl){return this.storage.clearClient(baseUrl)}clearActiveClient(baseUrl){return this.storage.clearActiveClient(baseUrl)}async saveAuthSession(baseUrl,client,tokens){this.assertFileMode();await this.storage.saveAuthSession(baseUrl,client,tokens)}clearAuthSession(baseUrl){return this.storage.clearAuthSession(baseUrl)}getStorageLocation(){return this.storage.getStorageLocation()}assertFileMode(){if(this.mode==="file")return;throw new AuthStoragePolicyError(createFileAuthStorageGuidance(this.configPath))}}class MigratingAuthStorage{primary;file;legacy;mode;configPath;onWarning;metadata;additionalLegacyStores;warnedAmbiguousPlaintext=false;requiresLoadLock;constructor(primary,file,legacy,mode,configPath="your GitHits config.toml",onWarning=()=>{},metadata,additionalLegacyStores=[]){this.primary=primary;this.file=file;this.legacy=legacy;this.mode=mode;this.configPath=configPath;this.onWarning=onWarning;this.metadata=metadata;this.additionalLegacyStores=additionalLegacyStores;this.requiresLoadLock=mode==="file"}async loadTokens(baseUrl){if(this.mode==="file"){return this.loadTokensFileMode(baseUrl)}return this.loadTokensKeychainMode(baseUrl)}async saveTokens(baseUrl,data){if(this.mode==="file"){await this.file.saveTokens(baseUrl,data);await this.saveMetadataBestEffort(baseUrl,data);return}try{await this.primary.saveTokens(baseUrl,data);await this.saveMetadataBestEffort(baseUrl,data)}catch(error){throw this.toPolicyError(error)}}async saveTokensIfUnchanged(baseUrl,expected,data){const current=await this.loadTokens(baseUrl);if(!this.sameTokenData(current,expected))return false;await this.saveTokens(baseUrl,data);return true}async clearTokens(baseUrl){const primaryError=await this.clearBestEffort(()=>this.primary.clearTokens(baseUrl));await this.clearBestEffort(()=>this.file.clearTokens(baseUrl));await this.clearBestEffort(()=>this.legacy.clearTokens(baseUrl));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearTokensIfUnchanged(baseUrl,expected){const current=await this.loadTokens(baseUrl);if(!this.sameTokenData(current,expected))return false;await this.clearTokens(baseUrl);return true}async clearActiveTokensIfUnchanged(baseUrl,expected){const current=await this.currentActiveTokens(baseUrl);if(!this.sameTokenData(current,expected))return false;let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearTokens(baseUrl));firstError??=error}const metadataError=await this.clearBestEffort(()=>this.metadata?.clear(baseUrl)??Promise.resolve());firstError??=metadataError;if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}return true}async loadClient(baseUrl){if(this.mode==="file"){return this.loadClientFileMode(baseUrl)}return this.loadClientKeychainMode(baseUrl)}async saveClient(baseUrl,data){if(this.mode==="file"){await this.file.saveClient(baseUrl,data);return}try{await this.primary.saveClient(baseUrl,data)}catch(error){throw this.toPolicyError(error)}}async clearClient(baseUrl){const primaryError=await this.clearBestEffort(()=>this.primary.clearClient(baseUrl));await this.clearBestEffort(()=>this.file.clearClient(baseUrl));await this.clearBestEffort(()=>this.legacy.clearClient(baseUrl));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearClient(baseUrl))}if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearActiveClient(baseUrl){let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearClient(baseUrl));firstError??=error}if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}}async saveAuthSession(baseUrl,client,tokens){if(this.mode==="file"){await this.file.saveAuthSession(baseUrl,client,tokens);await this.saveMetadataBestEffort(baseUrl,tokens);return}try{await this.primary.saveAuthSession(baseUrl,client,tokens);await this.saveMetadataBestEffort(baseUrl,tokens)}catch(error){throw this.toPolicyError(error)}}async clearAuthSession(baseUrl){const primaryError=await this.clearBestEffort(()=>this.primary.clearAuthSession(baseUrl));await this.clearBestEffort(()=>this.file.clearAuthSession(baseUrl));await this.clearBestEffort(()=>this.legacy.clearAuthSession(baseUrl));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearAuthSession(baseUrl))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}getStorageLocation(){return this.mode==="file"?this.file.getStorageLocation():this.primary.getStorageLocation()}async loadTokensKeychainMode(baseUrl){try{const primaryTokens=await this.primary.loadTokens(baseUrl);if(primaryTokens){await this.saveMetadataBestEffort(baseUrl,primaryTokens);return primaryTokens}}catch(error){throw this.toPolicyError(error)}return null}async loadTokensFileMode(baseUrl){const candidate=await this.selectPlaintextTokenCandidate(baseUrl);if(candidate){if(candidate.ambiguous){await this.file.saveTokens(baseUrl,candidate.data);for(const legacy of this.getLegacyStores()){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl))}}else if(candidate.source==="legacy"){await this.file.saveTokens(baseUrl,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearTokens(baseUrl))}await this.saveMetadataBestEffort(baseUrl,candidate.data);return candidate.data}return null}async loadClientKeychainMode(baseUrl){try{const primaryClient=await this.primary.loadClient(baseUrl);if(primaryClient)return primaryClient}catch(error){throw this.toPolicyError(error)}return null}async loadClientFileMode(baseUrl){const candidate=await this.selectPlaintextClientCandidate(baseUrl);if(candidate){if(candidate.ambiguous){await this.file.saveClient(baseUrl,candidate.data);for(const legacy of this.getLegacyStores()){await this.clearBestEffort(()=>legacy.clearClient(baseUrl))}}else if(candidate.source==="legacy"){await this.file.saveClient(baseUrl,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearClient(baseUrl))}return candidate.data}return null}async selectPlaintextTokenCandidate(baseUrl){const candidates=[];const fileTokens=await this.file.loadTokens(baseUrl);if(fileTokens){candidates.push({data:fileTokens,source:"file",storage:this.file,timestamp:fileTokens.createdAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyTokens=await legacy.loadTokens(baseUrl);if(legacyTokens){candidates.push({data:legacyTokens,source:"legacy",storage:legacy,timestamp:legacyTokens.createdAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}async selectPlaintextClientCandidate(baseUrl){const candidates=[];const fileClient=await this.file.loadClient(baseUrl);if(fileClient){candidates.push({data:fileClient,source:"file",storage:this.file,timestamp:fileClient.registeredAt,ambiguous:false})}for(const legacy of this.getLegacyStores()){const legacyClient=await legacy.loadClient(baseUrl);if(legacyClient){candidates.push({data:legacyClient,source:"legacy",storage:legacy,timestamp:legacyClient.registeredAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}selectNewestCandidate(candidates){if(candidates.length===0)return null;if(candidates.length===1)return candidates[0]??null;const parsed=candidates.map((candidate)=>({candidate,timestampMs:Date.parse(candidate.timestamp)}));if(parsed.some((entry)=>Number.isNaN(entry.timestampMs))){return this.selectCanonicalAmbiguousCandidate(candidates)}const sorted=[...parsed].sort((a,b)=>b.timestampMs-a.timestampMs);const first=sorted[0];const second=sorted[1];if(!first)return candidates[0]??null;if(second&&first.timestampMs===second.timestampMs){return this.selectCanonicalAmbiguousCandidate(candidates)}return first.candidate}selectCanonicalAmbiguousCandidate(candidates){const selected=candidates.find((candidate)=>candidate.source==="file")??null;if(!selected){this.warnAmbiguousPlaintext();return null}selected.ambiguous=true;return selected}getLegacyStores(){return[...this.additionalLegacyStores,this.legacy]}activeStores(){return this.mode==="file"?[this.file,...this.getLegacyStores()]:[this.primary]}async currentActiveTokens(baseUrl){if(this.mode==="file"){const candidate=await this.selectPlaintextTokenCandidate(baseUrl);return candidate?.data??null}try{return await this.primary.loadTokens(baseUrl)}catch(error){throw this.toPolicyError(error)}}async clearBestEffort(fn){try{await fn();return}catch(error){return error}}async saveMetadataBestEffort(baseUrl,tokens){await this.clearBestEffort(()=>this.metadata?.saveFromTokens(baseUrl,tokens)??Promise.resolve())}toPolicyError(error){if(!(error instanceof KeychainUnavailableError))return error;return new AuthStoragePolicyError(`System keychain is unavailable. ${createFileAuthStorageGuidance(this.configPath)}`)}warnAmbiguousPlaintext(){if(this.warnedAmbiguousPlaintext)return;this.warnedAmbiguousPlaintext=true;this.onWarning("Warning: multiple legacy plaintext auth entries exist with ambiguous timestamps; no canonical config-path entry was found, so the legacy entries were left intact.")}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}}import{ProxyAgent,fetch as undiciFetch}from"undici";var NODE_USE_ENV_PROXY="NODE_USE_ENV_PROXY";var USE_ENV_PROXY_FLAG="--use-env-proxy";function createCliFetch(options={}){const env=options.env??process.env;const baseFetch=options.baseFetch??globalThis.fetch;const proxyConfig=getProxyConfig(env);if(!proxyConfig.httpProxy&&!proxyConfig.httpsProxy){return baseFetch}if(isNativeEnvProxyActive({env,execArgv:options.execArgv??process.execArgv,nodeOptions:options.nodeOptions??env.NODE_OPTIONS,nodeVersion:options.nodeVersion??process.versions.node})){return baseFetch}validateProxySelection(proxyConfig.httpProxy);validateProxySelection(proxyConfig.httpsProxy);const fetchWithDispatcher=options.undiciFetch??undiciFetch;const createProxyAgent=options.createProxyAgent??((proxyUrl)=>new ProxyAgent({uri:proxyUrl,proxyTunnel:false}));const proxyAgents=new Map;return async(input,init)=>{const targetUrl=getRequestUrl(input);if(!targetUrl){return baseFetch(input,init)}const proxy=resolveProxyForUrl(targetUrl,proxyConfig);if(!proxy){return baseFetch(input,init)}let dispatcher=proxyAgents.get(proxy.value);if(!dispatcher){dispatcher=createProxyAgent(proxy.value);proxyAgents.set(proxy.value,dispatcher)}try{const undiciInit={...init,dispatcher};return await fetchWithDispatcher(input,undiciInit)}catch(error){throw createSanitizedProxyRequestError(proxy,error)}}}function createLazyCliFetch(options={}){let fetchFn;return async(input,init)=>{fetchFn??=createCliFetch(options);return await fetchFn(input,init)}}function getProxyConfig(env){return{httpProxy:getEnvSelection(env,"HTTP_PROXY"),httpsProxy:getEnvSelection(env,"HTTPS_PROXY"),noProxy:getEnvSelection(env,"NO_PROXY")?.value}}function isNativeEnvProxyActive(options){const envOptIn=options.env[NODE_USE_ENV_PROXY]==="1";const flagOptIn=hasUseEnvProxyFlag(options.execArgv)||hasUseEnvProxyFlag(splitNodeOptions(options.nodeOptions));if(envOptIn&&supportsNativeEnvProxyEnv(options.nodeVersion)){return true}return flagOptIn&&supportsNativeEnvProxyFlag(options.nodeVersion)}function resolveProxyForUrl(targetUrl,proxyConfig){if(shouldBypassProxy(targetUrl,proxyConfig.noProxy)){return}if(targetUrl.protocol==="http:"){return proxyConfig.httpProxy}if(targetUrl.protocol==="https:"){return proxyConfig.httpsProxy??proxyConfig.httpProxy}return}function redactProxyUrl(value){try{const url=new URL(value);url.username="";url.password="";url.pathname="";url.search="";url.hash="";return url.toString()}catch{return"<invalid proxy URL>"}}function getEnvSelection(env,upperName){const lowerName=upperName.toLowerCase();if(hasEnvKey(env,lowerName)){const lowerValue=env[lowerName];return lowerValue?{name:lowerName,value:lowerValue}:undefined}if(hasEnvKey(env,upperName)){const upperValue=env[upperName];return upperValue?{name:upperName,value:upperValue}:undefined}return}function hasEnvKey(env,key){return Object.hasOwn(env,key)}function validateProxySelection(selection){if(!selection){return}let parsed;try{parsed=new URL(selection.value)}catch{throw new Error(`${selection.name} must be an http:// or https:// proxy URL.`)}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:"||!parsed.host){throw new Error(`${selection.name} must be an http:// or https:// proxy URL.`)}}function getRequestUrl(input){try{if(typeof input==="string"||input instanceof URL){return new URL(input)}if(typeof Request!=="undefined"&&input instanceof Request){return new URL(input.url)}}catch{return}return}function shouldBypassProxy(targetUrl,noProxy){if(!noProxy){return false}if(noProxy.trim()==="*"){return true}const hostname=normalizeHostname(targetUrl.hostname);const port=Number.parseInt(targetUrl.port,10)||defaultPort(targetUrl);for(const rawEntry of noProxy.split(/[,\s]/)){const entry=rawEntry.trim().toLowerCase();if(!entry){continue}if(entry==="*"){return true}const{host:entryHost,port:entryPort}=parseNoProxyEntry(entry);if(entryPort&&entryPort!==port){continue}if(matchesNoProxyHost(hostname,entryHost)){return true}}return false}function matchesNoProxyHost(hostname,entryHost){const normalizedEntryHost=entryHost.replace(/^\*?\./,"");return hostname===normalizedEntryHost||hostname.endsWith(`.${normalizedEntryHost}`)}function parseNoProxyEntry(entry){const bracketedIpv6=entry.match(/^\[([^\]]+)\](?::(\d+))?$/);if(bracketedIpv6?.[1]){return{host:normalizeHostname(bracketedIpv6[1]),port:bracketedIpv6[2]?Number.parseInt(bracketedIpv6[2],10):0}}if(entry.includes(":")){const lastColon=entry.lastIndexOf(":");const maybePort=entry.slice(lastColon+1);const hostPart=entry.slice(0,lastColon);if(!hostPart.includes(":")&&/^\d+$/.test(maybePort)){return{host:normalizeHostname(hostPart),port:Number.parseInt(maybePort,10)}}return{host:normalizeHostname(entry),port:0}}return{host:normalizeHostname(entry),port:0}}function normalizeHostname(hostname){return hostname.replace(/^\[|\]$/g,"").toLowerCase()}function defaultPort(url){if(url.protocol==="http:"){return 80}if(url.protocol==="https:"){return 443}return 0}function hasUseEnvProxyFlag(args){return args.some((arg)=>arg===USE_ENV_PROXY_FLAG)}function splitNodeOptions(value){if(!value){return[]}return value.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)??[]}function supportsNativeEnvProxyEnv(nodeVersion){const parsed=parseNodeVersion(nodeVersion);if(!parsed){return false}const[major,minor]=parsed;if(major===22){return minor>=21}if(major===23){return false}return major>=24}function supportsNativeEnvProxyFlag(nodeVersion){const parsed=parseNodeVersion(nodeVersion);if(!parsed){return false}const[major,minor]=parsed;if(major===22){return minor>=21}if(major===24){return minor>=5}return major>=25}function parseNodeVersion(value){const match=value.match(/^(\d+)\.(\d+)\./);if(!match?.[1]||!match[2]){return}return[Number.parseInt(match[1],10),Number.parseInt(match[2],10)]}function createSanitizedProxyRequestError(proxy,error){const reason=sanitizeErrorMessage(error);return new Error(`Proxy request failed using ${proxy.name} (${redactProxyUrl(proxy.value)})${reason?`: ${reason}`:"."}`)}function sanitizeErrorMessage(error){if(!(error instanceof Error)||!error.message){return""}return error.message.replace(/https?:\/\/\S+/gi,(match)=>redactProxyUrl(match)).replace(/\b(?!https?:)[A-Za-z][A-Za-z0-9+.-]*:\/\/\S+/gi,"<redacted URL>")}import{writeSync}from"node:fs";var ENABLED_VALUES=new Set(["1","true","yes","on"]);function isTelemetryEnabled(env=process.env){const raw=env.GITHITS_TELEMETRY?.trim().toLowerCase();if(!raw)return false;return ENABLED_VALUES.has(raw)}class TelemetryCollector{enabled;now;write;sessionStartMs;spans=[];activeSpans=new Map;nextId=1;flushed=false;constructor(options={}){this.enabled=isTelemetryEnabled(options.env);this.now=options.now??(()=>globalThis.performance.now());this.write=options.write??((text)=>writeSync(process.stderr.fd,text));this.sessionStartMs=this.now()}isEnabled(){return this.enabled}startSpan(name,attributes){if(!this.enabled)return;const span={id:this.nextId++,name,startMs:this.now(),attributes:sanitiseAttributes(attributes)};this.spans.push(span);this.activeSpans.set(span.id,span);return{id:span.id}}endSpan(handle,attributes){if(!this.enabled||!handle)return;const span=this.activeSpans.get(handle.id);if(!span||span.endMs!==undefined)return;span.endMs=this.now();span.attributes=mergeAttributes(span.attributes,attributes);this.activeSpans.delete(handle.id)}flush(exitCode=0){if(!this.enabled||this.flushed)return;const nowMs=this.now();for(const span of this.activeSpans.values()){if(span.endMs!==undefined)continue;span.endMs=nowMs;span.endedAtExit=true}this.activeSpans.clear();this.write(formatTelemetryReport(this.spans,this.sessionStartMs,nowMs,exitCode));this.flushed=true}}async function withTelemetrySpan(name,operation,attributes){const handle=telemetryCollector.startSpan(name,attributes);try{const result=await operation();telemetryCollector.endSpan(handle);return result}catch(error){telemetryCollector.endSpan(handle,{error:true});throw error}}function startTelemetrySpan(name,attributes){return telemetryCollector.startSpan(name,attributes)}function endTelemetrySpan(handle,attributes){telemetryCollector.endSpan(handle,attributes)}function flushTelemetry(exitCode=0){telemetryCollector.flush(exitCode)}var telemetryCollector=new TelemetryCollector;function sanitiseAttributes(attributes){if(!attributes)return;const entries=Object.entries(attributes).filter(([,value])=>value!==undefined);if(entries.length===0)return;return Object.fromEntries(entries)}function mergeAttributes(initial,extra){if(!initial&&!extra)return;return sanitiseAttributes({...initial??{},...extra??{}})}function formatTelemetryReport(spans,sessionStartMs,sessionEndMs,exitCode){const lines=["[githits telemetry]",`exit: ${exitCode}`,`total: ${formatMs(sessionEndMs-sessionStartMs)}`];const orderedSpans=[...spans].sort((left,right)=>{if(left.startMs!==right.startMs){return left.startMs-right.startMs}return left.id-right.id});for(const span of orderedSpans){const endMs=span.endMs??sessionEndMs;const details=[`start +${formatMs(span.startMs-sessionStartMs)}`];if(span.endedAtExit){details.push("ended-at-exit")}const attrs=formatAttributes(span.attributes);if(attrs){details.push(attrs)}lines.push(`- ${span.name}: ${formatMs(endMs-span.startMs)} (${details.join(", ")})`)}return`${lines.join(`
1794
+ `)}
1795
+ `}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}
1796
+ `)}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}})}
1797
+ 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,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,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,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,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};