@githits/mcp 0.4.15 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,969 +0,0 @@
1
- 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(`
2
- `)}
3
- `}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 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 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}}function parseDetail(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail}catch{return body}return}class GitHitsServiceImpl{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params){return withTelemetrySpan("githits.search.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/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})},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.text()})}async getLanguages(){return withTelemetrySpan("githits.languages.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/languages`,{headers:this.headers()},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.json()})}async searchLanguages(query,limit=5){return withTelemetrySpan("githits.languages.search.request",async()=>{const params=new URLSearchParams({query,limit:String(limit)});const response=await fetchWithTimeout(`${this.apiUrl}/languages?${params.toString()}`,{headers:this.headers()},this.fetchOptions());if(!response.ok){throw await this.createError(response)}return response.json()})}async submitFeedback(params){return withTelemetrySpan("githits.feedback.request",async()=>{const response=await fetchWithTimeout(`${this.apiUrl}/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}})},this.fetchOptions());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(){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs}}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");switch(status){case 401:return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(parseDetail(body)||"Resource not found.");default:{if(status>=500){const detail=body?`: ${body}`:"";return new Error(`Server error (${status})${detail}`)}return new Error(body||`Request failed with status ${status}`)}}}}import{z}from"zod";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}
4
- `)}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"}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;let response;try{response=await fetchWithTimeout(`${baseUrl(request.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){debugLog("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);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}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)}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(!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}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;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;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 CodeNavigationTargetNotFoundError extends Error{availableVersions;constructor(message,availableVersions){super(message);this.availableVersions=availableVersions;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;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.name="CodeNavigationVersionNotFoundError"}}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;constructor(message,status,graphqlCode,retryable){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
5
- availableRefs {
6
- version
7
- ref
8
- }`;var TARGET_RESOLUTION_SELECTION=`
9
- targetResolution {
10
- requested {
11
- kind
12
- registry
13
- packageName
14
- version
15
- repoUrl
16
- gitRef
17
- commitSha
18
- }
19
- resolvedRequested {
20
- kind
21
- registry
22
- packageName
23
- version
24
- repoUrl
25
- gitRef
26
- commitSha
27
- }
28
- served {
29
- kind
30
- registry
31
- packageName
32
- version
33
- repoUrl
34
- gitRef
35
- commitSha
36
- }
37
- freshness
38
- freshnessReason
39
- indexingRef
40
- availableVersions {
41
- version
42
- ref
43
- }
44
- ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
45
- }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
46
- availableVersions {
47
- version
48
- ref
49
- }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
50
- availableVersions {
51
- version
52
- ref
53
- }
54
- availableRefs {
55
- version
56
- ref
57
- }`;var UNIFIED_SEARCH_QUERY=`
58
- query UnifiedSearch(
59
- $targets: [SearchPackageInput!]!
60
- $query: String!
61
- $sources: [DiscoverySearchSource!]
62
- $filters: DiscoverySearchFiltersInput
63
- $allowPartialResults: Boolean
64
- $limit: Int
65
- $offset: Int
66
- $waitTimeoutMs: Int
67
- ) {
68
- search(
69
- targets: $targets
70
- query: $query
71
- sources: $sources
72
- filters: $filters
73
- allowPartialResults: $allowPartialResults
74
- limit: $limit
75
- offset: $offset
76
- waitTimeoutMs: $waitTimeoutMs
77
- ) {
78
- completed
79
- searchRef
80
- result {
81
- query
82
- queryWarnings
83
- sources
84
- results {
85
- id
86
- resultType
87
- targetLabel
88
- requestedTargetLabel
89
- freshTargetLabel
90
- servedTargetLabel
91
- freshness
92
- title
93
- summary
94
- score
95
- highlights {
96
- title
97
- summary
98
- }
99
- locator {
100
- registry
101
- packageName
102
- version
103
- pageId
104
- sourceKind
105
- sourceUrl
106
- repoUrl
107
- gitRef
108
- requestedRef
109
- filePath
110
- startLine
111
- endLine
112
- fileContentHash
113
- symbolRef
114
- qualifiedPath
115
- kind
116
- category
117
- language
118
- }
119
- }
120
- page {
121
- offset
122
- limit
123
- returned
124
- hasMore
125
- }
126
- partialResults
127
- sourceStatus {
128
- source
129
- targetLabel
130
- requestedTargetLabel
131
- freshTargetLabel
132
- servedTargetLabel
133
- ${TARGET_RESOLUTION_SELECTION}
134
- indexingStatus
135
- codeIndexState
136
- resultCount
137
- appliedFilters
138
- ignoredFilters
139
- incompatibleFilters
140
- appliedQueryFeatures
141
- ignoredQueryFeatures
142
- incompatibleQueryFeatures
143
- note
144
- }
145
- }
146
- progress {
147
- searchRef
148
- status
149
- targetsTotal
150
- targetsReady
151
- elapsedMs
152
- query
153
- queryWarnings
154
- sources
155
- requestedSources
156
- targetMode
157
- requestedTargets {
158
- registry
159
- name
160
- version
161
- repoUrl
162
- gitRef
163
- }
164
- filters {
165
- fileIntent
166
- kind
167
- category
168
- publicOnly
169
- pathPrefix
170
- }
171
- limit
172
- offset
173
- targets {
174
- requested
175
- resolvedRequested
176
- served
177
- freshness
178
- indexingRef
179
- requestedRefKind
180
- ${TARGET_RESOLUTION_SELECTION}
181
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
182
- }
183
- expiresAt
184
- }
185
- }
186
- }`;var UNIFIED_SEARCH_STATUS_QUERY=`
187
- query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!) {
188
- discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults) {
189
- searchRef
190
- status
191
- targetsTotal
192
- targetsReady
193
- elapsedMs
194
- query
195
- queryWarnings
196
- sources
197
- requestedSources
198
- targetMode
199
- requestedTargets {
200
- registry
201
- name
202
- version
203
- repoUrl
204
- gitRef
205
- }
206
- filters {
207
- fileIntent
208
- kind
209
- category
210
- publicOnly
211
- pathPrefix
212
- }
213
- limit
214
- offset
215
- targets {
216
- requested
217
- resolvedRequested
218
- served
219
- freshness
220
- indexingRef
221
- requestedRefKind
222
- ${TARGET_RESOLUTION_SELECTION}
223
- ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
224
- }
225
- expiresAt
226
- results {
227
- query
228
- queryWarnings
229
- sources
230
- results {
231
- id
232
- resultType
233
- targetLabel
234
- requestedTargetLabel
235
- freshTargetLabel
236
- servedTargetLabel
237
- freshness
238
- title
239
- summary
240
- score
241
- highlights {
242
- title
243
- summary
244
- }
245
- locator {
246
- registry
247
- packageName
248
- version
249
- pageId
250
- sourceKind
251
- sourceUrl
252
- repoUrl
253
- gitRef
254
- requestedRef
255
- filePath
256
- startLine
257
- endLine
258
- fileContentHash
259
- symbolRef
260
- qualifiedPath
261
- kind
262
- category
263
- language
264
- }
265
- }
266
- page {
267
- offset
268
- limit
269
- returned
270
- hasMore
271
- }
272
- partialResults
273
- sourceStatus {
274
- source
275
- targetLabel
276
- requestedTargetLabel
277
- freshTargetLabel
278
- servedTargetLabel
279
- ${TARGET_RESOLUTION_SELECTION}
280
- indexingStatus
281
- codeIndexState
282
- resultCount
283
- appliedFilters
284
- ignoredFilters
285
- incompatibleFilters
286
- appliedQueryFeatures
287
- ignoredQueryFeatures
288
- incompatibleQueryFeatures
289
- note
290
- }
291
- }
292
- }
293
- }`;function debugUnifiedSearchRequest(variables){if(!isDebugAreaEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);debugLog("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){if(!isDebugAreaEnabled("code-nav-wire"))return;debugLog("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=z.object({version:z.string().nullable().optional(),ref:z.string()});var targetResolutionIdentitySchema=z.object({kind:z.string().nullable().optional(),registry:z.string().nullable().optional(),packageName:z.string().nullable().optional(),version:z.string().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional(),commitSha:z.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z.string().nullable().optional(),freshnessReason:z.string().nullable().optional(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional(),availableRefs:z.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLocatorSchema=z.object({registry:z.string().nullable().optional(),packageName:z.string().nullable().optional(),version:z.string().nullable().optional(),pageId:z.string().nullable().optional(),sourceKind:z.string().nullable().optional(),sourceUrl:z.string().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional(),requestedRef:z.string().nullable().optional(),filePath:z.string().nullable().optional(),startLine:z.number().int().nullable().optional(),endLine:z.number().int().nullable().optional(),fileContentHash:z.string().nullable().optional(),symbolRef:z.string().nullable().optional(),qualifiedPath:z.string().nullable().optional(),kind:z.string().nullable().optional(),category:z.string().nullable().optional(),language:z.string().nullable().optional()});var unifiedSearchHitSchema=z.object({id:z.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z.string(),requestedTargetLabel:z.string().nullable().optional(),freshTargetLabel:z.string().nullable().optional(),servedTargetLabel:z.string().nullable().optional(),freshness:z.string().nullable().optional(),title:z.string().nullable().optional(),summary:z.string().nullable().optional(),score:z.number().nullable().optional(),highlights:z.object({title:z.array(z.tuple([z.number().int(),z.number().int()])).nullable().optional(),summary:z.array(z.tuple([z.number().int(),z.number().int()])).nullable().optional()}).nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z.object({offset:z.number().int(),limit:z.number().int(),returned:z.number().int(),hasMore:z.boolean()});var unifiedSearchSourceStatusSchema=z.object({source:unifiedSearchSourceSchema,targetLabel:z.string(),requestedTargetLabel:z.string().nullable().optional(),freshTargetLabel:z.string().nullable().optional(),servedTargetLabel:z.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z.string().nullable().optional(),codeIndexState:z.string().nullable().optional(),resultCount:z.number().int().nullable().optional(),appliedFilters:z.array(z.string()),ignoredFilters:z.array(z.string()),incompatibleFilters:z.array(z.string()),appliedQueryFeatures:z.array(z.string()),ignoredQueryFeatures:z.array(z.string()),incompatibleQueryFeatures:z.array(z.string()),note:z.string().nullable().optional()});var unifiedSearchResultSchema=z.object({query:z.string(),queryWarnings:z.array(z.string()),sources:z.array(unifiedSearchSourceSchema),results:z.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z.boolean(),sourceStatus:z.array(unifiedSearchSourceStatusSchema)});var unifiedSearchSessionStatusSchema=z.enum(["PENDING","INDEXING","SEARCHING","COMPLETED","TIMEOUT","FAILED"]);var unifiedSearchFiltersSchema=z.object({fileIntent:z.string().nullable().optional(),kind:z.string().nullable().optional(),category:z.string().nullable().optional(),publicOnly:z.boolean().nullable().optional(),pathPrefix:z.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z.object({requested:z.string().nullable().optional(),resolvedRequested:z.string().nullable().optional(),served:z.string().nullable().optional(),freshness:z.string().nullable().optional(),indexingRef:z.string().nullable().optional(),requestedRefKind:z.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z.array(availableVersionSchema).nullable().optional(),availableRefs:z.array(availableVersionSchema).nullable().optional()});var unifiedSearchRequestedTargetSchema=z.object({registry:z.string().nullable().optional(),name:z.string().nullable().optional(),version:z.string().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional()});var unifiedSearchProgressSchema=z.object({searchRef:z.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z.number().int(),targetsReady:z.number().int(),elapsedMs:z.number().int(),query:z.string(),queryWarnings:z.array(z.string()),sources:z.array(unifiedSearchSourceSchema),requestedSources:z.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z.string().nullable().optional(),requestedTargets:z.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z.number().int().nullable().optional(),offset:z.number().int().nullable().optional(),targets:z.array(unifiedSearchProgressTargetSchema).nullable().optional(),expiresAt:z.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z.object({completed:z.boolean(),searchRef:z.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z.object({message:z.string(),extensions:z.record(z.string(),z.unknown()).optional()});var navigationResolutionSchema=z.object({requestedVersion:z.string().nullable().optional(),requestedRef:z.string().nullable().optional(),resolvedRef:z.string().nullable().optional(),commitSha:z.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z.object({hint:z.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z.object({path:z.string(),name:z.string().nullable().optional(),language:z.string().nullable().optional(),fileType:z.string().nullable().optional(),byteSize:z.number().int().nullable().optional()});var listRepoFilesResponseSchema=z.object({files:z.array(repoFileEntrySchema),total:z.number().int(),hasMore:z.boolean(),indexedVersion:z.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z.string(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional()});var listRepoFilesGraphQLResponseSchema=z.object({data:z.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
294
- query ListRepoFiles(
295
- $registry: Registry
296
- $packageName: String
297
- $repoUrl: String
298
- $gitRef: String
299
- $version: String
300
- $pathPrefix: String
301
- $pathSelectors: [FilePathSelectorInput!]
302
- $extensions: [String!]
303
- $fileTypes: [String!]
304
- $languages: [String!]
305
- $fileIntent: FileIntent
306
- $fileIntents: [FileIntent!]
307
- $excludeFileIntents: [FileIntent!]
308
- $excludeDocFiles: Boolean
309
- $excludeTestFiles: Boolean
310
- $includeHidden: Boolean
311
- $limit: Int
312
- $waitTimeoutMs: Int
313
- ) {
314
- listRepoFiles(
315
- registry: $registry
316
- packageName: $packageName
317
- repoUrl: $repoUrl
318
- gitRef: $gitRef
319
- version: $version
320
- pathPrefix: $pathPrefix
321
- pathSelectors: $pathSelectors
322
- extensions: $extensions
323
- fileTypes: $fileTypes
324
- languages: $languages
325
- fileIntent: $fileIntent
326
- fileIntents: $fileIntents
327
- excludeFileIntents: $excludeFileIntents
328
- excludeDocFiles: $excludeDocFiles
329
- excludeTestFiles: $excludeTestFiles
330
- includeHidden: $includeHidden
331
- limit: $limit
332
- waitTimeoutMs: $waitTimeoutMs
333
- ) {
334
- files {
335
- path
336
- name
337
- language
338
- fileType
339
- byteSize
340
- }
341
- total
342
- hasMore
343
- indexedVersion
344
- resolution {
345
- requestedVersion
346
- requestedRef
347
- resolvedRef
348
- commitSha
349
- }
350
- ${TARGET_RESOLUTION_SELECTION}
351
- diagnostics {
352
- hint
353
- }
354
- codeIndexState
355
- indexingRef
356
- availableVersions {
357
- version
358
- ref
359
- }
360
- }
361
- }`;var codeContextResponseSchema=z.object({content:z.string().nullable().optional(),filePath:z.string().nullable().optional(),language:z.string().nullable().optional(),totalLines:z.number().int().nullable().optional(),startLine:z.number().int().nullable().optional(),endLine:z.number().int().nullable().optional(),repoUrl:z.string().nullable().optional(),gitRef:z.string().nullable().optional(),isBinary:z.boolean().nullable().optional(),codeIndexState:z.string(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional(),targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z.object({data:z.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
362
- query FetchCodeContext(
363
- $registry: Registry
364
- $packageName: String
365
- $repoUrl: String
366
- $gitRef: String
367
- $version: String
368
- $filePath: String!
369
- $startLine: Int
370
- $endLine: Int
371
- $waitTimeoutMs: Int
372
- ) {
373
- fetchCodeContext(
374
- registry: $registry
375
- packageName: $packageName
376
- repoUrl: $repoUrl
377
- gitRef: $gitRef
378
- version: $version
379
- filePath: $filePath
380
- startLine: $startLine
381
- endLine: $endLine
382
- waitTimeoutMs: $waitTimeoutMs
383
- ) {
384
- content
385
- filePath
386
- language
387
- totalLines
388
- startLine
389
- endLine
390
- repoUrl
391
- gitRef
392
- isBinary
393
- codeIndexState
394
- indexingRef
395
- ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
396
- ${TARGET_RESOLUTION_SELECTION}
397
- }
398
- }`;var grepRepoMatchSchema=z.object({filePath:z.string(),line:z.number().int(),matchStartByte:z.number().int(),matchEndByte:z.number().int(),lineContent:z.string(),contextBefore:z.array(z.string()).nullable().optional(),contextAfter:z.array(z.string()).nullable().optional(),fileContentHash:z.string().nullable().optional(),fileIntent:z.string().nullable().optional(),symbolRowId:z.string().nullable().optional(),symbol:z.object({symbolRef:z.string().optional(),name:z.string().optional(),qualifiedPath:z.string().nullable().optional(),kind:z.string().nullable().optional(),category:z.string().nullable().optional(),arity:z.number().int().nullable().optional(),isPublic:z.boolean().nullable().optional(),filePath:z.string().nullable().optional(),startLine:z.number().int().nullable().optional(),endLine:z.number().int().nullable().optional(),code:z.string().nullable().optional(),callerCount:z.number().int().nullable().optional(),contentHash:z.string().nullable().optional(),parentSymbolRef:z.string().nullable().optional(),parentPath:z.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z.object({matches:z.array(grepRepoMatchSchema),nextCursor:z.string().nullable().optional(),hasMore:z.boolean(),truncatedReason:z.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z.number().int(),filesInScope:z.number().int(),binaryFilesSkipped:z.number().int(),filesTooLargeSkipped:z.number().int(),totalMatches:z.number().int(),uniqueFilesMatched:z.number().int(),indexedVersion:z.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z.string(),indexingRef:z.string().nullable().optional(),availableVersions:z.array(availableVersionSchema).nullable().optional()});var grepRepoGraphQLResponseSchema=z.object({data:z.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z.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(`
399
- `);const symbolBlock=symbolSelection.length>0?`
400
- symbol {
401
- ${symbolSelection}
402
- }`:"";return`
403
- query GrepRepo(
404
- $registry: Registry
405
- $packageName: String
406
- $repoUrl: String
407
- $gitRef: String
408
- $version: String
409
- $waitTimeoutMs: Int
410
- $pattern: String!
411
- $patternType: GrepPatternType
412
- $caseSensitive: Boolean
413
- $pathSelectors: [GrepPathSelectorInput!]
414
- $extensions: [String!]
415
- $excludeDocFiles: Boolean
416
- $excludeTestFiles: Boolean
417
- $allowUnscoped: Boolean
418
- $contextLinesBefore: Int
419
- $contextLinesAfter: Int
420
- $maxMatches: Int
421
- $maxMatchesPerFile: Int
422
- $cursor: String
423
- $symbolFields: [String!]
424
- ) {
425
- grepRepo(
426
- registry: $registry
427
- packageName: $packageName
428
- repoUrl: $repoUrl
429
- gitRef: $gitRef
430
- version: $version
431
- waitTimeoutMs: $waitTimeoutMs
432
- pattern: $pattern
433
- patternType: $patternType
434
- caseSensitive: $caseSensitive
435
- pathSelectors: $pathSelectors
436
- extensions: $extensions
437
- excludeDocFiles: $excludeDocFiles
438
- excludeTestFiles: $excludeTestFiles
439
- allowUnscoped: $allowUnscoped
440
- contextLinesBefore: $contextLinesBefore
441
- contextLinesAfter: $contextLinesAfter
442
- maxMatches: $maxMatches
443
- maxMatchesPerFile: $maxMatchesPerFile
444
- cursor: $cursor
445
- symbolFields: $symbolFields
446
- ) {
447
- matches {
448
- filePath
449
- line
450
- matchStartByte
451
- matchEndByte
452
- lineContent
453
- contextBefore
454
- contextAfter
455
- fileContentHash
456
- fileIntent
457
- symbolRowId${symbolBlock}
458
- }
459
- nextCursor
460
- totalMatches
461
- hasMore
462
- truncatedReason
463
- routeTaken
464
- filesScanned
465
- filesInScope
466
- binaryFilesSkipped
467
- filesTooLargeSkipped
468
- uniqueFilesMatched
469
- indexedVersion
470
- resolution {
471
- requestedVersion
472
- requestedRef
473
- resolvedRef
474
- commitSha
475
- }
476
- ${TARGET_RESOLUTION_SELECTION}
477
- codeIndexState
478
- indexingRef
479
- availableVersions {
480
- version
481
- ref
482
- }
483
- }
484
- }`}var unifiedSearchGraphQLResponseSchema=z.object({data:z.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z.object({data:z.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z.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});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){debugLog("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});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params)})}async searchStatus(searchRef){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef)})}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})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??false,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables);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){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,variables:{searchRef,includeResults:true}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){const status=response.status;const detail=parseDetail2(response.responseBody);if(status===401){return new AuthenticationError(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}createTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);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.";debugLog("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new CodeNavigationBackendError(isDebugAreaEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(this.createIndexingMessage(indexingRef),indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,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));case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message);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"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable);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)}}return new CodeNavigationBackendError(message,undefined,code,retryable)}createIndexingMessage(indexingRef){const base="Target is still indexing. Indexing usually completes within 30 seconds. Retry this request, or pass a longer wait timeout (CLI: `--wait 60000`, MCP: `wait_timeout_ms: 60000`) to block until ready.";if(indexingRef){return`${base} Indexing reference: ${indexingRef}.`}return base}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,note:entry.note??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})),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)})),expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){if(data.codeIndexState==="INDEXING"){const targetResolution=normaliseTargetResolution(data.targetResolution);throw new CodeNavigationIndexingError(this.createIndexingMessage(data.indexingRef??targetResolution?.indexingRef),data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution)}}async listFiles(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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:(error)=>error instanceof AuthenticationError,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:(error)=>error instanceof AuthenticationError,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 parseDetail2(body){if(!body)return;try{const parsed=JSON.parse(body);if(typeof parsed.detail==="string")return parsed.detail;if(typeof parsed.error==="string")return parsed.error}catch{return body}return}function buildTargetResolutionFallbackQueries(query){const candidates=[query.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),query.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),query.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),query.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 parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}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)??[]}}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;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"){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")}var DEFAULT_MCP_URL="https://mcp.githits.com";var DEFAULT_API_URL="https://api.githits.com";var DEFAULT_CODE_NAV_URL="https://pkgseer.dev";function getMcpUrl(){return process.env.GITHITS_MCP_URL??DEFAULT_MCP_URL}function getApiUrl(){return process.env.GITHITS_API_URL??DEFAULT_API_URL}function getCodeNavigationUrl(){const explicitUrl=process.env.GITHITS_CODE_NAV_URL??process.env.PKGSEER_URL;if(explicitUrl){return explicitUrl}return DEFAULT_CODE_NAV_URL}function getEnvApiToken(){return process.env.GITHITS_API_TOKEN}import{z as z2}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=z2.object({stargazersCount:z2.number().int().nullable().optional(),forksCount:z2.number().int().nullable().optional(),openIssuesCount:z2.number().int().nullable().optional(),archived:z2.boolean().nullable().optional(),language:z2.string().nullable().optional(),topics:z2.array(z2.string()).nullable().optional(),pushedAt:z2.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),description:z2.string().nullable().optional(),latestVersion:z2.string().nullable().optional(),latestVersionPublishedAt:z2.string().nullable().optional(),homepage:z2.string().nullable().optional(),repositoryUrl:z2.string().nullable().optional(),license:z2.string().nullable().optional(),downloadsLastMonth:z2.number().int().nullable().optional(),downloadsTotal:z2.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z2.object({osvId:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),publishedAt:z2.string().nullable().optional()});var packageSecurityOverviewSchema=z2.object({vulnerabilityCount:z2.number().int().nullable().optional(),hasCurrentVulnerabilities:z2.boolean().nullable().optional(),recentVulnerabilities:z2.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z2.object({version:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),body:z2.string().nullable().optional()});var packageSummaryResponseSchema=z2.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z2.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z2.object({message:z2.string(),extensions:z2.record(z2.string(),z2.unknown()).optional()});var graphQLResponseSchema=z2.object({data:z2.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
485
- query PackageSummary($registry: Registry!, $name: String!) {
486
- packageSummary(registry: $registry, name: $name) {
487
- package {
488
- name
489
- registry
490
- description
491
- latestVersion
492
- latestVersionPublishedAt
493
- homepage
494
- repositoryUrl
495
- license
496
- downloadsLastMonth
497
- downloadsTotal
498
- githubRepository {
499
- stargazersCount
500
- forksCount
501
- openIssuesCount
502
- archived
503
- language
504
- topics
505
- pushedAt
506
- }
507
- }
508
- security {
509
- vulnerabilityCount
510
- hasCurrentVulnerabilities
511
- recentVulnerabilities {
512
- osvId
513
- summary
514
- severityScore
515
- publishedAt
516
- }
517
- }
518
- latestChangelogs(limit: 3) {
519
- version
520
- publishedAt
521
- body
522
- }
523
- }
524
- }`;var packageVersionIdentitySchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),version:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),deprecated:z2.boolean().nullable().optional(),deprecationReason:z2.string().nullable().optional()});var vulnerabilityDetailSchema=z2.object({osvId:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),severityType:z2.string().nullable().optional(),affectedVersionRanges:z2.array(z2.string()).nullable().optional(),affectedVersionRangesCount:z2.number().int(),affectedVersionRangesTruncated:z2.boolean(),fixedInVersions:z2.array(z2.string()).nullable().optional(),publishedAt:z2.string().nullable().optional(),modifiedAt:z2.string().nullable().optional(),withdrawnAt:z2.string().nullable().optional(),aliases:z2.array(z2.string()).nullable().optional(),isMalicious:z2.boolean().nullable().optional(),affectsInspectedVersion:z2.boolean(),matchedAffectedVersionRanges:z2.array(z2.string()),duplicateIds:z2.array(z2.string())});var pageInfoSchema=z2.object({hasNextPage:z2.boolean(),endCursor:z2.string().nullable().optional(),totalCount:z2.number().int()});var vulnerabilityAdvisoryPageSchema=z2.object({entries:z2.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z2.object({affectedVulnerabilityCount:z2.number().int(),nonAffectingVulnerabilityCount:z2.number().int(),allVulnerabilityCount:z2.number().int(),currentVersionAffected:z2.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z2.array(z2.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z2.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z2.object({data:z2.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
525
- query PackageVulnerabilities(
526
- $registry: Registry!
527
- $name: String!
528
- $version: String
529
- $minSeverity: Float
530
- $includeWithdrawn: Boolean
531
- $scope: VulnerabilityScope = AFFECTED
532
- $after: String
533
- ) {
534
- packageVulnerabilities(
535
- registry: $registry
536
- name: $name
537
- version: $version
538
- minSeverity: $minSeverity
539
- includeWithdrawn: $includeWithdrawn
540
- ) {
541
- package {
542
- name
543
- registry
544
- version
545
- }
546
- security {
547
- affectedVulnerabilityCount
548
- nonAffectingVulnerabilityCount
549
- allVulnerabilityCount
550
- currentVersionAffected
551
- upgradePaths
552
- advisories(scope: $scope, first: 100, after: $after) {
553
- entries {
554
- osvId
555
- summary
556
- severityScore
557
- severityType
558
- affectedVersionRanges
559
- affectedVersionRangesCount
560
- affectedVersionRangesTruncated
561
- fixedInVersions
562
- publishedAt
563
- modifiedAt
564
- withdrawnAt
565
- aliases
566
- isMalicious
567
- affectsInspectedVersion
568
- matchedAffectedVersionRanges
569
- duplicateIds
570
- }
571
- pageInfo {
572
- hasNextPage
573
- endCursor
574
- totalCount
575
- }
576
- }
577
- }
578
- }
579
- }`;var directDependencySchema=z2.object({name:z2.string().nullable().optional(),versionConstraint:z2.string().nullable().optional(),type:z2.string().nullable().optional()});var dependencyGraphNodeSchema=z2.object({registry:z2.string(),name:z2.string(),version:z2.string().nullable().optional()});var dependencyGraphEdgeSchema=z2.object({fromIndex:z2.number().int().nullable().optional(),toIndex:z2.number().int(),constraint:z2.string().nullable().optional(),dependencyType:z2.string().nullable().optional()});var dependencyGraphSchema=z2.object({formatVersion:z2.number().int(),nodes:z2.array(dependencyGraphNodeSchema),edges:z2.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z2.object({totalVulnerabilities:z2.number().int(),critical:z2.number().int(),high:z2.number().int(),medium:z2.number().int(),low:z2.number().int(),unknown:z2.number().int()});var vulnerabilitySummaryDetailSchema=z2.object({osvId:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),summary:z2.string().nullable().optional(),severityScore:z2.number().nullable().optional(),severityType:z2.string().nullable().optional(),affectedVersionRanges:z2.array(z2.string()).nullable().optional(),fixedInVersions:z2.array(z2.string()).nullable().optional(),publishedAt:z2.string().nullable().optional(),modifiedAt:z2.string().nullable().optional(),withdrawnAt:z2.string().nullable().optional(),aliases:z2.array(z2.string()).nullable().optional(),isMalicious:z2.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z2.object({version:z2.string(),affectsResolvedVersion:z2.boolean(),matchedAffectedVersionRanges:z2.array(z2.string()),fixVersionsAboveResolved:z2.array(z2.string()),nearestFixedVersion:z2.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z2.object({registry:z2.string(),name:z2.string(),versions:z2.array(z2.string()),affectedCount:z2.number().int(),nonAffectingCount:z2.number().int(),totalCount:z2.number().int(),maxSeverityScore:z2.number().nullable().optional(),maxSeverityLabel:z2.string().nullable().optional(),advisoryIds:z2.array(z2.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z2.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z2.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z2.number().int(),affectedPackageCount:z2.number().int(),packages:z2.array(transitiveVulnerablePackageSchema),calculatedAt:z2.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z2.object({version:z2.string(),reason:z2.string().nullable().optional()});var deprecatedDependencySchema=z2.object({registry:z2.string(),name:z2.string(),versions:z2.array(z2.string()),reasons:z2.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z2.object({version:z2.string(),severity:z2.string()});var outdatedDependencySchema=z2.object({registry:z2.string(),name:z2.string(),latestVersion:z2.string().nullable().optional(),severity:z2.string(),versions:z2.array(outdatedDependencyVersionSchema),repositoryUrl:z2.string().nullable().optional()});var duplicateDependencySchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string(),versions:z2.array(z2.string())});var dependencyConflictEdgeSchema=z2.object({fromIndex:z2.number().int().nullable().optional(),toIndex:z2.number().int(),versionConstraint:z2.string(),dependencyType:z2.string()});var dependencyConflictSchema=z2.object({packageName:z2.string(),requiredVersions:z2.array(z2.string()),conflictingEdges:z2.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z2.object({registry:z2.string().nullable().optional(),name:z2.string(),versions:z2.array(z2.string()),requiredVersions:z2.array(z2.string()),conflictingEdges:z2.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z2.object({totalCount:z2.number().int(),deprecatedCount:z2.number().int(),outdatedCount:z2.number().int(),duplicateCount:z2.number().int(),conflictCount:z2.number().int(),deprecatedPackages:z2.array(deprecatedDependencySchema),outdatedPackages:z2.array(outdatedDependencySchema),duplicatePackages:z2.array(duplicateDependencySchema),conflicts:z2.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z2.object({cycleStart:z2.string(),circularPath:z2.array(z2.string()),displayChain:z2.string()});var environmentMarkerSchema=z2.object({type:z2.string().nullable().optional(),value:z2.string().nullable().optional(),raw:z2.string().nullable().optional()});var transitiveDependencySchema=z2.object({totalEdges:z2.number().int().nullable().optional(),uniquePackagesCount:z2.number().int().nullable().optional(),uniqueDependencies:z2.array(z2.string()).nullable().optional(),dependencyConflicts:z2.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z2.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z2.object({direct:z2.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z2.object({name:z2.string(),constraint:z2.string().nullable().optional()});var dependencyGroupSchema=z2.object({name:z2.string(),lifecycle:z2.string(),conditionType:z2.string(),conditionValue:z2.string().nullable().optional(),selectionMode:z2.string(),exclusiveGroup:z2.string().nullable().optional(),fallbackPriority:z2.number().int().nullable().optional(),compatibleWith:z2.array(z2.string()).nullable().optional(),defaultEnabled:z2.boolean().nullable().optional(),dependencies:z2.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z2.object({primaryGroup:z2.string().nullable().optional(),environmentMarkers:z2.array(environmentMarkerSchema).nullable().optional(),groups:z2.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z2.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z2.object({data:z2.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
580
- query PackageDependencies(
581
- $registry: Registry!
582
- $name: String!
583
- $version: String
584
- $includeTransitive: Boolean
585
- $maxDepth: Int
586
- $lifecycle: [String!]
587
- ) {
588
- packageDependencies(
589
- registry: $registry
590
- name: $name
591
- version: $version
592
- includeTransitive: $includeTransitive
593
- maxDepth: $maxDepth
594
- lifecycle: $lifecycle
595
- ) {
596
- package {
597
- name
598
- registry
599
- version
600
- }
601
- dependencies {
602
- # Backend-side summary block intentionally not selected — our
603
- # envelope computes runtime.count client-side from direct[].length
604
- # so the invariant runtime.count === runtime.items.length always
605
- # holds regardless of backend-side drift.
606
- direct {
607
- name
608
- versionConstraint
609
- type
610
- }
611
- transitive {
612
- totalEdges
613
- uniquePackagesCount
614
- uniqueDependencies
615
- dependencyConflicts {
616
- packageName
617
- requiredVersions
618
- conflictingEdges {
619
- fromIndex
620
- toIndex
621
- versionConstraint
622
- dependencyType
623
- }
624
- }
625
- circularDependencyCycles {
626
- cycleStart
627
- circularPath
628
- displayChain
629
- }
630
- dependencyGraph {
631
- formatVersion
632
- nodes {
633
- registry
634
- name
635
- version
636
- }
637
- edges {
638
- fromIndex
639
- toIndex
640
- constraint
641
- dependencyType
642
- }
643
- }
644
- }
645
- }
646
- dependencyGroups {
647
- primaryGroup
648
- environmentMarkers {
649
- type
650
- value
651
- raw
652
- }
653
- groups {
654
- name
655
- lifecycle
656
- conditionType
657
- conditionValue
658
- selectionMode
659
- exclusiveGroup
660
- fallbackPriority
661
- compatibleWith
662
- defaultEnabled
663
- dependencies {
664
- name
665
- constraint
666
- }
667
- }
668
- }
669
- }
670
- }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
671
- query PackageUpgradeDependencyProbe(
672
- $registry: Registry!
673
- $name: String!
674
- $version: String!
675
- $includeTransitiveRisk: Boolean!
676
- $includeTransitiveSecurity: Boolean!
677
- $includeDependencyIssues: Boolean!
678
- $includeDependencyChanges: Boolean!
679
- $includeGroups: Boolean!
680
- $lifecycle: [String!]
681
- $minSeverity: Float
682
- ) {
683
- packageDependencies(
684
- registry: $registry
685
- name: $name
686
- version: $version
687
- includeTransitive: $includeTransitiveRisk
688
- lifecycle: $lifecycle
689
- ) {
690
- package {
691
- name
692
- registry
693
- version
694
- publishedAt
695
- deprecated
696
- deprecationReason
697
- }
698
- dependencies {
699
- direct {
700
- name
701
- versionConstraint
702
- type
703
- }
704
- transitive @include(if: $includeTransitiveRisk) {
705
- dependencyGraph @include(if: $includeDependencyChanges) {
706
- formatVersion
707
- nodes {
708
- registry
709
- name
710
- version
711
- }
712
- edges {
713
- fromIndex
714
- toIndex
715
- constraint
716
- dependencyType
717
- }
718
- }
719
- vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
720
- affected {
721
- totalVulnerabilities
722
- critical
723
- high
724
- medium
725
- low
726
- unknown
727
- }
728
- nonAffecting {
729
- totalVulnerabilities
730
- critical
731
- high
732
- medium
733
- low
734
- unknown
735
- }
736
- combined {
737
- totalVulnerabilities
738
- critical
739
- high
740
- medium
741
- low
742
- unknown
743
- }
744
- totalPackagesAnalyzed
745
- affectedPackageCount
746
- calculatedAt
747
- packages {
748
- registry
749
- name
750
- versions
751
- affectedCount
752
- nonAffectingCount
753
- totalCount
754
- maxSeverityScore
755
- maxSeverityLabel
756
- advisoryIds(scope: AFFECTED)
757
- mostCritical {
758
- osvId
759
- registry
760
- packageName
761
- summary
762
- severityScore
763
- severityType
764
- affectedVersionRanges
765
- fixedInVersions
766
- publishedAt
767
- modifiedAt
768
- withdrawnAt
769
- aliases
770
- isMalicious
771
- }
772
- advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
773
- version
774
- affectsResolvedVersion
775
- matchedAffectedVersionRanges
776
- fixVersionsAboveResolved
777
- nearestFixedVersion
778
- advisory {
779
- osvId
780
- registry
781
- packageName
782
- summary
783
- severityScore
784
- severityType
785
- affectedVersionRanges
786
- fixedInVersions
787
- publishedAt
788
- modifiedAt
789
- withdrawnAt
790
- aliases
791
- isMalicious
792
- }
793
- }
794
- }
795
- }
796
- dependencyIssues @include(if: $includeDependencyIssues) {
797
- totalCount
798
- deprecatedCount
799
- outdatedCount
800
- duplicateCount
801
- conflictCount
802
- deprecatedPackages {
803
- registry
804
- name
805
- versions
806
- reasons {
807
- version
808
- reason
809
- }
810
- }
811
- outdatedPackages {
812
- registry
813
- name
814
- latestVersion
815
- severity
816
- versions {
817
- version
818
- severity
819
- }
820
- repositoryUrl
821
- }
822
- duplicatePackages {
823
- registry
824
- name
825
- versions
826
- }
827
- conflicts {
828
- registry
829
- name
830
- versions
831
- requiredVersions
832
- conflictingEdges {
833
- fromIndex
834
- toIndex
835
- versionConstraint
836
- dependencyType
837
- }
838
- }
839
- }
840
- }
841
- }
842
- dependencyGroups @include(if: $includeGroups) {
843
- primaryGroup
844
- environmentMarkers {
845
- type
846
- value
847
- raw
848
- }
849
- groups {
850
- name
851
- lifecycle
852
- conditionType
853
- conditionValue
854
- selectionMode
855
- exclusiveGroup
856
- fallbackPriority
857
- compatibleWith
858
- defaultEnabled
859
- dependencies {
860
- name
861
- constraint
862
- }
863
- }
864
- }
865
- }
866
- }`;var changelogPackageInfoSchema=z2.object({name:z2.string().nullable().optional(),registry:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),fromVersion:z2.string().nullable().optional(),toVersion:z2.string().nullable().optional(),limit:z2.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z2.object({version:z2.string().nullable().optional(),normalizedVersion:z2.string().nullable().optional(),body:z2.string().nullable().optional(),htmlUrl:z2.string().nullable().optional(),publishedAt:z2.string().nullable().optional(),metadata:z2.unknown().nullable().optional()});var changelogReportResponseSchema=z2.object({package:changelogPackageInfoSchema,source:z2.string().nullable().optional(),entries:z2.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z2.object({data:z2.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var PACKAGE_CHANGELOG_QUERY=`
867
- query PackageChangelog(
868
- $registry: Registry
869
- $name: String
870
- $repoUrl: String
871
- $gitRef: String
872
- $fromVersion: String
873
- $toVersion: String
874
- $limit: Int
875
- ) {
876
- packageChangelog(
877
- registry: $registry
878
- name: $name
879
- repoUrl: $repoUrl
880
- gitRef: $gitRef
881
- fromVersion: $fromVersion
882
- toVersion: $toVersion
883
- limit: $limit
884
- ) {
885
- package {
886
- name
887
- registry
888
- repoUrl
889
- fromVersion
890
- toVersion
891
- limit
892
- }
893
- source
894
- entries {
895
- version
896
- normalizedVersion
897
- body
898
- htmlUrl
899
- publishedAt
900
- metadata
901
- }
902
- }
903
- }`;var packageDocSourceKindSchema=z2.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z2.object({id:z2.string().nullable().optional(),title:z2.string().nullable().optional(),slug:z2.string().nullable().optional(),order:z2.number().int().nullable().optional(),linkName:z2.string().nullable().optional(),lastUpdatedAt:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z2.string().nullable().optional(),repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional()});var packageDocsPageInfoSchema=z2.object({hasNextPage:z2.boolean(),endCursor:z2.string().nullable().optional(),totalCount:z2.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),stale:z2.boolean().nullable().optional(),pages:z2.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z2.object({url:z2.string().nullable().optional(),label:z2.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z2.object({id:z2.string().nullable().optional(),title:z2.string().nullable().optional(),content:z2.string().nullable().optional(),contentFormat:z2.string().nullable().optional(),breadcrumbs:z2.array(z2.string()).nullable().optional(),linkName:z2.string().nullable().optional(),lastUpdatedAt:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z2.string().nullable().optional(),gitRef:z2.string().nullable().optional(),requestedRef:z2.string().nullable().optional(),filePath:z2.string().nullable().optional(),baseUrl:z2.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z2.object({registry:z2.string().nullable().optional(),packageName:z2.string().nullable().optional(),version:z2.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z2.object({data:z2.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z2.object({data:z2.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z2.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
904
- query ListPackageDocs(
905
- $registry: Registry!
906
- $packageName: String!
907
- $version: String
908
- $limit: Int
909
- $after: String
910
- ) {
911
- listPackageDocs(
912
- registry: $registry
913
- packageName: $packageName
914
- version: $version
915
- limit: $limit
916
- after: $after
917
- ) {
918
- registry
919
- packageName
920
- version
921
- stale
922
- pages {
923
- id
924
- title
925
- slug
926
- order
927
- linkName
928
- lastUpdatedAt
929
- sourceKind
930
- sourceUrl
931
- repoUrl
932
- gitRef
933
- requestedRef
934
- filePath
935
- }
936
- pageInfo {
937
- hasNextPage
938
- endCursor
939
- totalCount
940
- }
941
- }
942
- }`;var READ_PACKAGE_DOC_QUERY=`
943
- query ReadPackageDoc($pageId: String!) {
944
- getDocPage(pageId: $pageId) {
945
- registry
946
- packageName
947
- version
948
- sourceKind
949
- page {
950
- id
951
- title
952
- content
953
- contentFormat
954
- breadcrumbs
955
- linkName
956
- lastUpdatedAt
957
- sourceKind
958
- source {
959
- url
960
- label
961
- }
962
- repoUrl
963
- gitRef
964
- requestedRef
965
- filePath
966
- baseUrl
967
- }
968
- }
969
- }`;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 withTelemetrySpan("pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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){const status=response.status;const detail=parseDetail3(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)}createTransportError(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})}createGraphQLError(errors){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;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=pkg-graphql to inspect GraphQL details during local development.";debugLog("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message});return new PackageIntelligenceBackendError(isDebugAreaEnabled("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:break}return new PackageIntelligenceBackendError(message,undefined,code,retryable)}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 withTelemetrySpan("pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async packageDependencies(params){return withTelemetrySpan("pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withTelemetrySpan("pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}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})}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,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}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 version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version)=>({version:version.version,severity:version.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withTelemetrySpan("pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseChangelogReport(data,params)}normaliseChangelogReport(data,params){const source=data.source?.trim()?data.source:undefined;const rawEntries=data.entries??[];if(!source&&rawEntries.length===0){const target=params.repoUrl??(params.registry&&params.packageName?`${params.registry.toLowerCase()}:${params.packageName}`:"package");throw new PackageIntelligenceChangelogSourceNotFoundError(`No changelog source available for ${target} (tried GitHub Releases, CHANGELOG.md, and HexDocs).`)}const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined,metadata:entry.metadata??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 withTelemetrySpan("pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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 withTelemetrySpan("pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,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})}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 parseDetail3(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){return this.withTokenRefresh((service)=>service.search(params))}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){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:(error)=>error instanceof AuthenticationError,executeWithToken:async(token)=>{const service=this.serviceFactory?this.serviceFactory(this.apiUrl,token):new GitHitsServiceImpl(this.apiUrl,token,undefined,undefined,this.runtime);return operation(service)}})}}function createStaticTokenProvider(token){return{getToken:async()=>token,forceRefresh:async()=>{return}}}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_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 value in registryMap}import{createHash,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 createHash("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{}}}import{createHash as createHash2,randomBytes}from"node:crypto";export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,debugLog,withTelemetrySpan,startTelemetrySpan,endTelemetrySpan,flushTelemetry,AuthenticationError,GitHitsServiceImpl,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,CodeNavigationServiceImpl,DEFAULT_MCP_URL,DEFAULT_API_URL,DEFAULT_CODE_NAV_URL,getMcpUrl,getApiUrl,getCodeNavigationUrl,getEnvApiToken,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceChangelogSourceNotFoundError,PackageIntelligenceServiceImpl,RefreshingGitHitsService,createStaticTokenProvider,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST,toPkgseerRegistry,toPkgseerRegistryLowercase,isKnownPkgseerRegistryArg,createClientHeaderBuilder};