openapi

package
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 13 Imported by: 0

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:

  1. Parse YAML/JSON content into a typed Document using NewParser.
  2. Build a searchable Index with BuildIndex for fast lookups by operation ID, schema name, $ref target, etc.
  3. 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

View Source
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

View Source
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

View Source
const (
	VersionUnknown = navigator.VersionUnknown
	Version20      = navigator.Version20
	Version30      = navigator.Version30
	Version31      = navigator.Version31
	Version32      = navigator.Version32
)

Version constants.

View Source
const (
	FormatOAS2  = navigator.FormatOAS2
	FormatOAS3  = navigator.FormatOAS3
	FormatOAS31 = navigator.FormatOAS31
	FormatOAS32 = navigator.FormatOAS32
)

Format constants.

View Source
const (
	DocTypeUnknown    = navigator.DocTypeUnknown
	DocTypeRoot       = navigator.DocTypeRoot
	DocTypeFragment   = navigator.DocTypeFragment
	DocTypeNonOpenAPI = navigator.DocTypeNonOpenAPI
)

DocType constants.

View Source
const (
	DocumentKindUnknown = navigator.DocumentKindUnknown
	DocumentKindOpenAPI = navigator.DocumentKindOpenAPI
	DocumentKindArazzo  = navigator.DocumentKindArazzo
)

DocumentKind constants.

Variables

View Source
var FormatsForVersion = navigator.FormatsForVersion

FormatsForVersion delegates to navigator.FormatsForVersion.

View Source
var LocFromNode = navigator.LocFromNode

LocFromNode delegates to navigator.LocFromNode.

View Source
var LocOrFallback = navigator.LocOrFallback

LocOrFallback delegates to navigator.LocOrFallback.

View Source
var VersionFromString = navigator.VersionFromString

VersionFromString delegates to navigator.VersionFromString.

Functions

func ComponentRefPath

func ComponentRefPath(kind, name string) string

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(idx *navigator.Index) bool

NavigatorIndexIsMalformed reports whether Navigator found syntax-level issues, or the document root is not a mapping/object.

func NormalizeURI

func NormalizeURI(uri string) string

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 Callback

type Callback = navigator.Callback

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 Contact

type Contact = navigator.Contact

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 DocType

type DocType = navigator.DocType

Version and related types are aliases to navigator's canonical definitions.

type Document

type Document = navigator.Document

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 Example

type Example = navigator.Example

All model 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 Format

type Format = navigator.Format

Version and related types are aliases to navigator's canonical definitions.

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 Header = navigator.Header

All model types are aliases to navigator's canonical definitions.

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

func ParseAndIndex(content []byte) *Index

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

func (idx *Index) ComponentNames(kind string) []string

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) HasPath

func (idx *Index) HasPath(path string) bool

HasPath returns true if the given path template exists.

func (*Index) IsAPIDescription

func (idx *Index) IsAPIDescription() bool

IsAPIDescription returns true when Telescope recognized the file as a supported API-description document.

func (*Index) IsArazzo

func (idx *Index) IsArazzo() bool

IsArazzo returns true if the index represents a root Arazzo document.

func (*Index) IsMalformed

func (idx *Index) IsMalformed() bool

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) IsOpenAPI

func (idx *Index) IsOpenAPI() bool

IsOpenAPI returns true if the index represents a root OpenAPI document.

func (*Index) IsRootDocument

func (idx *Index) IsRootDocument() bool

IsRootDocument returns true for root OpenAPI or Arazzo documents.

func (*Index) NavigatorIndex

func (idx *Index) NavigatorIndex() *navigator.Index

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) RefsTo

func (idx *Index) RefsTo(target string) []RefUsage

RefsTo returns all usages that reference the given target.

func (*Index) Resolve

func (idx *Index) Resolve(ref string) (interface{}, error)

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

func (idx *Index) ResolveRef(ref string) (interface{}, error)

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

func (idx *Index) SchemaNames() []string

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 NewIndexCache

func NewIndexCache() *IndexCache

NewIndexCache creates a new index cache.

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 Info

type Info = navigator.Info

All model types are aliases to navigator's canonical definitions.

type License

type License = navigator.License

All model types are aliases to navigator's canonical definitions.

type Link = navigator.Link

All model types are aliases to navigator's canonical definitions.

type Loc

type Loc = navigator.Loc

All model types are aliases to navigator's canonical definitions.

type MediaType

type MediaType = navigator.MediaType

All model types are aliases to navigator's canonical definitions.

type MethodOperation

type MethodOperation = navigator.MethodOperation

All model types are aliases to navigator's canonical definitions.

type Node

type Node = navigator.Node

All model types are aliases to navigator's canonical definitions.

type OAuthFlow

type OAuthFlow = navigator.OAuthFlow

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 Operation

type Operation = navigator.Operation

All model types are aliases to navigator's canonical definitions.

type OperationRef

type OperationRef struct {
	Path      string
	Method    string
	Operation *Operation
}

OperationRef links an operation to its path and method.

type Parameter

type Parameter = navigator.Parameter

All model types are aliases to navigator's canonical definitions.

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.

func (*Parser) Parse

func (p *Parser) Parse() *Document

Parse walks the tree-sitter tree and returns a typed OpenAPI Document.

type PathItem

type PathItem = navigator.PathItem

All model types are aliases to navigator's canonical definitions.

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 Response

type Response = navigator.Response

All model types are aliases to navigator's canonical definitions.

type Schema

type Schema = navigator.Schema

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 Server

type Server = navigator.Server

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

type SortedPathEntry struct {
	Line uint32
	Char uint32
	Path string
	Item *PathItem
}

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

type SortedRefEntry struct {
	Line  uint32
	Char  uint32
	Index int
}

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.

type Tag

type Tag = navigator.Tag

All model types are aliases to navigator's canonical definitions.

type TagUsage

type TagUsage = navigator.TagUsage

All model types are aliases to navigator's canonical definitions.

type Version

type Version = navigator.Version

Version and related types are aliases to navigator's canonical definitions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL