@githits/mcp 0.25.1 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1528 @@
1
+ var DEFAULT_FETCH_TIMEOUT_MS=120000;class FetchTimeoutError2 extends Error{timeoutMs;constructor(timeoutMs,options){super(`Request timed out after ${timeoutMs}ms.`,options);this.name="FetchTimeoutError";this.timeoutMs=timeoutMs}}async function fetchWithTimeout(input,init={},options={}){const timeoutMs=options.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const timeoutSignal=AbortSignal.timeout(timeoutMs);const signal=init.signal?AbortSignal.any([init.signal,timeoutSignal]):timeoutSignal;const fetchFn=options.fetchFn??globalThis.fetch;let timeoutId;const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(new FetchTimeoutError2(timeoutMs))},timeoutMs)});try{return await Promise.race([fetchFn(input,{...init,signal}),timeout])}catch(cause){if(cause instanceof FetchTimeoutError2)throw cause;if(timeoutSignal.aborted&&!init.signal?.aborted){throw new FetchTimeoutError2(timeoutMs,{cause})}throw cause}finally{if(timeoutId)clearTimeout(timeoutId)}}function isFetchTimeoutError(error){return error instanceof FetchTimeoutError2}import{z}from"zod";var DEFAULT_MCP_URL2="https://mcp.githits.com";var DEFAULT_API_URL2="https://api.githits.com";var DEFAULT_CODE_NAV_URL2="https://oss.githits.dev";var ENVIRONMENT_SCHEMA=z.enum(["prod","dev"]);var SERVICE_URL_DEFAULTS={prod:{mcpUrl:DEFAULT_MCP_URL2,apiUrl:DEFAULT_API_URL2,codeNavigationUrl:DEFAULT_CODE_NAV_URL2},dev:{mcpUrl:"https://mcp-dev.githits.com",apiUrl:"https://api-dev.githits.com",codeNavigationUrl:"https://oss-dev.githits.dev"}};class ServiceUrlConfigError extends Error{constructor(message){super(message);this.name="ServiceUrlConfigError"}}function getGitHitsEnvironment(env=process.env){const value=env.GITHITS_ENV;const parsed=ENVIRONMENT_SCHEMA.safeParse(value===undefined||value.trim()===""?"prod":value);if(!parsed.success){throw new ServiceUrlConfigError("Invalid GITHITS_ENV: use prod or dev.")}return parsed.data}function getServiceUrlDefaults(environment){return SERVICE_URL_DEFAULTS[environment]}function getMcpUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_MCP_URL",defaults.mcpUrl,env)}function getApiUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_API_URL",defaults.apiUrl,env)}function getCodeNavigationUrl2(env=process.env){const defaults=getServiceUrlDefaults(getGitHitsEnvironment(env));return resolveServiceUrl("GITHITS_CODE_NAV_URL",defaults.codeNavigationUrl,env)}function validateServiceUrl(value,source){let parsed;try{parsed=new URL(value)}catch{throw new ServiceUrlConfigError(`Invalid ${source}: expected an HTTPS URL or an HTTP loopback URL.`)}if(parsed.protocol==="https:")return value;const hostname=parsed.hostname.replace(/^\[|\]$/g,"");const isLoopback=hostname==="localhost"||hostname==="127.0.0.1"||hostname==="::1";if(parsed.protocol==="http:"&&isLoopback)return value;throw new ServiceUrlConfigError(`Invalid ${source}: use HTTPS. Plain HTTP is allowed only for localhost, 127.0.0.1, or [::1].`)}function resolveServiceUrl(envName,defaultUrl,env){const override=env[envName];return override===undefined?defaultUrl:validateServiceUrl(override,envName)}function getEnvApiToken2(){return process.env.GITHITS_API_TOKEN}var TERMS_ACCEPTANCE_REQUIRED_CODE="TERMS_ACCEPTANCE_REQUIRED";var TERMS_URL="https://githits.com/legal/terms-of-service/";var TERMS_ACCEPTANCE_URL="https://app.githits.com/settings/privacy";class TermsAcceptanceRequiredError2 extends Error{code=TERMS_ACCEPTANCE_REQUIRED_CODE;termsUrl;acceptanceUrl;constructor(remediation={}){super("Terms acceptance required.");this.name="TermsAcceptanceRequiredError";this.termsUrl=remediation.termsUrl??TERMS_URL;this.acceptanceUrl=remediation.acceptanceUrl??TERMS_ACCEPTANCE_URL}}function createTermsAcceptanceError(payload){const record=parseErrorRecord(payload);if(!record)return;const contract=record.code===TERMS_ACCEPTANCE_REQUIRED_CODE?record:firstGraphQLErrorExtensions(record);if(contract?.code!==TERMS_ACCEPTANCE_REQUIRED_CODE)return;return new TermsAcceptanceRequiredError2({termsUrl:stringField(contract,"terms_url"),acceptanceUrl:stringField(contract,"acceptance_url")})}function throwIfTermsAcceptanceRequired(payload){const error=createTermsAcceptanceError(payload);if(error)throw error}function parseErrorRecord(payload){if(typeof payload==="string"){try{return parseErrorRecord(JSON.parse(payload))}catch{return}}return payload&&typeof payload==="object"?payload:undefined}function firstGraphQLErrorExtensions(record){const firstError=Array.isArray(record.errors)?record.errors[0]:undefined;if(!firstError||typeof firstError!=="object")return;const extensions=firstError.extensions;return extensions&&typeof extensions==="object"?extensions:undefined}function stringField(record,field){return typeof record[field]==="string"?record[field]:undefined}var PKGSEER_REGISTRY_ARGS=["npm","pypi","hex","crates","nuget","maven","zig","vcpkg","packagist","rubygems","go","swift"];var registryMap={npm:"NPM",pypi:"PYPI",hex:"HEX",crates:"CRATES",nuget:"NUGET",maven:"MAVEN",zig:"ZIG",vcpkg:"VCPKG",packagist:"PACKAGIST",rubygems:"RUBYGEMS",go:"GO",swift:"SWIFT"};var PKGSEER_REGISTRY_VALUES=Object.values(registryMap);var PKGSEER_REGISTRY_LIST2=PKGSEER_REGISTRY_ARGS.join(", ");function toPkgseerRegistry2(registry){return registryMap[registry]}function toPkgseerRegistryLowercase2(registry){for(const[lower,upper]of Object.entries(registryMap)){if(upper===registry)return lower}throw new Error(`Unknown registry value: ${String(registry)} (schema drift?)`)}function isKnownPkgseerRegistryArg(value){return Object.hasOwn(registryMap,value)}var AUTHENTICATION_REQUIRED_MESSAGE="Authentication required.";var LOCAL_AUTHENTICATION_MISSING_MESSAGE="No local GitHits authentication token found.";var SERVER_AUTHENTICATION_REJECTED_MESSAGE="GitHits could not accept the authentication token.";class AuthenticationError2 extends Error{source;constructor(message=AUTHENTICATION_REQUIRED_MESSAGE,source="local"){super(message);this.name="AuthenticationError";this.source=source}}class ApiRateLimitError2 extends Error{status=429;retryAfterSeconds;constructor(message="Request rate limited.",retryAfterSeconds){super(message);this.name="ApiRateLimitError";this.retryAfterSeconds=retryAfterSeconds}}var MAX_ERROR_DETAIL_LENGTH=500;function parseHttpErrorDetail(body,fields){if(!body)return;let parsed;try{parsed=JSON.parse(body)}catch{return}if(!isRecord(parsed))return;for(const field of fields){const value=parsed[field];if(typeof value!=="string")continue;const normalized=normalizeSingleLineText(value);if(!normalized)continue;if(normalized.length<=MAX_ERROR_DETAIL_LENGTH)return normalized;return`${normalized.slice(0,MAX_ERROR_DETAIL_LENGTH-3)}...`}return}function normalizeSingleLineText(value){const withoutControlCharacters=Array.from(value,(character)=>{const codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127?" ":character}).join("");return withoutControlCharacters.replace(/\s+/g," ").trim()}function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function withServiceDiagnostics(diagnostics,name,operation){return diagnostics?diagnostics.withOperation(name,operation):operation()}var DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS=240000;function isTokenRefreshableError(error){return error instanceof AuthenticationError2||error instanceof TermsAcceptanceRequiredError2}function parseRetryAfterSeconds(value,nowMs){const normalized=value?.trim();if(!normalized)return;if(/^\d+$/.test(normalized)){const delaySeconds=Number(normalized);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}if(/^[+-]?\d+(?:\.\d+)?$/.test(normalized))return;const isHttpDate=/^[A-Z][a-z]{2}, \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]+, \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT$/.test(normalized)||/^[A-Z][a-z]{2} [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(normalized);if(!isHttpDate)return;const retryAtMs=Date.parse(normalized);if(!Number.isFinite(retryAtMs))return;const delayMs=retryAtMs-nowMs;if(delayMs<0)return;const delaySeconds=Math.ceil(delayMs/1000);return Number.isSafeInteger(delaySeconds)?delaySeconds:undefined}class GitHitsServiceImpl2{apiUrl;token;fetchFn;fetchTimeoutMs;runtime;constructor(apiUrl,token,fetchFn,fetchTimeoutMs=undefined,runtime={}){this.apiUrl=apiUrl;this.token=token;this.fetchFn=fetchFn;this.fetchTimeoutMs=fetchTimeoutMs;this.runtime=runtime}async search(params,options){options?.signal?.throwIfAborted();return withServiceDiagnostics(this.runtime.diagnostics,"githits.search.request",async()=>{const response=await this.request("/search",{method:"POST",headers:this.headers(),body:JSON.stringify({query:params.query,language:params.language,license_mode:params.licenseMode??"strict",include_explanation:params.includeExplanation??false}),...options?.signal?{signal:options.signal}:{}},this.runtime.exampleRequestTimeoutMs??DEFAULT_EXAMPLE_REQUEST_TIMEOUT_MS);if(!response.ok){throw await this.createError(response)}return response.text()})}headers(){return{...this.runtime.clientHeaders?.(),Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":this.runtime.userAgent??"githits-cli"}}fetchOptions(defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){return{fetchFn:this.fetchFn,timeoutMs:this.fetchTimeoutMs??defaultTimeoutMs}}async request(path,init,defaultTimeoutMs=DEFAULT_FETCH_TIMEOUT_MS){const apiUrl=validateServiceUrl(this.apiUrl,"GITHITS_API_URL");const fetchOptions=this.fetchOptions(defaultTimeoutMs);try{return await fetchWithTimeout(`${apiUrl.replace(/\/+$/,"")}${path}`,init,fetchOptions)}catch(cause){if(isCallerAbort(cause,init.signal))throw cause;if(isFetchTimeoutError(cause)||isAbortError(cause)){throw new GitHitsRequestTimeoutError(fetchOptions.timeoutMs,cause)}if(cause instanceof TypeError){throw new Error("Could not connect to GitHits. Check your connection and GITHITS_API_URL, then try again.",{cause})}throw cause}}async createError(response){const status=response.status;const body=await response.text().catch(()=>"");const detail=parseHttpErrorDetail(body,["detail"]);throwIfTermsAcceptanceRequired(body);switch(status){case 401:return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case 403:return new Error("Access denied.");case 404:return new Error(detail||"Resource not found.");case 429:return new ApiRateLimitError2(undefined,parseRetryAfterSeconds(response.headers.get("Retry-After"),Date.now()));default:{if(status>=500){return new Error(`Server error (${status}). Try again shortly.${detail?` ${detail}`:""}`)}return new Error(`Request failed with status ${status}.${detail?` ${detail}`:""}`)}}}}class GitHitsRequestTimeoutError extends FetchTimeoutError2{constructor(timeoutMs,cause){super(timeoutMs,{cause});this.name="GitHitsRequestTimeoutError";this.message="Request to GitHits timed out. Try again."}}function isAbortError(error){return error instanceof Error&&error.name==="AbortError"}function isCallerAbort(error,signal){return Boolean(signal?.aborted&&(error===signal.reason||isAbortError(error)))}import{z as z4}from"zod";function parseAvailableArtifacts(raw){if(!Array.isArray(raw))return;const parsed=[];for(const item of raw){if(item&&typeof item==="object"&&"ref"in item){const entry=item;if(typeof entry.ref==="string"){parsed.push({ref:entry.ref,version:typeof entry.version==="string"?entry.version:undefined})}}}return parsed.length>0?parsed:undefined}class PkgseerTransportError extends Error{constructor(message,options){super(message,options);this.name="PkgseerTransportError"}}function baseUrl(endpointUrl){return endpointUrl.replace(/\/+$/,"")}async function postPkgseerGraphql(request){const userAgent=request.userAgent??"githits-cli";const timeoutMs=request.timeoutMs??DEFAULT_FETCH_TIMEOUT_MS;const endpointUrl=validateServiceUrl(request.endpointUrl,"package/source service URL");const clientHeaders=request.clientHeaders?.();let response;try{response=await fetchWithTimeout(`${baseUrl(endpointUrl)}/api/graphql`,{method:"POST",signal:request.signal,headers:{...clientHeaders,Authorization:`Bearer ${request.token}`,"Content-Type":"application/json","User-Agent":userAgent},body:JSON.stringify({query:request.query,variables:request.variables})},{fetchFn:request.fetchFn,timeoutMs})}catch(cause){request.signal?.throwIfAborted();if(request.diagnostics?.isEnabled("pkg-graphql")){request.diagnostics.debug("pkg-graphql",{event:"transport-error",errorName:cause instanceof Error?cause.name:typeof cause,hasCause:true})}throw new PkgseerTransportError("Network request failed before a response was received. Caller should re-wrap with a domain-specific message.",{cause})}const responseBody=await response.text().catch(()=>"");request.signal?.throwIfAborted();const parsedBody=parseJsonOrNull(responseBody);throwIfTermsAcceptanceRequired(parsedBody);return{status:response.status,responseBody,parsedBody}}function parseJsonOrNull(body){if(!body)return null;try{return JSON.parse(body)}catch{return null}}var 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 AuthenticationError2(LOCAL_AUTHENTICATION_MISSING_MESSAGE,"local")}try{return await options.executeWithToken(token)}catch(error){if(token.startsWith("ghi-")||!options.shouldRefresh(error)){throw error}const refreshedToken=await options.forceRefresh();if(!refreshedToken){throw error}return options.executeWithToken(refreshedToken)}}import{z as z2}from"zod";var INDEXING_DURATION_ESTIMATE_FIELDS=`
2
+ lowerSeconds
3
+ upperSeconds
4
+ elapsedSeconds
5
+ sampleCount
6
+ source`;var INDEXING_DURATION_ESTIMATE_SELECTION=`
7
+ indexingEstimate {
8
+ ${INDEXING_DURATION_ESTIMATE_FIELDS}
9
+ }`;var INDEXING_ESTIMATES_SELECTION=`
10
+ indexingEstimates {
11
+ kind
12
+ targets
13
+ repositoryUrl
14
+ commitSha
15
+ estimate {
16
+ ${INDEXING_DURATION_ESTIMATE_FIELDS}
17
+ }
18
+ unavailableReason
19
+ }`;var indexingDurationEstimateSchema=z2.object({lowerSeconds:z2.number().int().nullable().optional(),upperSeconds:z2.number().int().nullable().optional(),elapsedSeconds:z2.number().int().nullable().optional(),sampleCount:z2.number().int().nullable().optional(),source:z2.string().nullable().optional()}).nullable().optional();var discoveryIndexingEstimateSchema=z2.object({kind:z2.enum(["REPOSITORY","DOCUMENTATION"]),targets:z2.array(z2.string()),repositoryUrl:z2.string().nullish(),commitSha:z2.string().nullish(),estimate:indexingDurationEstimateSchema,unavailableReason:z2.enum(["NO_HISTORY","UNSUPPORTED_WORK"]).nullish()});function normaliseIndexingDurationEstimate(estimate){if(!estimate)return;const out={};if(typeof estimate.lowerSeconds==="number"){out.lowerSeconds=estimate.lowerSeconds}if(typeof estimate.upperSeconds==="number"){out.upperSeconds=estimate.upperSeconds}if(typeof estimate.elapsedSeconds==="number"){out.elapsedSeconds=estimate.elapsedSeconds}if(typeof estimate.sampleCount==="number"){out.sampleCount=estimate.sampleCount}if(typeof estimate.source==="string")out.source=estimate.source;return Object.keys(out).length>0?out:undefined}var indexingEstimatesSchema=z2.array(discoveryIndexingEstimateSchema).transform((entries)=>entries.map((entry)=>({kind:entry.kind,targets:[...entry.targets],repositoryUrl:entry.repositoryUrl??undefined,commitSha:entry.commitSha??undefined,unavailableReason:entry.unavailableReason??undefined,estimate:normaliseIndexingDurationEstimate(entry.estimate)})));function parseIndexingDurationEstimate(extensions){const raw=extensions?.estimated_indexing_duration??extensions?.estimatedIndexingDuration??extensions?.indexing_estimate??extensions?.indexingEstimate;const parsed=indexingDurationEstimateSchema.safeParse(normaliseRawIndexingDurationEstimate(raw));if(!parsed.success)return;return normaliseIndexingDurationEstimate(parsed.data)}function normaliseRawIndexingDurationEstimate(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return raw;const record=raw;return{lowerSeconds:record.lowerSeconds??record.lower_seconds,upperSeconds:record.upperSeconds??record.upper_seconds,elapsedSeconds:record.elapsedSeconds??record.elapsed_seconds,sampleCount:record.sampleCount??record.sample_count,source:record.source}}import{z as z3}from"zod";var READ_TARGET_SELECTION="target path selector startLine endLine";var positiveLineSchema=z3.number().int().positive();var readTargetInputSchema=z3.object({target:z3.string().min(1),path:z3.string().nullable().optional(),selector:z3.string().nullable().optional(),startLine:positiveLineSchema.nullable().optional(),endLine:positiveLineSchema.nullable().optional()}).superRefine((value,context)=>{if(value.startLine!=null&&value.endLine!=null&&value.endLine<value.startLine){context.addIssue({code:z3.ZodIssueCode.custom,path:["endLine"],message:"endLine must be greater than or equal to startLine"})}});function normaliseReadTarget(value){return{target:value.target,...value.path==null?{}:{path:value.path},...value.selector==null?{}:{selector:value.selector},...value.startLine==null?{}:{startLine:value.startLine},...value.endLine==null?{}:{endLine:value.endLine}}}var readTargetSchema=readTargetInputSchema.transform(normaliseReadTarget);var selectedReadTargetSchema=readTargetInputSchema.safeExtend({path:z3.string().nullable(),selector:z3.string().nullable(),startLine:positiveLineSchema.nullable(),endLine:positiveLineSchema.nullable()}).transform(normaliseReadTarget);class CodeNavigationAccessError extends Error{constructor(message){super(message);this.name="CodeNavigationAccessError"}}class CodeNavigationGraphQLError extends Error{code;constructor(message,code){super(message);this.code=code;this.name="CodeNavigationGraphQLError"}}class CodeNavigationIndexingError extends Error{indexingRef;availableVersions;availableRefs;targetResolution;indexingEstimate;hint;indexingEstimates;repoUrl;constructor(message,indexingRef,availableVersions,availableRefs,targetResolution=undefined,indexingEstimate=undefined,hint=undefined,indexingEstimates=undefined,repoUrl=undefined){super(message);this.indexingRef=indexingRef;this.availableVersions=availableVersions;this.availableRefs=availableRefs;this.targetResolution=targetResolution;this.indexingEstimate=indexingEstimate;this.hint=hint;this.indexingEstimates=indexingEstimates;this.repoUrl=repoUrl;this.name="CodeNavigationIndexingError"}}class CodeNavigationUnresolvableError extends Error{constructor(message){super(message);this.name="CodeNavigationUnresolvableError"}}class MalformedCodeNavigationResponseError extends Error{constructor(message){super(message);this.name="MalformedCodeNavigationResponseError"}}class CodeDiffError2 extends Error{details;partial;constructor(message,details=undefined,partial=undefined){super(message);this.details=details;this.partial=partial;this.name="CodeDiffError"}}class CodeNavigationTargetNotFoundError extends Error{availableVersions;repoUrl;requestedRef;metadata;constructor(message,availableVersions,repoUrl,requestedRef,metadata=undefined){super(message);this.availableVersions=availableVersions;this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.metadata=metadata;this.name="CodeNavigationTargetNotFoundError"}}class CodeNavigationFileNotFoundError extends Error{filePath;constructor(message,filePath){super(message);this.filePath=filePath;this.name="CodeNavigationFileNotFoundError"}}class CodeNavigationVersionNotFoundError extends Error{packageName;requestedVersion;latestIndexed;availableVersions;metadata;constructor(message,packageName,requestedVersion,latestIndexed,availableVersions,metadata=undefined){super(message);this.packageName=packageName;this.requestedVersion=requestedVersion;this.latestIndexed=latestIndexed;this.availableVersions=availableVersions;this.metadata=metadata;this.name="CodeNavigationVersionNotFoundError"}}class CodeNavigationRefNotFoundError extends Error{repoUrl;requestedRef;availableRefs;suggestedRefs;metadata;constructor(message,repoUrl,requestedRef,availableRefs,suggestedRefs,metadata=undefined){super(message);this.repoUrl=repoUrl;this.requestedRef=requestedRef;this.availableRefs=availableRefs;this.suggestedRefs=suggestedRefs;this.metadata=metadata;this.name="CodeNavigationRefNotFoundError"}}class CodeNavigationValidationError extends Error{constructor(message){super(message);this.name="CodeNavigationValidationError"}}class CodeNavigationFeatureFlagRequiredError extends Error{constructor(message){super(message);this.name="CodeNavigationFeatureFlagRequiredError"}}class CodeNavigationNetworkError extends Error{constructor(message,options){super(message,options);this.name="CodeNavigationNetworkError"}}class CodeNavigationBackendError extends Error{status;graphqlCode;retryable;metadata;constructor(message,status,graphqlCode,retryable,metadata=undefined){super(message);this.status=status;this.graphqlCode=graphqlCode;this.retryable=retryable;this.metadata=metadata;this.name="CodeNavigationBackendError"}}var TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION=`
20
+ availableRefs {
21
+ version
22
+ ref
23
+ }`;var TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION=`
24
+ suggestedRefs {
25
+ version
26
+ ref
27
+ }`;var DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION=`
28
+ suggestedRefs {
29
+ version
30
+ ref
31
+ }`;var DOC_COVERAGE_SELECTION=`
32
+ coverage {
33
+ coverageState
34
+ coverageReason
35
+ pagesCrawled
36
+ frontierRemaining
37
+ artifactOverflowPageCount
38
+ estimatedTotalPages
39
+ note
40
+ }`;var DOCUMENTATION_CONTRIBUTORS_SELECTION=`
41
+ contributors {
42
+ kind
43
+ state
44
+ freshness
45
+ resultCount
46
+ repositoryUrl
47
+ commitSha
48
+ siteKey
49
+ siteUrl
50
+ ${DOC_COVERAGE_SELECTION}
51
+ }`;var TARGET_RESOLUTION_SELECTION=`
52
+ targetResolution {
53
+ requested {
54
+ kind
55
+ registry
56
+ packageName
57
+ version
58
+ repoUrl
59
+ gitRef
60
+ commitSha
61
+ }
62
+ resolvedRequested {
63
+ kind
64
+ registry
65
+ packageName
66
+ version
67
+ repoUrl
68
+ gitRef
69
+ commitSha
70
+ committedAt
71
+ }
72
+ served {
73
+ kind
74
+ registry
75
+ packageName
76
+ version
77
+ repoUrl
78
+ gitRef
79
+ commitSha
80
+ committedAt
81
+ }
82
+ freshness
83
+ freshnessReason
84
+ indexingRef
85
+ availableVersions {
86
+ version
87
+ ref
88
+ }
89
+ ${TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION}
90
+ ${TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION}
91
+ }`;var CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION=`
92
+ availableVersions {
93
+ version
94
+ ref
95
+ }`;var DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION=`
96
+ availableVersions {
97
+ version
98
+ ref
99
+ }
100
+ availableRefs {
101
+ version
102
+ ref
103
+ }
104
+ ${DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION}`;var UNIFIED_SEARCH_LOCATOR_SELECTION=`
105
+ registry
106
+ packageName
107
+ version
108
+ pageId
109
+ docsReadTarget
110
+ sourceKind
111
+ sourceUrl
112
+ repoUrl
113
+ gitRef
114
+ commitSha
115
+ requestedRef
116
+ filePath
117
+ repositoryFilePath
118
+ startLine
119
+ endLine
120
+ evidenceRange {
121
+ startLine
122
+ endLine
123
+ matchLine
124
+ rangeKind
125
+ matchSpansTruncated
126
+ }
127
+ indexedRange {
128
+ startLine
129
+ endLine
130
+ }
131
+ symbolContext {
132
+ name
133
+ qualifiedPath
134
+ kind
135
+ relation
136
+ definitionRange {
137
+ filePath
138
+ repositoryFilePath
139
+ startLine
140
+ endLine
141
+ }
142
+ }
143
+ fileContentHash
144
+ symbolRef
145
+ qualifiedPath
146
+ kind
147
+ category
148
+ language`;var UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION=`
149
+ repositoryEvidence {
150
+ bm25MatchFields
151
+ semanticContext {
152
+ scopes {
153
+ name
154
+ qualifiedPath
155
+ kind
156
+ parentQualifiedPath
157
+ declarationStartLine
158
+ declarationEndLine
159
+ parameterNames
160
+ returnType
161
+ symbolRef
162
+ }
163
+ scopeChainTruncated
164
+ preferredRead {
165
+ targetLabel
166
+ registry
167
+ packageName
168
+ version
169
+ repoUrl
170
+ gitRef
171
+ commitSha
172
+ requestedRef
173
+ filePath
174
+ repositoryFilePath
175
+ startLine
176
+ endLine
177
+ }
178
+ }
179
+ matchedSource {
180
+ startLine
181
+ endLine
182
+ matchLine
183
+ rangeKind
184
+ matchSpansTruncated
185
+ linesOmittedBefore
186
+ linesOmittedAfter
187
+ lines {
188
+ lineNumber
189
+ text
190
+ highlights
191
+ prefixTruncated
192
+ suffixTruncated
193
+ }
194
+ }
195
+ }`;var UNIFIED_SEARCH_QUERY=`
196
+ query UnifiedSearch(
197
+ $targets: [SearchPackageInput!]!
198
+ $query: String!
199
+ $sources: [DiscoverySearchSource!]
200
+ $filters: DiscoverySearchFiltersInput
201
+ $allowPartialResults: Boolean
202
+ $limit: Int
203
+ $offset: Int
204
+ $waitTimeoutMs: Int
205
+ ) {
206
+ search(
207
+ targets: $targets
208
+ query: $query
209
+ sources: $sources
210
+ filters: $filters
211
+ allowPartialResults: $allowPartialResults
212
+ limit: $limit
213
+ offset: $offset
214
+ waitTimeoutMs: $waitTimeoutMs
215
+ ) {
216
+ completed
217
+ searchRef
218
+ result {
219
+ query
220
+ queryWarnings
221
+ sources
222
+ results {
223
+ readTarget { ${READ_TARGET_SELECTION} }
224
+ id
225
+ resultType
226
+ targetLabel
227
+ requestedTargetLabel
228
+ freshTargetLabel
229
+ servedTargetLabel
230
+ freshness
231
+ title
232
+ score
233
+ highlights {
234
+ title
235
+ }
236
+ documentationPreview {
237
+ text
238
+ highlights
239
+ }
240
+ ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
241
+ locator {
242
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
243
+ }
244
+ }
245
+ page {
246
+ offset
247
+ limit
248
+ returned
249
+ hasMore
250
+ }
251
+ partialResults
252
+ evidenceNotice
253
+ sourceStatus {
254
+ source
255
+ targetLabel
256
+ requestedTargetLabel
257
+ freshTargetLabel
258
+ servedTargetLabel
259
+ ${TARGET_RESOLUTION_SELECTION}
260
+ indexingStatus
261
+ codeIndexState
262
+ resultCount
263
+ appliedFilters
264
+ ignoredFilters
265
+ incompatibleFilters
266
+ appliedQueryFeatures
267
+ ignoredQueryFeatures
268
+ incompatibleQueryFeatures
269
+ suggestedSiteTargets
270
+ suggestedSiteTargetsTruncated
271
+ note
272
+ ${DOC_COVERAGE_SELECTION}
273
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
274
+ }
275
+ }
276
+ progress {
277
+ searchRef
278
+ status
279
+ targetsTotal
280
+ targetsReady
281
+ elapsedMs
282
+ ${INDEXING_ESTIMATES_SELECTION}
283
+ query
284
+ queryWarnings
285
+ sources
286
+ requestedSources
287
+ targetMode
288
+ requestedTargets {
289
+ registry
290
+ name
291
+ version
292
+ repoUrl
293
+ gitRef
294
+ site
295
+ }
296
+ filters {
297
+ fileIntent
298
+ kind
299
+ category
300
+ publicOnly
301
+ pathPrefix
302
+ }
303
+ limit
304
+ offset
305
+ targets {
306
+ requested
307
+ resolvedRequested
308
+ served
309
+ freshness
310
+ indexingRef
311
+ requestedRefKind
312
+ ${TARGET_RESOLUTION_SELECTION}
313
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
314
+ ${DOC_COVERAGE_SELECTION}
315
+ }
316
+ expiresAt
317
+ }
318
+ }
319
+ }`;var UNIFIED_SEARCH_STATUS_QUERY=`
320
+ query UnifiedSearchStatus($searchRef: String!, $includeResults: Boolean!, $waitTimeoutMs: Int) {
321
+ discoverySearchProgress(searchRef: $searchRef, includeResults: $includeResults, waitTimeoutMs: $waitTimeoutMs) {
322
+ searchRef
323
+ status
324
+ targetsTotal
325
+ targetsReady
326
+ elapsedMs
327
+ ${INDEXING_ESTIMATES_SELECTION}
328
+ query
329
+ queryWarnings
330
+ sources
331
+ requestedSources
332
+ targetMode
333
+ requestedTargets {
334
+ registry
335
+ name
336
+ version
337
+ repoUrl
338
+ gitRef
339
+ site
340
+ }
341
+ filters {
342
+ fileIntent
343
+ kind
344
+ category
345
+ publicOnly
346
+ pathPrefix
347
+ }
348
+ limit
349
+ offset
350
+ targets {
351
+ requested
352
+ resolvedRequested
353
+ served
354
+ freshness
355
+ indexingRef
356
+ requestedRefKind
357
+ ${TARGET_RESOLUTION_SELECTION}
358
+ ${DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION}
359
+ ${DOC_COVERAGE_SELECTION}
360
+ }
361
+ expiresAt
362
+ results {
363
+ query
364
+ queryWarnings
365
+ sources
366
+ results {
367
+ readTarget { ${READ_TARGET_SELECTION} }
368
+ id
369
+ resultType
370
+ targetLabel
371
+ requestedTargetLabel
372
+ freshTargetLabel
373
+ servedTargetLabel
374
+ freshness
375
+ title
376
+ score
377
+ highlights {
378
+ title
379
+ }
380
+ documentationPreview {
381
+ text
382
+ highlights
383
+ }
384
+ ${UNIFIED_SEARCH_REPOSITORY_EVIDENCE_SELECTION}
385
+ locator {
386
+ ${UNIFIED_SEARCH_LOCATOR_SELECTION}
387
+ }
388
+ }
389
+ page {
390
+ offset
391
+ limit
392
+ returned
393
+ hasMore
394
+ }
395
+ partialResults
396
+ evidenceNotice
397
+ sourceStatus {
398
+ source
399
+ targetLabel
400
+ requestedTargetLabel
401
+ freshTargetLabel
402
+ servedTargetLabel
403
+ ${TARGET_RESOLUTION_SELECTION}
404
+ indexingStatus
405
+ codeIndexState
406
+ resultCount
407
+ appliedFilters
408
+ ignoredFilters
409
+ incompatibleFilters
410
+ appliedQueryFeatures
411
+ ignoredQueryFeatures
412
+ incompatibleQueryFeatures
413
+ suggestedSiteTargets
414
+ suggestedSiteTargetsTruncated
415
+ note
416
+ ${DOC_COVERAGE_SELECTION}
417
+ ${DOCUMENTATION_CONTRIBUTORS_SELECTION}
418
+ }
419
+ }
420
+ }
421
+ }`;function debugUnifiedSearchRequest(variables,diagnostics){if(!diagnostics?.isEnabled("code-nav"))return;const serialised=serialiseForDebug(variables);const filters=asRecord(serialised.filters);diagnostics.debug("code-nav",{event:"request",operation:"search",targetCount:Array.isArray(serialised.targets)?serialised.targets.length:0,sources:Array.isArray(serialised.sources)?serialised.sources:[],hasFilters:filters!==undefined,filterKeys:filters?Object.keys(filters).sort():[],fileIntent:filters&&typeof filters.fileIntent==="string"?filters.fileIntent:"omitted",allowPartialResults:serialised.allowPartialResults===true,presentVariableKeys:Object.keys(serialised).sort(),hasLimit:typeof serialised.limit==="number",hasOffset:typeof serialised.offset==="number",waitTimeoutMs:typeof serialised.waitTimeoutMs==="number"?serialised.waitTimeoutMs:undefined})}function debugGraphqlWireRequest(operation,graphqlQuery,variables,diagnostics){if(!diagnostics?.isEnabled("code-nav-wire"))return;diagnostics.debug("code-nav-wire",{event:"wire-request",operation,graphqlQuery,variables:serialiseForDebug(variables)})}function serialiseForDebug(value){try{const text=JSON.stringify(value);if(!text)return{};const parsed=JSON.parse(text);return asRecord(parsed)??{}}catch{return{}}}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value)){return value}return}var availableVersionSchema=z4.object({version:z4.string().nullable().optional(),ref:z4.string()});var targetResolutionIdentitySchema=z4.object({kind:z4.string().nullable().optional(),registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),version:z4.string().nullable().optional(),repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),commitSha:z4.string().nullable().optional(),committedAt:z4.string().nullable().optional(),site:z4.string().nullable().optional()}).nullable().optional();var targetResolutionSchema=z4.object({requested:targetResolutionIdentitySchema,resolvedRequested:targetResolutionIdentitySchema,served:targetResolutionIdentitySchema,freshness:z4.string().nullable().optional(),freshnessReason:z4.string().nullable().optional(),indexingRef:z4.string().nullable().optional(),availableVersions:z4.array(availableVersionSchema).nullable().optional(),availableRefs:z4.array(availableVersionSchema).nullable().optional(),suggestedRefs:z4.array(availableVersionSchema).nullable().optional()}).nullable().optional();var unifiedSearchSourceSchema=z4.enum(["AUTO","DOCS","CODE","SYMBOL"]);var unifiedSearchResultTypeSchema=z4.enum(["DOCUMENTATION_PAGE","REPOSITORY_SYMBOL","REPOSITORY_CODE","REPOSITORY_DOC"]);var unifiedSearchLineRangeSchema=z4.object({startLine:z4.number().int().positive(),endLine:z4.number().int().positive()}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchEvidenceRangeSchema=unifiedSearchLineRangeSchema.extend({matchLine:z4.number().int().positive().nullable().optional(),rangeKind:z4.string().nullable().optional(),matchSpansTruncated:z4.boolean()});var unifiedSearchDefinitionRangeSchema=unifiedSearchLineRangeSchema.extend({filePath:z4.string(),repositoryFilePath:z4.string()});var unifiedSearchSymbolContextBaseSchema=z4.object({name:z4.string(),qualifiedPath:z4.string().nullable().optional(),kind:z4.string().nullable().optional()});var unifiedSearchSymbolContextSchema=z4.discriminatedUnion("relation",[unifiedSearchSymbolContextBaseSchema.extend({relation:z4.literal("ENCLOSES_MATCH"),definitionRange:unifiedSearchDefinitionRangeSchema}),unifiedSearchSymbolContextBaseSchema.extend({relation:z4.literal("ASSOCIATED_WITH_INDEXED_CHUNK"),definitionRange:unifiedSearchDefinitionRangeSchema.nullable().optional()})]);var unifiedSearchLocatorSchema=z4.object({registry:z4.string().nullable().optional(),packageName:z4.string().nullable().optional(),version:z4.string().nullable().optional(),pageId:z4.string().nullable().optional(),docsReadTarget:z4.string().nullable().optional(),sourceKind:z4.string().nullable().optional(),sourceUrl:z4.string().nullable().optional(),repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),commitSha:z4.string().nullable().optional(),requestedRef:z4.string().nullable().optional(),filePath:z4.string().nullable().optional(),repositoryFilePath:z4.string().nullable().optional(),startLine:z4.number().int().nullable().optional(),endLine:z4.number().int().nullable().optional(),evidenceRange:unifiedSearchEvidenceRangeSchema.nullable().optional(),indexedRange:unifiedSearchLineRangeSchema.nullable().optional(),symbolContext:unifiedSearchSymbolContextSchema.nullable().optional(),fileContentHash:z4.string().nullable().optional(),symbolRef:z4.string().nullable().optional(),qualifiedPath:z4.string().nullable().optional(),kind:z4.string().nullable().optional(),category:z4.string().nullable().optional(),language:z4.string().nullable().optional()});var unifiedSearchSemanticPreferredReadSchema=z4.object({targetLabel:z4.string(),registry:z4.string().nullable(),packageName:z4.string().nullable(),version:z4.string().nullable(),repoUrl:z4.string(),gitRef:z4.string(),commitSha:z4.string(),requestedRef:z4.string().nullable(),filePath:z4.string(),repositoryFilePath:z4.string(),startLine:unifiedSearchLineRangeSchema.shape.startLine,endLine:unifiedSearchLineRangeSchema.shape.endLine}).refine((range)=>range.startLine<=range.endLine,{message:"startLine must be less than or equal to endLine"});var unifiedSearchSemanticScopeSchema=z4.object({name:z4.string(),qualifiedPath:z4.string(),kind:z4.string(),parentQualifiedPath:z4.string().nullable(),declarationStartLine:z4.number().int().positive(),declarationEndLine:z4.number().int().positive(),parameterNames:z4.array(z4.string()),returnType:z4.string().nullable(),symbolRef:z4.string()}).refine((range)=>range.declarationStartLine<=range.declarationEndLine,{message:"declarationStartLine must be less than or equal to declarationEndLine"});var unifiedSearchSemanticContextSchema=z4.object({scopes:z4.array(unifiedSearchSemanticScopeSchema),scopeChainTruncated:z4.boolean(),preferredRead:unifiedSearchSemanticPreferredReadSchema});var unifiedSearchHighlightSchema=z4.tuple([z4.number().int().nonnegative(),z4.number().int().nonnegative()]).refine(([start,end])=>start<=end,{message:"highlight start must be less than or equal to end"});var unifiedSearchFocusedSourceLineSchema=z4.object({lineNumber:z4.number().int().positive(),text:z4.string(),highlights:z4.array(unifiedSearchHighlightSchema),prefixTruncated:z4.boolean(),suffixTruncated:z4.boolean()});var unifiedSearchBm25MatchFieldSchema=z4.enum(["SYMBOL_NAME","FILE_PATH","DOCUMENTATION","SOURCE_IDENTIFIER"]);var unifiedSearchMatchedSourceSchema=unifiedSearchLineRangeSchema.extend({matchLine:z4.number().int().positive().nullable(),rangeKind:z4.string(),matchSpansTruncated:z4.boolean(),lines:z4.array(unifiedSearchFocusedSourceLineSchema),linesOmittedBefore:z4.boolean(),linesOmittedAfter:z4.boolean()});var unifiedSearchDocumentationPreviewSchema=z4.object({text:z4.string().min(1),highlights:z4.array(unifiedSearchHighlightSchema)});var unifiedSearchRepositoryEvidenceSchema=z4.object({semanticContext:unifiedSearchSemanticContextSchema.nullable(),bm25MatchFields:z4.array(unifiedSearchBm25MatchFieldSchema).min(1).nullable().optional(),matchedSource:unifiedSearchMatchedSourceSchema.nullable().optional()});var contentSafetySchema=z4.object({filtered:z4.boolean(),modifications:z4.array(z4.enum(["INVISIBLE_CONTROLS_STRIPPED","HTML_COMMENTS_STRIPPED","IMAGES_REPLACED","UNSAFE_LINKS_NEUTRALIZED"]))});var unifiedSearchHitSchema=z4.object({readTarget:selectedReadTargetSchema.nullable(),id:z4.string(),resultType:unifiedSearchResultTypeSchema,targetLabel:z4.string(),requestedTargetLabel:z4.string().nullable().optional(),freshTargetLabel:z4.string().nullable().optional(),servedTargetLabel:z4.string().nullable().optional(),freshness:z4.string().nullable().optional(),title:z4.string().nullable().optional(),score:z4.number().nullable().optional(),highlights:z4.object({title:z4.array(z4.tuple([z4.number().int(),z4.number().int()])).nullable().optional()}).nullable().optional(),repositoryEvidence:unifiedSearchRepositoryEvidenceSchema.nullable().optional(),documentationPreview:unifiedSearchDocumentationPreviewSchema.nullable().optional(),locator:unifiedSearchLocatorSchema});var unifiedSearchPageInfoSchema=z4.object({offset:z4.number().int(),limit:z4.number().int(),returned:z4.number().int(),hasMore:z4.boolean()});var docCoverageSchema=z4.object({coverageState:z4.string(),coverageReason:z4.string().nullable().optional(),pagesCrawled:z4.number().int().nullable().optional(),frontierRemaining:z4.number().int().nullable().optional(),artifactOverflowPageCount:z4.number().int().nullable().optional(),estimatedTotalPages:z4.number().int().nullable().optional(),note:z4.string().nullable().optional()}).nullable().optional();var unifiedSearchDocumentationContributorSchema=z4.object({kind:z4.enum(["REPOSITORY_DOCS","DOCPACK"]),state:z4.enum(["SEARCHED","READY","PENDING","UNAVAILABLE"]),freshness:z4.enum(["CURRENT","PROVISIONAL","STALE"]).nullable().optional(),resultCount:z4.number().int().nonnegative(),repositoryUrl:z4.string().nullable().optional(),commitSha:z4.string().nullable().optional(),siteKey:z4.string().nullable().optional(),siteUrl:z4.string().nullable().optional(),coverage:docCoverageSchema});var unifiedSearchSourceStatusSchema=z4.object({source:unifiedSearchSourceSchema,targetLabel:z4.string(),requestedTargetLabel:z4.string().nullable().optional(),freshTargetLabel:z4.string().nullable().optional(),servedTargetLabel:z4.string().nullable().optional(),targetResolution:targetResolutionSchema,indexingStatus:z4.string().nullable().optional(),codeIndexState:z4.string().nullable().optional(),resultCount:z4.number().int().nullable().optional(),appliedFilters:z4.array(z4.string()),ignoredFilters:z4.array(z4.string()),incompatibleFilters:z4.array(z4.string()),appliedQueryFeatures:z4.array(z4.string()),ignoredQueryFeatures:z4.array(z4.string()),incompatibleQueryFeatures:z4.array(z4.string()),suggestedSiteTargets:z4.array(z4.string()),suggestedSiteTargetsTruncated:z4.boolean(),note:z4.string().nullable().optional(),coverage:docCoverageSchema,contributors:z4.array(unifiedSearchDocumentationContributorSchema)});var unifiedSearchResultSchema=z4.object({query:z4.string(),queryWarnings:z4.array(z4.string()),sources:z4.array(unifiedSearchSourceSchema),results:z4.array(unifiedSearchHitSchema),page:unifiedSearchPageInfoSchema,partialResults:z4.boolean(),sourceStatus:z4.array(unifiedSearchSourceStatusSchema),evidenceNotice:z4.string().nullable().optional()});var unifiedSearchSessionStatusSchema=z4.string().min(1);var unifiedSearchFiltersSchema=z4.object({fileIntent:z4.string().nullable().optional(),kind:z4.string().nullable().optional(),category:z4.string().nullable().optional(),publicOnly:z4.boolean().nullable().optional(),pathPrefix:z4.string().nullable().optional()}).nullable().optional();var unifiedSearchProgressTargetSchema=z4.object({requested:z4.string().nullable().optional(),resolvedRequested:z4.string().nullable().optional(),served:z4.string().nullable().optional(),freshness:z4.string().nullable().optional(),indexingRef:z4.string().nullable().optional(),requestedRefKind:z4.string().nullable().optional(),targetResolution:targetResolutionSchema,availableVersions:z4.array(availableVersionSchema).nullable().optional(),availableRefs:z4.array(availableVersionSchema).nullable().optional(),suggestedRefs:z4.array(availableVersionSchema).nullable().optional(),coverage:docCoverageSchema});var unifiedSearchRequestedTargetSchema=z4.object({registry:z4.string().nullable().optional(),name:z4.string().nullable().optional(),version:z4.string().nullable().optional(),repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),site:z4.string().nullable().optional()});var unifiedSearchProgressSchema=z4.object({searchRef:z4.string(),status:unifiedSearchSessionStatusSchema,targetsTotal:z4.number().int(),targetsReady:z4.number().int(),elapsedMs:z4.number().int(),query:z4.string(),queryWarnings:z4.array(z4.string()),sources:z4.array(unifiedSearchSourceSchema),requestedSources:z4.array(unifiedSearchSourceSchema).nullable().optional(),targetMode:z4.string().nullable().optional(),requestedTargets:z4.array(unifiedSearchRequestedTargetSchema).nullable().optional(),filters:unifiedSearchFiltersSchema,limit:z4.number().int().nullable().optional(),offset:z4.number().int().nullable().optional(),targets:z4.array(unifiedSearchProgressTargetSchema).nullable().optional(),indexingEstimates:indexingEstimatesSchema,expiresAt:z4.string().nullable().optional(),results:unifiedSearchResultSchema.nullable().optional()});var asyncUnifiedSearchResultSchema=z4.object({completed:z4.boolean(),searchRef:z4.string().nullable().optional(),result:unifiedSearchResultSchema.nullable().optional(),progress:unifiedSearchProgressSchema.nullable().optional()});var graphQLErrorSchema=z4.object({message:z4.string(),extensions:z4.record(z4.string(),z4.unknown()).optional()});var codeDiffGraphQLErrorSchema=z4.object({message:z4.string(),path:z4.array(z4.union([z4.string(),z4.number().int()])).nullable().optional(),extensions:z4.record(z4.string(),z4.unknown()).optional()});var codeDiffRegistrySchema=z4.enum(PKGSEER_REGISTRY_VALUES);var codeDiffPackageInfoSchema=z4.object({registry:codeDiffRegistrySchema,name:z4.string(),repoUrl:z4.string()});var codeDiffRefResolutionSchema=z4.object({requested:z4.string(),resolvedVersion:z4.string().nullable().optional(),ref:z4.string(),commitSha:z4.string(),refKind:z4.enum(["SHA","TAG","BRANCH","HEAD","UNKNOWN"]),versionSource:z4.enum(["REGISTRY","GIT_HEAD","TAG","RELEASE"]).nullable().optional()});var rawCodeDiffSummarySchema=z4.object({filesChanged:z4.number().int(),added:z4.number().int(),deleted:z4.number().int(),modified:z4.number().int(),modeChanged:z4.number().int(),typeChanged:z4.number().int(),inventoryComplete:z4.boolean(),unprojectableFiles:z4.number().int()});var rawCodeDiffScopeSchema=z4.object({status:z4.enum(["PACKAGE","REPOSITORY","UNKNOWN"]),fromSubpath:z4.string().nullable().optional(),toSubpath:z4.string().nullable().optional(),pathPrefix:z4.string().nullable().optional(),pathGlob:z4.string().nullable().optional()});var rawCodeDiffContentFailureSchema=z4.object({code:z4.string(),retryable:z4.boolean(),retryAfterMs:z4.number().int().nullable().optional(),stage:z4.string().nullable().optional(),limitKind:z4.string().nullable().optional()});var rawCodeDiffFileSchema=z4.object({path:z4.string(),pathEncoding:z4.enum(["UTF8","BYTE_ESCAPED"]),status:z4.enum(["ADDED","DELETED","MODIFIED"]),modeChanged:z4.boolean(),typeChanged:z4.boolean(),additions:z4.number().int().nullable().optional(),deletions:z4.number().int().nullable().optional(),patch:z4.string().nullable().optional(),contentStatus:z4.enum(["NOT_REQUESTED","STATS","PATCH","BINARY","METADATA_ONLY","OMITTED","UNAVAILABLE"]),contentOmissionReason:z4.string().nullable().optional(),contentSafety:contentSafetySchema});var rawCodeDiffSchema=z4.object({summary:rawCodeDiffSummarySchema,scope:rawCodeDiffScopeSchema,contentCoverage:z4.enum(["NOT_REQUESTED","COMPLETE","PARTIAL","FAILED"]),contentFailure:rawCodeDiffContentFailureSchema.nullable().optional(),files:z4.array(rawCodeDiffFileSchema),hasMoreFiles:z4.boolean()});var codeDiffResultSchema=z4.object({package:codeDiffPackageInfoSchema.nullable().optional(),fromResolution:codeDiffRefResolutionSchema,toResolution:codeDiffRefResolutionSchema,raw:rawCodeDiffSchema.nullable().optional()});var codeDiffGraphQLResponseSchema=z4.object({data:z4.object({codeDiff:codeDiffResultSchema.nullable().optional()}).nullable().optional(),errors:z4.array(codeDiffGraphQLErrorSchema).optional()});var CODE_DIFF_OPTION_KEYS=new Set(["maxFiles","maxPatchBytes","pathPrefix","pathGlob"]);var CODE_DIFF_COMMON_SELECTION=` package {
422
+ registry
423
+ name
424
+ repoUrl
425
+ }
426
+ fromResolution {
427
+ requested
428
+ resolvedVersion
429
+ ref
430
+ commitSha
431
+ refKind
432
+ versionSource
433
+ }
434
+ toResolution {
435
+ requested
436
+ resolvedVersion
437
+ ref
438
+ commitSha
439
+ refKind
440
+ versionSource
441
+ }
442
+ raw {
443
+ summary {
444
+ filesChanged
445
+ added
446
+ deleted
447
+ modified
448
+ modeChanged
449
+ typeChanged
450
+ inventoryComplete
451
+ unprojectableFiles
452
+ }
453
+ scope {
454
+ status
455
+ fromSubpath
456
+ toSubpath
457
+ pathPrefix
458
+ pathGlob
459
+ }
460
+ contentCoverage
461
+ contentFailure {
462
+ code
463
+ retryable
464
+ retryAfterMs
465
+ stage
466
+ limitKind
467
+ }
468
+ files {
469
+ path
470
+ pathEncoding
471
+ status
472
+ modeChanged
473
+ typeChanged
474
+ contentStatus
475
+ contentSafety {
476
+ filtered
477
+ modifications
478
+ }`;function buildCodeDiffQuery(mode){const contentFields=mode==="inventory"?"":mode==="stats"?`
479
+ additions
480
+ deletions`:`
481
+ additions
482
+ deletions
483
+ patch
484
+ contentOmissionReason`;return`
485
+ query CodeDiff(
486
+ $registry: Registry
487
+ $name: String
488
+ $fromVersion: String
489
+ $toVersion: String
490
+ $repoUrl: String
491
+ $fromRef: String
492
+ $toRef: String
493
+ $rawOptions: RawCodeDiffOptions
494
+ ) {
495
+ codeDiff(
496
+ registry: $registry
497
+ name: $name
498
+ fromVersion: $fromVersion
499
+ toVersion: $toVersion
500
+ repoUrl: $repoUrl
501
+ fromRef: $fromRef
502
+ toRef: $toRef
503
+ rawOptions: $rawOptions
504
+ ) {
505
+ ${CODE_DIFF_COMMON_SELECTION}${contentFields}
506
+ }
507
+ hasMoreFiles
508
+ }
509
+ }
510
+ }`}var navigationResolutionSchema=z4.object({requestedVersion:z4.string().nullable().optional(),requestedRef:z4.string().nullable().optional(),resolvedRef:z4.string().nullable().optional(),commitSha:z4.string().nullable().optional()}).nullable().optional();var navigationDiagnosticsSchema=z4.object({hint:z4.string().nullable().optional()}).nullable().optional();var repoFileEntrySchema=z4.object({path:z4.string(),name:z4.string().nullable().optional(),language:z4.string().nullable().optional(),fileType:z4.string().nullable().optional(),byteSize:z4.number().int().nullable().optional()});var listRepoFilesResponseSchema=z4.object({files:z4.array(repoFileEntrySchema),total:z4.number().int(),hasMore:z4.boolean(),indexedVersion:z4.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,diagnostics:navigationDiagnosticsSchema,codeIndexState:z4.string(),indexingRef:z4.string().nullable().optional(),availableVersions:z4.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,indexingEstimates:indexingEstimatesSchema});var listRepoFilesGraphQLResponseSchema=z4.object({data:z4.object({listRepoFiles:listRepoFilesResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema).optional()});var LIST_REPO_FILES_QUERY=`
511
+ query ListRepoFiles(
512
+ $registry: Registry
513
+ $packageName: String
514
+ $repoUrl: String
515
+ $gitRef: String
516
+ $version: String
517
+ $pathPrefix: String
518
+ $pathSelectors: [FilePathSelectorInput!]
519
+ $extensions: [String!]
520
+ $fileTypes: [String!]
521
+ $languages: [String!]
522
+ $fileIntent: FileIntent
523
+ $fileIntents: [FileIntent!]
524
+ $excludeFileIntents: [FileIntent!]
525
+ $excludeDocFiles: Boolean
526
+ $excludeTestFiles: Boolean
527
+ $includeHidden: Boolean
528
+ $limit: Int
529
+ $waitTimeoutMs: Int
530
+ ) {
531
+ listRepoFiles(
532
+ registry: $registry
533
+ packageName: $packageName
534
+ repoUrl: $repoUrl
535
+ gitRef: $gitRef
536
+ version: $version
537
+ pathPrefix: $pathPrefix
538
+ pathSelectors: $pathSelectors
539
+ extensions: $extensions
540
+ fileTypes: $fileTypes
541
+ languages: $languages
542
+ fileIntent: $fileIntent
543
+ fileIntents: $fileIntents
544
+ excludeFileIntents: $excludeFileIntents
545
+ excludeDocFiles: $excludeDocFiles
546
+ excludeTestFiles: $excludeTestFiles
547
+ includeHidden: $includeHidden
548
+ limit: $limit
549
+ waitTimeoutMs: $waitTimeoutMs
550
+ ) {
551
+ files {
552
+ path
553
+ name
554
+ language
555
+ fileType
556
+ byteSize
557
+ }
558
+ total
559
+ hasMore
560
+ indexedVersion
561
+ resolution {
562
+ requestedVersion
563
+ requestedRef
564
+ resolvedRef
565
+ commitSha
566
+ }
567
+ ${TARGET_RESOLUTION_SELECTION}
568
+ diagnostics {
569
+ hint
570
+ }
571
+ codeIndexState
572
+ indexingRef
573
+ availableVersions {
574
+ version
575
+ ref
576
+ }
577
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
578
+ ${INDEXING_ESTIMATES_SELECTION}
579
+ }
580
+ }`;var codeContextResponseSchema=z4.object({content:z4.string().nullable().optional(),filePath:z4.string().nullable().optional(),language:z4.string().nullable().optional(),totalLines:z4.number().int().nullable().optional(),startLine:z4.number().int().nullable().optional(),endLine:z4.number().int().nullable().optional(),repoUrl:z4.string().nullable().optional(),gitRef:z4.string().nullable().optional(),isBinary:z4.boolean().nullable().optional(),codeIndexState:z4.string(),indexingRef:z4.string().nullable().optional(),availableVersions:z4.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,indexingEstimates:indexingEstimatesSchema,targetResolution:targetResolutionSchema});var fetchCodeContextGraphQLResponseSchema=z4.object({data:z4.object({fetchCodeContext:codeContextResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema).optional()});var FETCH_CODE_CONTEXT_QUERY=`
581
+ query FetchCodeContext(
582
+ $registry: Registry
583
+ $packageName: String
584
+ $repoUrl: String
585
+ $gitRef: String
586
+ $version: String
587
+ $filePath: String!
588
+ $startLine: Int
589
+ $endLine: Int
590
+ $waitTimeoutMs: Int
591
+ ) {
592
+ fetchCodeContext(
593
+ registry: $registry
594
+ packageName: $packageName
595
+ repoUrl: $repoUrl
596
+ gitRef: $gitRef
597
+ version: $version
598
+ filePath: $filePath
599
+ startLine: $startLine
600
+ endLine: $endLine
601
+ waitTimeoutMs: $waitTimeoutMs
602
+ ) {
603
+ content
604
+ filePath
605
+ language
606
+ totalLines
607
+ startLine
608
+ endLine
609
+ repoUrl
610
+ gitRef
611
+ isBinary
612
+ codeIndexState
613
+ indexingRef
614
+ ${CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION}
615
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
616
+ ${INDEXING_ESTIMATES_SELECTION}
617
+ ${TARGET_RESOLUTION_SELECTION}
618
+ }
619
+ }`;var grepRepoMatchSchema=z4.object({filePath:z4.string(),line:z4.number().int(),matchStartByte:z4.number().int(),matchEndByte:z4.number().int(),lineContent:z4.string(),contextBefore:z4.array(z4.string()).nullable().optional(),contextAfter:z4.array(z4.string()).nullable().optional(),fileContentHash:z4.string().nullable().optional(),fileIntent:z4.string().nullable().optional(),symbolRowId:z4.string().nullable().optional(),symbol:z4.object({symbolRef:z4.string().optional(),name:z4.string().optional(),qualifiedPath:z4.string().nullable().optional(),kind:z4.string().nullable().optional(),category:z4.string().nullable().optional(),arity:z4.number().int().nullable().optional(),isPublic:z4.boolean().nullable().optional(),filePath:z4.string().nullable().optional(),startLine:z4.number().int().nullable().optional(),endLine:z4.number().int().nullable().optional(),contentHash:z4.string().nullable().optional(),parentPath:z4.string().nullable().optional()}).nullable().optional()});var grepRepoResponseSchema=z4.object({matches:z4.array(grepRepoMatchSchema),nextCursor:z4.string().nullable().optional(),hasMore:z4.boolean(),truncatedReason:z4.enum(["NONE","MAX_MATCHES","MAX_MATCHES_PER_FILE","DEADLINE"]),routeTaken:z4.enum(["SINGLE_FILE","CONTENT_INDEX"]).nullable().optional(),filesScanned:z4.number().int(),filesInScope:z4.number().int(),binaryFilesSkipped:z4.number().int(),filesTooLargeSkipped:z4.number().int(),totalMatches:z4.number().int(),uniqueFilesMatched:z4.number().int(),indexedVersion:z4.string().nullable().optional(),resolution:navigationResolutionSchema,targetResolution:targetResolutionSchema,codeIndexState:z4.string(),indexingRef:z4.string().nullable().optional(),availableVersions:z4.array(availableVersionSchema).nullable().optional(),indexingEstimate:indexingDurationEstimateSchema,indexingEstimates:indexingEstimatesSchema});var grepRepoGraphQLResponseSchema=z4.object({data:z4.object({grepRepo:grepRepoResponseSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema).optional()});var GREP_REPO_SYMBOL_SELECTIONS={symbol_ref:"symbolRef",name:"name",qualified_path:"qualifiedPath",kind:"kind",category:"category",arity:"arity",is_public:"isPublic",file_path:"filePath",start_line:"startLine",end_line:"endLine",content_hash:"contentHash",parent_path:"parentPath"};function buildGrepRepoQuery(symbolFields){const symbolSelection=(symbolFields??[]).map((field)=>GREP_REPO_SYMBOL_SELECTIONS[field]).filter((field)=>Boolean(field)).filter((field,index,fields)=>fields.indexOf(field)===index).join(`
620
+ `);const symbolBlock=symbolSelection.length>0?`
621
+ symbol {
622
+ ${symbolSelection}
623
+ }`:"";return`
624
+ query GrepRepo(
625
+ $registry: Registry
626
+ $packageName: String
627
+ $repoUrl: String
628
+ $gitRef: String
629
+ $version: String
630
+ $waitTimeoutMs: Int
631
+ $pattern: String!
632
+ $patternType: GrepPatternType
633
+ $caseSensitive: Boolean
634
+ $pathSelectors: [GrepPathSelectorInput!]
635
+ $extensions: [String!]
636
+ $excludeDocFiles: Boolean
637
+ $excludeTestFiles: Boolean
638
+ $allowUnscoped: Boolean
639
+ $contextLinesBefore: Int
640
+ $contextLinesAfter: Int
641
+ $maxMatches: Int
642
+ $maxMatchesPerFile: Int
643
+ $cursor: String
644
+ $symbolFields: [String!]
645
+ ) {
646
+ grepRepo(
647
+ registry: $registry
648
+ packageName: $packageName
649
+ repoUrl: $repoUrl
650
+ gitRef: $gitRef
651
+ version: $version
652
+ waitTimeoutMs: $waitTimeoutMs
653
+ pattern: $pattern
654
+ patternType: $patternType
655
+ caseSensitive: $caseSensitive
656
+ pathSelectors: $pathSelectors
657
+ extensions: $extensions
658
+ excludeDocFiles: $excludeDocFiles
659
+ excludeTestFiles: $excludeTestFiles
660
+ allowUnscoped: $allowUnscoped
661
+ contextLinesBefore: $contextLinesBefore
662
+ contextLinesAfter: $contextLinesAfter
663
+ maxMatches: $maxMatches
664
+ maxMatchesPerFile: $maxMatchesPerFile
665
+ cursor: $cursor
666
+ symbolFields: $symbolFields
667
+ ) {
668
+ matches {
669
+ filePath
670
+ line
671
+ matchStartByte
672
+ matchEndByte
673
+ lineContent
674
+ contextBefore
675
+ contextAfter
676
+ fileContentHash
677
+ fileIntent
678
+ symbolRowId${symbolBlock}
679
+ }
680
+ nextCursor
681
+ totalMatches
682
+ hasMore
683
+ truncatedReason
684
+ routeTaken
685
+ filesScanned
686
+ filesInScope
687
+ binaryFilesSkipped
688
+ filesTooLargeSkipped
689
+ uniqueFilesMatched
690
+ indexedVersion
691
+ resolution {
692
+ requestedVersion
693
+ requestedRef
694
+ resolvedRef
695
+ commitSha
696
+ }
697
+ ${TARGET_RESOLUTION_SELECTION}
698
+ codeIndexState
699
+ indexingRef
700
+ availableVersions {
701
+ version
702
+ ref
703
+ }
704
+ ${INDEXING_DURATION_ESTIMATE_SELECTION}
705
+ ${INDEXING_ESTIMATES_SELECTION}
706
+ }
707
+ }`}var unifiedSearchGraphQLResponseSchema=z4.object({data:z4.object({search:asyncUnifiedSearchResultSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema).optional()});var unifiedSearchStatusGraphQLResponseSchema=z4.object({data:z4.object({discoverySearchProgress:unifiedSearchProgressSchema.nullable().optional()}).nullable().optional(),errors:z4.array(graphQLErrorSchema).optional()});class CodeNavigationServiceImpl2{codeNavigationUrl;tokenProvider;fetchFn;runtime;constructor(codeNavigationUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.codeNavigationUrl=codeNavigationUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async postGraphqlWithTargetResolutionFallback(input){const response=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:input.query,variables:input.variables,timeoutMs:input.timeoutMs,signal:input.signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(response.status<200||response.status>=300)return response;if(!hasSchemaMismatchErrors(response.parsedBody))return response;for(const fallbackQuery of buildTargetResolutionFallbackQueries(input.query)){if(this.runtime.diagnostics?.isEnabled("code-nav")){this.runtime.diagnostics.debug("code-nav",{event:"target-resolution-query-fallback"})}const fallbackResponse=await postPkgseerGraphql({endpointUrl:this.codeNavigationUrl,token:input.token,query:fallbackQuery,variables:input.variables,timeoutMs:input.timeoutMs,signal:input.signal,fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics});if(!hasSchemaMismatchErrors(fallbackResponse.parsedBody)){return fallbackResponse}}return response}async search(params,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearch(token,params,options)})}async searchStatus(searchRef,waitTimeoutMs=0,options){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options)})}async codeDiff(params){validateCodeDiffParams(params);return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeCodeDiff(token,params)})}async executeCodeDiff(token,params){const query=buildCodeDiffQuery(params.mode);const variables=buildCodeDiffVariables(params);debugGraphqlWireRequest("codeDiff",query,variables,this.runtime.diagnostics);let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query,variables})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=codeDiffGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const data=parsed.data.data?.codeDiff;const errors=parsed.data.errors??[];if(errors.length>0){const rawErrors=errors.filter(isCodeDiffRawError);if(rawErrors.length>0){throw new CodeDiffError2(rawErrors.map((error)=>error.message).join(", "),parseCodeDiffErrorDetails(rawErrors),data?normaliseCodeDiffPartial(data):undefined)}throw this.createCodeDiffRootError(errors)}if(!data?.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return normaliseCodeDiffResult(data)}createCodeDiffRootError(errors){const graphQLErrors=errors.map(({message,extensions})=>({message,extensions}));const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;if(code==="AUTHENTICATION_REQUIRED"){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(code==="UNAUTHORIZED"||code==="FORBIDDEN"||code==="FEATURE_FLAG_REQUIRED"||isClientUpdateRequiredGraphQLError({message,code})||isGraphQLSchemaMismatchError({message,code})||code===undefined&&isAuthMessage(message)){return this.createGraphQLError(graphQLErrors)}return new CodeDiffError2(message,parseCodeDiffErrorDetails(errors))}async executeUnifiedSearch(token,params,options){if(params.targets.length===0){throw new CodeNavigationValidationError("At least one search target is required.")}let response;const variables={targets:params.targets.map((target)=>({registry:target.registry,name:target.packageName,version:target.version,repoUrl:target.repoUrl,gitRef:target.gitRef,site:target.site})),query:params.query,sources:params.sources,filters:params.filters,allowPartialResults:params.allowPartialResults??true,limit:params.limit,offset:params.offset,waitTimeoutMs:params.waitTimeoutMs};debugUnifiedSearchRequest(variables,this.runtime.diagnostics);debugGraphqlWireRequest("search",UNIFIED_SEARCH_QUERY,variables,this.runtime.diagnostics);try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_QUERY,variables,timeoutMs:Math.max(DEFAULT_FETCH_TIMEOUT_MS,(params.waitTimeoutMs??0)+30000),signal:options?.signal})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.search;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}return this.normaliseUnifiedSearchOutcome(data)}async executeUnifiedSearchStatus(token,searchRef,waitTimeoutMs,options){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:UNIFIED_SEARCH_STATUS_QUERY,timeoutMs:Math.max(DEFAULT_FETCH_TIMEOUT_MS,waitTimeoutMs+30000),signal:options?.signal,variables:{searchRef,includeResults:true,waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=unifiedSearchStatusGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.discoverySearchProgress;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}const progress=this.normaliseUnifiedSearchProgress(data);const result=data.results?this.normaliseUnifiedSearchResult(data.results):undefined;if(result&&progress.status==="COMPLETED"){return{state:"completed",completed:true,searchRef:progress.searchRef,result,progress}}return{state:"incomplete",completed:false,searchRef:progress.searchRef,result,progress}}createHttpError(response){return createCodeNavigationHttpError(response)}createTransportError(error){return createCodeNavigationTransportError(error)}createGraphQLError(errors){return createCodeNavigationGraphQLError(errors,this.runtime)}normaliseUnifiedSearchOutcome(data){const progress=data.progress?this.normaliseUnifiedSearchProgress(data.progress):undefined;if(data.completed){if(!data.result){throw new MalformedCodeNavigationResponseError("Completed unified search response missing result payload.")}return{state:"completed",completed:true,searchRef:data.searchRef??undefined,result:this.normaliseUnifiedSearchResult(data.result),progress}}const searchRef=data.searchRef??progress?.searchRef;if(!searchRef){throw new MalformedCodeNavigationResponseError("Incomplete unified search response missing search reference.")}const result=data.result?this.normaliseUnifiedSearchResult(data.result):undefined;return{state:"incomplete",completed:false,searchRef,result,progress}}normaliseUnifiedSearchResult(result){return{query:result.query,queryWarnings:result.queryWarnings,sources:result.sources,results:result.results.map((entry)=>({readTarget:entry.readTarget,id:entry.id,resultType:entry.resultType,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,freshness:entry.freshness??undefined,title:entry.title??undefined,score:entry.score??undefined,highlights:entry.highlights?{title:entry.highlights.title??undefined}:undefined,repositoryEvidence:entry.repositoryEvidence,documentationPreview:entry.documentationPreview,locator:normaliseUnifiedSearchLocator(entry.locator)})),page:{offset:result.page.offset,limit:result.page.limit,returned:result.page.returned,hasMore:result.page.hasMore},partialResults:result.partialResults,sourceStatus:result.sourceStatus.map((entry)=>({source:entry.source,targetLabel:entry.targetLabel,requestedTargetLabel:entry.requestedTargetLabel??undefined,freshTargetLabel:entry.freshTargetLabel??undefined,servedTargetLabel:entry.servedTargetLabel??undefined,targetResolution:normaliseTargetResolution(entry.targetResolution),indexingStatus:entry.indexingStatus??undefined,codeIndexState:entry.codeIndexState??undefined,resultCount:entry.resultCount??undefined,appliedFilters:entry.appliedFilters,ignoredFilters:entry.ignoredFilters,incompatibleFilters:entry.incompatibleFilters,appliedQueryFeatures:entry.appliedQueryFeatures,ignoredQueryFeatures:entry.ignoredQueryFeatures,incompatibleQueryFeatures:entry.incompatibleQueryFeatures,suggestedSiteTargets:entry.suggestedSiteTargets,suggestedSiteTargetsTruncated:entry.suggestedSiteTargetsTruncated,note:entry.note??undefined,coverage:normaliseDocCoverage(entry.coverage),contributors:entry.contributors.map((contributor)=>({kind:contributor.kind,state:contributor.state,freshness:contributor.freshness??undefined,resultCount:contributor.resultCount,repositoryUrl:contributor.repositoryUrl??undefined,commitSha:contributor.commitSha??undefined,siteKey:contributor.siteKey??undefined,siteUrl:contributor.siteUrl??undefined,coverage:normaliseDocCoverage(contributor.coverage,{preserveNone:true})}))})),evidenceNotice:result.evidenceNotice??undefined}}normaliseUnifiedSearchProgress(progress){return{searchRef:progress.searchRef,status:progress.status,targetsTotal:progress.targetsTotal,targetsReady:progress.targetsReady,elapsedMs:progress.elapsedMs,query:progress.query,queryWarnings:progress.queryWarnings,sources:progress.sources,requestedSources:progress.requestedSources??undefined,targetMode:normaliseTargetMode(progress.targetMode),requestedTargets:progress.requestedTargets?.map((target)=>({registry:target.registry?target.registry:undefined,name:target.name??undefined,version:target.version??undefined,repoUrl:target.repoUrl??undefined,gitRef:target.gitRef??undefined,site:target.site??undefined})),filters:normaliseProgressFilters(progress.filters),limit:progress.limit??undefined,offset:progress.offset??undefined,targets:progress.targets?.map((target)=>({requested:target.requested??undefined,resolvedRequested:target.resolvedRequested??undefined,served:target.served??undefined,freshness:target.freshness??undefined,indexingRef:target.indexingRef??undefined,requestedRefKind:normaliseRequestedRefKind(target.requestedRefKind),targetResolution:normaliseTargetResolution(target.targetResolution),availableVersions:normaliseAvailableVersions(target.availableVersions),availableRefs:normaliseAvailableVersions(target.availableRefs),suggestedRefs:normaliseAvailableVersions(target.suggestedRefs),coverage:normaliseDocCoverage(target.coverage)})),indexingEstimates:progress.indexingEstimates,expiresAt:progress.expiresAt??undefined}}throwIfIndexing(data){throwIfCodeContextIndexing(data)}async listFiles(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListFiles(token,params)})}async executeListFiles(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:LIST_REPO_FILES_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,pathPrefix:params.pathPrefix,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,fileTypes:params.fileTypes,languages:params.languages,fileIntent:params.fileIntent,fileIntents:params.fileIntents,excludeFileIntents:params.excludeFileIntents,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,includeHidden:params.includeHidden,limit:params.limit,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=listRepoFilesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.listRepoFiles;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{files:data.files.map((entry)=>({path:entry.path,name:entry.name??undefined,language:entry.language??undefined,fileType:entry.fileType??undefined,byteSize:entry.byteSize??undefined})),total:data.total,hasMore:data.hasMore,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),hint:data.diagnostics?.hint??undefined,indexingEstimates:data.indexingEstimates}}async readFile(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadFile(token,params)})}async executeReadFile(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:FETCH_CODE_CONTEXT_QUERY,variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,filePath:params.filePath,startLine:params.startLine,endLine:params.endLine,waitTimeoutMs:params.waitTimeoutMs}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=fetchCodeContextGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.fetchCodeContext;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return normaliseCodeContextResult(data)}async grepRepo(params){return executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeGrepRepo(token,params)})}async executeGrepRepo(token,params){let response;try{response=await this.postGraphqlWithTargetResolutionFallback({token,query:buildGrepRepoQuery(params.symbolFields),variables:{registry:params.target.registry,packageName:params.target.packageName,repoUrl:params.target.repoUrl,gitRef:params.target.gitRef,version:params.target.version,waitTimeoutMs:params.waitTimeoutMs,pattern:params.pattern,patternType:params.patternType,caseSensitive:params.caseSensitive,pathSelectors:params.pathSelectors?.map((entry)=>({kind:entry.kind,value:entry.value})),extensions:params.extensions,excludeDocFiles:params.excludeDocFiles,excludeTestFiles:params.excludeTestFiles,allowUnscoped:params.allowUnscoped,contextLinesBefore:params.contextLinesBefore,contextLinesAfter:params.contextLinesAfter,maxMatches:params.maxMatches,maxMatchesPerFile:params.maxMatchesPerFile,cursor:params.cursor,symbolFields:params.symbolFields}})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=grepRepoGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.grepRepo;if(!data){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}this.throwIfIndexing(data);return{matches:data.matches.map((entry)=>({filePath:entry.filePath,line:entry.line,matchStartByte:entry.matchStartByte,matchEndByte:entry.matchEndByte,lineContent:entry.lineContent,contextBefore:entry.contextBefore??undefined,contextAfter:entry.contextAfter??undefined,fileContentHash:entry.fileContentHash??undefined,fileIntent:entry.fileIntent??undefined,symbolRowId:entry.symbolRowId??undefined,symbol:entry.symbol?{symbolRef:entry.symbol.symbolRef,name:entry.symbol.name,qualifiedPath:entry.symbol.qualifiedPath??undefined,kind:entry.symbol.kind??undefined,category:entry.symbol.category??undefined,arity:entry.symbol.arity??undefined,isPublic:entry.symbol.isPublic??undefined,filePath:entry.symbol.filePath??undefined,startLine:entry.symbol.startLine??undefined,endLine:entry.symbol.endLine??undefined,contentHash:entry.symbol.contentHash??undefined,parentPath:entry.symbol.parentPath??undefined}:undefined})),nextCursor:data.nextCursor??undefined,hasMore:data.hasMore,truncatedReason:data.truncatedReason,routeTaken:data.routeTaken??undefined,filesScanned:data.filesScanned,filesInScope:data.filesInScope,binaryFilesSkipped:data.binaryFilesSkipped,filesTooLargeSkipped:data.filesTooLargeSkipped,totalMatches:data.totalMatches,uniqueFilesMatched:data.uniqueFilesMatched,indexedVersion:data.indexedVersion??undefined,resolution:data.resolution?{requestedVersion:data.resolution.requestedVersion??undefined,requestedRef:data.resolution.requestedRef??undefined,resolvedRef:data.resolution.resolvedRef??undefined,commitSha:data.resolution.commitSha??undefined}:undefined,targetResolution:normaliseTargetResolution(data.targetResolution),indexingEstimates:data.indexingEstimates}}}function normaliseUnifiedSearchLocator(value){return{registry:value.registry??undefined,packageName:value.packageName??undefined,version:value.version??undefined,pageId:value.pageId??undefined,docsReadTarget:value.docsReadTarget??undefined,sourceKind:value.sourceKind??undefined,sourceUrl:value.sourceUrl??undefined,repoUrl:value.repoUrl??undefined,gitRef:value.gitRef??undefined,commitSha:value.commitSha??undefined,requestedRef:value.requestedRef??undefined,filePath:value.filePath??undefined,repositoryFilePath:value.repositoryFilePath??undefined,startLine:value.startLine??undefined,endLine:value.endLine??undefined,evidenceRange:value.evidenceRange?{startLine:value.evidenceRange.startLine,endLine:value.evidenceRange.endLine,matchLine:value.evidenceRange.matchLine??undefined,rangeKind:value.evidenceRange.rangeKind??undefined,matchSpansTruncated:value.evidenceRange.matchSpansTruncated}:undefined,indexedRange:value.indexedRange?{startLine:value.indexedRange.startLine,endLine:value.indexedRange.endLine}:undefined,symbolContext:value.symbolContext?normaliseUnifiedSearchSymbolContext(value.symbolContext):undefined,fileContentHash:value.fileContentHash??undefined,symbolRef:value.symbolRef??undefined,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined,category:value.category??undefined,language:value.language??undefined}}function normaliseUnifiedSearchSymbolContext(value){const identity={name:value.name,qualifiedPath:value.qualifiedPath??undefined,kind:value.kind??undefined};if(value.relation==="ENCLOSES_MATCH"){return{...identity,relation:"encloses_match",definitionRange:normaliseUnifiedSearchDefinitionRange(value.definitionRange)}}return{...identity,relation:"associated_with_indexed_chunk",definitionRange:value.definitionRange?normaliseUnifiedSearchDefinitionRange(value.definitionRange):undefined}}function normaliseUnifiedSearchDefinitionRange(value){return{filePath:value.filePath,repositoryFilePath:value.repositoryFilePath,startLine:value.startLine,endLine:value.endLine}}function validateCodeDiffParams(params){const paramsRecord=asRecord(params);if(!paramsRecord){throw new CodeNavigationValidationError("CodeDiff params must be an object.")}if(paramsRecord.mode!=="inventory"&&paramsRecord.mode!=="stats"&&paramsRecord.mode!=="patches"){throw new CodeNavigationValidationError("CodeDiff mode must be inventory, stats, or patches.")}if(typeof paramsRecord.from!=="string"||paramsRecord.from.length===0){throw new CodeNavigationValidationError("CodeDiff from ref or version must not be empty.")}if(typeof paramsRecord.to!=="string"||paramsRecord.to.length===0){throw new CodeNavigationValidationError("CodeDiff to ref or version must not be empty.")}const target=asRecord(paramsRecord.target);if(!target){throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}if(Object.hasOwn(target,"registry")&&Object.hasOwn(target,"packageName")&&!Object.hasOwn(target,"repoUrl")){if(!codeDiffRegistrySchema.safeParse(target.registry).success){throw new CodeNavigationValidationError("CodeDiff package target has an unsupported registry.")}if(typeof target.packageName!=="string"||target.packageName.length===0){throw new CodeNavigationValidationError("CodeDiff package target name must not be empty.")}}else if(Object.hasOwn(target,"repoUrl")&&!Object.hasOwn(target,"registry")&&!Object.hasOwn(target,"packageName")){if(typeof target.repoUrl!=="string"||target.repoUrl.length===0){throw new CodeNavigationValidationError("CodeDiff repository target URL must not be empty.")}}else if((Object.hasOwn(target,"registry")||Object.hasOwn(target,"packageName"))&&Object.hasOwn(target,"repoUrl")){const conflictingKeys=["registry","packageName","repoUrl"].filter((key)=>Object.hasOwn(target,key)).join(", ");throw new CodeNavigationValidationError(`CodeDiff target has conflicting present keys: ${conflictingKeys}. Target shape is determined by key presence, even when a value is undefined.`)}else{throw new CodeNavigationValidationError("CodeDiff target must be a package or repository target.")}const optionsValue=paramsRecord.options;if(optionsValue===undefined)return;const options=asRecord(optionsValue);if(!options){throw new CodeNavigationValidationError("CodeDiff options must be an object when supplied.")}for(const key of Object.keys(options)){if(!CODE_DIFF_OPTION_KEYS.has(key)){throw new CodeNavigationValidationError(`CodeDiff options contains unknown key '${key}'.`)}}validateCodeDiffIntegerOption(options.maxFiles,"maxFiles",1,300);validateCodeDiffIntegerOption(options.maxPatchBytes,"maxPatchBytes",1024,2097152);validateCodeDiffPathOption(options.pathPrefix,"pathPrefix");validateCodeDiffPathOption(options.pathGlob,"pathGlob")}function validateCodeDiffIntegerOption(value,name,minimum,maximum){if(value===undefined)return;if(typeof value!=="number"||!Number.isInteger(value)||value<minimum||value>maximum){throw new CodeNavigationValidationError(`CodeDiff ${name} must be an integer from ${minimum} through ${maximum}.`)}}function validateCodeDiffPathOption(value,name){if(value===undefined)return;if(typeof value!=="string"){throw new CodeNavigationValidationError(`CodeDiff ${name} must be a string when supplied.`)}if(value.length===0){throw new CodeNavigationValidationError(`CodeDiff ${name} must not be empty when supplied.`)}if(new TextEncoder().encode(value).byteLength>1024){throw new CodeNavigationValidationError(`CodeDiff ${name} must be at most 1024 bytes.`)}}function buildCodeDiffVariables(params){const target=params.target;const variables={};if("registry"in target){variables.registry=target.registry;variables.name=target.packageName;variables.fromVersion=params.from;variables.toVersion=params.to}else{variables.repoUrl=target.repoUrl;variables.fromRef=params.from;variables.toRef=params.to}const rawOptions=Object.fromEntries(Object.entries(params.options??{}).filter(([,value])=>value!==undefined));if(Object.keys(rawOptions).length>0)variables.rawOptions=rawOptions;return variables}function isCodeDiffRawError(error){return error.path?.some((part)=>part==="raw")??false}function normaliseCodeDiffResult(result){if(!result.raw){throw new MalformedCodeNavigationResponseError("CodeDiff response missing non-null raw result.")}return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:normaliseRawCodeDiff(result.raw)}}function normaliseCodeDiffPartial(result){return{package:normaliseCodeDiffPackage(result.package),fromResolution:normaliseCodeDiffResolution(result.fromResolution),toResolution:normaliseCodeDiffResolution(result.toResolution),raw:result.raw?normaliseRawCodeDiff(result.raw):undefined}}function normaliseCodeDiffPackage(value){if(!value)return;return{registry:value.registry,name:value.name,repoUrl:value.repoUrl}}function normaliseCodeDiffResolution(value){return{requested:value.requested,resolvedVersion:value.resolvedVersion??undefined,ref:value.ref,commitSha:value.commitSha,refKind:value.refKind,versionSource:value.versionSource??undefined}}function normaliseRawCodeDiff(value){return{summary:value.summary,scope:{status:value.scope.status,fromSubpath:value.scope.fromSubpath??undefined,toSubpath:value.scope.toSubpath??undefined,pathPrefix:value.scope.pathPrefix??undefined,pathGlob:value.scope.pathGlob??undefined},contentCoverage:value.contentCoverage,contentFailure:value.contentFailure?{code:value.contentFailure.code,retryable:value.contentFailure.retryable,retryAfterMs:value.contentFailure.retryAfterMs??undefined,stage:value.contentFailure.stage??undefined,limitKind:value.contentFailure.limitKind??undefined}:undefined,files:value.files.map((file)=>({path:file.path,pathEncoding:file.pathEncoding,status:file.status,modeChanged:file.modeChanged,typeChanged:file.typeChanged,additions:file.additions??undefined,deletions:file.deletions??undefined,patch:file.patch??undefined,contentStatus:file.contentStatus,contentOmissionReason:file.contentOmissionReason??undefined,contentSafety:{filtered:file.contentSafety.filtered,modifications:file.contentSafety.modifications}})),hasMoreFiles:value.hasMoreFiles}}function parseCodeDiffErrorDetails(errors){const extensions=getPrimaryExtensions(errors);if(!extensions)return;const details={};if(typeof extensions.code==="string")details.code=extensions.code;if(typeof extensions.retryable==="boolean"){details.retryable=extensions.retryable}if(extensions.side==="from"||extensions.side==="to"){details.side=extensions.side}const publishedVersions=parseCodeDiffStringArray(extensions.published_versions);if(publishedVersions)details.publishedVersions=publishedVersions;if(typeof extensions.published_versions_truncated==="boolean"){details.publishedVersionsTruncated=extensions.published_versions_truncated}const availableVersions=parseCodeDiffErrorRefs(extensions.available_versions);if(availableVersions)details.availableVersions=availableVersions;if(typeof extensions.registry==="string"){details.registry=extensions.registry}if(typeof extensions.retry_after_ms==="number"&&Number.isInteger(extensions.retry_after_ms)&&extensions.retry_after_ms>=0){details.retryAfterMs=extensions.retry_after_ms}if(typeof extensions.stage==="string")details.stage=extensions.stage;if(typeof extensions.limit_kind==="string"){details.limitKind=extensions.limit_kind}if(typeof extensions.repo_url==="string"){details.repoUrl=extensions.repo_url}if(typeof extensions.git_ref==="string")details.gitRef=extensions.git_ref;const availableRefs=parseCodeDiffErrorRefs(extensions.available_refs);if(availableRefs)details.availableRefs=availableRefs;const suggestedRefs=parseCodeDiffErrorRefs(extensions.suggested_refs);if(suggestedRefs)details.suggestedRefs=suggestedRefs;const refKinds=parseCodeDiffStringArray(extensions.ref_kinds);if(refKinds)details.refKinds=refKinds;return Object.keys(details).length>0?details:undefined}function parseCodeDiffStringArray(value){if(!Array.isArray(value))return;if(value.some((entry)=>typeof entry!=="string"))return;return value}function parseCodeDiffErrorRefs(value){if(!Array.isArray(value))return;const refs=[];for(const entry of value){if(!entry||typeof entry!=="object"||Array.isArray(entry)){return}const record=entry;if(typeof record.ref!=="string"||record.version!==undefined&&record.version!==null&&typeof record.version!=="string"){return}refs.push({ref:record.ref,version:typeof record.version==="string"?record.version:undefined})}return refs}function createCodeNavigationHttpError(response){const status=response.status;const detail=parseHttpErrorDetail(response.responseBody,["detail","error"]);if(status===401){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new CodeNavigationAccessError(detail??"Code navigation access denied.")}if(status>=500){return new CodeNavigationBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new CodeNavigationBackendError(detail??`Request failed with status ${status}`,status)}function createCodeNavigationTransportError(error){if(isFetchTimeoutError(error.cause)){return new CodeNavigationBackendError("Code navigation request timed out.",undefined,"TIMEOUT",true)}return new CodeNavigationNetworkError("Could not reach the code navigation service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createCodeNavigationGraphQLError(errors,runtime={}){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;const indexingRef=getGraphQLIndexingRef(errors);const indexingEstimate=parseIndexingDurationEstimate(extensions);const errorMetadata=parseGraphQLErrorMetadata(extensions,indexingEstimate);if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,runtime.clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=code-nav-wire to inspect GraphQL details during local development.";if(runtime.diagnostics?.isEnabled("code-nav")){runtime.diagnostics.debug("code-nav",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new CodeNavigationBackendError(runtime.diagnostics?.isEnabled("code-nav-wire")?message:sanitized,undefined,code,retryable)}switch(code){case"PACKAGE_INDEXING":return new CodeNavigationIndexingError(message,indexingRef,parseAvailableVersions(extensions),parseAvailableRefs(extensions),parseTargetResolution(extensions),indexingEstimate,typeof extensions?.hint==="string"?extensions.hint:undefined,undefined,parseGraphQLRepoUrl(extensions));case"GREP_PATTERN_TOO_SHORT":case"GREP_PATTERN_TOO_LONG":case"GREP_PATTERN_INVALID":case"GREP_INVALID_REGEX":case"GREP_UNSUPPORTED_PATTERN":case"GREP_PATTERN_TOO_UNSELECTIVE":case"GREP_SCOPE_REQUIRED":case"GREP_SELECTOR_INVALID":case"GREP_CURSOR_INVALID":case"GREP_CONTEXT_TOO_LARGE":case"GREP_CONTEXT_NEGATIVE":case"GREP_MAX_MATCHES_TOO_LARGE":case"GREP_MAX_MATCHES_INVALID":return new CodeNavigationValidationError(message);case"VERSION_NOT_FOUND":return new CodeNavigationVersionNotFoundError(message,typeof extensions?.package==="string"?extensions.package:undefined,typeof extensions?.requested_version==="string"?extensions.requested_version:undefined,typeof extensions?.latest_indexed==="string"?extensions.latest_indexed:undefined,parseAvailableVersions(extensions),errorMetadata);case"REF_NOT_FOUND":return new CodeNavigationRefNotFoundError(message,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),parseAvailableRefs(extensions),parseSuggestedRefs(extensions),errorMetadata);case"NOT_FOUND":case"PACKAGE_NOT_FOUND":case"NO_REPOSITORY_URL":return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"REPOSITORY_NOT_FOUND":return new CodeNavigationTargetNotFoundError(message,undefined,parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata);case"FILE_NOT_FOUND":return new CodeNavigationFileNotFoundError(message,typeof extensions?.file_path==="string"?extensions.file_path:typeof extensions?.filePath==="string"?extensions.filePath:undefined);case"UNSUPPORTED_REGISTRY":case"VALIDATION_ERROR":return new CodeNavigationValidationError(message);case"FEATURE_FLAG_REQUIRED":return new CodeNavigationFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"GREP_FILE_TOO_LARGE":case"GREP_TIMEOUT":case"GREP_SERVICE_UNAVAILABLE":case"GREP_FAILED":case"GREP_INDEX_NOT_AVAILABLE":case"FILE_PATH_EXCLUDED":case"SOURCE_FILE_INVENTORY_UNKNOWN":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata);default:break}if(code===undefined){if(isAuthMessage(message)){return new CodeNavigationAccessError("Code navigation access denied. This feature may not be enabled for your account.")}if(isUnresolvableMessage(message)){return new CodeNavigationUnresolvableError(message)}if(isTargetNotFoundMessage(message)){return new CodeNavigationTargetNotFoundError(message,parseAvailableVersions(extensions),parseGraphQLRepoUrl(extensions),parseGraphQLGitRef(extensions),errorMetadata)}}return new CodeNavigationBackendError(message,undefined,code,retryable,errorMetadata)}function buildTargetResolutionFallbackQueries(query){const withoutSuggestedRefs=query.replaceAll(TARGET_RESOLUTION_SUGGESTED_REFS_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_SUGGESTED_REFS_SELECTION,"");const candidates=[withoutSuggestedRefs,withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_AVAILABLE_REFS_SELECTION,""),withoutSuggestedRefs.replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,""),withoutSuggestedRefs.replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,""),withoutSuggestedRefs.replaceAll(TARGET_RESOLUTION_SELECTION,"").replaceAll(DISCOVERY_TARGET_PROGRESS_RETRY_SELECTION,"").replaceAll(CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,"")];return candidates.filter((candidate,index,all)=>candidate!==query&&all.indexOf(candidate)===index)}function hasSchemaMismatchErrors(parsedBody){if(!parsedBody||typeof parsedBody!=="object")return false;const errors=parsedBody.errors;if(!Array.isArray(errors))return false;return errors.some((entry)=>{if(!entry||typeof entry!=="object")return false;const error=entry;if(typeof error.message!=="string")return false;const code=typeof error.extensions?.code==="string"?error.extensions.code:undefined;return isGraphQLSchemaMismatchError({message:error.message,code})})}function getPrimaryExtensions(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}function getGraphQLIndexingRef(errors){for(const error of errors){const indexingRef=error.extensions?.indexing_ref??error.extensions?.indexingRef;if(typeof indexingRef==="string")return indexingRef}return}function parseAvailableVersions(extensions){const raw=extensions?.available_versions??extensions?.availableVersions;return parseAvailableArtifacts(raw)}function parseAvailableRefs(extensions){const raw=extensions?.available_refs??extensions?.availableRefs;return parseAvailableArtifacts(raw)}function parseSuggestedRefs(extensions){const raw=extensions?.suggested_refs??extensions?.suggestedRefs;return parseAvailableArtifacts(raw)}function parseGraphQLErrorMetadata(extensions,indexingEstimate){const metadata={};if(typeof extensions?.hint==="string")metadata.hint=extensions.hint;const filePath=extensions?.file_path??extensions?.filePath;if(typeof filePath==="string")metadata.filePath=filePath;const exclusionReason=extensions?.exclusion_reason??extensions?.exclusionReason;if(typeof exclusionReason==="string"){metadata.exclusionReason=exclusionReason}const availableVersions=parseAvailableVersions(extensions);if(availableVersions?.length)metadata.availableVersions=availableVersions;const availableRefs=parseAvailableRefs(extensions);if(availableRefs?.length)metadata.availableRefs=availableRefs;const suggestedRefs=parseSuggestedRefs(extensions);if(suggestedRefs?.length)metadata.suggestedRefs=suggestedRefs;const targetResolution=parseTargetResolution(extensions);if(targetResolution)metadata.targetResolution=targetResolution;if(indexingEstimate)metadata.indexingEstimate=indexingEstimate;return Object.keys(metadata).length>0?metadata:undefined}function parseGraphQLRepoUrl(extensions){return typeof extensions?.repo_url==="string"?extensions.repo_url:typeof extensions?.repoUrl==="string"?extensions.repoUrl:undefined}function parseGraphQLGitRef(extensions){return typeof extensions?.git_ref==="string"?extensions.git_ref:typeof extensions?.gitRef==="string"?extensions.gitRef:undefined}function parseTargetResolution(extensions){const raw=extensions?.target_resolution??extensions?.targetResolution;const parsed=targetResolutionSchema.safeParse(raw);if(!parsed.success)return;return normaliseTargetResolution(parsed.data)}function normaliseCodeContextResult(data){return{filePath:data.filePath??undefined,language:data.language??undefined,totalLines:data.totalLines??undefined,startLine:data.startLine??undefined,endLine:data.endLine??undefined,content:data.content??undefined,isBinary:data.isBinary??undefined,targetResolution:normaliseTargetResolution(data.targetResolution),availableVersions:normaliseAvailableVersions(data.availableVersions),indexingEstimates:data.indexingEstimates}}function throwIfCodeContextIndexing(data){if(data.codeIndexState!=="INDEXING")return;const targetResolution=normaliseTargetResolution(data.targetResolution);const indexingEstimate=normaliseIndexingDurationEstimate(data.indexingEstimate);throw new CodeNavigationIndexingError("Target is indexing.",data.indexingRef??targetResolution?.indexingRef,normaliseAvailableVersions(data.availableVersions)??targetResolution?.availableVersions,targetResolution?.availableRefs,targetResolution,indexingEstimate,undefined,data.indexingEstimates)}function parseCodeContextResult(data){const parsed=codeContextResponseSchema.safeParse(data);if(!parsed.success){throw new MalformedCodeNavigationResponseError("Malformed response from code navigation service.")}throwIfCodeContextIndexing(parsed.data);return normaliseCodeContextResult(parsed.data)}function normaliseAvailableVersions(entries){if(!entries||entries.length===0)return;return entries.map((entry)=>({version:entry.version??undefined,ref:entry.ref}))}function normaliseTargetResolution(resolution){if(!resolution)return;return{requested:normaliseTargetResolutionIdentity(resolution.requested),resolvedRequested:normaliseTargetResolutionIdentity(resolution.resolvedRequested),served:normaliseTargetResolutionIdentity(resolution.served),freshness:resolution.freshness??undefined,freshnessReason:resolution.freshnessReason??undefined,indexingRef:resolution.indexingRef??undefined,availableVersions:normaliseAvailableVersions(resolution.availableVersions)??[],availableRefs:normaliseAvailableVersions(resolution.availableRefs)??[],suggestedRefs:normaliseAvailableVersions(resolution.suggestedRefs)??[]}}function normaliseDocCoverage(coverage,options={}){if(!coverage)return;if(coverage.coverageState==="NONE"&&!options.preserveNone){return}const out={coverageState:coverage.coverageState};if(coverage.coverageReason)out.coverageReason=coverage.coverageReason;if(typeof coverage.pagesCrawled==="number"){out.pagesCrawled=coverage.pagesCrawled}if(typeof coverage.frontierRemaining==="number"||coverage.frontierRemaining===null){out.frontierRemaining=coverage.frontierRemaining}if(typeof coverage.artifactOverflowPageCount==="number"){out.artifactOverflowPageCount=coverage.artifactOverflowPageCount}if(typeof coverage.estimatedTotalPages==="number"){out.estimatedTotalPages=coverage.estimatedTotalPages}if(coverage.note)out.note=coverage.note;return out}function normaliseTargetResolutionIdentity(identity){if(!identity)return;const out={};if(identity.kind)out.kind=identity.kind;if(identity.registry)out.registry=identity.registry;if(identity.packageName)out.packageName=identity.packageName;if(identity.version)out.version=identity.version;if(identity.repoUrl)out.repoUrl=identity.repoUrl;if(identity.gitRef)out.gitRef=identity.gitRef;if(identity.commitSha)out.commitSha=identity.commitSha;if(identity.committedAt)out.committedAt=identity.committedAt;if(identity.site)out.site=identity.site;return Object.keys(out).length>0?out:undefined}function isAuthMessage(message){const lower=message.toLowerCase();return lower.includes("unauthorized")||lower.includes("forbidden")||lower.includes("permission")||lower.includes("authentication")}function normaliseTargetMode(value){if(value==="PACKAGES"||value==="REPO"||value==="MIXED"||value==="SITES"||value==="SITE"){return value}return}function normaliseRequestedRefKind(value){switch(value){case"OMITTED_VERSION":case"LATEST_VERSION":case"EXACT_VERSION":case"DEFAULT_BRANCH":case"HEAD":case"BRANCH":case"SHA":return value;default:return}}function normaliseProgressFilters(filters){if(!filters)return;const out={};if(filters.fileIntent)out.fileIntent=filters.fileIntent;if(filters.kind)out.kind=filters.kind;if(filters.category)out.category=filters.category;if(typeof filters.publicOnly==="boolean"){out.publicOnly=filters.publicOnly}if(filters.pathPrefix)out.pathPrefix=filters.pathPrefix;return Object.keys(out).length>0?out:undefined}function isTargetNotFoundMessage(message){const lower=message.toLowerCase();return lower.includes("not found")||lower.includes("unknown package")||lower.includes("no such package")||lower.includes("does not exist")}function isUnresolvableMessage(message){const lower=message.toLowerCase();return lower.includes("could not resolve")||lower.includes("cannot resolve")}import{z as z5}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 PackageIntelligenceDocumentationSectionUnresolvedError extends Error{reason;constructor(message,reason){super(message);this.reason=reason;this.name="PackageIntelligenceDocumentationSectionUnresolvedError"}}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"}}var githubRepositorySchema=z5.object({stargazersCount:z5.number().int().nullable().optional(),forksCount:z5.number().int().nullable().optional(),openIssuesCount:z5.number().int().nullable().optional(),archived:z5.boolean().nullable().optional(),language:z5.string().nullable().optional(),topics:z5.array(z5.string()).nullable().optional(),pushedAt:z5.string().nullable().optional()}).nullable().optional();var packageIdentitySchema=z5.object({name:z5.string().nullable().optional(),registry:z5.string().nullable().optional(),description:z5.string().nullable().optional(),latestVersion:z5.string().nullable().optional(),latestVersionPublishedAt:z5.string().nullable().optional(),versionCount:z5.number().int().nullable().optional(),downloadsRefreshedAt:z5.string().nullable().optional(),homepage:z5.string().nullable().optional(),repositoryUrl:z5.string().nullable().optional(),license:z5.string().nullable().optional(),downloadsLastMonth:z5.number().int().nullable().optional(),downloadsTotal:z5.number().int().nullable().optional(),githubRepository:githubRepositorySchema});var vulnerabilityOverviewSchema=z5.object({osvId:z5.string().nullable().optional(),summary:z5.string().nullable().optional(),severityScore:z5.number().nullable().optional(),publishedAt:z5.string().nullable().optional()});var packageSecurityOverviewSchema=z5.object({vulnerabilityCount:z5.number().int().nullable().optional(),allVulnerabilityCount:z5.number().int(),hasCurrentVulnerabilities:z5.boolean().nullable().optional(),recentVulnerabilities:z5.array(vulnerabilityOverviewSchema).nullable().optional()}).nullable().optional();var changelogEntrySchema=z5.object({version:z5.string().nullable().optional(),publishedAt:z5.string().nullable().optional(),body:z5.string().nullable().optional()});var packageSummaryResponseSchema=z5.object({package:packageIdentitySchema.nullable().optional(),security:packageSecurityOverviewSchema,latestChangelogs:z5.array(changelogEntrySchema).nullable().optional()});var graphQLErrorSchema2=z5.object({message:z5.string(),extensions:z5.record(z5.string(),z5.unknown()).optional()});var graphQLResponseSchema=z5.object({data:z5.object({packageSummary:packageSummaryResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var PACKAGE_SUMMARY_QUERY=`
708
+ query PackageSummary(
709
+ $registry: Registry!
710
+ $name: String!
711
+ $includeVerboseFields: Boolean! = true
712
+ ) {
713
+ packageSummary(registry: $registry, name: $name) {
714
+ package {
715
+ name
716
+ registry
717
+ description
718
+ latestVersion
719
+ latestVersionPublishedAt
720
+ homepage
721
+ repositoryUrl
722
+ license
723
+ downloadsLastMonth
724
+ downloadsTotal
725
+ versionCount @include(if: $includeVerboseFields)
726
+ downloadsRefreshedAt @include(if: $includeVerboseFields)
727
+ githubRepository {
728
+ stargazersCount
729
+ forksCount
730
+ openIssuesCount
731
+ archived
732
+ language @include(if: $includeVerboseFields)
733
+ topics @include(if: $includeVerboseFields)
734
+ pushedAt @include(if: $includeVerboseFields)
735
+ }
736
+ }
737
+ security {
738
+ vulnerabilityCount
739
+ allVulnerabilityCount
740
+ hasCurrentVulnerabilities
741
+ recentVulnerabilities @include(if: $includeVerboseFields) {
742
+ osvId
743
+ summary
744
+ severityScore
745
+ publishedAt
746
+ }
747
+ }
748
+ latestChangelogs(limit: 3) @include(if: $includeVerboseFields) {
749
+ version
750
+ publishedAt
751
+ body
752
+ }
753
+ }
754
+ }`;var packageVersionIdentitySchema=z5.object({name:z5.string().nullable().optional(),registry:z5.string().nullable().optional(),version:z5.string().nullable().optional(),publishedAt:z5.string().nullable().optional(),deprecated:z5.boolean().nullable().optional(),deprecationReason:z5.string().nullable().optional()});var vulnerabilityDetailSchema=z5.object({osvId:z5.string().nullable().optional(),summary:z5.string().nullable().optional(),severityScore:z5.number().nullable().optional(),severityType:z5.string().nullable().optional(),affectedVersionRanges:z5.array(z5.string()).nullable().optional(),affectedVersionRangesCount:z5.number().int(),affectedVersionRangesTruncated:z5.boolean(),fixedInVersions:z5.array(z5.string()).nullable().optional(),publishedAt:z5.string().nullable().optional(),modifiedAt:z5.string().nullable().optional(),withdrawnAt:z5.string().nullable().optional(),aliases:z5.array(z5.string()).nullable().optional(),isMalicious:z5.boolean().nullable().optional(),affectsInspectedVersion:z5.boolean(),matchedAffectedVersionRanges:z5.array(z5.string()),duplicateIds:z5.array(z5.string())});var pageInfoSchema=z5.object({hasNextPage:z5.boolean(),endCursor:z5.string().nullable().optional(),totalCount:z5.number().int()});var vulnerabilityAdvisoryPageSchema=z5.object({entries:z5.array(vulnerabilityDetailSchema),pageInfo:pageInfoSchema});var vulnerabilitySecurityDetailsSchema=z5.object({affectedVulnerabilityCount:z5.number().int(),nonAffectingVulnerabilityCount:z5.number().int(),allVulnerabilityCount:z5.number().int(),currentVersionAffected:z5.boolean().nullable().optional(),advisories:vulnerabilityAdvisoryPageSchema,upgradePaths:z5.array(z5.string()).nullable().optional()}).nullable().optional();var vulnerabilityReportResponseSchema=z5.object({package:packageVersionIdentitySchema.nullable().optional(),security:vulnerabilitySecurityDetailsSchema});var vulnerabilitiesGraphQLResponseSchema=z5.object({data:z5.object({packageVulnerabilities:vulnerabilityReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var transitiveAuditAdvisorySchema=z5.object({osvId:z5.string().nullable().optional(),summary:z5.string().nullable().optional(),severityScore:z5.number().nullable().optional(),affectedVersionRanges:z5.array(z5.string()).nullable().optional(),fixedInVersions:z5.array(z5.string()).nullable().optional(),publishedAt:z5.string().nullable().optional(),modifiedAt:z5.string().nullable().optional(),aliases:z5.array(z5.string()).nullable().optional(),isMalicious:z5.boolean().nullable().optional()});var transitiveAuditOccurrenceSchema=z5.object({version:z5.string(),affectsResolvedVersion:z5.boolean(),matchedAffectedVersionRanges:z5.array(z5.string()),fixVersionsAboveResolved:z5.array(z5.string()),nearestFixedVersion:z5.string().nullable().optional(),advisory:transitiveAuditAdvisorySchema});var transitiveAuditPackageSchema=z5.object({registry:z5.string(),name:z5.string(),selectedCount:z5.number().int().nonnegative(),advisoryOccurrences:z5.array(transitiveAuditOccurrenceSchema).nullable().optional()});var transitiveAuditSummarySchema=z5.object({selected:z5.object({totalVulnerabilities:z5.number().int().nonnegative()}),totalPackagesAnalyzed:z5.number().int().nonnegative(),packages:z5.array(transitiveAuditPackageSchema),calculatedAt:z5.string().nullable().optional()});var transitiveAuditResponseSchema=z5.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:z5.object({transitive:z5.object({vulnerabilitySummary:transitiveAuditSummarySchema.nullable().optional()}).nullable().optional()}).nullable().optional()});var transitiveAuditGraphQLResponseSchema=z5.object({data:z5.object({packageDependencies:transitiveAuditResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var PACKAGE_VULNERABILITIES_QUERY=`
755
+ query PackageVulnerabilities(
756
+ $registry: Registry!
757
+ $name: String!
758
+ $version: String
759
+ $minSeverity: Float
760
+ $includeWithdrawn: Boolean
761
+ $scope: VulnerabilityScope = AFFECTED
762
+ $after: String
763
+ ) {
764
+ packageVulnerabilities(
765
+ registry: $registry
766
+ name: $name
767
+ version: $version
768
+ minSeverity: $minSeverity
769
+ includeWithdrawn: $includeWithdrawn
770
+ ) {
771
+ package {
772
+ name
773
+ registry
774
+ version
775
+ }
776
+ security {
777
+ affectedVulnerabilityCount
778
+ nonAffectingVulnerabilityCount
779
+ allVulnerabilityCount
780
+ currentVersionAffected
781
+ upgradePaths
782
+ advisories(scope: $scope, first: 100, after: $after) {
783
+ entries {
784
+ osvId
785
+ summary
786
+ severityScore
787
+ severityType
788
+ affectedVersionRanges
789
+ affectedVersionRangesCount
790
+ affectedVersionRangesTruncated
791
+ fixedInVersions
792
+ publishedAt
793
+ modifiedAt
794
+ withdrawnAt
795
+ aliases
796
+ isMalicious
797
+ affectsInspectedVersion
798
+ matchedAffectedVersionRanges
799
+ duplicateIds
800
+ }
801
+ pageInfo {
802
+ hasNextPage
803
+ endCursor
804
+ totalCount
805
+ }
806
+ }
807
+ }
808
+ }
809
+ }`;var TRANSITIVE_AUDIT_SCOPE_FIELDS={AFFECTED:{summary:"affected",packageCount:"affectedCount"},NON_AFFECTING:{summary:"nonAffecting",packageCount:"nonAffectingCount"},ALL:{summary:"combined",packageCount:"totalCount"}};function buildPackageTransitiveVulnerabilityAuditQuery(scope){const fields=TRANSITIVE_AUDIT_SCOPE_FIELDS[scope];return`
810
+ query PackageTransitiveVulnerabilityAudit(
811
+ $registry: Registry!
812
+ $name: String!
813
+ $version: String!
814
+ $minSeverity: Float
815
+ $scope: VulnerabilityScope!
816
+ $includeTransitiveAdvisoryDetails: Boolean! = false
817
+ ) {
818
+ packageDependencies(
819
+ registry: $registry
820
+ name: $name
821
+ version: $version
822
+ includeTransitive: true
823
+ ) {
824
+ package {
825
+ name
826
+ registry
827
+ version
828
+ }
829
+ dependencies {
830
+ transitive {
831
+ vulnerabilitySummary(minSeverity: $minSeverity) {
832
+ selected: ${fields.summary} {
833
+ totalVulnerabilities
834
+ }
835
+ totalPackagesAnalyzed
836
+ calculatedAt
837
+ packages {
838
+ registry
839
+ name
840
+ selectedCount: ${fields.packageCount}
841
+ advisoryOccurrences(scope: $scope, minSeverity: $minSeverity) {
842
+ version
843
+ affectsResolvedVersion
844
+ matchedAffectedVersionRanges
845
+ fixVersionsAboveResolved
846
+ nearestFixedVersion
847
+ advisory {
848
+ osvId
849
+ summary
850
+ severityScore
851
+ affectedVersionRanges @include(if: $includeTransitiveAdvisoryDetails)
852
+ fixedInVersions @include(if: $includeTransitiveAdvisoryDetails)
853
+ publishedAt
854
+ modifiedAt
855
+ aliases
856
+ isMalicious
857
+ }
858
+ }
859
+ }
860
+ }
861
+ }
862
+ }
863
+ }
864
+ }`}var directDependencySchema=z5.object({name:z5.string().nullable().optional(),versionConstraint:z5.string().nullable().optional(),type:z5.string().nullable().optional()});var dependencyGraphNodeSchema=z5.object({registry:z5.string(),name:z5.string(),version:z5.string().nullable().optional()});var dependencyGraphEdgeSchema=z5.object({fromIndex:z5.number().int().nullable().optional(),toIndex:z5.number().int(),constraint:z5.string().nullable().optional(),dependencyType:z5.string().nullable().optional()});var dependencyGraphSchema=z5.object({formatVersion:z5.number().int(),nodes:z5.array(dependencyGraphNodeSchema),edges:z5.array(dependencyGraphEdgeSchema)});var vulnerabilityCountSummarySchema=z5.object({totalVulnerabilities:z5.number().int(),critical:z5.number().int(),high:z5.number().int(),medium:z5.number().int(),low:z5.number().int(),unknown:z5.number().int()});var vulnerabilitySummaryDetailSchema=z5.object({osvId:z5.string().nullable().optional(),registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),summary:z5.string().nullable().optional(),severityScore:z5.number().nullable().optional(),severityType:z5.string().nullable().optional(),affectedVersionRanges:z5.array(z5.string()).nullable().optional(),fixedInVersions:z5.array(z5.string()).nullable().optional(),publishedAt:z5.string().nullable().optional(),modifiedAt:z5.string().nullable().optional(),withdrawnAt:z5.string().nullable().optional(),aliases:z5.array(z5.string()).nullable().optional(),isMalicious:z5.boolean().nullable().optional()});var transitiveDependencyVulnerabilitySchema=z5.object({version:z5.string(),affectsResolvedVersion:z5.boolean(),matchedAffectedVersionRanges:z5.array(z5.string()),fixVersionsAboveResolved:z5.array(z5.string()),nearestFixedVersion:z5.string().nullable().optional(),advisory:vulnerabilitySummaryDetailSchema});var transitiveVulnerablePackageSchema=z5.object({registry:z5.string(),name:z5.string(),versions:z5.array(z5.string()),affectedCount:z5.number().int(),nonAffectingCount:z5.number().int(),totalCount:z5.number().int(),maxSeverityScore:z5.number().nullable().optional(),maxSeverityLabel:z5.string().nullable().optional(),advisoryIds:z5.array(z5.string()),mostCritical:vulnerabilitySummaryDetailSchema.nullable().optional(),advisoryOccurrences:z5.array(transitiveDependencyVulnerabilitySchema).nullable().optional()});var transitiveVulnerabilitySummarySchema=z5.object({affected:vulnerabilityCountSummarySchema,nonAffecting:vulnerabilityCountSummarySchema,combined:vulnerabilityCountSummarySchema,totalPackagesAnalyzed:z5.number().int(),affectedPackageCount:z5.number().int(),packages:z5.array(transitiveVulnerablePackageSchema),calculatedAt:z5.string().nullable().optional()}).nullable().optional();var dependencyDeprecationReasonSchema=z5.object({version:z5.string(),reason:z5.string().nullable().optional()});var deprecatedDependencySchema=z5.object({registry:z5.string(),name:z5.string(),versions:z5.array(z5.string()),reasons:z5.array(dependencyDeprecationReasonSchema)});var outdatedDependencyVersionSchema=z5.object({version:z5.string(),severity:z5.string()});var outdatedDependencySchema=z5.object({registry:z5.string(),name:z5.string(),latestVersion:z5.string().nullable().optional(),severity:z5.string(),versions:z5.array(outdatedDependencyVersionSchema),repositoryUrl:z5.string().nullable().optional()});var duplicateDependencySchema=z5.object({registry:z5.string().nullable().optional(),name:z5.string(),versions:z5.array(z5.string())});var dependencyConflictEdgeSchema=z5.object({fromIndex:z5.number().int().nullable().optional(),toIndex:z5.number().int(),versionConstraint:z5.string(),dependencyType:z5.string()});var dependencyConflictSchema=z5.object({packageName:z5.string(),requiredVersions:z5.array(z5.string()),conflictingEdges:z5.array(dependencyConflictEdgeSchema)});var dependencyIssueConflictSchema=z5.object({registry:z5.string().nullable().optional(),name:z5.string(),versions:z5.array(z5.string()),requiredVersions:z5.array(z5.string()),conflictingEdges:z5.array(dependencyConflictEdgeSchema)});var dependencyIssuesSummarySchema=z5.object({totalCount:z5.number().int(),deprecatedCount:z5.number().int(),outdatedCount:z5.number().int(),duplicateCount:z5.number().int(),conflictCount:z5.number().int(),deprecatedPackages:z5.array(deprecatedDependencySchema),outdatedPackages:z5.array(outdatedDependencySchema),duplicatePackages:z5.array(duplicateDependencySchema),conflicts:z5.array(dependencyIssueConflictSchema)}).nullable().optional();var circularDependencyCycleSchema=z5.object({cycleStart:z5.string(),circularPath:z5.array(z5.string()),displayChain:z5.string()});var environmentMarkerSchema=z5.object({type:z5.string().nullable().optional(),value:z5.string().nullable().optional(),raw:z5.string().nullable().optional()});var transitiveDependencySchema=z5.object({totalEdges:z5.number().int().nullable().optional(),uniquePackagesCount:z5.number().int().nullable().optional(),uniqueDependencies:z5.array(z5.string()).nullable().optional(),dependencyConflicts:z5.array(dependencyConflictSchema).nullable().optional(),circularDependencyCycles:z5.array(circularDependencyCycleSchema).nullable().optional(),dependencyGraph:dependencyGraphSchema.nullable().optional(),vulnerabilitySummary:transitiveVulnerabilitySummarySchema,dependencyIssues:dependencyIssuesSummarySchema}).nullable().optional();var dependencyBundleSchema=z5.object({direct:z5.array(directDependencySchema).nullable().optional(),transitive:transitiveDependencySchema}).nullable().optional();var groupDependencySchema=z5.object({name:z5.string(),constraint:z5.string().nullable().optional()});var dependencyGroupSchema=z5.object({name:z5.string(),lifecycle:z5.string(),conditionType:z5.string(),conditionValue:z5.string().nullable().optional(),selectionMode:z5.string(),exclusiveGroup:z5.string().nullable().optional(),fallbackPriority:z5.number().int().nullable().optional(),compatibleWith:z5.array(z5.string()).nullable().optional(),defaultEnabled:z5.boolean().nullable().optional(),dependencies:z5.array(groupDependencySchema)});var dependencyGroupsInfoSchema=z5.object({primaryGroup:z5.string().nullable().optional(),environmentMarkers:z5.array(environmentMarkerSchema).nullable().optional(),groups:z5.array(dependencyGroupSchema)}).nullable().optional();var dependencyReportResponseSchema=z5.object({package:packageVersionIdentitySchema.nullable().optional(),dependencies:dependencyBundleSchema,dependencyGroups:dependencyGroupsInfoSchema});var dependenciesGraphQLResponseSchema=z5.object({data:z5.object({packageDependencies:dependencyReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var PACKAGE_DEPENDENCIES_QUERY=`
865
+ query PackageDependencies(
866
+ $registry: Registry!
867
+ $name: String!
868
+ $version: String
869
+ $includeTransitive: Boolean
870
+ $includeTransitiveDetails: Boolean! = true
871
+ $includeDependencyGraph: Boolean! = true
872
+ $includeGroups: Boolean! = true
873
+ $includeDependencyIssues: Boolean! = false
874
+ $maxDepth: Int
875
+ $lifecycle: [String!]
876
+ ) {
877
+ packageDependencies(
878
+ registry: $registry
879
+ name: $name
880
+ version: $version
881
+ includeTransitive: $includeTransitive
882
+ maxDepth: $maxDepth
883
+ lifecycle: $lifecycle
884
+ ) {
885
+ package {
886
+ name
887
+ registry
888
+ version
889
+ }
890
+ dependencies {
891
+ # Backend-side summary block intentionally not selected — our
892
+ # envelope computes runtime.count client-side from direct[].length
893
+ # so the invariant runtime.count === runtime.items.length always
894
+ # holds regardless of backend-side drift.
895
+ direct {
896
+ name
897
+ versionConstraint
898
+ type
899
+ }
900
+ transitive {
901
+ totalEdges @include(if: $includeTransitiveDetails)
902
+ uniquePackagesCount @include(if: $includeTransitiveDetails)
903
+ uniqueDependencies @include(if: $includeTransitiveDetails)
904
+ dependencyConflicts @include(if: $includeTransitiveDetails) {
905
+ packageName
906
+ requiredVersions
907
+ conflictingEdges {
908
+ fromIndex
909
+ toIndex
910
+ versionConstraint
911
+ dependencyType
912
+ }
913
+ }
914
+ circularDependencyCycles @include(if: $includeTransitiveDetails) {
915
+ cycleStart
916
+ circularPath
917
+ displayChain
918
+ }
919
+ dependencyGraph @include(if: $includeDependencyGraph) {
920
+ formatVersion
921
+ nodes {
922
+ registry
923
+ name
924
+ version
925
+ }
926
+ edges {
927
+ fromIndex
928
+ toIndex
929
+ constraint
930
+ dependencyType
931
+ }
932
+ }
933
+ dependencyIssues @include(if: $includeDependencyIssues) {
934
+ totalCount
935
+ deprecatedCount
936
+ outdatedCount
937
+ duplicateCount
938
+ conflictCount
939
+ deprecatedPackages {
940
+ registry
941
+ name
942
+ versions
943
+ reasons {
944
+ version
945
+ reason
946
+ }
947
+ }
948
+ outdatedPackages {
949
+ registry
950
+ name
951
+ latestVersion
952
+ severity
953
+ versions {
954
+ version
955
+ severity
956
+ }
957
+ repositoryUrl
958
+ }
959
+ duplicatePackages {
960
+ registry
961
+ name
962
+ versions
963
+ }
964
+ conflicts {
965
+ registry
966
+ name
967
+ versions
968
+ requiredVersions
969
+ conflictingEdges {
970
+ fromIndex
971
+ toIndex
972
+ versionConstraint
973
+ dependencyType
974
+ }
975
+ }
976
+ }
977
+ }
978
+ }
979
+ dependencyGroups @include(if: $includeGroups) {
980
+ primaryGroup
981
+ environmentMarkers {
982
+ type
983
+ value
984
+ raw
985
+ }
986
+ groups {
987
+ name
988
+ lifecycle
989
+ conditionType
990
+ conditionValue
991
+ selectionMode
992
+ exclusiveGroup
993
+ fallbackPriority
994
+ compatibleWith
995
+ defaultEnabled
996
+ dependencies {
997
+ name
998
+ constraint
999
+ }
1000
+ }
1001
+ }
1002
+ }
1003
+ }`;var PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY=`
1004
+ query PackageUpgradeDependencyProbe(
1005
+ $registry: Registry!
1006
+ $name: String!
1007
+ $version: String!
1008
+ $includeTransitiveRisk: Boolean!
1009
+ $includeTransitiveSecurity: Boolean!
1010
+ $includeDependencyIssues: Boolean!
1011
+ $includeDependencyChanges: Boolean!
1012
+ $includeGroups: Boolean!
1013
+ $lifecycle: [String!]
1014
+ $minSeverity: Float
1015
+ ) {
1016
+ packageDependencies(
1017
+ registry: $registry
1018
+ name: $name
1019
+ version: $version
1020
+ includeTransitive: $includeTransitiveRisk
1021
+ lifecycle: $lifecycle
1022
+ ) {
1023
+ package {
1024
+ name
1025
+ registry
1026
+ version
1027
+ publishedAt
1028
+ deprecated
1029
+ deprecationReason
1030
+ }
1031
+ dependencies {
1032
+ direct {
1033
+ name
1034
+ versionConstraint
1035
+ type
1036
+ }
1037
+ transitive @include(if: $includeTransitiveRisk) {
1038
+ dependencyGraph @include(if: $includeDependencyChanges) {
1039
+ formatVersion
1040
+ nodes {
1041
+ registry
1042
+ name
1043
+ version
1044
+ }
1045
+ edges {
1046
+ fromIndex
1047
+ toIndex
1048
+ constraint
1049
+ dependencyType
1050
+ }
1051
+ }
1052
+ vulnerabilitySummary(minSeverity: $minSeverity) @include(if: $includeTransitiveSecurity) {
1053
+ affected {
1054
+ totalVulnerabilities
1055
+ critical
1056
+ high
1057
+ medium
1058
+ low
1059
+ unknown
1060
+ }
1061
+ nonAffecting {
1062
+ totalVulnerabilities
1063
+ critical
1064
+ high
1065
+ medium
1066
+ low
1067
+ unknown
1068
+ }
1069
+ combined {
1070
+ totalVulnerabilities
1071
+ critical
1072
+ high
1073
+ medium
1074
+ low
1075
+ unknown
1076
+ }
1077
+ totalPackagesAnalyzed
1078
+ affectedPackageCount
1079
+ calculatedAt
1080
+ packages {
1081
+ registry
1082
+ name
1083
+ versions
1084
+ affectedCount
1085
+ nonAffectingCount
1086
+ totalCount
1087
+ maxSeverityScore
1088
+ maxSeverityLabel
1089
+ advisoryIds(scope: AFFECTED)
1090
+ mostCritical {
1091
+ osvId
1092
+ registry
1093
+ packageName
1094
+ summary
1095
+ severityScore
1096
+ severityType
1097
+ affectedVersionRanges
1098
+ fixedInVersions
1099
+ publishedAt
1100
+ modifiedAt
1101
+ withdrawnAt
1102
+ aliases
1103
+ isMalicious
1104
+ }
1105
+ advisoryOccurrences(scope: AFFECTED, minSeverity: $minSeverity, limit: 5) {
1106
+ version
1107
+ affectsResolvedVersion
1108
+ matchedAffectedVersionRanges
1109
+ fixVersionsAboveResolved
1110
+ nearestFixedVersion
1111
+ advisory {
1112
+ osvId
1113
+ registry
1114
+ packageName
1115
+ summary
1116
+ severityScore
1117
+ severityType
1118
+ affectedVersionRanges
1119
+ fixedInVersions
1120
+ publishedAt
1121
+ modifiedAt
1122
+ withdrawnAt
1123
+ aliases
1124
+ isMalicious
1125
+ }
1126
+ }
1127
+ }
1128
+ }
1129
+ dependencyIssues @include(if: $includeDependencyIssues) {
1130
+ totalCount
1131
+ deprecatedCount
1132
+ outdatedCount
1133
+ duplicateCount
1134
+ conflictCount
1135
+ deprecatedPackages {
1136
+ registry
1137
+ name
1138
+ versions
1139
+ reasons {
1140
+ version
1141
+ reason
1142
+ }
1143
+ }
1144
+ outdatedPackages {
1145
+ registry
1146
+ name
1147
+ latestVersion
1148
+ severity
1149
+ versions {
1150
+ version
1151
+ severity
1152
+ }
1153
+ repositoryUrl
1154
+ }
1155
+ duplicatePackages {
1156
+ registry
1157
+ name
1158
+ versions
1159
+ }
1160
+ conflicts {
1161
+ registry
1162
+ name
1163
+ versions
1164
+ requiredVersions
1165
+ conflictingEdges {
1166
+ fromIndex
1167
+ toIndex
1168
+ versionConstraint
1169
+ dependencyType
1170
+ }
1171
+ }
1172
+ }
1173
+ }
1174
+ }
1175
+ dependencyGroups @include(if: $includeGroups) {
1176
+ primaryGroup
1177
+ environmentMarkers {
1178
+ type
1179
+ value
1180
+ raw
1181
+ }
1182
+ groups {
1183
+ name
1184
+ lifecycle
1185
+ conditionType
1186
+ conditionValue
1187
+ selectionMode
1188
+ exclusiveGroup
1189
+ fallbackPriority
1190
+ compatibleWith
1191
+ defaultEnabled
1192
+ dependencies {
1193
+ name
1194
+ constraint
1195
+ }
1196
+ }
1197
+ }
1198
+ }
1199
+ }`;var packageUpgradeAdvisorySchema=z5.object({id:z5.string().nullable().optional(),aliases:z5.array(z5.string()),summary:z5.string().nullable().optional(),severity:z5.number().nullable().optional(),severityLabel:z5.string().nullable().optional(),fixedIn:z5.array(z5.string()),isMalicious:z5.boolean().nullable().optional()});var packageUpgradeVersionVulnerabilitySummarySchema=z5.object({version:z5.string(),publishedAt:z5.string().nullable().optional(),deprecated:z5.boolean().nullable().optional(),deprecationReason:z5.string().nullable().optional(),affectedCount:z5.number().int(),nonAffectingCount:z5.number().int(),allCount:z5.number().int(),lastModifiedAt:z5.string().nullable().optional(),advisories:z5.array(packageUpgradeAdvisorySchema)}).nullable().optional();var packageUpgradeTransitivePackagePageSchema=z5.object({entries:z5.array(z5.object({id:z5.string(),registry:z5.string(),name:z5.string(),versions:z5.array(z5.string()),affectedCount:z5.number().int(),maxSeverityScore:z5.number().nullable().optional(),maxSeverityLabel:z5.string().nullable().optional(),advisoryIds:z5.array(z5.string())})),totalCount:z5.number().int(),truncated:z5.boolean()});var packageUpgradeTransitiveSecuritySchema=z5.object({currentAffected:z5.number().int(),targetAffected:z5.number().int(),introducedPackages:z5.array(z5.string()),fixedPackages:z5.array(z5.string()),introducedPackageDetails:packageUpgradeTransitivePackagePageSchema,fixedPackageDetails:packageUpgradeTransitivePackagePageSchema,stillAffectedPackageDetails:packageUpgradeTransitivePackagePageSchema}).nullable().optional();var packageUpgradeSecuritySchema=z5.object({current:packageUpgradeVersionVulnerabilitySummarySchema,target:packageUpgradeVersionVulnerabilitySummarySchema,added:z5.array(packageUpgradeAdvisorySchema),removed:z5.array(packageUpgradeAdvisorySchema),notAddressed:z5.array(packageUpgradeAdvisorySchema),fixed:z5.array(packageUpgradeAdvisorySchema),introduced:z5.array(packageUpgradeAdvisorySchema),unchanged:z5.array(packageUpgradeAdvisorySchema),transitive:packageUpgradeTransitiveSecuritySchema});var packageUpgradeChangelogEntrySchema=z5.object({version:z5.string().nullable().optional(),publishedAt:z5.string().nullable().optional(),htmlUrl:z5.string().nullable().optional(),body:z5.string().nullable().optional(),bodyPreview:z5.string().nullable().optional(),headline:z5.string().nullable().optional(),signals:z5.array(z5.string())});var packageUpgradeChangelogSchema=z5.object({source:z5.string().nullable().optional(),fallback:z5.string().nullable().optional(),entries:z5.array(packageUpgradeChangelogEntrySchema),sampledEntries:z5.array(packageUpgradeChangelogEntrySchema),keywordEntries:z5.array(packageUpgradeChangelogEntrySchema),totalKeywordEntries:z5.number().int(),totalEntries:z5.number().int(),totalEntriesWithBodies:z5.number().int(),truncated:z5.boolean(),hasReleaseNoteBodies:z5.boolean(),breakingSignals:z5.array(z5.string()),migrationSignals:z5.array(z5.string())});var packageUpgradeCompatibilitySchema=z5.object({peerDependencyChanges:z5.array(z5.string()),notes:z5.array(z5.string())}).nullable().optional();var packageUpgradeDependencyChangeItemSchema=z5.object({name:z5.string(),registry:z5.string().nullable().optional(),version:z5.string().nullable().optional(),fromVersions:z5.array(z5.string()),toVersions:z5.array(z5.string()),constraint:z5.string().nullable().optional(),type:z5.string().nullable().optional()});var packageUpgradeDependencyChangeGroupSchema=z5.object({added:z5.array(packageUpgradeDependencyChangeItemSchema),removed:z5.array(packageUpgradeDependencyChangeItemSchema),changed:z5.array(packageUpgradeDependencyChangeItemSchema)});var packageUpgradeDependencyChangesSchema=z5.object({direct:packageUpgradeDependencyChangeGroupSchema,transitive:packageUpgradeDependencyChangeGroupSchema}).nullable().optional();var packageUpgradeDependencyIssuesSchema=z5.object({currentTotal:z5.number().int(),targetTotal:z5.number().int(),introducedDeprecated:z5.array(z5.string()),introducedDuplicates:z5.array(z5.string()),introducedConflicts:z5.array(z5.string()),introducedOutdated:z5.array(z5.string())}).nullable().optional();var packageUpgradeReviewSchema=z5.object({registry:z5.string(),name:z5.string(),currentVersion:z5.string(),targetVersion:z5.string(),latestVersion:z5.string().nullable().optional(),versionDelta:z5.string(),security:packageUpgradeSecuritySchema,changelog:packageUpgradeChangelogSchema,compatibility:packageUpgradeCompatibilitySchema,dependencyChanges:packageUpgradeDependencyChangesSchema,dependencyIssues:packageUpgradeDependencyIssuesSchema,unknowns:z5.array(z5.string())});var packageUpgradeReviewResponseSchema=z5.object({summary:z5.object({total:z5.number().int(),withUnknowns:z5.number().int(),withAddedAdvisories:z5.number().int(),withBreakingSignals:z5.number().int(),withDirectDependencyChanges:z5.number().int(),withTransitiveVulnerabilityAdditions:z5.number().int()}),reviews:z5.array(packageUpgradeReviewSchema)});var packageUpgradeReviewGraphQLResponseSchema=z5.object({data:z5.object({packageUpgradeReview:packageUpgradeReviewResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var PACKAGE_UPGRADE_REVIEW_QUERY=`
1200
+ query PackageUpgradeReview(
1201
+ $packages: [PackageUpgradeReviewPackageInput!]!
1202
+ $includeTransitiveSecurity: Boolean!
1203
+ $includeDependencyIssues: Boolean!
1204
+ $minSeverity: Float
1205
+ $changelogLimit: Int!
1206
+ ) {
1207
+ packageUpgradeReview(
1208
+ packages: $packages
1209
+ includeTransitiveSecurity: $includeTransitiveSecurity
1210
+ minSeverity: $minSeverity
1211
+ changelogLimit: $changelogLimit
1212
+ ) {
1213
+ summary {
1214
+ total
1215
+ withUnknowns
1216
+ withAddedAdvisories
1217
+ withBreakingSignals
1218
+ withDirectDependencyChanges
1219
+ withTransitiveVulnerabilityAdditions
1220
+ }
1221
+ reviews {
1222
+ registry
1223
+ name
1224
+ currentVersion
1225
+ targetVersion
1226
+ latestVersion
1227
+ versionDelta
1228
+ security {
1229
+ current {
1230
+ version
1231
+ publishedAt
1232
+ deprecated
1233
+ deprecationReason
1234
+ affectedCount
1235
+ nonAffectingCount
1236
+ allCount
1237
+ lastModifiedAt
1238
+ advisories {
1239
+ ...PackageUpgradeAdvisoryFields
1240
+ }
1241
+ }
1242
+ target {
1243
+ version
1244
+ publishedAt
1245
+ deprecated
1246
+ deprecationReason
1247
+ affectedCount
1248
+ nonAffectingCount
1249
+ allCount
1250
+ lastModifiedAt
1251
+ advisories {
1252
+ ...PackageUpgradeAdvisoryFields
1253
+ }
1254
+ }
1255
+ added {
1256
+ ...PackageUpgradeAdvisoryFields
1257
+ }
1258
+ removed {
1259
+ ...PackageUpgradeAdvisoryFields
1260
+ }
1261
+ notAddressed {
1262
+ ...PackageUpgradeAdvisoryFields
1263
+ }
1264
+ fixed {
1265
+ ...PackageUpgradeAdvisoryFields
1266
+ }
1267
+ introduced {
1268
+ ...PackageUpgradeAdvisoryFields
1269
+ }
1270
+ unchanged {
1271
+ ...PackageUpgradeAdvisoryFields
1272
+ }
1273
+ transitive @include(if: $includeTransitiveSecurity) {
1274
+ currentAffected
1275
+ targetAffected
1276
+ introducedPackages
1277
+ fixedPackages
1278
+ introducedPackageDetails(first: 50) {
1279
+ ...PackageUpgradeTransitivePackagePageFields
1280
+ }
1281
+ fixedPackageDetails(first: 50) {
1282
+ ...PackageUpgradeTransitivePackagePageFields
1283
+ }
1284
+ stillAffectedPackageDetails(first: 50) {
1285
+ ...PackageUpgradeTransitivePackagePageFields
1286
+ }
1287
+ }
1288
+ }
1289
+ changelog {
1290
+ source
1291
+ fallback
1292
+ entries {
1293
+ ...PackageUpgradeChangelogEntryFields
1294
+ }
1295
+ sampledEntries {
1296
+ ...PackageUpgradeChangelogEntryFields
1297
+ }
1298
+ keywordEntries {
1299
+ ...PackageUpgradeChangelogEntryFields
1300
+ }
1301
+ totalKeywordEntries
1302
+ totalEntries
1303
+ totalEntriesWithBodies
1304
+ truncated
1305
+ hasReleaseNoteBodies
1306
+ breakingSignals
1307
+ migrationSignals
1308
+ }
1309
+ compatibility {
1310
+ peerDependencyChanges
1311
+ notes
1312
+ }
1313
+ dependencyChanges {
1314
+ direct {
1315
+ ...PackageUpgradeDependencyChangeGroupFields
1316
+ }
1317
+ transitive {
1318
+ ...PackageUpgradeDependencyChangeGroupFields
1319
+ }
1320
+ }
1321
+ dependencyIssues @include(if: $includeDependencyIssues) {
1322
+ currentTotal
1323
+ targetTotal
1324
+ introducedDeprecated
1325
+ introducedDuplicates
1326
+ introducedConflicts
1327
+ introducedOutdated
1328
+ }
1329
+ unknowns
1330
+ }
1331
+ }
1332
+ }
1333
+
1334
+ fragment PackageUpgradeAdvisoryFields on PackageUpgradeAdvisorySummary {
1335
+ id
1336
+ aliases
1337
+ summary
1338
+ severity
1339
+ severityLabel
1340
+ fixedIn
1341
+ isMalicious
1342
+ }
1343
+
1344
+ fragment PackageUpgradeTransitivePackagePageFields on PackageUpgradeTransitivePackagePage {
1345
+ entries {
1346
+ id
1347
+ registry
1348
+ name
1349
+ versions
1350
+ affectedCount
1351
+ maxSeverityScore
1352
+ maxSeverityLabel
1353
+ advisoryIds
1354
+ }
1355
+ totalCount
1356
+ truncated
1357
+ }
1358
+
1359
+ fragment PackageUpgradeChangelogEntryFields on PackageUpgradeChangelogEntry {
1360
+ version
1361
+ publishedAt
1362
+ htmlUrl
1363
+ body
1364
+ bodyPreview
1365
+ headline
1366
+ signals
1367
+ }
1368
+
1369
+ fragment PackageUpgradeDependencyChangeGroupFields on PackageUpgradeDependencyChangeGroup {
1370
+ added {
1371
+ name
1372
+ registry
1373
+ version
1374
+ fromVersions
1375
+ toVersions
1376
+ constraint
1377
+ type
1378
+ }
1379
+ removed {
1380
+ name
1381
+ registry
1382
+ version
1383
+ fromVersions
1384
+ toVersions
1385
+ constraint
1386
+ type
1387
+ }
1388
+ changed {
1389
+ name
1390
+ registry
1391
+ version
1392
+ fromVersions
1393
+ toVersions
1394
+ constraint
1395
+ type
1396
+ }
1397
+ }`;var changelogPackageInfoSchema=z5.object({name:z5.string().nullable().optional(),registry:z5.string().nullable().optional(),fromVersion:z5.string().nullable().optional(),toVersion:z5.string().nullable().optional(),limit:z5.number().int().nullable().optional()}).nullable().optional();var changelogEntryDetailSchema=z5.object({version:z5.string().nullable().optional(),normalizedVersion:z5.string().nullable().optional(),body:z5.string().nullable().optional(),htmlUrl:z5.string().nullable().optional(),publishedAt:z5.string().nullable().optional()});var changelogReportResponseSchema=z5.object({package:changelogPackageInfoSchema,source:z5.string().nullable().optional(),entries:z5.array(changelogEntryDetailSchema).nullable().optional()});var changelogGraphQLResponseSchema=z5.object({data:z5.object({packageChangelog:changelogReportResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var exactChangelogDetailSchema=z5.object({detailSource:z5.string().nullable().optional(),hasChangelog:z5.boolean(),entry:changelogEntryDetailSchema.nullable().optional()});var exactChangelogGraphQLResponseSchema=z5.object({data:z5.object({packageInfo:z5.object({selectedVersion:z5.object({resolvedVersion:z5.string(),changelog:exactChangelogDetailSchema.nullable().optional()}).nullable().optional()}).nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var PACKAGE_CHANGELOG_QUERY=`
1398
+ query PackageChangelog(
1399
+ $registry: Registry!
1400
+ $name: String!
1401
+ $fromVersion: String
1402
+ $toVersion: String
1403
+ $limit: Int
1404
+ $includeBodies: Boolean! = true
1405
+ ) {
1406
+ packageChangelog(
1407
+ registry: $registry
1408
+ name: $name
1409
+ fromVersion: $fromVersion
1410
+ toVersion: $toVersion
1411
+ limit: $limit
1412
+ ) {
1413
+ package {
1414
+ name
1415
+ registry
1416
+ fromVersion
1417
+ toVersion
1418
+ limit
1419
+ }
1420
+ source
1421
+ entries {
1422
+ version
1423
+ normalizedVersion
1424
+ body @include(if: $includeBodies)
1425
+ htmlUrl
1426
+ publishedAt
1427
+ }
1428
+ }
1429
+ }`;var PACKAGE_CHANGELOG_EXACT_QUERY=`
1430
+ query PackageChangelogExact(
1431
+ $registry: Registry!
1432
+ $name: String!
1433
+ $version: String
1434
+ $includeBodies: Boolean! = true
1435
+ ) {
1436
+ packageInfo(registry: $registry, name: $name, version: $version) {
1437
+ selectedVersion {
1438
+ resolvedVersion
1439
+ changelog {
1440
+ detailSource
1441
+ hasChangelog
1442
+ entry {
1443
+ normalizedVersion
1444
+ body @include(if: $includeBodies)
1445
+ htmlUrl
1446
+ publishedAt
1447
+ }
1448
+ }
1449
+ }
1450
+ }
1451
+ }`;function normaliseChangelogSource(raw){const trimmed=raw?.trim();if(!trimmed)return;return trimmed.toLowerCase()}var packageDocSourceKindSchema=z5.enum(["CRAWLED","REPOSITORY"]);var packageDocPageSummarySchema=z5.object({id:z5.string().nullable().optional(),readTarget:readTargetSchema,title:z5.string().nullable().optional(),slug:z5.string().nullable().optional(),order:z5.number().int().nullable().optional(),linkName:z5.string().nullable().optional(),lastUpdatedAt:z5.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),sourceUrl:z5.string().nullable().optional(),repoUrl:z5.string().nullable().optional(),gitRef:z5.string().nullable().optional(),requestedRef:z5.string().nullable().optional(),filePath:z5.string().nullable().optional()});var packageDocsPageInfoSchema=z5.object({hasNextPage:z5.boolean(),endCursor:z5.string().nullable().optional(),totalCount:z5.number().int().nullable().optional()}).nullable().optional();var packageDocsListResponseSchema=z5.object({indexingEstimates:indexingEstimatesSchema,registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),version:z5.string().nullable().optional(),stale:z5.boolean().nullable().optional(),codeIndexState:z5.string().nullable().optional(),pages:z5.array(packageDocPageSummarySchema).nullable().optional(),pageInfo:packageDocsPageInfoSchema});var packageDocSourceSchema=z5.object({url:z5.string().nullable().optional(),label:z5.string().nullable().optional()}).nullable().optional();var packageDocPageSchema=z5.object({id:z5.string().nullable().optional(),docsReadTarget:z5.string(),title:z5.string().nullable().optional(),content:z5.string().nullable().optional(),contentFormat:z5.string().nullable().optional(),breadcrumbs:z5.array(z5.string()).nullable().optional(),linkName:z5.string().nullable().optional(),lastUpdatedAt:z5.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),source:packageDocSourceSchema,repoUrl:z5.string().nullable().optional(),gitRef:z5.string().nullable().optional(),requestedRef:z5.string().nullable().optional(),filePath:z5.string().nullable().optional(),baseUrl:z5.string().nullable().optional()}).nullable().optional();var packageDocResultResponseSchema=z5.object({registry:z5.string().nullable().optional(),packageName:z5.string().nullable().optional(),version:z5.string().nullable().optional(),sourceKind:packageDocSourceKindSchema.nullable().optional(),contentRange:z5.object({startLine:z5.number().int().positive().nullable(),endLine:z5.number().int().positive().nullable(),totalLines:z5.number().int().nonnegative(),anchor:z5.string().nullable()}).superRefine((range,context)=>{const empty=range.totalLines===0;if(empty&&(range.startLine!==null||range.endLine!==null)){context.addIssue({code:"custom",message:"Empty documentation must have null range bounds."})}if(!empty&&(range.startLine===null||range.endLine===null)){context.addIssue({code:"custom",message:"Non-empty documentation must have range bounds."})}if(range.startLine!==null&&range.endLine!==null&&(range.startLine>range.endLine||range.endLine>range.totalLines)){context.addIssue({code:"custom",message:"Documentation range must fit within the complete page."})}}),page:packageDocPageSchema});var packageDocsListGraphQLResponseSchema=z5.object({data:z5.object({listPackageDocs:packageDocsListResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var packageDocReadGraphQLResponseSchema=z5.object({data:z5.object({getDocPage:packageDocResultResponseSchema.nullable().optional()}).nullable().optional(),errors:z5.array(graphQLErrorSchema2).optional()});var LIST_PACKAGE_DOCS_QUERY=`
1452
+ query ListPackageDocs(
1453
+ $registry: Registry!
1454
+ $packageName: String!
1455
+ $version: String
1456
+ $limit: Int
1457
+ $after: String
1458
+ ) {
1459
+ listPackageDocs(
1460
+ registry: $registry
1461
+ packageName: $packageName
1462
+ version: $version
1463
+ limit: $limit
1464
+ after: $after
1465
+ ) {
1466
+ registry
1467
+ packageName
1468
+ version
1469
+ stale
1470
+ codeIndexState
1471
+ ${INDEXING_ESTIMATES_SELECTION}
1472
+ pages {
1473
+ id
1474
+ readTarget { target }
1475
+ title
1476
+ slug
1477
+ order
1478
+ linkName
1479
+ lastUpdatedAt
1480
+ sourceKind
1481
+ sourceUrl
1482
+ repoUrl
1483
+ gitRef
1484
+ requestedRef
1485
+ filePath
1486
+ }
1487
+ pageInfo {
1488
+ hasNextPage
1489
+ endCursor
1490
+ totalCount
1491
+ }
1492
+ }
1493
+ }`;var READ_PACKAGE_DOC_QUERY=`
1494
+ query ReadPackageDoc($pageId: String!, $startLine: Int, $endLine: Int) {
1495
+ getDocPage(pageId: $pageId, startLine: $startLine, endLine: $endLine) {
1496
+ registry
1497
+ packageName
1498
+ version
1499
+ sourceKind
1500
+ contentRange {
1501
+ startLine
1502
+ endLine
1503
+ totalLines
1504
+ anchor
1505
+ }
1506
+ page {
1507
+ id
1508
+ docsReadTarget
1509
+ title
1510
+ content
1511
+ contentFormat
1512
+ breadcrumbs
1513
+ linkName
1514
+ lastUpdatedAt
1515
+ sourceKind
1516
+ source {
1517
+ url
1518
+ label
1519
+ }
1520
+ repoUrl
1521
+ gitRef
1522
+ requestedRef
1523
+ filePath
1524
+ baseUrl
1525
+ }
1526
+ }
1527
+ }`;class PackageIntelligenceServiceImpl2{endpointUrl;tokenProvider;fetchFn;runtime;constructor(endpointUrl,tokenProvider,fetchFn=globalThis.fetch,runtime={}){this.endpointUrl=endpointUrl;this.tokenProvider=tokenProvider;this.fetchFn=fetchFn;this.runtime=runtime}async packageSummary(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.summary.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageSummary(token,params)}))}async executePackageSummary(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_SUMMARY_QUERY,variables:{registry:params.registry,name:params.packageName,includeVerboseFields:params.includeVerboseFields!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=graphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageSummary;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalise(data)}createHttpError(response){return createPackageIntelligenceHttpError(response)}createTransportError(error){return createPackageIntelligenceTransportError(error)}createGraphQLError(errors){return createPackageIntelligenceGraphQLError(errors,this.runtime.clientVersion,this.runtime.diagnostics)}normalise(data){const name=data.package?.name??undefined;const latestVersion=data.package?.latestVersion??undefined;if(!name||!latestVersion){throw new MalformedPackageIntelligenceResponseError("Package summary response missing required name/latestVersion.")}const pkg=data.package;const github=pkg?.githubRepository;const identity={name,latestVersion,registry:pkg?.registry??undefined,description:pkg?.description??undefined,latestVersionPublishedAt:pkg?.latestVersionPublishedAt??undefined,homepage:pkg?.homepage??undefined,repositoryUrl:pkg?.repositoryUrl??undefined,license:pkg?.license??undefined,downloadsLastMonth:pkg?.downloadsLastMonth??undefined,downloadsTotal:pkg?.downloadsTotal??undefined,versionCount:pkg?.versionCount??undefined,downloadsRefreshedAt:pkg?.downloadsRefreshedAt??undefined,githubRepository:github?{stargazersCount:github.stargazersCount??undefined,forksCount:github.forksCount??undefined,openIssuesCount:github.openIssuesCount??undefined,archived:github.archived??undefined,language:github.language??undefined,topics:github.topics??undefined,pushedAt:github.pushedAt??undefined}:undefined};const security=data.security?{vulnerabilityCount:data.security.vulnerabilityCount??undefined,allVulnerabilityCount:data.security.allVulnerabilityCount,hasCurrentVulnerabilities:data.security.hasCurrentVulnerabilities??undefined,recentVulnerabilities:data.security.recentVulnerabilities?.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,publishedAt:vuln.publishedAt??undefined}))??undefined}:undefined;const latestChangelogs=data.latestChangelogs?.map((entry)=>({version:entry.version??undefined,publishedAt:entry.publishedAt??undefined,body:entry.body??undefined}))??undefined;return{package:identity,security,latestChangelogs}}async packageVulnerabilities(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.vulnerabilities.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageVulnerabilities(token,params)}))}async executePackageVulnerabilities(token,params){let after=null;let firstPage;const entries=[];const seenCursors=new Set;do{const page=await this.fetchPackageVulnerabilitiesPage(token,params,after);if(!firstPage)firstPage=page;const advisoryPage=page.security?.advisories;if(!advisoryPage){after=null;break}entries.push(...advisoryPage.entries);if(advisoryPage.pageInfo.hasNextPage){const nextCursor=advisoryPage.pageInfo.endCursor;if(!nextCursor){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination omitted next cursor.")}if(seenCursors.has(nextCursor)){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination repeated a cursor.")}seenCursors.add(nextCursor);after=nextCursor}else{after=null}}while(after!==null);if(!firstPage){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}if(firstPage.security){const expectedCount=firstPage.security.advisories.pageInfo.totalCount;if(entries.length!==expectedCount){throw new MalformedPackageIntelligenceResponseError("Vulnerability response pagination returned an incomplete advisory set.")}}const data=firstPage.security?{...firstPage,security:{...firstPage.security,advisories:{...firstPage.security.advisories,entries}}}:firstPage;const report=this.normaliseVulnerabilityReport(data);if(params.includeTransitive===true){report.transitive=await this.fetchTransitiveVulnerabilityAudit(token,report.package,params.minSeverity,params.advisoryScope??"AFFECTED",params)}return report}async fetchPackageVulnerabilitiesPage(token,params,after){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_VULNERABILITIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,minSeverity:params.minSeverity,includeWithdrawn:params.includeWithdrawn,scope:params.advisoryScope,after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=vulnerabilitiesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageVulnerabilities;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return data}normaliseVulnerabilityReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const security=data.security?{affectedVulnerabilityCount:data.security.affectedVulnerabilityCount,nonAffectingVulnerabilityCount:data.security.nonAffectingVulnerabilityCount,allVulnerabilityCount:data.security.allVulnerabilityCount,currentVersionAffected:data.security.currentVersionAffected??undefined,vulnerabilities:data.security.advisories.entries.map((vuln)=>({osvId:vuln.osvId??undefined,summary:vuln.summary??undefined,severityScore:vuln.severityScore??undefined,severityType:vuln.severityType??undefined,affectedVersionRanges:vuln.affectedVersionRanges??undefined,affectedVersionRangesCount:vuln.affectedVersionRangesCount,affectedVersionRangesTruncated:vuln.affectedVersionRangesTruncated,fixedInVersions:vuln.fixedInVersions??undefined,publishedAt:vuln.publishedAt??undefined,modifiedAt:vuln.modifiedAt??undefined,withdrawnAt:vuln.withdrawnAt??undefined,aliases:vuln.aliases??undefined,isMalicious:vuln.isMalicious??undefined,affectsInspectedVersion:vuln.affectsInspectedVersion,matchedAffectedVersionRanges:vuln.matchedAffectedVersionRanges,duplicateIds:vuln.duplicateIds})),upgradePaths:data.security.upgradePaths??undefined}:undefined;return{package:identity,security}}async fetchTransitiveVulnerabilityAudit(token,directIdentity,minSeverity,advisoryScope,params){if(!directIdentity.registry){throw new MalformedPackageIntelligenceResponseError("Vulnerability report response missing registry for transitive audit.")}let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:buildPackageTransitiveVulnerabilityAuditQuery(advisoryScope),variables:{registry:params.registry,name:directIdentity.name,version:directIdentity.version,minSeverity,scope:advisoryScope,includeTransitiveAdvisoryDetails:params.includeTransitiveAdvisoryDetails===true},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=transitiveAuditGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),{registry:params.registry,packageName:directIdentity.name,version:directIdentity.version})}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const packageIdentity=data.package;if(packageIdentity?.name!==directIdentity.name||packageIdentity.registry!==directIdentity.registry||packageIdentity.version!==directIdentity.version){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response package identity differs from the direct report.")}const summary=data.dependencies?.transitive?.vulnerabilitySummary;if(!summary){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit response missing vulnerability summary.")}return this.normaliseTransitiveVulnerabilityAudit(summary,advisoryScope)}normaliseTransitiveVulnerabilityAudit(summary,advisoryScope){const packages=summary.packages.filter((pkg)=>pkg.selectedCount>0).map((pkg)=>{const occurrences=pkg.advisoryOccurrences??[];if(occurrences.length!==pkg.selectedCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit package occurrence count differs from selected count.")}return{registry:pkg.registry,name:pkg.name,occurrenceCount:pkg.selectedCount,occurrences:occurrences.map((occurrence)=>{const isAffected=occurrence.affectsResolvedVersion;if(advisoryScope==="AFFECTED"&&!isAffected||advisoryScope==="NON_AFFECTING"&&isAffected){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence differs from the requested scope.")}const hasMatchedAffectedRange=occurrence.matchedAffectedVersionRanges.length>0;if(isAffected!==hasMatchedAffectedRange){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence has inconsistent affectedness proof.")}const hasHigherFixes=occurrence.fixVersionsAboveResolved.length>0;const nearestFixedVersion=occurrence.nearestFixedVersion??undefined;const hasNearestFix=nearestFixedVersion!==undefined;if(!isAffected&&(hasHigherFixes||hasNearestFix)||hasHigherFixes!==hasNearestFix||hasNearestFix&&!occurrence.fixVersionsAboveResolved.includes(nearestFixedVersion)){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit fix metadata is inconsistent.")}return{version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion,advisory:this.normaliseTransitiveAuditAdvisory(occurrence.advisory)}})}});const normalisedOccurrenceCount=packages.reduce((total,pkg)=>total+pkg.occurrences.length,0);const occurrenceCount=summary.selected.totalVulnerabilities;if(normalisedOccurrenceCount!==occurrenceCount){throw new MalformedPackageIntelligenceResponseError("Transitive vulnerability audit occurrence count differs from selected total.")}return{advisoryScope,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,packageCount:packages.length,occurrenceCount,calculatedAt:summary.calculatedAt??undefined,packages}}async packageDependencies(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.dependencies.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageDependencies(token,params)}))}async packageUpgradeDependencyProbe(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-dependency-probe.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeDependencyProbe(token,params)}))}async packageUpgradeReview(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.upgrade-review.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageUpgradeReview(token,params)}))}async executePackageUpgradeReview(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_REVIEW_QUERY,variables:{packages:params.packages,includeTransitiveSecurity:params.includeTransitiveSecurity,includeDependencyIssues:params.includeDependencyIssues,minSeverity:params.minSeverity,changelogLimit:params.changelogLimit},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageUpgradeReviewGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.packageUpgradeReview;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return stripNullProperties(data)}async executePackageUpgradeDependencyProbe(token,params){const includeTransitiveRisk=params.includeTransitiveSecurity===true||params.includeDependencyIssues===true||params.includeDependencyChanges===true;let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_UPGRADE_DEPENDENCY_PROBE_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitiveRisk,includeTransitiveSecurity:params.includeTransitiveSecurity===true,includeDependencyIssues:params.includeDependencyIssues===true,includeDependencyChanges:params.includeDependencyChanges===true,includeGroups:params.includeGroups===true,lifecycle:params.includeGroups===true?["peer"]:undefined,minSeverity:params.minSeverity},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseDependencyReport(data)}async executePackageDependencies(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_DEPENDENCIES_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeTransitive:params.includeDependencyIssues===true?true:params.includeTransitive,includeTransitiveDetails:params.includeTransitiveDetails!==false,includeDependencyGraph:params.includeTransitive===true||params.includeDependencyIssues===true,includeDependencyIssues:params.includeDependencyIssues===true,includeGroups:params.includeGroups!==false,maxDepth:params.maxDepth,lifecycle:params.lifecycle&&params.lifecycle.length>0?params.lifecycle:undefined},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=dependenciesGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageDependencies;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}const report=this.normaliseDependencyReport(data);if(params.includeDependencyIssues===true){const transitive=report.dependencies?.transitive;if(!transitive?.dependencyIssues){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency issues.")}if(!transitive.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Dependency issue analysis response missing dependency graph.")}}if(params.includeTransitive===true){const transitive=report.dependencies?.transitive;const hasConflictEdges=transitive?.dependencyConflicts?.some((conflict)=>conflict.conflictingEdges.length>0);if(hasConflictEdges&&!transitive?.dependencyGraph){throw new MalformedPackageIntelligenceResponseError("Transitive dependency conflict edges response missing dependency graph.")}}return report}normaliseDependencyReport(data){const name=data.package?.name??undefined;const version=data.package?.version??undefined;if(!name||!version){throw new MalformedPackageIntelligenceResponseError("Package dependencies response missing required name/version.")}const identity={name,version,registry:data.package?.registry??undefined,publishedAt:data.package?.publishedAt??undefined,deprecated:data.package?.deprecated??undefined,deprecationReason:data.package?.deprecationReason??undefined};const bundle=data.dependencies;const dependencies=bundle?{direct:bundle.direct?.map((entry)=>{if(!entry.name){throw new MalformedPackageIntelligenceResponseError("Dependency entry missing required name.")}return{name:entry.name,versionConstraint:entry.versionConstraint??undefined,type:entry.type??undefined}})??undefined,transitive:bundle.transitive?{totalEdges:bundle.transitive.totalEdges??undefined,uniquePackagesCount:bundle.transitive.uniquePackagesCount??undefined,uniqueDependencies:bundle.transitive.uniqueDependencies??undefined,dependencyConflicts:bundle.transitive.dependencyConflicts?.map((c)=>({packageName:c.packageName,requiredVersions:c.requiredVersions,conflictingEdges:c.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))??undefined,circularDependencyCycles:bundle.transitive.circularDependencyCycles?.map((cycle)=>({cycleStart:cycle.cycleStart,circularPath:cycle.circularPath,displayChain:cycle.displayChain}))??undefined,dependencyGraph:bundle.transitive.dependencyGraph?{formatVersion:bundle.transitive.dependencyGraph.formatVersion,nodes:bundle.transitive.dependencyGraph.nodes.map((n)=>({registry:n.registry,name:n.name,version:n.version??undefined})),edges:bundle.transitive.dependencyGraph.edges.map((e)=>({fromIndex:e.fromIndex??undefined,toIndex:e.toIndex,constraint:e.constraint??undefined,dependencyType:e.dependencyType??undefined}))}:undefined,vulnerabilitySummary:this.normaliseTransitiveVulnerabilitySummary(bundle.transitive.vulnerabilitySummary),dependencyIssues:this.normaliseDependencyIssuesSummary(bundle.transitive.dependencyIssues)}:undefined}:undefined;const dependencyGroups=data.dependencyGroups?{primaryGroup:data.dependencyGroups.primaryGroup??undefined,environmentMarkers:data.dependencyGroups.environmentMarkers?.map((m)=>({type:m.type??undefined,value:m.value??undefined,raw:m.raw??undefined}))??undefined,groups:data.dependencyGroups.groups.map((group)=>({name:group.name,lifecycle:group.lifecycle,conditionType:group.conditionType,conditionValue:group.conditionValue??undefined,selectionMode:group.selectionMode,exclusiveGroup:group.exclusiveGroup??undefined,fallbackPriority:group.fallbackPriority??undefined,compatibleWith:group.compatibleWith??undefined,defaultEnabled:group.defaultEnabled??undefined,dependencies:group.dependencies.map((entry)=>({name:entry.name,constraint:entry.constraint??undefined}))}))}:undefined;return{package:identity,dependencies,dependencyGroups}}normaliseTransitiveVulnerabilitySummary(summary){if(!summary)return;return{affected:summary.affected,nonAffecting:summary.nonAffecting,combined:summary.combined,totalPackagesAnalyzed:summary.totalPackagesAnalyzed,affectedPackageCount:summary.affectedPackageCount,calculatedAt:summary.calculatedAt??undefined,packages:summary.packages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,nonAffectingCount:pkg.nonAffectingCount,totalCount:pkg.totalCount,maxSeverityScore:pkg.maxSeverityScore??undefined,maxSeverityLabel:pkg.maxSeverityLabel??undefined,advisoryIds:pkg.advisoryIds,mostCritical:pkg.mostCritical?this.normaliseVulnerabilitySummaryDetail(pkg.mostCritical):undefined,advisoryOccurrences:pkg.advisoryOccurrences?.map((occurrence)=>({version:occurrence.version,affectsResolvedVersion:occurrence.affectsResolvedVersion,matchedAffectedVersionRanges:occurrence.matchedAffectedVersionRanges,fixVersionsAboveResolved:occurrence.fixVersionsAboveResolved,nearestFixedVersion:occurrence.nearestFixedVersion??undefined,advisory:this.normaliseVulnerabilitySummaryDetail(occurrence.advisory)}))??undefined}))}}normaliseVulnerabilitySummaryDetail(advisory){return{osvId:advisory.osvId??undefined,registry:advisory.registry??undefined,packageName:advisory.packageName??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,severityType:advisory.severityType??undefined,affectedVersionRanges:advisory.affectedVersionRanges??undefined,fixedInVersions:advisory.fixedInVersions??undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,withdrawnAt:advisory.withdrawnAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseTransitiveAuditAdvisory(advisory){return{osvId:advisory.osvId??undefined,summary:advisory.summary??undefined,severityScore:advisory.severityScore??undefined,affectedVersionRanges:advisory.affectedVersionRanges?.length?advisory.affectedVersionRanges:undefined,fixedInVersions:advisory.fixedInVersions?.length?advisory.fixedInVersions:undefined,publishedAt:advisory.publishedAt??undefined,modifiedAt:advisory.modifiedAt??undefined,aliases:advisory.aliases??undefined,isMalicious:advisory.isMalicious??undefined}}normaliseDependencyIssuesSummary(issues){if(!issues)return;return{totalCount:issues.totalCount,deprecatedCount:issues.deprecatedCount,outdatedCount:issues.outdatedCount,duplicateCount:issues.duplicateCount,conflictCount:issues.conflictCount,deprecatedPackages:issues.deprecatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,versions:pkg.versions,reasons:pkg.reasons.map((reason)=>({version:reason.version,reason:reason.reason??undefined}))})),outdatedPackages:issues.outdatedPackages.map((pkg)=>({registry:pkg.registry,name:pkg.name,latestVersion:pkg.latestVersion??undefined,severity:pkg.severity,versions:pkg.versions.map((version)=>({version:version.version,severity:version.severity})),repositoryUrl:pkg.repositoryUrl??undefined})),duplicatePackages:issues.duplicatePackages.map((pkg)=>({registry:pkg.registry??undefined,name:pkg.name,versions:pkg.versions})),conflicts:issues.conflicts.map((conflict)=>({registry:conflict.registry??undefined,name:conflict.name,versions:conflict.versions,requiredVersions:conflict.requiredVersions,conflictingEdges:conflict.conflictingEdges.map((edge)=>({fromIndex:edge.fromIndex??undefined,toIndex:edge.toIndex,versionConstraint:edge.versionConstraint,dependencyType:edge.dependencyType}))}))}}async packageChangelog(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.changelog.request",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executePackageChangelog(token,params)}))}async executePackageChangelog(token,params){if(params.version!==undefined){return this.executeExactPackageChangelog(token,params)}return this.executeTimelinePackageChangelog(token,params)}async executeTimelinePackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_QUERY,variables:{registry:params.registry,name:params.packageName,fromVersion:params.fromVersion,toVersion:params.toVersion,limit:params.limit,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=changelogGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.packageChangelog;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseTimelineChangelogReport(data)}async executeExactPackageChangelog(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:PACKAGE_CHANGELOG_EXACT_QUERY,variables:{registry:params.registry,name:params.packageName,version:params.version,includeBodies:params.includeBodies!==false},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=exactChangelogGraphQLResponseSchema.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 selected=parsed.data.data?.packageInfo?.selectedVersion;if(!selected){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normaliseExactChangelogReport(selected,params)}normaliseTimelineChangelogReport(data){const source=normaliseChangelogSource(data.source);const rawEntries=data.entries??[];const entries=rawEntries.map((entry)=>({version:entry.version??undefined,normalizedVersion:entry.normalizedVersion??undefined,body:entry.body??undefined,htmlUrl:entry.htmlUrl??undefined,publishedAt:entry.publishedAt??undefined}));const packageInfo=data.package?{name:data.package.name??undefined,registry:data.package.registry??undefined,fromVersion:data.package.fromVersion??undefined,toVersion:data.package.toVersion??undefined,limit:data.package.limit??undefined}:undefined;return{package:packageInfo,source,entries}}normaliseExactChangelogReport(selected,params){const changelog=selected.changelog??undefined;const entry=changelog?.entry??undefined;const hasChangelog=changelog?.hasChangelog??false;return{package:{name:params.packageName,registry:toPkgseerRegistryLowercase2(params.registry)},source:normaliseChangelogSource(changelog?.detailSource),entries:[{version:selected.resolvedVersion,normalizedVersion:entry?.normalizedVersion??undefined,body:entry?.body??undefined,htmlUrl:entry?.htmlUrl??undefined,publishedAt:entry?.publishedAt??undefined,hasChangelog}]}}async listPackageDocs(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.list",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeListPackageDocs(token,params)}))}async executeListPackageDocs(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:LIST_PACKAGE_DOCS_QUERY,variables:{registry:params.registry,packageName:params.packageName,version:params.version,limit:params.limit,after:params.after},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocsListGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw promoteGenericVersionNotFound(this.createGraphQLError(parsed.data.errors),params)}const data=parsed.data.data?.listPackageDocs;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return this.normalisePackageDocsList(data)}normalisePackageDocsList(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,stale:data.stale??undefined,codeIndexState:data.codeIndexState??undefined,indexingEstimates:data.indexingEstimates,pages:data.pages?.map((page)=>({id:page.id??undefined,docsReadTarget:page.readTarget.target,title:page.title??undefined,slug:page.slug??undefined,order:page.order??undefined,linkName:page.linkName??undefined,lastUpdatedAt:page.lastUpdatedAt??undefined,sourceKind:page.sourceKind??undefined,sourceUrl:page.sourceUrl??undefined,repoUrl:page.repoUrl??undefined,gitRef:page.gitRef??undefined,requestedRef:page.requestedRef??undefined,filePath:page.filePath??undefined}))??[],pageInfo:data.pageInfo?{hasNextPage:data.pageInfo.hasNextPage,endCursor:data.pageInfo.endCursor??undefined,totalCount:data.pageInfo.totalCount??undefined}:undefined}}async readPackageDoc(params){return withServiceDiagnostics(this.runtime.diagnostics,"pkg-intel.docs.read",()=>executeWithTokenRefresh({getToken:()=>this.tokenProvider.getToken(),forceRefresh:()=>this.tokenProvider.forceRefresh(),shouldRefresh:isTokenRefreshableError,executeWithToken:(token)=>this.executeReadPackageDoc(token,params)}))}async executeReadPackageDoc(token,params){let response;try{response=await postPkgseerGraphql({endpointUrl:this.endpointUrl,token,query:READ_PACKAGE_DOC_QUERY,variables:{pageId:params.pageId,...params.startLine!==undefined?{startLine:params.startLine}:{},...params.endLine!==undefined?{endLine:params.endLine}:{}},fetchFn:this.fetchFn,clientHeaders:this.runtime.clientHeaders,userAgent:this.runtime.userAgent,diagnostics:this.runtime.diagnostics})}catch(cause){if(cause instanceof PkgseerTransportError){throw this.createTransportError(cause)}throw cause}if(response.status<200||response.status>=300){throw this.createHttpError(response)}const parsed=packageDocReadGraphQLResponseSchema.safeParse(response.parsedBody);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}if(parsed.data.errors&&parsed.data.errors.length>0){throw this.createGraphQLError(parsed.data.errors)}const data=parsed.data.data?.getDocPage;if(!data){throw new MalformedPackageIntelligenceResponseError("Empty response from the package-intelligence service.")}return normalisePackageDocResult(data)}}function normalisePackageDocResult(data){return{registry:data.registry??undefined,packageName:data.packageName??undefined,version:data.version??undefined,sourceKind:data.sourceKind??undefined,contentRange:{startLine:data.contentRange.startLine??undefined,endLine:data.contentRange.endLine??undefined,totalLines:data.contentRange.totalLines,anchor:data.contentRange.anchor??undefined},page:data.page?{id:data.page.id??undefined,docsReadTarget:data.page.docsReadTarget,title:data.page.title??undefined,content:data.page.content??undefined,contentFormat:data.page.contentFormat??undefined,breadcrumbs:data.page.breadcrumbs??undefined,linkName:data.page.linkName??undefined,lastUpdatedAt:data.page.lastUpdatedAt??undefined,sourceKind:data.page.sourceKind??undefined,source:data.page.source?{url:data.page.source.url??undefined,label:data.page.source.label??undefined}:undefined,repoUrl:data.page.repoUrl??undefined,gitRef:data.page.gitRef??undefined,requestedRef:data.page.requestedRef??undefined,filePath:data.page.filePath??undefined,baseUrl:data.page.baseUrl??undefined}:undefined}}function parsePackageDocResult(data){const parsed=packageDocResultResponseSchema.safeParse(data);if(!parsed.success){throw new MalformedPackageIntelligenceResponseError("Malformed response from the package-intelligence service.")}return normalisePackageDocResult(parsed.data)}function stripNullProperties(value){if(Array.isArray(value))return value.map(stripNullProperties);if(!value||typeof value!=="object")return value;const result={};for(const[key,child]of Object.entries(value)){if(child!==null)result[key]=stripNullProperties(child)}return result}function createPackageIntelligenceHttpError(response){const status=response.status;const detail=parseHttpErrorDetail(response.responseBody,["detail","error"]);if(status===401){return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server")}if(status===403){return new PackageIntelligenceAccessError(detail??"Access denied.")}if(status>=500){return new PackageIntelligenceBackendError(detail?`Server error (${status}): ${detail}`:`Server error (${status})`,status)}return new PackageIntelligenceBackendError(detail??`Request failed with status ${status}`,status)}function createPackageIntelligenceTransportError(error){if(isFetchTimeoutError(error.cause)){return new PackageIntelligenceBackendError("Package intelligence request timed out.",undefined,"TIMEOUT",true)}return new PackageIntelligenceNetworkError("Could not reach the package intelligence service. Check your connection or set GITHITS_CODE_NAV_URL.",{cause:error})}function createPackageIntelligenceGraphQLError(errors,clientVersion,diagnostics){const message=errors.map((error)=>error.message).join(", ");const extensions=getPrimaryExtensions2(errors);const code=typeof extensions?.code==="string"?extensions.code:undefined;const retryable=typeof extensions?.retryable==="boolean"?extensions.retryable:undefined;if(isClientUpdateRequiredGraphQLError({message,code})){return new ClientUpdateRequiredError(undefined,undefined,clientVersion)}if(isGraphQLSchemaMismatchError({message,code})){const sanitized="Backend protocol mismatch. Your CLI may be newer than the server, or the server may require a newer CLI. Run `githits update-check` to verify your installed version. Set GITHITS_DEBUG=pkg-graphql to inspect GraphQL details during local development.";if(diagnostics?.isEnabled("pkg-graphql")){diagnostics.debug("pkg-graphql",{event:"graphql-schema-mismatch",code:code??"omitted",message})}return new PackageIntelligenceBackendError(diagnostics?.isEnabled("pkg-graphql")?message:sanitized,undefined,code,retryable)}switch(code){case"NOT_FOUND":case"PACKAGE_NOT_FOUND":return new PackageIntelligenceTargetNotFoundError(message);case"VERSION_NOT_FOUND":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"DOCUMENTATION_SECTION_UNRESOLVED":return new PackageIntelligenceDocumentationSectionUnresolvedError(message,parseDocumentationSectionUnresolvedReason(extensions?.reason));case"FEATURE_FLAG_REQUIRED":return new PackageIntelligenceFeatureFlagRequiredError(message);case"AUTHENTICATION_REQUIRED":case"UNAUTHORIZED":return new AuthenticationError2(SERVER_AUTHENTICATION_REJECTED_MESSAGE,"server");case"FORBIDDEN":return new PackageIntelligenceAccessError("Access denied. This feature may not be enabled for your account.");case"UPSTREAM_ERROR":case"TIMEOUT":case"RATE_LIMITED":case"INTERNAL_ERROR":case"UNKNOWN_ERROR":return new PackageIntelligenceBackendError(message,undefined,code,retryable);default:return new PackageIntelligenceBackendError(message,undefined,code,retryable)}}function parseDocumentationSectionUnresolvedReason(value){switch(value){case"not_found":case"ambiguous":case"inexact_range":case"unsupported_format":return value;default:return}}function getPrimaryExtensions2(errors){for(const error of errors){if(error.extensions&&Object.keys(error.extensions).length>0){return error.extensions}}return}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}
1528
+ export{CLIENT_UPDATE_REQUIRED_REASON,ClientUpdateRequiredError,isClientUpdateRequiredGraphQLError,isGraphQLSchemaMismatchError,parseAvailableArtifacts,DEFAULT_FETCH_TIMEOUT_MS,FetchTimeoutError2,isFetchTimeoutError,parseHttpErrorDetail,DEFAULT_MCP_URL2,DEFAULT_API_URL2,DEFAULT_CODE_NAV_URL2,getMcpUrl2,getApiUrl2,getCodeNavigationUrl2,getEnvApiToken2,TermsAcceptanceRequiredError2,PkgseerTransportError,postPkgseerGraphql,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,isKnownPkgseerRegistryArg,SERVER_AUTHENTICATION_REJECTED_MESSAGE,AuthenticationError2,ApiRateLimitError2,withServiceDiagnostics,isTokenRefreshableError,GitHitsServiceImpl2,executeWithTokenRefresh,INDEXING_DURATION_ESTIMATE_SELECTION,INDEXING_ESTIMATES_SELECTION,indexingEstimatesSchema,parseIndexingDurationEstimate,READ_TARGET_SELECTION,selectedReadTargetSchema,CodeNavigationAccessError,CodeNavigationGraphQLError,CodeNavigationIndexingError,CodeNavigationUnresolvableError,MalformedCodeNavigationResponseError,CodeDiffError2,CodeNavigationTargetNotFoundError,CodeNavigationFileNotFoundError,CodeNavigationVersionNotFoundError,CodeNavigationRefNotFoundError,CodeNavigationValidationError,CodeNavigationFeatureFlagRequiredError,CodeNavigationNetworkError,CodeNavigationBackendError,TARGET_RESOLUTION_SELECTION,CODE_CONTEXT_AVAILABLE_VERSIONS_SELECTION,CodeNavigationServiceImpl2,createCodeNavigationHttpError,createCodeNavigationGraphQLError,parseCodeContextResult,PackageIntelligenceAccessError,PackageIntelligenceFeatureFlagRequiredError,PackageIntelligenceNetworkError,PackageIntelligenceBackendError,PackageIntelligenceGraphQLError,PackageIntelligenceTargetNotFoundError,PackageIntelligenceValidationError,PackageIntelligenceDocumentationSectionUnresolvedError,PackageIntelligenceVersionNotFoundError,MalformedPackageIntelligenceResponseError,PackageIntelligenceServiceImpl2,parsePackageDocResult,createPackageIntelligenceHttpError,createPackageIntelligenceTransportError,createPackageIntelligenceGraphQLError};