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