githits 0.11.0 → 0.11.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/.plugin/plugin.json +1 -1
- package/AGENTS.md +6 -4
- package/dist/cli.js +86 -86
- package/dist/index.js +1 -1
- package/dist/shared/{chunk-ycxd233m.js → chunk-crw6vamv.js} +1 -1
- package/dist/shared/chunk-kz6tqqfb.js +1725 -0
- package/dist/shared/{chunk-gjab0gcw.js → chunk-mjj3pj7r.js} +1 -1
- package/gemini-extension.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +2 -2
- package/skills/githits-code/SKILL.md +1 -1
- package/skills/githits-code/references/code-and-docs.md +1 -1
- package/skills/githits-mcp/SKILL.md +46 -1
- package/dist/shared/chunk-em3sdzv2.js +0 -1725
|
@@ -0,0 +1,1725 @@
|
|
|
1
|
+
import{__require,version}from"./chunk-mjj3pj7r.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")}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 z2}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 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}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}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)}import{z}from"zod";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 delaySeconds2=Number(normalized);return Number.isSafeInteger(delaySeconds2)?delaySeconds2: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 INDEXING_WAIT_HINT="Wait until ready with CLI `--wait 60000` or MCP `wait_timeout_ms: 60000`.";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_QUERY=`
|
|
92
|
+
query UnifiedSearch(
|
|
93
|
+
$targets: [SearchPackageInput!]!
|
|
94
|
+
$query: String!
|
|
95
|
+
$sources: [DiscoverySearchSource!]
|
|
96
|
+
$filters: DiscoverySearchFiltersInput
|
|
97
|
+
$allowPartialResults: Boolean
|
|
98
|
+
$limit: Int
|
|
99
|
+
$offset: Int
|
|
100
|
+
$waitTimeoutMs: Int
|
|
101
|
+
) {
|
|
102
|
+
search(
|
|
103
|
+
targets: $targets
|
|
104
|
+
query: $query
|
|
105
|
+
sources: $sources
|
|
106
|
+
filters: $filters
|
|
107
|
+
allowPartialResults: $allowPartialResults
|
|
108
|
+
limit: $limit
|
|
109
|
+
offset: $offset
|
|
110
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
111
|
+
) {
|
|
112
|
+
completed
|
|
113
|
+
searchRef
|
|
114
|
+
result {
|
|
115
|
+
query
|
|
116
|
+
queryWarnings
|
|
117
|
+
sources
|
|
118
|
+
results {
|
|
119
|
+
id
|
|
120
|
+
resultType
|
|
121
|
+
targetLabel
|
|
122
|
+
requestedTargetLabel
|
|
123
|
+
freshTargetLabel
|
|
124
|
+
servedTargetLabel
|
|
125
|
+
freshness
|
|
126
|
+
title
|
|
127
|
+
summary
|
|
128
|
+
score
|
|
129
|
+
highlights {
|
|
130
|
+
title
|
|
131
|
+
summary
|
|
132
|
+
}
|
|
133
|
+
locator {
|
|
134
|
+
registry
|
|
135
|
+
packageName
|
|
136
|
+
version
|
|
137
|
+
pageId
|
|
138
|
+
sourceKind
|
|
139
|
+
sourceUrl
|
|
140
|
+
repoUrl
|
|
141
|
+
gitRef
|
|
142
|
+
requestedRef
|
|
143
|
+
filePath
|
|
144
|
+
startLine
|
|
145
|
+
endLine
|
|
146
|
+
fileContentHash
|
|
147
|
+
symbolRef
|
|
148
|
+
qualifiedPath
|
|
149
|
+
kind
|
|
150
|
+
category
|
|
151
|
+
language
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
page {
|
|
155
|
+
offset
|
|
156
|
+
limit
|
|
157
|
+
returned
|
|
158
|
+
hasMore
|
|
159
|
+
}
|
|
160
|
+
partialResults
|
|
161
|
+
evidenceNotice
|
|
162
|
+
sourceStatus {
|
|
163
|
+
source
|
|
164
|
+
targetLabel
|
|
165
|
+
requestedTargetLabel
|
|
166
|
+
freshTargetLabel
|
|
167
|
+
servedTargetLabel
|
|
168
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
169
|
+
indexingStatus
|
|
170
|
+
codeIndexState
|
|
171
|
+
resultCount
|
|
172
|
+
appliedFilters
|
|
173
|
+
ignoredFilters
|
|
174
|
+
incompatibleFilters
|
|
175
|
+
appliedQueryFeatures
|
|
176
|
+
ignoredQueryFeatures
|
|
177
|
+
incompatibleQueryFeatures
|
|
178
|
+
suggestedSiteTargets
|
|
179
|
+
suggestedSiteTargetsTruncated
|
|
180
|
+
note
|
|
181
|
+
${DOC_COVERAGE_SELECTION}
|
|
182
|
+
${DOCUMENTATION_CONTRIBUTORS_SELECTION}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
progress {
|
|
186
|
+
searchRef
|
|
187
|
+
status
|
|
188
|
+
targetsTotal
|
|
189
|
+
targetsReady
|
|
190
|
+
elapsedMs
|
|
191
|
+
query
|
|
192
|
+
queryWarnings
|
|
193
|
+
sources
|
|
194
|
+
requestedSources
|
|
195
|
+
targetMode
|
|
196
|
+
requestedTargets {
|
|
197
|
+
registry
|
|
198
|
+
name
|
|
199
|
+
version
|
|
200
|
+
repoUrl
|
|
201
|
+
gitRef
|
|
202
|
+
site
|
|
203
|
+
}
|
|
204
|
+
filters {
|
|
205
|
+
fileIntent
|
|
206
|
+
kind
|
|
207
|
+
category
|
|
208
|
+
publicOnly
|
|
209
|
+
pathPrefix
|
|
210
|
+
}
|
|
211
|
+
limit
|
|
212
|
+
offset
|
|
213
|
+
targets {
|
|
214
|
+
requested
|
|
215
|
+
resolvedRequested
|
|
216
|
+
served
|
|
217
|
+
freshness
|
|
218
|
+
indexingRef
|
|
219
|
+
requestedRefKind
|
|
220
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
221
|
+
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
222
|
+
${DOC_COVERAGE_SELECTION}
|
|
223
|
+
}
|
|
224
|
+
expiresAt
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}`;var UNIFIED_SEARCH_STATUS_QUERY=`
|
|
228
|
+
query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
|
|
229
|
+
discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
|
|
230
|
+
searchRef
|
|
231
|
+
status
|
|
232
|
+
targetsTotal
|
|
233
|
+
targetsReady
|
|
234
|
+
elapsedMs
|
|
235
|
+
query
|
|
236
|
+
queryWarnings
|
|
237
|
+
sources
|
|
238
|
+
requestedSources
|
|
239
|
+
targetMode
|
|
240
|
+
requestedTargets {
|
|
241
|
+
registry
|
|
242
|
+
name
|
|
243
|
+
version
|
|
244
|
+
repoUrl
|
|
245
|
+
gitRef
|
|
246
|
+
site
|
|
247
|
+
}
|
|
248
|
+
filters {
|
|
249
|
+
fileIntent
|
|
250
|
+
kind
|
|
251
|
+
category
|
|
252
|
+
publicOnly
|
|
253
|
+
pathPrefix
|
|
254
|
+
}
|
|
255
|
+
limit
|
|
256
|
+
offset
|
|
257
|
+
targets {
|
|
258
|
+
requested
|
|
259
|
+
resolvedRequested
|
|
260
|
+
served
|
|
261
|
+
freshness
|
|
262
|
+
indexingRef
|
|
263
|
+
requestedRefKind
|
|
264
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
265
|
+
${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
|
|
266
|
+
${DOC_COVERAGE_SELECTION}
|
|
267
|
+
}
|
|
268
|
+
expiresAt
|
|
269
|
+
results {
|
|
270
|
+
query
|
|
271
|
+
queryWarnings
|
|
272
|
+
sources
|
|
273
|
+
results {
|
|
274
|
+
id
|
|
275
|
+
resultType
|
|
276
|
+
targetLabel
|
|
277
|
+
requestedTargetLabel
|
|
278
|
+
freshTargetLabel
|
|
279
|
+
servedTargetLabel
|
|
280
|
+
freshness
|
|
281
|
+
title
|
|
282
|
+
summary
|
|
283
|
+
score
|
|
284
|
+
highlights {
|
|
285
|
+
title
|
|
286
|
+
summary
|
|
287
|
+
}
|
|
288
|
+
locator {
|
|
289
|
+
registry
|
|
290
|
+
packageName
|
|
291
|
+
version
|
|
292
|
+
pageId
|
|
293
|
+
sourceKind
|
|
294
|
+
sourceUrl
|
|
295
|
+
repoUrl
|
|
296
|
+
gitRef
|
|
297
|
+
requestedRef
|
|
298
|
+
filePath
|
|
299
|
+
startLine
|
|
300
|
+
endLine
|
|
301
|
+
fileContentHash
|
|
302
|
+
symbolRef
|
|
303
|
+
qualifiedPath
|
|
304
|
+
kind
|
|
305
|
+
category
|
|
306
|
+
language
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
page {
|
|
310
|
+
offset
|
|
311
|
+
limit
|
|
312
|
+
returned
|
|
313
|
+
hasMore
|
|
314
|
+
}
|
|
315
|
+
partialResults
|
|
316
|
+
evidenceNotice
|
|
317
|
+
sourceStatus {
|
|
318
|
+
source
|
|
319
|
+
targetLabel
|
|
320
|
+
requestedTargetLabel
|
|
321
|
+
freshTargetLabel
|
|
322
|
+
servedTargetLabel
|
|
323
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
324
|
+
indexingStatus
|
|
325
|
+
codeIndexState
|
|
326
|
+
resultCount
|
|
327
|
+
appliedFilters
|
|
328
|
+
ignoredFilters
|
|
329
|
+
incompatibleFilters
|
|
330
|
+
appliedQueryFeatures
|
|
331
|
+
ignoredQueryFeatures
|
|
332
|
+
incompatibleQueryFeatures
|
|
333
|
+
suggestedSiteTargets
|
|
334
|
+
suggestedSiteTargetsTruncated
|
|
335
|
+
note
|
|
336
|
+
${DOC_COVERAGE_SELECTION}
|
|
337
|
+
${DOCUMENTATION_CONTRIBUTORS_SELECTION}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}`;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=z2.object({version:z2.string().nullable().optional(),ref:z2.string()});var indexingDurationEstimateSchema=z2.object({lowerSeconds:z2.number().int().nullable().optional(),upperSeconds:z2.number().int().nullable().optional(),elapsedSeconds:z2.number().int().nullable().optional(),sampleCount:z2.number().int().nullable().optional(),source:z2.string().nullable().optional()}).nullable().optional();var targetResolutionIdentitySchema=z2.object({kind:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),commitSha:z2.string().nullable().optional(),site:z2.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z2.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z2.string().nullable().optional(),freshnessReason:z2.string().nullable().optional(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),availableRefs:z2.array(availableVersionSchema).nullable().optional(),suggestedRefs:z2.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z2.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z2.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLocatorSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),pageId:z2.string().nullable().optional(),sourceKind:z2.string().nullable().optional(),sourceUrl:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),startLine:z2.number().int().nullable().optional(),endLine:z2.number().int().nullable().optional(),fileContentHash:z2.string().nullable().optional(),symbolRef:z2.string().nullable().optional(),qualifiedPath:z2.string().nullable().optional(),kind:z2.string().nullable().optional(),category:z2.string().nullable().optional(),language:z2.string().nullable().optional()});var unifiedSearchHitSchema=z2.object({id:z2.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z2.string(),requestedTargetLabel:z2.string().nullable().optional(),freshTargetLabel:z2.string().nullable().optional(),servedTargetLabel:z2.string().nullable().optional(),freshness:z2.string().nullable().optional(),title:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),score:z2.number().nullable().optional(),highlights:z2.object({title:z2.array(z2.tuple([z2.number().int(),z2.number().int()])).nullable().optional(),summary:z2.array(z2.tuple([z2.number().int(),z2.number().int()])).nullable().optional()}).nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z2.object({offset:z2.number().int(),limit:z2.number().int(),returned:z2.number().int(),hasMore:z2.boolean()});var docCoverageSchema=z2.object({coverageState:z2.string(),coverageReason:z2.string().nullable().optional(),pagesCrawled:z2.number().int().nullable().optional(),frontierRemaining:z2.number().int().nullable().optional(),artifactOverflowPageCount:z2.number().int().nullable().optional(),estimatedTotalPages:z2.number().int().nullable().optional(),note:z2.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z2.object({kind:z2.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z2.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z2.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z2.number().int().nonnegative(),repositoryUrl:z2.string().nullable().optional(),commitSha:z2.string().nullable().optional(),siteKey:z2.string().nullable().optional(),siteUrl:z2.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z2.object({source:unifiedSearchSourceSchema,targetLabel:z2.string(),requestedTargetLabel:z2.string().nullable().optional(),freshTargetLabel:z2.string().nullable().optional(),servedTargetLabel:z2.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z2.string().nullable().optional(),codeIndexState:z2.string().nullable().optional(),resultCount:z2.number().int().nullable().optional(),appliedFilters:z2.array(z2.string()),ignoredFilters:z2.array(z2.string()),incompatibleFilters:z2.array(z2.string()),appliedQueryFeatures:z2.array(z2.string()),ignoredQueryFeatures:z2.array(z2.string()),incompatibleQueryFeatures:z2.array(z2.string()),suggestedSiteTargets:z2.array(z2.string()),suggestedSiteTargetsTruncated:z2.boolean(),note:z2.string().nullable().optional(),coverage:docCoverageSchema,contributors:z2.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z2.object({query:z2.string(),queryWarnings:z2.array(z2.string()),sources:z2.array(unifiedSearchSourceSchema),results:z2.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z2.boolean(),sourceStatus:z2.array(unifiedSearchSourceStatusSchema),evidenceNotice:z2.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z2.string().min(1);var unifiedSearchFiltersSchema=z2.object({fileIntent:z2.string().nullable().optional(),kind:z2.string().nullable().optional(),category:z2.string().nullable().optional(),publicOnly:z2.boolean().nullable().optional(),pathPrefix:z2.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z2.object({requested:z2.string().nullable().optional(),resolvedRequested:z2.string().nullable().optional(),served:z2.string().nullable().optional(),freshness:z2.string().nullable().optional(),indexingRef:z2.string().nullable().optional(),requestedRefKind:z2.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z2.array(availableVersionSchema).nullable().optional(),availableRefs:z2.array(availableVersionSchema).nullable().optional(),suggestedRefs:z2.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string().nullable().optional(),version:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),site:z2.string().nullable().optional()});var unifiedSearchProgressSchema=z2.object({searchRef:z2.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z2.number().int(),targetsReady:z2.number().int(),elapsedMs:z2.number().int(),query:z2.string(),queryWarnings:z2.array(z2.string()),sources:z2.array(unifiedSearchSourceSchema),requestedSources:z2.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z2.string().nullable().optional(),requestedTargets:z2.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z2.number().int().nullable().optional(),offset:z2.number().int().nullable().optional(),targets:z2.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z2.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z2.object({completed:z2.boolean(),searchRef:z2.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z2.object({message:z2.string(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var codeDiffGraphQLErrorSchema=z2.object({message:z2.string(),path:z2.array(z2.union([z2.string(),z2.number().int()])).nullable().optional(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var codeDiffRegistrySchema=z2.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z2.object({registry:codeDiffRegistrySchema,name:z2.string(),repoUrl:z2.string()});var codeDiffRefResolutionSchema=z2.object({requested:z2.string(),resolvedVersion:z2.string().nullable().optional(),ref:z2.string(),commitSha:z2.string(),refKind:z2.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z2.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z2.object({filesChanged:z2.number().int(),added:z2.number().int(),deleted:z2.number().int(),modified:z2.number().int(),modeChanged:z2.number().int(),typeChanged:z2.number().int(),inventoryComplete:z2.boolean(),unprojectableFiles:z2.number().int()});var rawCodeDiffScopeSchema=z2.object({status:z2.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z2.string().nullable().optional(),toSubpath:z2.string().nullable().optional(),pathPrefix:z2.string().nullable().optional(),pathGlob:z2.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z2.object({code:z2.string(),retryable:z2.boolean(),retryAfterMs:z2.number().int().nullable().optional(),stage:z2.string().nullable().optional(),limitKind:z2.string().nullable().optional()});var contentSafetySchema=z2.object({filtered:z2.boolean(),modifications:z2.array(z2.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var rawCodeDiffFileSchema=z2.object({path:z2.string(),pathEncoding:z2.enum(["UTF8","BYTE_ESCAPED"]),status:z2.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z2.boolean(),typeChanged:z2.boolean(),additions:z2.number().int().nullable().optional(),deletions:z2.number().int().nullable().optional(),patch:z2.string().nullable().optional(),contentStatus:z2.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z2.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z2.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z2.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z2.array(rawCodeDiffFileSchema),hasMoreFiles:z2.boolean()});var codeDiffResultSchema=z2.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z2.object({data:z2.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z2.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
|
|
342
|
+
registry
|
|
343
|
+
name
|
|
344
|
+
repoUrl
|
|
345
|
+
}
|
|
346
|
+
fromResolution {
|
|
347
|
+
requested
|
|
348
|
+
resolvedVersion
|
|
349
|
+
ref
|
|
350
|
+
commitSha
|
|
351
|
+
refKind
|
|
352
|
+
versionSource
|
|
353
|
+
}
|
|
354
|
+
toResolution {
|
|
355
|
+
requested
|
|
356
|
+
resolvedVersion
|
|
357
|
+
ref
|
|
358
|
+
commitSha
|
|
359
|
+
refKind
|
|
360
|
+
versionSource
|
|
361
|
+
}
|
|
362
|
+
raw {
|
|
363
|
+
summary {
|
|
364
|
+
filesChanged
|
|
365
|
+
added
|
|
366
|
+
deleted
|
|
367
|
+
modified
|
|
368
|
+
modeChanged
|
|
369
|
+
typeChanged
|
|
370
|
+
inventoryComplete
|
|
371
|
+
unprojectableFiles
|
|
372
|
+
}
|
|
373
|
+
scope {
|
|
374
|
+
status
|
|
375
|
+
fromSubpath
|
|
376
|
+
toSubpath
|
|
377
|
+
pathPrefix
|
|
378
|
+
pathGlob
|
|
379
|
+
}
|
|
380
|
+
contentCoverage
|
|
381
|
+
contentFailure {
|
|
382
|
+
code
|
|
383
|
+
retryable
|
|
384
|
+
retryAfterMs
|
|
385
|
+
stage
|
|
386
|
+
limitKind
|
|
387
|
+
}
|
|
388
|
+
files {
|
|
389
|
+
path
|
|
390
|
+
pathEncoding
|
|
391
|
+
status
|
|
392
|
+
modeChanged
|
|
393
|
+
typeChanged
|
|
394
|
+
contentStatus
|
|
395
|
+
contentSafety {
|
|
396
|
+
filtered
|
|
397
|
+
modifications
|
|
398
|
+
}`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
|
|
399
|
+
additions
|
|
400
|
+
deletions`:`
|
|
401
|
+
additions
|
|
402
|
+
deletions
|
|
403
|
+
patch
|
|
404
|
+
contentOmissionReason`;return`
|
|
405
|
+
query CodeDiff(
|
|
406
|
+
$registry: Registry
|
|
407
|
+
$name: String
|
|
408
|
+
$fromVersion: String
|
|
409
|
+
$toVersion: String
|
|
410
|
+
$repoUrl: String
|
|
411
|
+
$fromRef: String
|
|
412
|
+
$toRef: String
|
|
413
|
+
$rawOptions: RawCodeDiffOptions
|
|
414
|
+
) {
|
|
415
|
+
codeDiff(
|
|
416
|
+
registry: $registry
|
|
417
|
+
name: $name
|
|
418
|
+
fromVersion: $fromVersion
|
|
419
|
+
toVersion: $toVersion
|
|
420
|
+
repoUrl: $repoUrl
|
|
421
|
+
fromRef: $fromRef
|
|
422
|
+
toRef: $toRef
|
|
423
|
+
rawOptions: $rawOptions
|
|
424
|
+
) {
|
|
425
|
+
${CODE_DIFF_COMMON_SELECTION}${contentFields}
|
|
426
|
+
}
|
|
427
|
+
hasMoreFiles
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}`}var navigationResolutionSchema=z2.object({requestedVersion:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),resolvedRef:z2.string().nullable().optional(),commitSha:z2.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z2.object({hint:z2.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z2.object({path:z2.string(),name:z2.string().nullable().optional(),language:z2.string().nullable().optional(),fileType:z2.string().nullable().optional(),byteSize:z2.number().int().nullable().optional()});var listRepoFilesResponseSchema=z2.object({files:z2.array(repoFileEntrySchema),total:z2.number().int(),hasMore:z2.boolean(),indexedVersion:z2.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z2.string(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var listRepoFilesGraphQLResponseSchema=z2.object({data:z2.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
|
|
431
|
+
query ListRepoFiles(
|
|
432
|
+
$registry: Registry
|
|
433
|
+
$packageName: String
|
|
434
|
+
$repoUrl: String
|
|
435
|
+
$gitRef: String
|
|
436
|
+
$version: String
|
|
437
|
+
$pathPrefix: String
|
|
438
|
+
$pathSelectors: [FilePathSelectorInput!]
|
|
439
|
+
$extensions: [String!]
|
|
440
|
+
$fileTypes: [String!]
|
|
441
|
+
$languages: [String!]
|
|
442
|
+
$fileIntent: FileIntent
|
|
443
|
+
$fileIntents: [FileIntent!]
|
|
444
|
+
$excludeFileIntents: [FileIntent!]
|
|
445
|
+
$excludeDocFiles: Boolean
|
|
446
|
+
$excludeTestFiles: Boolean
|
|
447
|
+
$includeHidden: Boolean
|
|
448
|
+
$limit: Int
|
|
449
|
+
$waitTimeoutMs: Int
|
|
450
|
+
) {
|
|
451
|
+
listRepoFiles(
|
|
452
|
+
registry: $registry
|
|
453
|
+
packageName: $packageName
|
|
454
|
+
repoUrl: $repoUrl
|
|
455
|
+
gitRef: $gitRef
|
|
456
|
+
version: $version
|
|
457
|
+
pathPrefix: $pathPrefix
|
|
458
|
+
pathSelectors: $pathSelectors
|
|
459
|
+
extensions: $extensions
|
|
460
|
+
fileTypes: $fileTypes
|
|
461
|
+
languages: $languages
|
|
462
|
+
fileIntent: $fileIntent
|
|
463
|
+
fileIntents: $fileIntents
|
|
464
|
+
excludeFileIntents: $excludeFileIntents
|
|
465
|
+
excludeDocFiles: $excludeDocFiles
|
|
466
|
+
excludeTestFiles: $excludeTestFiles
|
|
467
|
+
includeHidden: $includeHidden
|
|
468
|
+
limit: $limit
|
|
469
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
470
|
+
) {
|
|
471
|
+
files {
|
|
472
|
+
path
|
|
473
|
+
name
|
|
474
|
+
language
|
|
475
|
+
fileType
|
|
476
|
+
byteSize
|
|
477
|
+
}
|
|
478
|
+
total
|
|
479
|
+
hasMore
|
|
480
|
+
indexedVersion
|
|
481
|
+
resolution {
|
|
482
|
+
requestedVersion
|
|
483
|
+
requestedRef
|
|
484
|
+
resolvedRef
|
|
485
|
+
commitSha
|
|
486
|
+
}
|
|
487
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
488
|
+
diagnostics {
|
|
489
|
+
hint
|
|
490
|
+
}
|
|
491
|
+
codeIndexState
|
|
492
|
+
indexingRef
|
|
493
|
+
availableVersions {
|
|
494
|
+
version
|
|
495
|
+
ref
|
|
496
|
+
}
|
|
497
|
+
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
498
|
+
}
|
|
499
|
+
}`;var codeContextResponseSchema=z2.object({content:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),language:z2.string().nullable().optional(),totalLines:z2.number().int().nullable().optional(),startLine:z2.number().int().nullable().optional(),endLine:z2.number().int().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),isBinary:z2.boolean().nullable().optional(),codeIndexState:z2.string(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z2.object({data:z2.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
|
|
500
|
+
query FetchCodeContext(
|
|
501
|
+
$registry: Registry
|
|
502
|
+
$packageName: String
|
|
503
|
+
$repoUrl: String
|
|
504
|
+
$gitRef: String
|
|
505
|
+
$version: String
|
|
506
|
+
$filePath: String!
|
|
507
|
+
$startLine: Int
|
|
508
|
+
$endLine: Int
|
|
509
|
+
$waitTimeoutMs: Int
|
|
510
|
+
) {
|
|
511
|
+
fetchCodeContext(
|
|
512
|
+
registry: $registry
|
|
513
|
+
packageName: $packageName
|
|
514
|
+
repoUrl: $repoUrl
|
|
515
|
+
gitRef: $gitRef
|
|
516
|
+
version: $version
|
|
517
|
+
filePath: $filePath
|
|
518
|
+
startLine: $startLine
|
|
519
|
+
endLine: $endLine
|
|
520
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
521
|
+
) {
|
|
522
|
+
content
|
|
523
|
+
filePath
|
|
524
|
+
language
|
|
525
|
+
totalLines
|
|
526
|
+
startLine
|
|
527
|
+
endLine
|
|
528
|
+
repoUrl
|
|
529
|
+
gitRef
|
|
530
|
+
isBinary
|
|
531
|
+
codeIndexState
|
|
532
|
+
indexingRef
|
|
533
|
+
${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
|
|
534
|
+
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
535
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
536
|
+
}
|
|
537
|
+
}`;var grepRepoMatchSchema=z2.object({filePath:z2.string(),line:z2.number().int(),matchStartByte:z2.number().int(),matchEndByte:z2.number().int(),lineContent:z2.string(),contextBefore:z2.array(z2.string()).nullable().optional(),contextAfter:z2.array(z2.string()).nullable().optional(),fileContentHash:z2.string().nullable().optional(),fileIntent:z2.string().nullable().optional(),symbolRowId:z2.string().nullable().optional(),symbol:z2.object({symbolRef:z2.string().optional(),name:z2.string().optional(),qualifiedPath:z2.string().nullable().optional(),kind:z2.string().nullable().optional(),category:z2.string().nullable().optional(),arity:z2.number().int().nullable().optional(),isPublic:z2.boolean().nullable().optional(),filePath:z2.string().nullable().optional(),startLine:z2.number().int().nullable().optional(),endLine:z2.number().int().nullable().optional(),code:z2.string().nullable().optional(),callerCount:z2.number().int().nullable().optional(),contentHash:z2.string().nullable().optional(),parentSymbolRef:z2.string().nullable().optional(),parentPath:z2.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z2.object({matches:z2.array(grepRepoMatchSchema),nextCursor:z2.string().nullable().optional(),hasMore:z2.boolean(),truncatedReason:z2.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z2.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z2.number().int(),filesInScope:z2.number().int(),binaryFilesSkipped:z2.number().int(),filesTooLargeSkipped:z2.number().int(),totalMatches:z2.number().int(),uniqueFilesMatched:z2.number().int(),indexedVersion:z2.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z2.string(),indexingRef:z2.string().nullable().optional(),availableVersions:z2.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema});var grepRepoGraphQLResponseSchema=z2.object({data:z2.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.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",code:"code",caller_count:"callerCount",content_hash:"contentHash",parent_symbol_ref:"parentSymbolRef",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(`
|
|
538
|
+
`);const symbolBlock=symbolSelection.length>0?`
|
|
539
|
+
symbol {
|
|
540
|
+
${symbolSelection}
|
|
541
|
+
}`:"";return`
|
|
542
|
+
query GrepRepo(
|
|
543
|
+
$registry: Registry
|
|
544
|
+
$packageName: String
|
|
545
|
+
$repoUrl: String
|
|
546
|
+
$gitRef: String
|
|
547
|
+
$version: String
|
|
548
|
+
$waitTimeoutMs: Int
|
|
549
|
+
$pattern: String!
|
|
550
|
+
$patternType: GrepPatternType
|
|
551
|
+
$caseSensitive: Boolean
|
|
552
|
+
$pathSelectors: [GrepPathSelectorInput!]
|
|
553
|
+
$extensions: [String!]
|
|
554
|
+
$excludeDocFiles: Boolean
|
|
555
|
+
$excludeTestFiles: Boolean
|
|
556
|
+
$allowUnscoped: Boolean
|
|
557
|
+
$contextLinesBefore: Int
|
|
558
|
+
$contextLinesAfter: Int
|
|
559
|
+
$maxMatches: Int
|
|
560
|
+
$maxMatchesPerFile: Int
|
|
561
|
+
$cursor: String
|
|
562
|
+
$symbolFields: [String!]
|
|
563
|
+
) {
|
|
564
|
+
grepRepo(
|
|
565
|
+
registry: $registry
|
|
566
|
+
packageName: $packageName
|
|
567
|
+
repoUrl: $repoUrl
|
|
568
|
+
gitRef: $gitRef
|
|
569
|
+
version: $version
|
|
570
|
+
waitTimeoutMs: $waitTimeoutMs
|
|
571
|
+
pattern: $pattern
|
|
572
|
+
patternType: $patternType
|
|
573
|
+
caseSensitive: $caseSensitive
|
|
574
|
+
pathSelectors: $pathSelectors
|
|
575
|
+
extensions: $extensions
|
|
576
|
+
excludeDocFiles: $excludeDocFiles
|
|
577
|
+
excludeTestFiles: $excludeTestFiles
|
|
578
|
+
allowUnscoped: $allowUnscoped
|
|
579
|
+
contextLinesBefore: $contextLinesBefore
|
|
580
|
+
contextLinesAfter: $contextLinesAfter
|
|
581
|
+
maxMatches: $maxMatches
|
|
582
|
+
maxMatchesPerFile: $maxMatchesPerFile
|
|
583
|
+
cursor: $cursor
|
|
584
|
+
symbolFields: $symbolFields
|
|
585
|
+
) {
|
|
586
|
+
matches {
|
|
587
|
+
filePath
|
|
588
|
+
line
|
|
589
|
+
matchStartByte
|
|
590
|
+
matchEndByte
|
|
591
|
+
lineContent
|
|
592
|
+
contextBefore
|
|
593
|
+
contextAfter
|
|
594
|
+
fileContentHash
|
|
595
|
+
fileIntent
|
|
596
|
+
symbolRowId${symbolBlock}
|
|
597
|
+
}
|
|
598
|
+
nextCursor
|
|
599
|
+
totalMatches
|
|
600
|
+
hasMore
|
|
601
|
+
truncatedReason
|
|
602
|
+
routeTaken
|
|
603
|
+
filesScanned
|
|
604
|
+
filesInScope
|
|
605
|
+
binaryFilesSkipped
|
|
606
|
+
filesTooLargeSkipped
|
|
607
|
+
uniqueFilesMatched
|
|
608
|
+
indexedVersion
|
|
609
|
+
resolution {
|
|
610
|
+
requestedVersion
|
|
611
|
+
requestedRef
|
|
612
|
+
resolvedRef
|
|
613
|
+
commitSha
|
|
614
|
+
}
|
|
615
|
+
${TARGET_RESOLUTION_SELECTION}
|
|
616
|
+
codeIndexState
|
|
617
|
+
indexingRef
|
|
618
|
+
availableVersions {
|
|
619
|
+
version
|
|
620
|
+
ref
|
|
621
|
+
}
|
|
622
|
+
${INDEXING_DURATION_ESTIMATE_SELECTION}
|
|
623
|
+
}
|
|
624
|
+
}`}var unifiedSearchGraphQLResponseSchema=z2.object({data:z2.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z2.object({data:z2.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z2.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:message2,extensions:extensions2})=>({message:message2,extensions:extensions2}));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:{registry:entry.locator.registry??undefined,packageName:entry.locator.packageName??undefined,version:entry.locator.version??undefined,pageId:entry.locator.pageId??undefined,sourceKind:entry.locator.sourceKind??undefined,sourceUrl:entry.locator.sourceUrl??undefined,repoUrl:entry.locator.repoUrl??undefined,gitRef:entry.locator.gitRef??undefined,requestedRef:entry.locator.requestedRef??undefined,filePath:entry.locator.filePath??undefined,startLine:entry.locator.startLine??undefined,endLine:entry.locator.endLine??undefined,fileContentHash:entry.locator.fileContentHash??undefined,symbolRef:entry.locator.symbolRef??undefined,qualifiedPath:entry.locator.qualifiedPath??undefined,kind:entry.locator.kind??undefined,category:entry.locator.category??undefined,language:entry.locator.language??undefined}})),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,code:entry.symbol.code??undefined,callerCount:entry.symbol.callerCount??undefined,contentHash:entry.symbol.contentHash??undefined,parentSymbolRef:entry.symbol.parentSymbolRef??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 validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&¶msRecord.mode!=="stats"&¶msRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}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 z3}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=z3.object({stargazersCount:z3.number().int().nullable().optional(),forksCount:z3.number().int().nullable().optional(),openIssuesCount:z3.number().int().nullable().optional(),archived:z3.boolean().nullable().optional(),language:z3.string().nullable().optional(),topics:z3.array(z3.string()).nullable().optional(),pushedAt:z3.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),description:z3.string().nullable().optional(),latestVersion:z3.string().nullable().optional(),latestVersionPublishedAt:z3.string().nullable().optional(),homepage:z3.string().nullable().optional(),repositoryUrl:z3.string().nullable().optional(),license:z3.string().nullable().optional(),downloadsLastMonth:z3.number().int().nullable().optional(),downloadsTotal:z3.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z3.object({osvId:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),publishedAt:z3.string().nullable().optional()});var packageSecurityOverviewSchema=z3.object({vulnerabilityCount:z3.number().int().nullable().optional(),hasCurrentVulnerabilities:z3.boolean().nullable().optional(),recentVulnerabilities:z3.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z3.object({version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),body:z3.string().nullable().optional()});var packageSummaryResponseSchema=z3.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z3.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z3.object({message:z3.string(),extensions:z3.record(z3.string(),z3.unknown()).optional()});var graphQLResponseSchema=z3.object({data:z3.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
|
|
625
|
+
query PackageSummary(
|
|
626
|
+
$registry: Registry!
|
|
627
|
+
$name: String!
|
|
628
|
+
$includeVerboseFields: Boolean! = true
|
|
629
|
+
) {
|
|
630
|
+
packageSummary(registry: $registry, name: $name) {
|
|
631
|
+
package {
|
|
632
|
+
name
|
|
633
|
+
registry
|
|
634
|
+
description
|
|
635
|
+
latestVersion
|
|
636
|
+
latestVersionPublishedAt
|
|
637
|
+
homepage
|
|
638
|
+
repositoryUrl
|
|
639
|
+
license
|
|
640
|
+
downloadsLastMonth
|
|
641
|
+
downloadsTotal
|
|
642
|
+
githubRepository {
|
|
643
|
+
stargazersCount
|
|
644
|
+
forksCount
|
|
645
|
+
openIssuesCount
|
|
646
|
+
archived
|
|
647
|
+
language @include(if: $includeVerboseFields)
|
|
648
|
+
topics @include(if: $includeVerboseFields)
|
|
649
|
+
pushedAt @include(if: $includeVerboseFields)
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
security {
|
|
653
|
+
vulnerabilityCount
|
|
654
|
+
hasCurrentVulnerabilities
|
|
655
|
+
recentVulnerabilities @include(if: $includeVerboseFields) {
|
|
656
|
+
osvId
|
|
657
|
+
summary
|
|
658
|
+
severityScore
|
|
659
|
+
publishedAt
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
|
|
663
|
+
version
|
|
664
|
+
publishedAt
|
|
665
|
+
body
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}`;var packageVersionIdentitySchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),deprecated:z3.boolean().nullable().optional(),deprecationReason:z3.string().nullable().optional()});var vulnerabilityDetailSchema=z3.object({osvId:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),severityType:z3.string().nullable().optional(),affectedVersionRanges:z3.array(z3.string()).nullable().optional(),affectedVersionRangesCount:z3.number().int(),affectedVersionRangesTruncated:z3.boolean(),fixedInVersions:z3.array(z3.string()).nullable().optional(),publishedAt:z3.string().nullable().optional(),modifiedAt:z3.string().nullable().optional(),withdrawnAt:z3.string().nullable().optional(),aliases:z3.array(z3.string()).nullable().optional(),isMalicious:z3.boolean().nullable().optional(),affectsInspectedVersion:z3.boolean(),matchedAffectedVersionRanges:z3.array(z3.string()),duplicateIds:z3.array(z3.string())});var pageInfoSchema=z3.object({hasNextPage:z3.boolean(),endCursor:z3.string().nullable().optional(),totalCount:z3.number().int()});var vulnerabilityAdvisoryPageSchema=z3.object({entries:z3.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z3.object({affectedVulnerabilityCount:z3.number().int(),nonAffectingVulnerabilityCount:z3.number().int(),allVulnerabilityCount:z3.number().int(),currentVersionAffected:z3.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z3.array(z3.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z3.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z3.object({data:z3.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
|
|
669
|
+
query PackageVulnerabilities(
|
|
670
|
+
$registry: Registry!
|
|
671
|
+
$name: String!
|
|
672
|
+
$version: String
|
|
673
|
+
$minSeverity: Float
|
|
674
|
+
$includeWithdrawn: Boolean
|
|
675
|
+
$scope: VulnerabilityScope = AFFECTED
|
|
676
|
+
$after: String
|
|
677
|
+
) {
|
|
678
|
+
packageVulnerabilities(
|
|
679
|
+
registry: $registry
|
|
680
|
+
name: $name
|
|
681
|
+
version: $version
|
|
682
|
+
minSeverity: $minSeverity
|
|
683
|
+
includeWithdrawn: $includeWithdrawn
|
|
684
|
+
) {
|
|
685
|
+
package {
|
|
686
|
+
name
|
|
687
|
+
registry
|
|
688
|
+
version
|
|
689
|
+
}
|
|
690
|
+
security {
|
|
691
|
+
affectedVulnerabilityCount
|
|
692
|
+
nonAffectingVulnerabilityCount
|
|
693
|
+
allVulnerabilityCount
|
|
694
|
+
currentVersionAffected
|
|
695
|
+
upgradePaths
|
|
696
|
+
advisories(scope: $scope, first: 100, after: $after) {
|
|
697
|
+
entries {
|
|
698
|
+
osvId
|
|
699
|
+
summary
|
|
700
|
+
severityScore
|
|
701
|
+
severityType
|
|
702
|
+
affectedVersionRanges
|
|
703
|
+
affectedVersionRangesCount
|
|
704
|
+
affectedVersionRangesTruncated
|
|
705
|
+
fixedInVersions
|
|
706
|
+
publishedAt
|
|
707
|
+
modifiedAt
|
|
708
|
+
withdrawnAt
|
|
709
|
+
aliases
|
|
710
|
+
isMalicious
|
|
711
|
+
affectsInspectedVersion
|
|
712
|
+
matchedAffectedVersionRanges
|
|
713
|
+
duplicateIds
|
|
714
|
+
}
|
|
715
|
+
pageInfo {
|
|
716
|
+
hasNextPage
|
|
717
|
+
endCursor
|
|
718
|
+
totalCount
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}`;var directDependencySchema=z3.object({name:z3.string().nullable().optional(),versionConstraint:z3.string().nullable().optional(),type:z3.string().nullable().optional()});var dependencyGraphNodeSchema=z3.object({registry:z3.string(),name:z3.string(),version:z3.string().nullable().optional()});var dependencyGraphEdgeSchema=z3.object({fromIndex:z3.number().int().nullable().optional(),toIndex:z3.number().int(),constraint:z3.string().nullable().optional(),dependencyType:z3.string().nullable().optional()});var dependencyGraphSchema=z3.object({formatVersion:z3.number().int(),nodes:z3.array(dependencyGraphNodeSchema),edges:z3.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z3.object({totalVulnerabilities:z3.number().int(),critical:z3.number().int(),high:z3.number().int(),medium:z3.number().int(),low:z3.number().int(),unknown:z3.number().int()});var vulnerabilitySummaryDetailSchema=z3.object({osvId:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),summary:z3.string().nullable().optional(),severityScore:z3.number().nullable().optional(),severityType:z3.string().nullable().optional(),affectedVersionRanges:z3.array(z3.string()).nullable().optional(),fixedInVersions:z3.array(z3.string()).nullable().optional(),publishedAt:z3.string().nullable().optional(),modifiedAt:z3.string().nullable().optional(),withdrawnAt:z3.string().nullable().optional(),aliases:z3.array(z3.string()).nullable().optional(),isMalicious:z3.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z3.object({version:z3.string(),affectsResolvedVersion:z3.boolean(),matchedAffectedVersionRanges:z3.array(z3.string()),fixVersionsAboveResolved:z3.array(z3.string()),nearestFixedVersion:z3.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z3.object({registry:z3.string(),name:z3.string(),versions:z3.array(z3.string()),affectedCount:z3.number().int(),nonAffectingCount:z3.number().int(),totalCount:z3.number().int(),maxSeverityScore:z3.number().nullable().optional(),maxSeverityLabel:z3.string().nullable().optional(),advisoryIds:z3.array(z3.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z3.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z3.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z3.number().int(),affectedPackageCount:z3.number().int(),packages:z3.array(transitiveVulnerablePackageSchema),calculatedAt:z3.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z3.object({version:z3.string(),reason:z3.string().nullable().optional()});var deprecatedDependencySchema=z3.object({registry:z3.string(),name:z3.string(),versions:z3.array(z3.string()),reasons:z3.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z3.object({version:z3.string(),severity:z3.string()});var outdatedDependencySchema=z3.object({registry:z3.string(),name:z3.string(),latestVersion:z3.string().nullable().optional(),severity:z3.string(),versions:z3.array(outdatedDependencyVersionSchema),repositoryUrl:z3.string().nullable().optional()});var duplicateDependencySchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string(),versions:z3.array(z3.string())});var dependencyConflictEdgeSchema=z3.object({fromIndex:z3.number().int().nullable().optional(),toIndex:z3.number().int(),versionConstraint:z3.string(),dependencyType:z3.string()});var dependencyConflictSchema=z3.object({packageName:z3.string(),requiredVersions:z3.array(z3.string()),conflictingEdges:z3.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z3.object({registry:z3.string().nullable().optional(),name:z3.string(),versions:z3.array(z3.string()),requiredVersions:z3.array(z3.string()),conflictingEdges:z3.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z3.object({totalCount:z3.number().int(),deprecatedCount:z3.number().int(),outdatedCount:z3.number().int(),duplicateCount:z3.number().int(),conflictCount:z3.number().int(),deprecatedPackages:z3.array(deprecatedDependencySchema),outdatedPackages:z3.array(outdatedDependencySchema),duplicatePackages:z3.array(duplicateDependencySchema),conflicts:z3.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z3.object({cycleStart:z3.string(),circularPath:z3.array(z3.string()),displayChain:z3.string()});var environmentMarkerSchema=z3.object({type:z3.string().nullable().optional(),value:z3.string().nullable().optional(),raw:z3.string().nullable().optional()});var transitiveDependencySchema=z3.object({totalEdges:z3.number().int().nullable().optional(),uniquePackagesCount:z3.number().int().nullable().optional(),uniqueDependencies:z3.array(z3.string()).nullable().optional(),dependencyConflicts:z3.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z3.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z3.object({direct:z3.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z3.object({name:z3.string(),constraint:z3.string().nullable().optional()});var dependencyGroupSchema=z3.object({name:z3.string(),lifecycle:z3.string(),conditionType:z3.string(),conditionValue:z3.string().nullable().optional(),selectionMode:z3.string(),exclusiveGroup:z3.string().nullable().optional(),fallbackPriority:z3.number().int().nullable().optional(),compatibleWith:z3.array(z3.string()).nullable().optional(),defaultEnabled:z3.boolean().nullable().optional(),dependencies:z3.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z3.object({primaryGroup:z3.string().nullable().optional(),environmentMarkers:z3.array(environmentMarkerSchema).nullable().optional(),groups:z3.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z3.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z3.object({data:z3.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
|
|
724
|
+
query PackageDependencies(
|
|
725
|
+
$registry: Registry!
|
|
726
|
+
$name: String!
|
|
727
|
+
$version: String
|
|
728
|
+
$includeTransitive: Boolean
|
|
729
|
+
$includeTransitiveDetails: Boolean! = true
|
|
730
|
+
$includeDependencyGraph: Boolean! = true
|
|
731
|
+
$includeGroups: Boolean! = true
|
|
732
|
+
$maxDepth: Int
|
|
733
|
+
$lifecycle: [String!]
|
|
734
|
+
) {
|
|
735
|
+
packageDependencies(
|
|
736
|
+
registry: $registry
|
|
737
|
+
name: $name
|
|
738
|
+
version: $version
|
|
739
|
+
includeTransitive: $includeTransitive
|
|
740
|
+
maxDepth: $maxDepth
|
|
741
|
+
lifecycle: $lifecycle
|
|
742
|
+
) {
|
|
743
|
+
package {
|
|
744
|
+
name
|
|
745
|
+
registry
|
|
746
|
+
version
|
|
747
|
+
}
|
|
748
|
+
dependencies {
|
|
749
|
+
# Backend-side summary block intentionally not selected — our
|
|
750
|
+
# envelope computes runtime.count client-side from direct[].length
|
|
751
|
+
# so the invariant runtime.count === runtime.items.length always
|
|
752
|
+
# holds regardless of backend-side drift.
|
|
753
|
+
direct {
|
|
754
|
+
name
|
|
755
|
+
versionConstraint
|
|
756
|
+
type
|
|
757
|
+
}
|
|
758
|
+
transitive {
|
|
759
|
+
totalEdges @include(if: $includeTransitiveDetails)
|
|
760
|
+
uniquePackagesCount @include(if: $includeTransitiveDetails)
|
|
761
|
+
uniqueDependencies @include(if: $includeTransitiveDetails)
|
|
762
|
+
dependencyConflicts @include(if: $includeTransitiveDetails) {
|
|
763
|
+
packageName
|
|
764
|
+
requiredVersions
|
|
765
|
+
conflictingEdges {
|
|
766
|
+
fromIndex
|
|
767
|
+
toIndex
|
|
768
|
+
versionConstraint
|
|
769
|
+
dependencyType
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
circularDependencyCycles @include(if: $includeTransitiveDetails) {
|
|
773
|
+
cycleStart
|
|
774
|
+
circularPath
|
|
775
|
+
displayChain
|
|
776
|
+
}
|
|
777
|
+
dependencyGraph @include(if: $includeDependencyGraph) {
|
|
778
|
+
formatVersion
|
|
779
|
+
nodes {
|
|
780
|
+
registry
|
|
781
|
+
name
|
|
782
|
+
version
|
|
783
|
+
}
|
|
784
|
+
edges {
|
|
785
|
+
fromIndex
|
|
786
|
+
toIndex
|
|
787
|
+
constraint
|
|
788
|
+
dependencyType
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
dependencyGroups @include(if: $includeGroups) {
|
|
794
|
+
primaryGroup
|
|
795
|
+
environmentMarkers {
|
|
796
|
+
type
|
|
797
|
+
value
|
|
798
|
+
raw
|
|
799
|
+
}
|
|
800
|
+
groups {
|
|
801
|
+
name
|
|
802
|
+
lifecycle
|
|
803
|
+
conditionType
|
|
804
|
+
conditionValue
|
|
805
|
+
selectionMode
|
|
806
|
+
exclusiveGroup
|
|
807
|
+
fallbackPriority
|
|
808
|
+
compatibleWith
|
|
809
|
+
defaultEnabled
|
|
810
|
+
dependencies {
|
|
811
|
+
name
|
|
812
|
+
constraint
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
|
|
818
|
+
query PackageUpgradeDependencyProbe(
|
|
819
|
+
$registry: Registry!
|
|
820
|
+
$name: String!
|
|
821
|
+
$version: String!
|
|
822
|
+
$includeTransitiveRisk: Boolean!
|
|
823
|
+
$includeTransitiveSecurity: Boolean!
|
|
824
|
+
$includeDependencyIssues: Boolean!
|
|
825
|
+
$includeDependencyChanges: Boolean!
|
|
826
|
+
$includeGroups: Boolean!
|
|
827
|
+
$lifecycle: [String!]
|
|
828
|
+
$minSeverity: Float
|
|
829
|
+
) {
|
|
830
|
+
packageDependencies(
|
|
831
|
+
registry: $registry
|
|
832
|
+
name: $name
|
|
833
|
+
version: $version
|
|
834
|
+
includeTransitive: $includeTransitiveRisk
|
|
835
|
+
lifecycle: $lifecycle
|
|
836
|
+
) {
|
|
837
|
+
package {
|
|
838
|
+
name
|
|
839
|
+
registry
|
|
840
|
+
version
|
|
841
|
+
publishedAt
|
|
842
|
+
deprecated
|
|
843
|
+
deprecationReason
|
|
844
|
+
}
|
|
845
|
+
dependencies {
|
|
846
|
+
direct {
|
|
847
|
+
name
|
|
848
|
+
versionConstraint
|
|
849
|
+
type
|
|
850
|
+
}
|
|
851
|
+
transitive @include(if: $includeTransitiveRisk) {
|
|
852
|
+
dependencyGraph @include(if: $includeDependencyChanges) {
|
|
853
|
+
formatVersion
|
|
854
|
+
nodes {
|
|
855
|
+
registry
|
|
856
|
+
name
|
|
857
|
+
version
|
|
858
|
+
}
|
|
859
|
+
edges {
|
|
860
|
+
fromIndex
|
|
861
|
+
toIndex
|
|
862
|
+
constraint
|
|
863
|
+
dependencyType
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
|
|
867
|
+
affected {
|
|
868
|
+
totalVulnerabilities
|
|
869
|
+
critical
|
|
870
|
+
high
|
|
871
|
+
medium
|
|
872
|
+
low
|
|
873
|
+
unknown
|
|
874
|
+
}
|
|
875
|
+
nonAffecting {
|
|
876
|
+
totalVulnerabilities
|
|
877
|
+
critical
|
|
878
|
+
high
|
|
879
|
+
medium
|
|
880
|
+
low
|
|
881
|
+
unknown
|
|
882
|
+
}
|
|
883
|
+
combined {
|
|
884
|
+
totalVulnerabilities
|
|
885
|
+
critical
|
|
886
|
+
high
|
|
887
|
+
medium
|
|
888
|
+
low
|
|
889
|
+
unknown
|
|
890
|
+
}
|
|
891
|
+
totalPackagesAnalyzed
|
|
892
|
+
affectedPackageCount
|
|
893
|
+
calculatedAt
|
|
894
|
+
packages {
|
|
895
|
+
registry
|
|
896
|
+
name
|
|
897
|
+
versions
|
|
898
|
+
affectedCount
|
|
899
|
+
nonAffectingCount
|
|
900
|
+
totalCount
|
|
901
|
+
maxSeverityScore
|
|
902
|
+
maxSeverityLabel
|
|
903
|
+
advisoryIds(scope: AFFECTED)
|
|
904
|
+
mostCritical {
|
|
905
|
+
osvId
|
|
906
|
+
registry
|
|
907
|
+
packageName
|
|
908
|
+
summary
|
|
909
|
+
severityScore
|
|
910
|
+
severityType
|
|
911
|
+
affectedVersionRanges
|
|
912
|
+
fixedInVersions
|
|
913
|
+
publishedAt
|
|
914
|
+
modifiedAt
|
|
915
|
+
withdrawnAt
|
|
916
|
+
aliases
|
|
917
|
+
isMalicious
|
|
918
|
+
}
|
|
919
|
+
advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
|
|
920
|
+
version
|
|
921
|
+
affectsResolvedVersion
|
|
922
|
+
matchedAffectedVersionRanges
|
|
923
|
+
fixVersionsAboveResolved
|
|
924
|
+
nearestFixedVersion
|
|
925
|
+
advisory {
|
|
926
|
+
osvId
|
|
927
|
+
registry
|
|
928
|
+
packageName
|
|
929
|
+
summary
|
|
930
|
+
severityScore
|
|
931
|
+
severityType
|
|
932
|
+
affectedVersionRanges
|
|
933
|
+
fixedInVersions
|
|
934
|
+
publishedAt
|
|
935
|
+
modifiedAt
|
|
936
|
+
withdrawnAt
|
|
937
|
+
aliases
|
|
938
|
+
isMalicious
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
dependencyIssues @include(if: $includeDependencyIssues) {
|
|
944
|
+
totalCount
|
|
945
|
+
deprecatedCount
|
|
946
|
+
outdatedCount
|
|
947
|
+
duplicateCount
|
|
948
|
+
conflictCount
|
|
949
|
+
deprecatedPackages {
|
|
950
|
+
registry
|
|
951
|
+
name
|
|
952
|
+
versions
|
|
953
|
+
reasons {
|
|
954
|
+
version
|
|
955
|
+
reason
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
outdatedPackages {
|
|
959
|
+
registry
|
|
960
|
+
name
|
|
961
|
+
latestVersion
|
|
962
|
+
severity
|
|
963
|
+
versions {
|
|
964
|
+
version
|
|
965
|
+
severity
|
|
966
|
+
}
|
|
967
|
+
repositoryUrl
|
|
968
|
+
}
|
|
969
|
+
duplicatePackages {
|
|
970
|
+
registry
|
|
971
|
+
name
|
|
972
|
+
versions
|
|
973
|
+
}
|
|
974
|
+
conflicts {
|
|
975
|
+
registry
|
|
976
|
+
name
|
|
977
|
+
versions
|
|
978
|
+
requiredVersions
|
|
979
|
+
conflictingEdges {
|
|
980
|
+
fromIndex
|
|
981
|
+
toIndex
|
|
982
|
+
versionConstraint
|
|
983
|
+
dependencyType
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
dependencyGroups @include(if: $includeGroups) {
|
|
990
|
+
primaryGroup
|
|
991
|
+
environmentMarkers {
|
|
992
|
+
type
|
|
993
|
+
value
|
|
994
|
+
raw
|
|
995
|
+
}
|
|
996
|
+
groups {
|
|
997
|
+
name
|
|
998
|
+
lifecycle
|
|
999
|
+
conditionType
|
|
1000
|
+
conditionValue
|
|
1001
|
+
selectionMode
|
|
1002
|
+
exclusiveGroup
|
|
1003
|
+
fallbackPriority
|
|
1004
|
+
compatibleWith
|
|
1005
|
+
defaultEnabled
|
|
1006
|
+
dependencies {
|
|
1007
|
+
name
|
|
1008
|
+
constraint
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
}`;var packageUpgradeAdvisorySchema=z3.object({id:z3.string().nullable().optional(),aliases:z3.array(z3.string()),summary:z3.string().nullable().optional(),severity:z3.number().nullable().optional(),severityLabel:z3.string().nullable().optional(),fixedIn:z3.array(z3.string()),isMalicious:z3.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z3.object({version:z3.string(),publishedAt:z3.string().nullable().optional(),deprecated:z3.boolean().nullable().optional(),deprecationReason:z3.string().nullable().optional(),affectedCount:z3.number().int(),nonAffectingCount:z3.number().int(),allCount:z3.number().int(),lastModifiedAt:z3.string().nullable().optional(),advisories:z3.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z3.object({entries:z3.array(z3.object({id:z3.string(),registry:z3.string(),name:z3.string(),versions:z3.array(z3.string()),affectedCount:z3.number().int(),maxSeverityScore:z3.number().nullable().optional(),maxSeverityLabel:z3.string().nullable().optional(),advisoryIds:z3.array(z3.string())})),totalCount:z3.number().int(),truncated:z3.boolean()});var packageUpgradeTransitiveSecuritySchema=z3.object({currentAffected:z3.number().int(),targetAffected:z3.number().int(),introducedPackages:z3.array(z3.string()),fixedPackages:z3.array(z3.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z3.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z3.array(packageUpgradeAdvisorySchema),removed:z3.array(packageUpgradeAdvisorySchema),notAddressed:z3.array(packageUpgradeAdvisorySchema),fixed:z3.array(packageUpgradeAdvisorySchema),introduced:z3.array(packageUpgradeAdvisorySchema),unchanged:z3.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z3.object({version:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional(),htmlUrl:z3.string().nullable().optional(),body:z3.string().nullable().optional(),bodyPreview:z3.string().nullable().optional(),headline:z3.string().nullable().optional(),signals:z3.array(z3.string())});var packageUpgradeChangelogSchema=z3.object({source:z3.string().nullable().optional(),fallback:z3.string().nullable().optional(),entries:z3.array(packageUpgradeChangelogEntrySchema),sampledEntries:z3.array(packageUpgradeChangelogEntrySchema),keywordEntries:z3.array(packageUpgradeChangelogEntrySchema),totalKeywordEntries:z3.number().int(),totalEntries:z3.number().int(),totalEntriesWithBodies:z3.number().int(),truncated:z3.boolean(),hasReleaseNoteBodies:z3.boolean(),breakingSignals:z3.array(z3.string()),migrationSignals:z3.array(z3.string())});var packageUpgradeCompatibilitySchema=z3.object({peerDependencyChanges:z3.array(z3.string()),notes:z3.array(z3.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z3.object({name:z3.string(),registry:z3.string().nullable().optional(),version:z3.string().nullable().optional(),fromVersions:z3.array(z3.string()),toVersions:z3.array(z3.string()),constraint:z3.string().nullable().optional(),type:z3.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z3.object({added:z3.array(packageUpgradeDependencyChangeItemSchema),removed:z3.array(packageUpgradeDependencyChangeItemSchema),changed:z3.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z3.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z3.object({currentTotal:z3.number().int(),targetTotal:z3.number().int(),introducedDeprecated:z3.array(z3.string()),introducedDuplicates:z3.array(z3.string()),introducedConflicts:z3.array(z3.string()),introducedOutdated:z3.array(z3.string())}).nullable().optional();var packageUpgradeReviewSchema=z3.object({registry:z3.string(),name:z3.string(),currentVersion:z3.string(),targetVersion:z3.string(),latestVersion:z3.string().nullable().optional(),versionDelta:z3.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknowns:z3.array(z3.string())});var packageUpgradeReviewResponseSchema=z3.object({summary:z3.object({total:z3.number().int(),withUnknowns:z3.number().int(),withAddedAdvisories:z3.number().int(),withBreakingSignals:z3.number().int(),withDirectDependencyChanges:z3.number().int(),withTransitiveVulnerabilityAdditions:z3.number().int()}),reviews:z3.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z3.object({data:z3.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_UPGRADE_REVIEW_QUERY=`
|
|
1014
|
+
query PackageUpgradeReview(
|
|
1015
|
+
$packages: [PackageUpgradeReviewPackageInput!]!
|
|
1016
|
+
$includeTransitiveSecurity: Boolean!
|
|
1017
|
+
$includeDependencyIssues: Boolean!
|
|
1018
|
+
$minSeverity: Float
|
|
1019
|
+
$changelogLimit: Int!
|
|
1020
|
+
) {
|
|
1021
|
+
packageUpgradeReview(
|
|
1022
|
+
packages: $packages
|
|
1023
|
+
includeTransitiveSecurity: $includeTransitiveSecurity
|
|
1024
|
+
minSeverity: $minSeverity
|
|
1025
|
+
changelogLimit: $changelogLimit
|
|
1026
|
+
) {
|
|
1027
|
+
summary {
|
|
1028
|
+
total
|
|
1029
|
+
withUnknowns
|
|
1030
|
+
withAddedAdvisories
|
|
1031
|
+
withBreakingSignals
|
|
1032
|
+
withDirectDependencyChanges
|
|
1033
|
+
withTransitiveVulnerabilityAdditions
|
|
1034
|
+
}
|
|
1035
|
+
reviews {
|
|
1036
|
+
registry
|
|
1037
|
+
name
|
|
1038
|
+
currentVersion
|
|
1039
|
+
targetVersion
|
|
1040
|
+
latestVersion
|
|
1041
|
+
versionDelta
|
|
1042
|
+
security {
|
|
1043
|
+
current {
|
|
1044
|
+
version
|
|
1045
|
+
publishedAt
|
|
1046
|
+
deprecated
|
|
1047
|
+
deprecationReason
|
|
1048
|
+
affectedCount
|
|
1049
|
+
nonAffectingCount
|
|
1050
|
+
allCount
|
|
1051
|
+
lastModifiedAt
|
|
1052
|
+
advisories {
|
|
1053
|
+
...PackageUpgradeAdvisoryFields
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
target {
|
|
1057
|
+
version
|
|
1058
|
+
publishedAt
|
|
1059
|
+
deprecated
|
|
1060
|
+
deprecationReason
|
|
1061
|
+
affectedCount
|
|
1062
|
+
nonAffectingCount
|
|
1063
|
+
allCount
|
|
1064
|
+
lastModifiedAt
|
|
1065
|
+
advisories {
|
|
1066
|
+
...PackageUpgradeAdvisoryFields
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
added {
|
|
1070
|
+
...PackageUpgradeAdvisoryFields
|
|
1071
|
+
}
|
|
1072
|
+
removed {
|
|
1073
|
+
...PackageUpgradeAdvisoryFields
|
|
1074
|
+
}
|
|
1075
|
+
notAddressed {
|
|
1076
|
+
...PackageUpgradeAdvisoryFields
|
|
1077
|
+
}
|
|
1078
|
+
fixed {
|
|
1079
|
+
...PackageUpgradeAdvisoryFields
|
|
1080
|
+
}
|
|
1081
|
+
introduced {
|
|
1082
|
+
...PackageUpgradeAdvisoryFields
|
|
1083
|
+
}
|
|
1084
|
+
unchanged {
|
|
1085
|
+
...PackageUpgradeAdvisoryFields
|
|
1086
|
+
}
|
|
1087
|
+
transitive @include(if: $includeTransitiveSecurity) {
|
|
1088
|
+
currentAffected
|
|
1089
|
+
targetAffected
|
|
1090
|
+
introducedPackages
|
|
1091
|
+
fixedPackages
|
|
1092
|
+
introducedPackageDetails(first: 50) {
|
|
1093
|
+
...PackageUpgradeTransitivePackagePageFields
|
|
1094
|
+
}
|
|
1095
|
+
fixedPackageDetails(first: 50) {
|
|
1096
|
+
...PackageUpgradeTransitivePackagePageFields
|
|
1097
|
+
}
|
|
1098
|
+
stillAffectedPackageDetails(first: 50) {
|
|
1099
|
+
...PackageUpgradeTransitivePackagePageFields
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
changelog {
|
|
1104
|
+
source
|
|
1105
|
+
fallback
|
|
1106
|
+
entries {
|
|
1107
|
+
...PackageUpgradeChangelogEntryFields
|
|
1108
|
+
}
|
|
1109
|
+
sampledEntries {
|
|
1110
|
+
...PackageUpgradeChangelogEntryFields
|
|
1111
|
+
}
|
|
1112
|
+
keywordEntries {
|
|
1113
|
+
...PackageUpgradeChangelogEntryFields
|
|
1114
|
+
}
|
|
1115
|
+
totalKeywordEntries
|
|
1116
|
+
totalEntries
|
|
1117
|
+
totalEntriesWithBodies
|
|
1118
|
+
truncated
|
|
1119
|
+
hasReleaseNoteBodies
|
|
1120
|
+
breakingSignals
|
|
1121
|
+
migrationSignals
|
|
1122
|
+
}
|
|
1123
|
+
compatibility {
|
|
1124
|
+
peerDependencyChanges
|
|
1125
|
+
notes
|
|
1126
|
+
}
|
|
1127
|
+
dependencyChanges {
|
|
1128
|
+
direct {
|
|
1129
|
+
...PackageUpgradeDependencyChangeGroupFields
|
|
1130
|
+
}
|
|
1131
|
+
transitive {
|
|
1132
|
+
...PackageUpgradeDependencyChangeGroupFields
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
dependencyIssues @include(if: $includeDependencyIssues) {
|
|
1136
|
+
currentTotal
|
|
1137
|
+
targetTotal
|
|
1138
|
+
introducedDeprecated
|
|
1139
|
+
introducedDuplicates
|
|
1140
|
+
introducedConflicts
|
|
1141
|
+
introducedOutdated
|
|
1142
|
+
}
|
|
1143
|
+
unknowns
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
|
|
1149
|
+
id
|
|
1150
|
+
aliases
|
|
1151
|
+
summary
|
|
1152
|
+
severity
|
|
1153
|
+
severityLabel
|
|
1154
|
+
fixedIn
|
|
1155
|
+
isMalicious
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
|
|
1159
|
+
entries {
|
|
1160
|
+
id
|
|
1161
|
+
registry
|
|
1162
|
+
name
|
|
1163
|
+
versions
|
|
1164
|
+
affectedCount
|
|
1165
|
+
maxSeverityScore
|
|
1166
|
+
maxSeverityLabel
|
|
1167
|
+
advisoryIds
|
|
1168
|
+
}
|
|
1169
|
+
totalCount
|
|
1170
|
+
truncated
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
|
|
1174
|
+
version
|
|
1175
|
+
publishedAt
|
|
1176
|
+
htmlUrl
|
|
1177
|
+
body
|
|
1178
|
+
bodyPreview
|
|
1179
|
+
headline
|
|
1180
|
+
signals
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
|
|
1184
|
+
added {
|
|
1185
|
+
name
|
|
1186
|
+
registry
|
|
1187
|
+
version
|
|
1188
|
+
fromVersions
|
|
1189
|
+
toVersions
|
|
1190
|
+
constraint
|
|
1191
|
+
type
|
|
1192
|
+
}
|
|
1193
|
+
removed {
|
|
1194
|
+
name
|
|
1195
|
+
registry
|
|
1196
|
+
version
|
|
1197
|
+
fromVersions
|
|
1198
|
+
toVersions
|
|
1199
|
+
constraint
|
|
1200
|
+
type
|
|
1201
|
+
}
|
|
1202
|
+
changed {
|
|
1203
|
+
name
|
|
1204
|
+
registry
|
|
1205
|
+
version
|
|
1206
|
+
fromVersions
|
|
1207
|
+
toVersions
|
|
1208
|
+
constraint
|
|
1209
|
+
type
|
|
1210
|
+
}
|
|
1211
|
+
}`;var changelogPackageInfoSchema=z3.object({name:z3.string().nullable().optional(),registry:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),fromVersion:z3.string().nullable().optional(),toVersion:z3.string().nullable().optional(),limit:z3.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z3.object({version:z3.string().nullable().optional(),normalizedVersion:z3.string().nullable().optional(),body:z3.string().nullable().optional(),htmlUrl:z3.string().nullable().optional(),publishedAt:z3.string().nullable().optional()});var changelogReportResponseSchema=z3.object({package:changelogPackageInfoSchema,source:z3.string().nullable().optional(),entries:z3.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z3.object({data:z3.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var PACKAGE_CHANGELOG_QUERY=`
|
|
1212
|
+
query PackageChangelog(
|
|
1213
|
+
$registry: Registry
|
|
1214
|
+
$name: String
|
|
1215
|
+
$repoUrl: String
|
|
1216
|
+
$gitRef: String
|
|
1217
|
+
$fromVersion: String
|
|
1218
|
+
$toVersion: String
|
|
1219
|
+
$limit: Int
|
|
1220
|
+
$includeBodies: Boolean! = true
|
|
1221
|
+
) {
|
|
1222
|
+
packageChangelog(
|
|
1223
|
+
registry: $registry
|
|
1224
|
+
name: $name
|
|
1225
|
+
repoUrl: $repoUrl
|
|
1226
|
+
gitRef: $gitRef
|
|
1227
|
+
fromVersion: $fromVersion
|
|
1228
|
+
toVersion: $toVersion
|
|
1229
|
+
limit: $limit
|
|
1230
|
+
) {
|
|
1231
|
+
package {
|
|
1232
|
+
name
|
|
1233
|
+
registry
|
|
1234
|
+
repoUrl
|
|
1235
|
+
fromVersion
|
|
1236
|
+
toVersion
|
|
1237
|
+
limit
|
|
1238
|
+
}
|
|
1239
|
+
source
|
|
1240
|
+
entries {
|
|
1241
|
+
version
|
|
1242
|
+
normalizedVersion
|
|
1243
|
+
body @include(if: $includeBodies)
|
|
1244
|
+
htmlUrl
|
|
1245
|
+
publishedAt
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}`;var packageDocSourceKindSchema=z3.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z3.object({id:z3.string().nullable().optional(),title:z3.string().nullable().optional(),slug:z3.string().nullable().optional(),order:z3.number().int().nullable().optional(),linkName:z3.string().nullable().optional(),lastUpdatedAt:z3.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z3.string().nullable().optional(),repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional()});var packageDocsPageInfoSchema=z3.object({hasNextPage:z3.boolean(),endCursor:z3.string().nullable().optional(),totalCount:z3.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),stale:z3.boolean().nullable().optional(),pages:z3.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z3.object({url:z3.string().nullable().optional(),label:z3.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z3.object({id:z3.string().nullable().optional(),title:z3.string().nullable().optional(),content:z3.string().nullable().optional(),contentFormat:z3.string().nullable().optional(),breadcrumbs:z3.array(z3.string()).nullable().optional(),linkName:z3.string().nullable().optional(),lastUpdatedAt:z3.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z3.string().nullable().optional(),gitRef:z3.string().nullable().optional(),requestedRef:z3.string().nullable().optional(),filePath:z3.string().nullable().optional(),baseUrl:z3.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z3.object({registry:z3.string().nullable().optional(),packageName:z3.string().nullable().optional(),version:z3.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z3.object({data:z3.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z3.object({data:z3.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z3.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
|
|
1249
|
+
query ListPackageDocs(
|
|
1250
|
+
$registry: Registry!
|
|
1251
|
+
$packageName: String!
|
|
1252
|
+
$version: String
|
|
1253
|
+
$limit: Int
|
|
1254
|
+
$after: String
|
|
1255
|
+
) {
|
|
1256
|
+
listPackageDocs(
|
|
1257
|
+
registry: $registry
|
|
1258
|
+
packageName: $packageName
|
|
1259
|
+
version: $version
|
|
1260
|
+
limit: $limit
|
|
1261
|
+
after: $after
|
|
1262
|
+
) {
|
|
1263
|
+
registry
|
|
1264
|
+
packageName
|
|
1265
|
+
version
|
|
1266
|
+
stale
|
|
1267
|
+
pages {
|
|
1268
|
+
id
|
|
1269
|
+
title
|
|
1270
|
+
slug
|
|
1271
|
+
order
|
|
1272
|
+
linkName
|
|
1273
|
+
lastUpdatedAt
|
|
1274
|
+
sourceKind
|
|
1275
|
+
sourceUrl
|
|
1276
|
+
repoUrl
|
|
1277
|
+
gitRef
|
|
1278
|
+
requestedRef
|
|
1279
|
+
filePath
|
|
1280
|
+
}
|
|
1281
|
+
pageInfo {
|
|
1282
|
+
hasNextPage
|
|
1283
|
+
endCursor
|
|
1284
|
+
totalCount
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
}`;var READ_PACKAGE_DOC_QUERY=`
|
|
1288
|
+
query ReadPackageDoc($pageId: String!) {
|
|
1289
|
+
getDocPage(pageId: $pageId) {
|
|
1290
|
+
registry
|
|
1291
|
+
packageName
|
|
1292
|
+
version
|
|
1293
|
+
sourceKind
|
|
1294
|
+
page {
|
|
1295
|
+
id
|
|
1296
|
+
title
|
|
1297
|
+
content
|
|
1298
|
+
contentFormat
|
|
1299
|
+
breadcrumbs
|
|
1300
|
+
linkName
|
|
1301
|
+
lastUpdatedAt
|
|
1302
|
+
sourceKind
|
|
1303
|
+
source {
|
|
1304
|
+
url
|
|
1305
|
+
label
|
|
1306
|
+
}
|
|
1307
|
+
repoUrl
|
|
1308
|
+
gitRef
|
|
1309
|
+
requestedRef
|
|
1310
|
+
filePath
|
|
1311
|
+
baseUrl
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
}`;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,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,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 version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version:version2,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.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&¶ms.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version2=data.package?.version??undefined;if(!name||!version2){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version:version2,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((version2)=>({version:version2.version,severity:version2.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,repoUrl:params.repoUrl,gitRef:params.gitRef,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&¶ms.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,repoUrl:data.package.repoUrl??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}async listPackageDocs(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,pages:data.pages?.map((page)=>({id:page.id??undefined,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"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 z4}from"zod";var latestVersionMaliciousEvidenceSchema=z4.object({advisories:z4.array(z4.object({osvId:z4.string(),classificationReasons:z4.array(z4.string())})).max(5),totalCount:z4.number().int().nonnegative(),truncated:z4.boolean()}).nullable();var listCandidateSchema=z4.object({kind:z4.string(),canonicalKey:z4.string(),confidence:z4.string(),latestVersionMaliciousStatus:z4.string(),latestVersionMaliciousEvidence:latestVersionMaliciousEvidenceSchema,description:z4.string().nullable().optional(),repositoryUrl:z4.string().nullable().optional(),stars:z4.number().int().nullable().optional(),downloadsLastMonth:z4.number().int().nullable().optional(),downloadsTotal:z4.number().int().nullable().optional(),docsAvailable:z4.boolean(),codeAvailable:z4.boolean()});var targetReferenceSchema=listCandidateSchema.pick({kind:true,canonicalKey:true,confidence:true});var detailedCandidateSchema=listCandidateSchema.extend({displayName:z4.string(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),latestVersion:z4.string().nullable().optional(),repositoryOwner:z4.string().nullable().optional(),repositoryName:z4.string().nullable().optional(),documentationUrl:z4.string().nullable().optional(),matchedAliases:z4.array(z4.string()),matchTier:z4.number().int(),score:z4.number(),reason:z4.string().nullable().optional()});var graphQLErrorSchema3=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});function responseSchema(candidateSchema){const resultSchema=z4.object({best:targetReferenceSchema.nullable(),protectedMatches:z4.array(targetReferenceSchema),candidates:z4.array(candidateSchema),ambiguous:z4.boolean(),ambiguousReason:z4.string()});return z4.object({data:z4.object({resolveTarget:resultSchema.nullable()}).nullable().optional(),errors:z4.array(graphQLErrorSchema3).optional()})}var RESOLVE_TARGET_QUERY=`
|
|
1315
|
+
query ResolveTarget(
|
|
1316
|
+
$name: String!
|
|
1317
|
+
$query: String
|
|
1318
|
+
$registries: [Registry!]
|
|
1319
|
+
$preferredKinds: [TargetResolutionKind!]
|
|
1320
|
+
$intentHints: [String!]
|
|
1321
|
+
$limit: Int!
|
|
1322
|
+
$includeDetailedFields: Boolean!
|
|
1323
|
+
) {
|
|
1324
|
+
resolveTarget(
|
|
1325
|
+
name: $name
|
|
1326
|
+
query: $query
|
|
1327
|
+
registries: $registries
|
|
1328
|
+
preferredKinds: $preferredKinds
|
|
1329
|
+
intentHints: $intentHints
|
|
1330
|
+
limit: $limit
|
|
1331
|
+
) {
|
|
1332
|
+
best {
|
|
1333
|
+
...ResolveTargetReferenceFields
|
|
1334
|
+
}
|
|
1335
|
+
protectedMatches {
|
|
1336
|
+
...ResolveTargetReferenceFields
|
|
1337
|
+
}
|
|
1338
|
+
candidates {
|
|
1339
|
+
...ResolveTargetListFields
|
|
1340
|
+
...ResolveTargetJsonFields @include(if: $includeDetailedFields)
|
|
1341
|
+
}
|
|
1342
|
+
ambiguous
|
|
1343
|
+
ambiguousReason
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
fragment ResolveTargetReferenceFields on TargetResolutionCandidate {
|
|
1348
|
+
kind
|
|
1349
|
+
canonicalKey
|
|
1350
|
+
confidence
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
fragment ResolveTargetListFields on TargetResolutionCandidate {
|
|
1354
|
+
kind
|
|
1355
|
+
canonicalKey
|
|
1356
|
+
confidence
|
|
1357
|
+
latestVersionMaliciousStatus
|
|
1358
|
+
latestVersionMaliciousEvidence {
|
|
1359
|
+
advisories {
|
|
1360
|
+
osvId
|
|
1361
|
+
classificationReasons
|
|
1362
|
+
}
|
|
1363
|
+
totalCount
|
|
1364
|
+
truncated
|
|
1365
|
+
}
|
|
1366
|
+
description
|
|
1367
|
+
repositoryUrl
|
|
1368
|
+
stars
|
|
1369
|
+
downloadsLastMonth
|
|
1370
|
+
downloadsTotal
|
|
1371
|
+
docsAvailable
|
|
1372
|
+
codeAvailable
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
fragment ResolveTargetJsonFields on TargetResolutionCandidate {
|
|
1376
|
+
displayName
|
|
1377
|
+
registry
|
|
1378
|
+
packageName
|
|
1379
|
+
latestVersion
|
|
1380
|
+
repositoryOwner
|
|
1381
|
+
repositoryName
|
|
1382
|
+
documentationUrl
|
|
1383
|
+
matchedAliases
|
|
1384
|
+
matchTier
|
|
1385
|
+
score
|
|
1386
|
+
reason
|
|
1387
|
+
}`;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(detailedCandidateSchema):responseSchema(listCandidateSchema)).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.")}return{best:result.best?normaliseReference(result.best):undefined,protectedMatches:result.protectedMatches.map(normaliseReference),candidates:result.candidates.map(normaliseCandidate),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};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 normaliseCandidate(candidate){const result={kind:candidate.kind,canonicalKey:candidate.canonicalKey,confidence:candidate.confidence,latestVersionMaliciousStatus:candidate.latestVersionMaliciousStatus,docsAvailable:candidate.docsAvailable,codeAvailable:candidate.codeAvailable};assignDefined(result,"description",candidate.description);assignDefined(result,"latestVersionMaliciousEvidence",candidate.latestVersionMaliciousEvidence);assignDefined(result,"repositoryUrl",candidate.repositoryUrl);assignDefined(result,"stars",candidate.stars);assignDefined(result,"downloadsLastMonth",candidate.downloadsLastMonth);assignDefined(result,"downloadsTotal",candidate.downloadsTotal);if("matchedAliases"in candidate){assignDefined(result,"displayName",candidate.displayName);assignDefined(result,"registry",candidate.registry);assignDefined(result,"packageName",candidate.packageName);assignDefined(result,"latestVersion",candidate.latestVersion);assignDefined(result,"repositoryOwner",candidate.repositoryOwner);assignDefined(result,"repositoryName",candidate.repositoryName);assignDefined(result,"documentationUrl",candidate.documentationUrl);assignDefined(result,"matchedAliases",candidate.matchedAliases);assignDefined(result,"matchTier",candidate.matchTier);assignDefined(result,"score",candidate.score);assignDefined(result,"reason",candidate.reason)}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 z5}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=z5.object({auth:z5.object({storage:z5.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}: ${z5.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(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return null;return stored.tokens[normalizeBaseUrl(baseUrl2)]??null}async saveTokens(baseUrl2,data){const stored=await this.loadAuthFile()??{version:1,tokens:{}};stored.tokens[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.authPath,JSON.stringify(stored,null,2),FILE_MODE)}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const stored=await this.loadAuthFile();if(!stored)return;delete stored.tokens[normalizeBaseUrl(baseUrl2)];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(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.clearTokensIfUnchanged(baseUrl2,expected)}async loadClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return null;return stored.clients[normalizeBaseUrl(baseUrl2)]??null}async clearClient(baseUrl2){const stored=await this.loadClientFile();if(!stored)return;delete stored.clients[normalizeBaseUrl(baseUrl2)];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(baseUrl2,data){const stored=await this.loadClientFile()??{version:1,clients:{}};stored.clients[normalizeBaseUrl(baseUrl2)]=data;await this.fs.ensureDir(this.configDir,DIR_MODE);await this.fs.atomicWriteFile(this.clientPath,JSON.stringify(stored,null,2),FILE_MODE)}clearActiveClient(baseUrl2){return this.clearClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}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(baseUrl2,reason){try{const stored=await this.loadFile()??{version:1,events:{}};stored.events[normalizeBaseUrl(baseUrl2)]={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(baseUrl2){const stored=await this.loadFile();if(!stored)return null;const event=stored.events[normalizeBaseUrl(baseUrl2)]??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 z6}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 body2=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body2,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=z6.object({authorization_endpoint:z6.string().min(1),token_endpoint:z6.string().min(1),registration_endpoint:z6.string().min(1)});var CLIENT_REGISTRATION_SCHEMA=z6.object({client_id:z6.string().min(1),client_secret:z6.string().min(1)});var EXPIRES_IN_SCHEMA=z6.union([z6.number(),z6.string().trim().regex(/^\d+(?:\.\d+)?$/).transform(Number)]).pipe(z6.number().positive());var TOKEN_RESPONSE_SCHEMA=z6.object({access_token:z6.string().min(1),refresh_token:z6.string().min(1),expires_in:EXPIRES_IN_SCHEMA.optional()});var REFRESH_TOKEN_RESPONSE_SCHEMA=z6.object({access_token:z6.string().min(1),refresh_token:z6.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>
|
|
1388
|
+
<html><head>
|
|
1389
|
+
<title>GitHits CLI</title>
|
|
1390
|
+
<meta charset="utf-8">
|
|
1391
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1392
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
1393
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
1394
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
|
|
1395
|
+
<style>
|
|
1396
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
1397
|
+
body {
|
|
1398
|
+
margin: 0;
|
|
1399
|
+
min-height: 100vh;
|
|
1400
|
+
width: 100%;
|
|
1401
|
+
padding: 16px;
|
|
1402
|
+
background: #21262d;
|
|
1403
|
+
color: #ffffff;
|
|
1404
|
+
font-family: 'Inter', sans-serif;
|
|
1405
|
+
display: flex;
|
|
1406
|
+
align-items: center;
|
|
1407
|
+
justify-content: center;
|
|
1408
|
+
}
|
|
1409
|
+
.content {
|
|
1410
|
+
display: flex;
|
|
1411
|
+
flex-direction: column;
|
|
1412
|
+
align-items: center;
|
|
1413
|
+
gap: 20px;
|
|
1414
|
+
padding: 0 16px;
|
|
1415
|
+
}
|
|
1416
|
+
.message {
|
|
1417
|
+
display: flex;
|
|
1418
|
+
flex-direction: column;
|
|
1419
|
+
align-items: center;
|
|
1420
|
+
gap: 8px;
|
|
1421
|
+
}
|
|
1422
|
+
.success-icon {
|
|
1423
|
+
width: 48px;
|
|
1424
|
+
height: 48px;
|
|
1425
|
+
border-radius: 50%;
|
|
1426
|
+
border: 2px solid #57fec9;
|
|
1427
|
+
background: transparent;
|
|
1428
|
+
display: flex;
|
|
1429
|
+
align-items: center;
|
|
1430
|
+
justify-content: center;
|
|
1431
|
+
}
|
|
1432
|
+
.heading {
|
|
1433
|
+
font-family: 'Lexend', sans-serif;
|
|
1434
|
+
font-weight: 600;
|
|
1435
|
+
font-size: 32px;
|
|
1436
|
+
line-height: 40px;
|
|
1437
|
+
color: #ffffff;
|
|
1438
|
+
margin: 0;
|
|
1439
|
+
text-align: center;
|
|
1440
|
+
text-wrap: pretty;
|
|
1441
|
+
}
|
|
1442
|
+
.text {
|
|
1443
|
+
font-family: 'Inter', sans-serif;
|
|
1444
|
+
font-weight: 400;
|
|
1445
|
+
font-size: 16px;
|
|
1446
|
+
line-height: 24px;
|
|
1447
|
+
margin: 0;
|
|
1448
|
+
text-align: center;
|
|
1449
|
+
text-wrap: pretty;
|
|
1450
|
+
}
|
|
1451
|
+
.text-muted {
|
|
1452
|
+
color: #abb2bf;
|
|
1453
|
+
}${COPY_BTN_CSS}
|
|
1454
|
+
</style>
|
|
1455
|
+
</head>
|
|
1456
|
+
<body>
|
|
1457
|
+
<div class="content">
|
|
1458
|
+
<div class="success-icon" aria-hidden="true">
|
|
1459
|
+
<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">
|
|
1460
|
+
<polyline points="20 6 9 17 4 12" />
|
|
1461
|
+
</svg>
|
|
1462
|
+
</div>
|
|
1463
|
+
<div class="message">
|
|
1464
|
+
<h1 class="heading">${escapeHtml(title)}</h1>
|
|
1465
|
+
<p class="text text-muted">You can close this window and return to your terminal.</p>
|
|
1466
|
+
</div>
|
|
1467
|
+
|
|
1468
|
+
<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">
|
|
1469
|
+
<title>GitHits</title>
|
|
1470
|
+
<defs>
|
|
1471
|
+
<linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
|
|
1472
|
+
<stop offset="0" style="stop-color: #ff4fae" />
|
|
1473
|
+
<stop offset="1" style="stop-color: #ff872f" />
|
|
1474
|
+
</linearGradient>
|
|
1475
|
+
</defs>
|
|
1476
|
+
<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" />
|
|
1477
|
+
<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)" />
|
|
1478
|
+
<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" />
|
|
1479
|
+
</svg>
|
|
1480
|
+
|
|
1481
|
+
${HELP_CTA}
|
|
1482
|
+
</div>
|
|
1483
|
+
${COPY_SCRIPT_HTML}
|
|
1484
|
+
</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>
|
|
1485
|
+
<html><head>
|
|
1486
|
+
<title>GitHits CLI</title>
|
|
1487
|
+
<meta charset="utf-8">
|
|
1488
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1489
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
1490
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
1491
|
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Lexend:wght@600&display=swap" rel="stylesheet">
|
|
1492
|
+
<style>
|
|
1493
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
1494
|
+
body {
|
|
1495
|
+
margin: 0;
|
|
1496
|
+
min-height: 100vh;
|
|
1497
|
+
width: 100%;
|
|
1498
|
+
padding: 16px;
|
|
1499
|
+
background: #21262d;
|
|
1500
|
+
color: #ffffff;
|
|
1501
|
+
font-family: 'Inter', sans-serif;
|
|
1502
|
+
display: flex;
|
|
1503
|
+
align-items: center;
|
|
1504
|
+
justify-content: center;
|
|
1505
|
+
}
|
|
1506
|
+
.content {
|
|
1507
|
+
display: flex;
|
|
1508
|
+
flex-direction: column;
|
|
1509
|
+
align-items: center;
|
|
1510
|
+
gap: 20px;
|
|
1511
|
+
padding: 0 16px;
|
|
1512
|
+
}
|
|
1513
|
+
.message {
|
|
1514
|
+
display: flex;
|
|
1515
|
+
flex-direction: column;
|
|
1516
|
+
align-items: center;
|
|
1517
|
+
gap: 8px;
|
|
1518
|
+
}
|
|
1519
|
+
.error-icon {
|
|
1520
|
+
width: 48px;
|
|
1521
|
+
height: 48px;
|
|
1522
|
+
border-radius: 50%;
|
|
1523
|
+
border: 2px solid #ff5a6a;
|
|
1524
|
+
background: transparent;
|
|
1525
|
+
display: flex;
|
|
1526
|
+
align-items: center;
|
|
1527
|
+
justify-content: center;
|
|
1528
|
+
}
|
|
1529
|
+
.heading {
|
|
1530
|
+
font-family: 'Lexend', sans-serif;
|
|
1531
|
+
font-weight: 600;
|
|
1532
|
+
font-size: 32px;
|
|
1533
|
+
line-height: 40px;
|
|
1534
|
+
color: #ffffff;
|
|
1535
|
+
margin: 0;
|
|
1536
|
+
text-align: center;
|
|
1537
|
+
text-wrap: pretty;
|
|
1538
|
+
}
|
|
1539
|
+
.text {
|
|
1540
|
+
font-family: 'Inter', sans-serif;
|
|
1541
|
+
font-weight: 400;
|
|
1542
|
+
font-size: 16px;
|
|
1543
|
+
line-height: 24px;
|
|
1544
|
+
margin: 0;
|
|
1545
|
+
text-align: center;
|
|
1546
|
+
text-wrap: pretty;
|
|
1547
|
+
}
|
|
1548
|
+
.text-muted {
|
|
1549
|
+
color: #abb2bf;
|
|
1550
|
+
}
|
|
1551
|
+
.footer-text {
|
|
1552
|
+
font-family: 'Inter', sans-serif;
|
|
1553
|
+
font-weight: 400;
|
|
1554
|
+
font-size: 12px;
|
|
1555
|
+
line-height: 16px;
|
|
1556
|
+
color: #abb2bf;
|
|
1557
|
+
margin: 0;
|
|
1558
|
+
text-align: center;
|
|
1559
|
+
text-wrap: pretty;
|
|
1560
|
+
}
|
|
1561
|
+
.footer-link {
|
|
1562
|
+
color: inherit;
|
|
1563
|
+
text-decoration: underline;
|
|
1564
|
+
text-underline-offset: 2px;
|
|
1565
|
+
}
|
|
1566
|
+
.error-code {
|
|
1567
|
+
font-family: 'Inter', sans-serif;
|
|
1568
|
+
font-weight: 400;
|
|
1569
|
+
font-size: 12px;
|
|
1570
|
+
line-height: 16px;
|
|
1571
|
+
color: #abb2bf;
|
|
1572
|
+
opacity: 0.7;
|
|
1573
|
+
margin: 4px 0 0;
|
|
1574
|
+
text-align: center;
|
|
1575
|
+
}
|
|
1576
|
+
.error-code code {
|
|
1577
|
+
font-size: 11px;
|
|
1578
|
+
padding: 0 5px;
|
|
1579
|
+
}
|
|
1580
|
+
code {
|
|
1581
|
+
font-family: 'Consolas', monospace;
|
|
1582
|
+
font-size: 13px;
|
|
1583
|
+
background: rgba(255, 255, 255, 0.08);
|
|
1584
|
+
padding: 1px 6px;
|
|
1585
|
+
border-radius: 4px;
|
|
1586
|
+
color: #ffffff;
|
|
1587
|
+
}${COPY_BTN_CSS}
|
|
1588
|
+
</style>
|
|
1589
|
+
</head>
|
|
1590
|
+
<body>
|
|
1591
|
+
<div class="content">
|
|
1592
|
+
<div class="error-icon" aria-hidden="true">
|
|
1593
|
+
<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">
|
|
1594
|
+
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
1595
|
+
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
1596
|
+
</svg>
|
|
1597
|
+
</div>
|
|
1598
|
+
|
|
1599
|
+
<div class="message">
|
|
1600
|
+
<h1 class="heading">Sign-in failed</h1>
|
|
1601
|
+
<p class="text text-muted">${escapeHtml(error)}</p>
|
|
1602
|
+
${errorCodeHtml}
|
|
1603
|
+
</div>
|
|
1604
|
+
|
|
1605
|
+
${ctaHtml??""}
|
|
1606
|
+
|
|
1607
|
+
<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">
|
|
1608
|
+
<title>GitHits</title>
|
|
1609
|
+
<defs>
|
|
1610
|
+
<linearGradient id="wm-grad" x1="234.9" y1="64.7" x2="555.5" y2="64.7" gradientUnits="userSpaceOnUse">
|
|
1611
|
+
<stop offset="0" style="stop-color: #ff4fae" />
|
|
1612
|
+
<stop offset="1" style="stop-color: #ff872f" />
|
|
1613
|
+
</linearGradient>
|
|
1614
|
+
</defs>
|
|
1615
|
+
<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" />
|
|
1616
|
+
<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)" />
|
|
1617
|
+
<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" />
|
|
1618
|
+
</svg>
|
|
1619
|
+
|
|
1620
|
+
<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>
|
|
1621
|
+
</div>
|
|
1622
|
+
${COPY_SCRIPT_HTML}
|
|
1623
|
+
</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(`
|
|
1624
|
+
`);return`<div class="cli-cta">
|
|
1625
|
+
<p class="tip">${introHtml}</p>
|
|
1626
|
+
${buttons}
|
|
1627
|
+
</div>`}var COPY_BTN_CSS=`
|
|
1628
|
+
.wordmark {
|
|
1629
|
+
margin: 16px 0;
|
|
1630
|
+
}
|
|
1631
|
+
.cli-cta {
|
|
1632
|
+
display: flex;
|
|
1633
|
+
flex-direction: column;
|
|
1634
|
+
align-items: center;
|
|
1635
|
+
gap: 12px;
|
|
1636
|
+
margin: 16px 0 0;
|
|
1637
|
+
}
|
|
1638
|
+
.wordmark + .cli-cta {
|
|
1639
|
+
margin-top: 0;
|
|
1640
|
+
}
|
|
1641
|
+
.tip {
|
|
1642
|
+
font-family: 'Inter', sans-serif;
|
|
1643
|
+
font-weight: 400;
|
|
1644
|
+
font-size: 14px;
|
|
1645
|
+
line-height: 20px;
|
|
1646
|
+
color: #d5d9df;
|
|
1647
|
+
margin: 0;
|
|
1648
|
+
text-align: center;
|
|
1649
|
+
text-wrap: pretty;
|
|
1650
|
+
}
|
|
1651
|
+
.githits-cli-btn {
|
|
1652
|
+
display: inline-flex;
|
|
1653
|
+
align-items: center;
|
|
1654
|
+
gap: 0.5rem;
|
|
1655
|
+
background-color: rgba(255, 255, 255, 0.08);
|
|
1656
|
+
border: none;
|
|
1657
|
+
border-radius: 0.5rem;
|
|
1658
|
+
padding: 1rem 1.25rem;
|
|
1659
|
+
font-family: Consolas, ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
|
|
1660
|
+
font-size: 14px;
|
|
1661
|
+
font-weight: 500;
|
|
1662
|
+
color: #abb2bf;
|
|
1663
|
+
cursor: pointer;
|
|
1664
|
+
line-height: 1;
|
|
1665
|
+
transition: background-color 0.2s ease, transform 0.1s ease, color 0.2s ease;
|
|
1666
|
+
}
|
|
1667
|
+
.githits-cli-btn:hover {
|
|
1668
|
+
color: #d5d9df;
|
|
1669
|
+
}
|
|
1670
|
+
.githits-cli-btn:active {
|
|
1671
|
+
transform: scale(0.98);
|
|
1672
|
+
}
|
|
1673
|
+
.githits-cli-btn:focus-visible {
|
|
1674
|
+
outline: 2px solid #abb2bf;
|
|
1675
|
+
outline-offset: 2px;
|
|
1676
|
+
}
|
|
1677
|
+
.githits-cli-cmd {
|
|
1678
|
+
white-space: nowrap;
|
|
1679
|
+
}
|
|
1680
|
+
.githits-cli-icon {
|
|
1681
|
+
width: 14px;
|
|
1682
|
+
height: 14px;
|
|
1683
|
+
color: #abb2bf;
|
|
1684
|
+
flex-shrink: 0;
|
|
1685
|
+
}
|
|
1686
|
+
.githits-cli-btn.copied .githits-cli-icon-copy { display: none; }
|
|
1687
|
+
.githits-cli-btn:not(.copied) .githits-cli-icon-check { display: none; }
|
|
1688
|
+
.githits-cli-btn.copied .githits-cli-icon { color: #abb2bf; }`;var COPY_SCRIPT_HTML=`<script>
|
|
1689
|
+
(function() {
|
|
1690
|
+
var timers = new WeakMap();
|
|
1691
|
+
var buttons = document.querySelectorAll('.githits-cli-btn');
|
|
1692
|
+
for (var i = 0; i < buttons.length; i++) {
|
|
1693
|
+
buttons[i].addEventListener('click', function(e) {
|
|
1694
|
+
var target = e.currentTarget;
|
|
1695
|
+
var text = target.getAttribute('data-copy');
|
|
1696
|
+
if (!text || !navigator.clipboard) return;
|
|
1697
|
+
navigator.clipboard.writeText(text).then(function() {
|
|
1698
|
+
target.classList.add('copied');
|
|
1699
|
+
var existing = timers.get(target);
|
|
1700
|
+
if (existing) clearTimeout(existing);
|
|
1701
|
+
timers.set(target, setTimeout(function() {
|
|
1702
|
+
target.classList.remove('copied');
|
|
1703
|
+
timers.delete(target);
|
|
1704
|
+
}, 1500));
|
|
1705
|
+
});
|
|
1706
|
+
});
|
|
1707
|
+
}
|
|
1708
|
+
})();
|
|
1709
|
+
</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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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(baseUrl2){const stored=await this.loadFile();if(!stored)return null;const metadata=stored.sessions[normalizeBaseUrl(baseUrl2)]??null;return isAuthSessionMetadata(metadata)?metadata:null}async saveFromTokens(baseUrl2,tokens){const stored=await this.loadFile()??{version:1,sessions:{}};stored.sessions[normalizeBaseUrl(baseUrl2)]={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(baseUrl2){const stored=await this.loadFile();if(!stored)return;delete stored.sessions[normalizeBaseUrl(baseUrl2)];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,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 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 rename(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(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidTokenData(data))return null;return data}async saveTokens(baseUrl2,data){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const key=`${TOKEN_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.clearTokensIfUnchanged(baseUrl2,expected)}async loadClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;const json=this.keyring.getPassword(SERVICE_NAME,key);const data=parseJsonOrNull2(json);if(data!==null&&!isValidClientRegistration(data))return null;return data}async saveClient(baseUrl2,data){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.setPassword(SERVICE_NAME,key,JSON.stringify(data))}async clearClient(baseUrl2){const key=`${CLIENT_PREFIX}${normalizeBaseUrl(baseUrl2)}`;this.keyring.deletePassword(SERVICE_NAME,key)}clearActiveClient(baseUrl2){return this.clearClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){await this.saveClient(baseUrl2,client);await this.saveTokens(baseUrl2,tokens)}async clearAuthSession(baseUrl2){await clearAuthSessionBestEffort(()=>this.clearTokens(baseUrl2),()=>this.clearClient(baseUrl2))}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 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(baseUrl2){return this.lockLoads?this.withAuthStorageLock(()=>this.storage.loadTokens(baseUrl2)):this.storage.loadTokens(baseUrl2)}saveTokens(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveTokens(baseUrl2,data))}saveTokensIfUnchanged(baseUrl2,expected,data){return this.withAuthStorageLock(()=>this.storage.saveTokensIfUnchanged(baseUrl2,expected,data))}clearTokens(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearTokens(baseUrl2))}clearTokensIfUnchanged(baseUrl2,expected){return this.withAuthStorageLock(()=>this.storage.clearTokensIfUnchanged(baseUrl2,expected))}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.withAuthStorageLock(()=>this.storage.clearActiveTokensIfUnchanged(baseUrl2,expected))}loadClient(baseUrl2){return this.lockLoads?this.withAuthStorageLock(()=>this.storage.loadClient(baseUrl2)):this.storage.loadClient(baseUrl2)}saveClient(baseUrl2,data){return this.withAuthStorageLock(()=>this.storage.saveClient(baseUrl2,data))}clearClient(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearClient(baseUrl2))}clearActiveClient(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearActiveClient(baseUrl2))}saveAuthSession(baseUrl2,client,tokens){return this.withAuthStorageLock(()=>this.storage.saveAuthSession(baseUrl2,client,tokens))}clearAuthSession(baseUrl2){return this.withAuthStorageLock(()=>this.storage.clearAuthSession(baseUrl2))}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();if(currentOwner.state==="present"&¤tOwner.owner.id===owner.id){await this.deleteFileForCleanup(this.ownerPath())}if(!await this.deleteFileForCleanup(claimPath)){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;await this.fileSystemService.deleteDirIfEmpty(this.lockPath).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}`)}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:stdout2}=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 stdout2.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:stat2}=await import("node:fs/promises");return(await stat2(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.
|
|
1710
|
+
|
|
1711
|
+
Options:
|
|
1712
|
+
1. Unlock or fix your system keychain.
|
|
1713
|
+
2. Use GITHITS_API_TOKEN for CI/automation.
|
|
1714
|
+
3. If you accept storing OAuth credentials unencrypted on disk, set:
|
|
1715
|
+
|
|
1716
|
+
[auth]
|
|
1717
|
+
storage = "file"
|
|
1718
|
+
|
|
1719
|
+
in ${configPath}, or run with GITHITS_AUTH_STORAGE=file.
|
|
1720
|
+
|
|
1721
|
+
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(baseUrl2){return this.storage.loadTokens(baseUrl2)}async saveTokens(baseUrl2,data){this.assertFileMode();await this.storage.saveTokens(baseUrl2,data)}async saveTokensIfUnchanged(baseUrl2,expected,data){this.assertFileMode();return this.storage.saveTokensIfUnchanged(baseUrl2,expected,data)}clearTokens(baseUrl2){return this.storage.clearTokens(baseUrl2)}clearTokensIfUnchanged(baseUrl2,expected){return this.storage.clearTokensIfUnchanged(baseUrl2,expected)}clearActiveTokensIfUnchanged(baseUrl2,expected){return this.storage.clearActiveTokensIfUnchanged(baseUrl2,expected)}loadClient(baseUrl2){return this.storage.loadClient(baseUrl2)}async saveClient(baseUrl2,data){this.assertFileMode();await this.storage.saveClient(baseUrl2,data)}clearClient(baseUrl2){return this.storage.clearClient(baseUrl2)}clearActiveClient(baseUrl2){return this.storage.clearActiveClient(baseUrl2)}async saveAuthSession(baseUrl2,client,tokens){this.assertFileMode();await this.storage.saveAuthSession(baseUrl2,client,tokens)}clearAuthSession(baseUrl2){return this.storage.clearAuthSession(baseUrl2)}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(baseUrl2){if(this.mode==="file"){return this.loadTokensFileMode(baseUrl2)}return this.loadTokensKeychainMode(baseUrl2)}async saveTokens(baseUrl2,data){if(this.mode==="file"){await this.file.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data);return}try{await this.primary.saveTokens(baseUrl2,data);await this.saveMetadataBestEffort(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async saveTokensIfUnchanged(baseUrl2,expected,data){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.saveTokens(baseUrl2,data);return true}async clearTokens(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.file.clearTokens(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearTokens(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearTokensIfUnchanged(baseUrl2,expected){const current=await this.loadTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;await this.clearTokens(baseUrl2);return true}async clearActiveTokensIfUnchanged(baseUrl2,expected){const current=await this.currentActiveTokens(baseUrl2);if(!this.sameTokenData(current,expected))return false;let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearTokens(baseUrl2));firstError??=error}const metadataError=await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());firstError??=metadataError;if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}return true}async loadClient(baseUrl2){if(this.mode==="file"){return this.loadClientFileMode(baseUrl2)}return this.loadClientKeychainMode(baseUrl2)}async saveClient(baseUrl2,data){if(this.mode==="file"){await this.file.saveClient(baseUrl2,data);return}try{await this.primary.saveClient(baseUrl2,data)}catch(error){throw this.toPolicyError(error)}}async clearClient(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearClient(baseUrl2));await this.clearBestEffort(()=>this.file.clearClient(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearClient(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearClient(baseUrl2))}if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}async clearActiveClient(baseUrl2){let firstError;for(const store of this.activeStores()){const error=await this.clearBestEffort(()=>store.clearClient(baseUrl2));firstError??=error}if(firstError&&!(firstError instanceof KeychainUnavailableError)){throw firstError}}async saveAuthSession(baseUrl2,client,tokens){if(this.mode==="file"){await this.file.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens);return}try{await this.primary.saveAuthSession(baseUrl2,client,tokens);await this.saveMetadataBestEffort(baseUrl2,tokens)}catch(error){throw this.toPolicyError(error)}}async clearAuthSession(baseUrl2){const primaryError=await this.clearBestEffort(()=>this.primary.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.file.clearAuthSession(baseUrl2));await this.clearBestEffort(()=>this.legacy.clearAuthSession(baseUrl2));for(const legacy of this.additionalLegacyStores){await this.clearBestEffort(()=>legacy.clearAuthSession(baseUrl2))}await this.clearBestEffort(()=>this.metadata?.clear(baseUrl2)??Promise.resolve());if(primaryError&&!(primaryError instanceof KeychainUnavailableError)){throw primaryError}}getStorageLocation(){return this.mode==="file"?this.file.getStorageLocation():this.primary.getStorageLocation()}async loadTokensKeychainMode(baseUrl2){try{const primaryTokens=await this.primary.loadTokens(baseUrl2);if(primaryTokens){await this.saveMetadataBestEffort(baseUrl2,primaryTokens);return primaryTokens}}catch(error){throw this.toPolicyError(error)}return null}async loadTokensFileMode(baseUrl2){const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);if(candidate){if(candidate.ambiguous){await this.file.saveTokens(baseUrl2,candidate.data);for(const legacy of this.getLegacyStores()){await this.clearBestEffort(()=>legacy.clearTokens(baseUrl2))}}else if(candidate.source==="legacy"){await this.file.saveTokens(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearTokens(baseUrl2))}await this.saveMetadataBestEffort(baseUrl2,candidate.data);return candidate.data}return null}async loadClientKeychainMode(baseUrl2){try{const primaryClient=await this.primary.loadClient(baseUrl2);if(primaryClient)return primaryClient}catch(error){throw this.toPolicyError(error)}return null}async loadClientFileMode(baseUrl2){const candidate=await this.selectPlaintextClientCandidate(baseUrl2);if(candidate){if(candidate.ambiguous){await this.file.saveClient(baseUrl2,candidate.data);for(const legacy of this.getLegacyStores()){await this.clearBestEffort(()=>legacy.clearClient(baseUrl2))}}else if(candidate.source==="legacy"){await this.file.saveClient(baseUrl2,candidate.data);await this.clearBestEffort(()=>candidate.storage.clearClient(baseUrl2))}return candidate.data}return null}async selectPlaintextTokenCandidate(baseUrl2){const candidates=[];const fileTokens=await this.file.loadTokens(baseUrl2);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(baseUrl2);if(legacyTokens){candidates.push({data:legacyTokens,source:"legacy",storage:legacy,timestamp:legacyTokens.createdAt,ambiguous:false})}}return this.selectNewestCandidate(candidates)}async selectPlaintextClientCandidate(baseUrl2){const candidates=[];const fileClient=await this.file.loadClient(baseUrl2);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(baseUrl2);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(baseUrl2){if(this.mode==="file"){const candidate=await this.selectPlaintextTokenCandidate(baseUrl2);return candidate?.data??null}try{return await this.primary.loadTokens(baseUrl2)}catch(error){throw this.toPolicyError(error)}}async clearBestEffort(fn){try{await fn();return}catch(error){return error}}async saveMetadataBestEffort(baseUrl2,tokens){await this.clearBestEffort(()=>this.metadata?.saveFromTokens(baseUrl2,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(`
|
|
1722
|
+
`)}
|
|
1723
|
+
`}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}
|
|
1724
|
+
`)}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}/${version}`;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 loadAutoLoginAuthSessionMetadata(){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 clearAutoLoginAuthSessionMetadata(){const fileSystemService=new FileSystemServiceImpl;const metadataStorage=new AuthSessionMetadataStorage(fileSystemService);await metadataStorage.clear(getMcpStorageKeyUrl())}async function createAuthCommandDependencies(){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 createLogoutCommandDependencies(){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 createAuthStatusDependencies(){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 createContainer(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:version,agentProvider:options.agentProvider});const diagnostics={withOperation:withTelemetrySpan,isEnabled:isDebugAreaEnabled,debug:debugLog};const serviceRuntime={clientHeaders,userAgent:USER_AGENT,clientVersion:version,diagnostics};const envToken=getEnvApiToken();if(envToken){const authStorage2=createAuthStorageForMode(fileSystemService,"keychain");const tokenProvider=createStaticTokenProvider(envToken);const codeNavigationService2=new CodeNavigationServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const packageIntelligenceService2=new PackageIntelligenceServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);const resolveTargetService2=new ResolveTargetServiceImpl(codeNavigationUrl,tokenProvider,fetchFn,serviceRuntime);return{authStorage:authStorage2,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken:envToken,hasValidToken:true,envApiToken:envToken,codeNavigationUrl,codeNavigationService:codeNavigationService2,packageIntelligenceService:packageIntelligenceService2,resolveTargetService:resolveTargetService2,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);return{authStorage,authService,browserService,fileSystemService,mcpUrl,apiUrl,apiToken,hasValidToken:apiToken!==undefined,envApiToken:undefined,codeNavigationUrl,codeNavigationService,packageIntelligenceService,resolveTargetService,githitsService:new RefreshingGitHitsService(apiUrl,tokenManager,(innerApiUrl,token)=>new GitHitsServiceImpl(innerApiUrl,token,fetchFn,undefined,serviceRuntime),serviceRuntime),tokenProvider:tokenManager}})}
|
|
1725
|
+
export{LOCAL_AUTHENTICATION_MISSING_MESSAGE,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError,ApiRateLimitError,FetchTimeoutError,fetchWithTimeout,isFetchTimeoutError,TERMS_URL,TermsAcceptanceRequiredError,CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,validateServiceUrl,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,normalizeSingleLineText,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,recordAuthFingerprint,loadAutoLoginAuthSessionMetadata,clearAutoLoginAuthSessionMetadata,createAuthCommandDependencies,createLogoutCommandDependencies,createAuthStatusDependencies,createContainer};
|