Documentation
¶
Overview ¶
Package openapi provides a typed model for OpenAPI 3.x documents with tree-sitter-powered parsing and source location tracking.
The core workflow is:
- Parse YAML/JSON content into a typed Document using NewParser.
- Build a searchable Index with BuildIndex for fast lookups by operation ID, schema name, $ref target, etc.
- Navigate the model using strongly-typed fields on Document, Operation, Schema, PathItem, and other OpenAPI object types.
Every model element carries a Loc value that maps it back to its exact position in the source file, enabling precise diagnostics.
For consumers that don't need tree-sitter integration (e.g., plugins receiving serialized specs), ParseAndIndex provides a convenience function that parses raw YAML/JSON bytes directly into an Index.
Thread-safe caching of indexes across multiple documents is available via IndexCache.
Supported Versions ¶
OpenAPI 2.0 (Swagger), 3.0, 3.1, and 3.2 are detected and parsed. The Version type provides constants for version discrimination.
Package openapi provides a typed OpenAPI model built directly on tree-sitter parse trees. It supports OpenAPI 2.0 (Swagger), 3.0.x, 3.1.x, and 3.2.x with incremental index updates driven by tree-sitter TreeDiff.
Index ¶
- Constants
- Variables
- func ComponentRefPath(kind, name string) string
- func FirstComponentAtOrAfter(entries []SortedComponentEntry, line uint32) int
- func FirstPathAtOrAfter(entries []SortedPathEntry, line uint32) int
- func FirstRefAtOrAfter(entries []SortedRefEntry, line uint32) int
- func IsOpenAPIFile(tree *treesitter.Tree, uri string) bool
- func NavigatorIndexIsMalformed(idx *navigator.Index) bool
- func NormalizeURI(uri string) string
- type ArazzoDocument
- type Callback
- type ClassifyResult
- type ComponentKind
- type Components
- type Contact
- type DescriptionValue
- type Discriminator
- type DocType
- type Document
- type DocumentKind
- type Example
- type ExternalDocs
- type FileFormat
- type Format
- type FragmentType
- type Header
- type Index
- func (idx *Index) AllOperations() []*OperationRef
- func (idx *Index) ComponentNames(kind string) []string
- func (idx *Index) DocumentKind() DocumentKind
- func (idx *Index) HasPath(path string) bool
- func (idx *Index) IsAPIDescription() bool
- func (idx *Index) IsArazzo() bool
- func (idx *Index) IsMalformed() bool
- func (idx *Index) IsOpenAPI() bool
- func (idx *Index) IsRootDocument() bool
- func (idx *Index) NavigatorIndex() *navigator.Index
- func (idx *Index) PrimaryValue() interface{}
- func (idx *Index) RefsTo(target string) []RefUsage
- func (idx *Index) Resolve(ref string) (interface{}, error)
- func (idx *Index) ResolveRef(ref string) (interface{}, error)
- func (idx *Index) SchemaNames() []string
- func (idx *Index) SortedComponents() []SortedComponentEntry
- func (idx *Index) SortedPaths() []SortedPathEntry
- func (idx *Index) SortedRefs() []SortedRefEntry
- type IndexCache
- func (c *IndexCache) All() map[protocol.DocumentURI]*Index
- func (c *IndexCache) Delete(uri protocol.DocumentURI)
- func (c *IndexCache) FindByOperationID(opID string) (protocol.DocumentURI, *OperationRef)
- func (c *IndexCache) FindRefTarget(ref string) (protocol.DocumentURI, interface{})
- func (c *IndexCache) Get(uri protocol.DocumentURI) *Index
- func (c *IndexCache) Rebuild(uri protocol.DocumentURI) *Index
- func (c *IndexCache) Set(uri protocol.DocumentURI, idx *Index)
- func (c *IndexCache) SetBuilder(fn func(protocol.DocumentURI) *Index)
- func (c *IndexCache) SetGeneratedBuilder(fn func(protocol.DocumentURI) *Index)
- type Info
- type License
- type Link
- type Loc
- type MediaType
- type MethodOperation
- type Node
- type OAuthFlow
- type OAuthFlows
- type Operation
- type OperationRef
- type Parameter
- type Parser
- type PathItem
- type RefUsage
- type RequestBody
- type Response
- type Schema
- type SecurityRequirement
- type SecurityRequirementEntry
- type SecurityScheme
- type Server
- type ServerVariable
- type SortedComponentEntry
- type SortedPathEntry
- type SortedRefEntry
- type Tag
- type TagUsage
- type Version
Constants ¶
const ( // YAMLBlockMappingPair matches key-value pairs in YAML block mappings. YAMLBlockMappingPair = `(block_mapping_pair key: (flow_node) @key value: (_) @value)` // YAMLRefValue matches $ref key-value pairs in YAML. YAMLRefValue = `(block_mapping_pair key: (flow_node) @key (#eq? @key "$ref") value: (_) @value)` // YAMLFlowMappingPair matches key-value pairs in YAML flow mappings. YAMLFlowMappingPair = `(flow_pair key: (flow_node) @key value: (_) @value)` // YAMLFlowRefValue matches $ref in flow mappings. YAMLFlowRefValue = `(flow_pair key: (flow_node) @key (#eq? @key "$ref") value: (_) @value)` // YAMLDocumentRoot matches the top-level mapping in a YAML document. YAMLDocumentRoot = `(stream (document (block_node (block_mapping) @root)))` // YAMLBlockMapping matches any block mapping. YAMLBlockMapping = `(block_mapping) @mapping` // YAMLError matches syntax errors. YAMLError = `(ERROR) @error` )
YAML queries - target tree-sitter-yaml node types
const ( // JSONPair matches key-value pairs in JSON objects. JSONPair = `(pair key: (string) @key value: (_) @value)` // JSONRefPair matches $ref key-value pairs in JSON. JSONRefPair = `(pair key: (string) @key (#eq? @key "\"$ref\"") value: (_) @value)` // JSONObject matches object nodes. JSONObject = `(object) @obj` // JSONDocumentRoot matches the top-level object in a JSON document. JSONDocumentRoot = `(document (object) @root)` // JSONError matches syntax errors. JSONError = `(ERROR) @error` )
JSON queries - target tree-sitter-json node types
const ( VersionUnknown = navigator.VersionUnknown Version20 = navigator.Version20 Version30 = navigator.Version30 Version31 = navigator.Version31 Version32 = navigator.Version32 )
Version constants.
const ( FormatOAS2 = navigator.FormatOAS2 FormatOAS3 = navigator.FormatOAS3 FormatOAS31 = navigator.FormatOAS31 FormatOAS32 = navigator.FormatOAS32 )
Format constants.
const ( DocTypeUnknown = navigator.DocTypeUnknown DocTypeRoot = navigator.DocTypeRoot DocTypeFragment = navigator.DocTypeFragment DocTypeNonOpenAPI = navigator.DocTypeNonOpenAPI )
DocType constants.
const ( DocumentKindUnknown = navigator.DocumentKindUnknown DocumentKindOpenAPI = navigator.DocumentKindOpenAPI DocumentKindArazzo = navigator.DocumentKindArazzo )
DocumentKind constants.
Variables ¶
var FormatsForVersion = navigator.FormatsForVersion
FormatsForVersion delegates to navigator.FormatsForVersion.
var LocFromNode = navigator.LocFromNode
LocFromNode delegates to navigator.LocFromNode.
var LocOrFallback = navigator.LocOrFallback
LocOrFallback delegates to navigator.LocOrFallback.
var VersionFromString = navigator.VersionFromString
VersionFromString delegates to navigator.VersionFromString.
Functions ¶
func ComponentRefPath ¶
ComponentRefPath returns the $ref string for a component.
func FirstComponentAtOrAfter ¶
func FirstComponentAtOrAfter(entries []SortedComponentEntry, line uint32) int
func FirstPathAtOrAfter ¶
func FirstPathAtOrAfter(entries []SortedPathEntry, line uint32) int
func FirstRefAtOrAfter ¶
func FirstRefAtOrAfter(entries []SortedRefEntry, line uint32) int
FirstIndexAtOrAfter returns the index of the first sorted entry whose start line is >= line, or len(entries) if none qualifies. Used by semantic-tokens range walks to skip past everything above the viewport in O(log N).
func IsOpenAPIFile ¶
func IsOpenAPIFile(tree *treesitter.Tree, uri string) bool
IsOpenAPIFile performs a lightweight check to determine if a tree represents an OpenAPI document by looking for the openapi or swagger key at the root.
func NavigatorIndexIsMalformed ¶
NavigatorIndexIsMalformed reports whether Navigator found syntax-level issues, or the document root is not a mapping/object.
func NormalizeURI ¶
NormalizeURI canonicalizes a file:// URI so that URIs produced by the LSP client and by the server's pathToURI function compare equal as map keys. It delegates to gossip's protocol.NormalizeURI which cleans the path, removes host/query/fragment, and re-serializes.
Types ¶
type ArazzoDocument ¶
type ArazzoDocument = navigator.ArazzoDocument
All model types are aliases to navigator's canonical definitions.
type ClassifyResult ¶
type ClassifyResult struct {
DocType DocType
Version Version
VersionString string
Format FileFormat
}
ClassifyResult holds the result of classifying a document.
func Classify ¶
func Classify(tree *treesitter.Tree, uri string) ClassifyResult
Classify determines the OpenAPI version and document type from a tree-sitter tree.
type ComponentKind ¶
type ComponentKind int
ComponentKind identifies which Components.* bucket a SortedComponentEntry came from so the semantic-tokens emitter can dispatch without re-reading the underlying map.
const ( ComponentKindSchema ComponentKind = iota ComponentKindSecurityScheme )
type Components ¶
type Components = navigator.Components
All model types are aliases to navigator's canonical definitions.
type DescriptionValue ¶
type DescriptionValue = navigator.DescriptionValue
All model types are aliases to navigator's canonical definitions.
type Discriminator ¶
type Discriminator = navigator.Discriminator
All model types are aliases to navigator's canonical definitions.
type DocumentKind ¶
type DocumentKind = navigator.DocumentKind
Version and related types are aliases to navigator's canonical definitions.
type ExternalDocs ¶
type ExternalDocs = navigator.ExternalDocs
All model types are aliases to navigator's canonical definitions.
type FileFormat ¶
type FileFormat int
FileFormat identifies whether a document is YAML or JSON based on file extension.
const ( FormatUnknown FileFormat = iota FormatYAML FormatJSON )
func FormatFromURI ¶
func FormatFromURI(uri string) FileFormat
FormatFromURI determines the file format from a URI or file path.
type FragmentType ¶
type FragmentType int
FragmentType classifies a non-root OpenAPI file by the kind of object it represents. Used to select the appropriate JSON Schema for validation.
const ( FragmentUnknown FragmentType = iota FragmentSchema // Schema Object (type, properties, items, etc.) FragmentPathItem // Path Item (get, post, put, delete, etc.) FragmentOperation // Operation (operationId, responses, etc.) FragmentParameter // Parameter (in + name) FragmentRequestBody // Request Body (content without in) FragmentResponse // Response (description + content/headers) FragmentHeader // Header (schema without in/name/methods) FragmentSecurityScheme // Security Scheme (type: apiKey|http|oauth2|openIdConnect) FragmentComponents // Components (schemas, responses, parameters, etc.) FragmentServer // Server (url) )
func DetectFragmentType ¶
func DetectFragmentType(tree *treesitter.Tree, format FileFormat) FragmentType
DetectFragmentType examines the root-level keys of a tree-sitter AST and returns the most likely OpenAPI fragment type. Returns FragmentUnknown if the file does not appear to be an OpenAPI fragment.
func (FragmentType) String ¶
func (f FragmentType) String() string
String returns a human-readable name for the fragment type.
type Index ¶
type Index struct {
Document *Document
Arazzo *ArazzoDocument
Operations map[string]*OperationRef // operationId -> ref
OperationsByPath map[string][]OperationRef // path -> operations
Schemas map[string]*Schema // component name -> schema
Parameters map[string]*Parameter // component name -> parameter
Responses map[string]*Response // component name -> response
SecuritySchemes map[string]*SecurityScheme // scheme name -> scheme
Refs map[string][]RefUsage // $ref target -> usages
AllRefs []RefUsage // all $ref usages in the doc
Tags map[string]*Tag // tag name -> tag
Version Version
Format FileFormat
Kind DocumentKind
// contains filtered or unexported fields
}
Index provides fast lookups into a parsed OpenAPI document.
The navigator-backed index is computed lazily on first access via NavigatorIndex() / navIndex(); BuildIndex itself only invokes navigator for documents that are known-or-suspected to be Arazzo (which requires navigator's model to branch into IndexFromNavigator). For the common OpenAPI path we skip the ~400k-allocation navigator.ParseContent and amortize that cost across the features that actually dereference nav.
func BuildIndex ¶
func BuildIndex(tree *treesitter.Tree, doc *document.Document) *Index
BuildIndex creates a full index from a parsed tree and document.
func IndexFromNavigator ¶
func IndexFromNavigator(navIdx *navigator.Index, uri protocol.DocumentURI) *Index
IndexFromNavigator converts a navigator.Index to telescope's openapi.Index. The model types (Document, Schema, etc.) are shared via aliases so no deep copy is needed. Only the index-level bookkeeping fields are mapped.
func ParseAndIndex ¶
ParseAndIndex parses raw YAML/JSON content into an OpenAPI Index without requiring tree-sitter. Delegates to navigator's standalone parser. Returns a minimal Index with DocTypeUnknown for unparseable content.
func (*Index) AllOperations ¶
func (idx *Index) AllOperations() []*OperationRef
AllOperations returns all indexed operations.
func (*Index) ComponentNames ¶
ComponentNames returns the names of all components of a given kind.
func (*Index) DocumentKind ¶
func (idx *Index) DocumentKind() DocumentKind
DocumentKind returns the API-description family represented by the index. This accessor does NOT trigger lazy navigator parsing because the kind is populated eagerly whenever BuildIndex can determine it — the only path that would still need navigator is a document whose telescope parser produced an unknown DocType, and in that case falling back to the parsed Document type already reports the correct kind.
Kind / nav reads are guarded by navMu so they synchronize with lazy nav initialization (which writes both). The lock is a no-op on indexes constructed without BuildIndex (e.g. IndexFromNavigator fixtures).
func (*Index) IsAPIDescription ¶
IsAPIDescription returns true when Telescope recognized the file as a supported API-description document.
func (*Index) IsMalformed ¶
IsMalformed reports whether Navigator found syntax-level issues that should be left to the YAML/JSON language servers instead of Telescope. This triggers the lazy navigator parse since the malformed-check is fundamentally a navigator concern.
func (*Index) IsRootDocument ¶
IsRootDocument returns true for root OpenAPI or Arazzo documents.
func (*Index) NavigatorIndex ¶
NavigatorIndex returns the navigator-backed index, parsing it lazily on first access. Returns nil only when the original BuildIndex invocation had no tree/document source to parse from.
func (*Index) PrimaryValue ¶
func (idx *Index) PrimaryValue() interface{}
PrimaryValue returns the canonical top-level value for this index. Navigator-backed indexes use Navigator's whole-document/fragment semantics.
func (*Index) Resolve ¶
Resolve resolves a $ref string to a model element. Returns nil and an error if the ref cannot be resolved within this index.
func (*Index) ResolveRef ¶
ResolveRef resolves a JSON Reference ($ref) string to the corresponding model element within this index. Supports local references like #/components/schemas/Pet.
func (*Index) SchemaNames ¶
SchemaNames returns all component schema names.
func (*Index) SortedComponents ¶
func (idx *Index) SortedComponents() []SortedComponentEntry
SortedComponents returns Document.Components.{Schemas,SecuritySchemes} ordered by NameLoc start position. Entries without a valid NameLoc are skipped. Callers must not mutate the returned slice.
func (*Index) SortedPaths ¶
func (idx *Index) SortedPaths() []SortedPathEntry
SortedPaths returns Document.Paths ordered by the path item's key location. Paths without a resolved PathLoc are skipped (they have no sensible sort position). Callers must not mutate the returned slice.
func (*Index) SortedRefs ¶
func (idx *Index) SortedRefs() []SortedRefEntry
SortedRefs returns AllRefs ordered by (Loc.Range.Start.Line, Start.Character). Lazy: the sort happens on first call. Subsequent calls return the same backing slice; callers must not mutate it.
type IndexCache ¶
type IndexCache struct {
// contains filtered or unexported fields
}
IndexCache provides a thread-safe cache of per-document indexes.
func (*IndexCache) All ¶
func (c *IndexCache) All() map[protocol.DocumentURI]*Index
All returns all cached indexes.
func (*IndexCache) Delete ¶
func (c *IndexCache) Delete(uri protocol.DocumentURI)
Delete removes the index for a URI. The URI is normalized before lookup.
func (*IndexCache) FindByOperationID ¶
func (c *IndexCache) FindByOperationID(opID string) (protocol.DocumentURI, *OperationRef)
FindByOperationID searches all cached indexes for an operationId.
func (*IndexCache) FindRefTarget ¶
func (c *IndexCache) FindRefTarget(ref string) (protocol.DocumentURI, interface{})
FindRefTarget searches all cached indexes for a $ref target.
func (*IndexCache) Get ¶
func (c *IndexCache) Get(uri protocol.DocumentURI) *Index
Get returns the cached index for a URI. If no cached entry exists and a builder has been registered via SetBuilder, it builds, caches, and returns the index on demand. The URI is normalized before lookup.
The generation-loop builder (installed via SetGeneratedBuilder) is consulted before either the cache or the regular builder: this keeps generated-spec consumers reading the loop's in-memory bytes instead of a stale disk copy.
func (*IndexCache) Rebuild ¶
func (c *IndexCache) Rebuild(uri protocol.DocumentURI) *Index
Rebuild forces the registered builder to run even when a cached entry already exists. Handlers for open documents can use this to prefer the freshest live-buffer view over a potentially stale cached projection.
func (*IndexCache) Set ¶
func (c *IndexCache) Set(uri protocol.DocumentURI, idx *Index)
Set stores an index for a URI. The URI is normalized before storage.
func (*IndexCache) SetBuilder ¶
func (c *IndexCache) SetBuilder(fn func(protocol.DocumentURI) *Index)
SetBuilder registers a fallback function that builds the index on-demand when Get finds no cached entry. The builder must be safe for concurrent use.
func (*IndexCache) SetGeneratedBuilder ¶
func (c *IndexCache) SetGeneratedBuilder(fn func(protocol.DocumentURI) *Index)
SetGeneratedBuilder registers a higher-priority builder consulted before the regular builder and cache. The generation loop installs one so navigator + barrelman see the loop's in-memory spec bytes for generated URIs (both the telescope-generated:// virtual URI and the configured on-disk path) rather than stale disk-cached bytes.
type MethodOperation ¶
type MethodOperation = navigator.MethodOperation
All model types are aliases to navigator's canonical definitions.
type OAuthFlows ¶
type OAuthFlows = navigator.OAuthFlows
All model types are aliases to navigator's canonical definitions.
type OperationRef ¶
OperationRef links an operation to its path and method.
type Parser ¶
type Parser struct {
// contains filtered or unexported fields
}
Parser builds an OpenAPI Document from a tree-sitter parse tree.
func NewParser ¶
func NewParser(tree *treesitter.Tree, format FileFormat) *Parser
NewParser creates a parser for a given tree and file format.
type RefUsage ¶
type RefUsage struct {
URI protocol.DocumentURI
Loc Loc
Target string // the $ref target value (e.g. "#/components/schemas/Foo")
From string // JSONPath-like location of the reference
}
RefUsage tracks where a $ref is used.
type RequestBody ¶
type RequestBody = navigator.RequestBody
All model types are aliases to navigator's canonical definitions.
type SecurityRequirement ¶
type SecurityRequirement = navigator.SecurityRequirement
All model types are aliases to navigator's canonical definitions.
type SecurityRequirementEntry ¶
type SecurityRequirementEntry = navigator.SecurityRequirementEntry
All model types are aliases to navigator's canonical definitions.
type SecurityScheme ¶
type SecurityScheme = navigator.SecurityScheme
All model types are aliases to navigator's canonical definitions.
type ServerVariable ¶
type ServerVariable = navigator.ServerVariable
All model types are aliases to navigator's canonical definitions.
type SortedComponentEntry ¶
type SortedComponentEntry struct {
Line uint32
Char uint32
Kind ComponentKind
Name string
Schema *Schema
SecurityScheme *SecurityScheme
}
SortedComponentEntry is an ordered snapshot of a Components.* declaration location. Exactly one of Schema or SecurityScheme is non-nil, determined by Kind.
type SortedPathEntry ¶
SortedPathEntry is an ordered snapshot of a path template location. Item points into the underlying Document.Paths map, which is immutable once BuildIndex returns, so sharing pointers is safe.
type SortedRefEntry ¶
SortedRefEntry is an ordered snapshot of a $ref usage for range-scoped walks. Index is the position inside idx.AllRefs; keeping it as an index (rather than a pointer) avoids aliasing concerns if AllRefs is ever reallocated and keeps the snapshot copyable.