ir

package
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 44 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ParameterComponentRefPrefix   = "#/components/parameters/"
	HeaderComponentRefPrefix      = "#/components/headers/"
	RequestBodyComponentRefPrefix = "#/components/requestBodies/"
	ResponseComponentRefPrefix    = "#/components/responses/"
	ExampleComponentRefPrefix     = "#/components/examples/"
)

Variables

This section is empty.

Functions

func OpenAPIExampleValue added in v1.8.0

func OpenAPIExampleValue(attr *expr.AttributeExpr, raw any) (any, bool)

OpenAPIExampleValue normalizes an example and reports whether it completely represents its attribute's OpenAPI schema.

func ParameterComponentName

func ParameterComponentName(parameter *Parameter) string

func ParseOperationIDTemplate added in v1.10.0

func ParseOperationIDTemplate(template, service, method string, routeIndex int) string

ParseOperationIDTemplate renders an OpenAPI operationId template. It replaces {service} and {method} with canonical snake_case components and expands or removes the optional (...{routeIndex}) group. A route index greater than zero is appended as "#<index>" when the template uses service or method placeholders but has no such group. A template without recognized placeholders is returned unchanged.

func RenderBodyTypes

func RenderBodyTypes(bodyTypes *BodyTypes) (map[string]map[string]*RenderedEndpointBodies, map[string]*openapi.Schema)

RenderBodyTypes converts IR endpoint bodies and components to rendered OpenAPI schemas.

func RenderExternalDocs

func RenderExternalDocs(docs *ExternalDocs) *openapi.ExternalDocs

RenderExternalDocs converts IR external docs to the concrete OpenAPI type.

func RenderSchema

func RenderSchema(schema *Schema) *openapi.Schema

RenderSchema converts an IR schema to the concrete OpenAPI schema type.

func RenderSchemaMap

func RenderSchemaMap(schemas map[string]*Schema) map[string]*openapi.Schema

RenderSchemaMap converts a schema map.

func ValidateComponentIdentities added in v1.10.0

func ValidateComponentIdentities(claims []ComponentIdentity) error

ValidateComponentIdentities rejects explicit component names claimed for different values. Identical claims are safe to share.

func ValidateOperationIdentities added in v1.10.0

func ValidateOperationIdentities(claims []OperationIdentity) error

ValidateOperationIdentities rejects duplicate OpenAPI path templates, duplicate method/path slots, and duplicate operation IDs.

Types

type Analyzer

type Analyzer struct {
	// contains filtered or unexported fields
}

Analyzer converts expr types into IR schemas and endpoint body models.

func NewAnalyzer

func NewAnalyzer(rand *expr.ExampleGenerator, closeObjects bool, options ...AnalyzerOption) *Analyzer

NewAnalyzer creates a schema analyzer. Builtin examples consume shared prepared values and documentation plans. WithExampleValue selects an explicit custom projection or retained declared values.

func (*Analyzer) AnalyzeSchema

func (a *Analyzer) AnalyzeSchema(attr *expr.AttributeExpr, noref ...bool) *Schema

AnalyzeSchema builds an IR schema for the given attribute.

func (*Analyzer) AnalyzeSchemaWithContext added in v1.8.0

func (a *Analyzer) AnalyzeSchemaWithContext(attr *expr.AttributeExpr, context string, noref ...bool) *Schema

AnalyzeSchemaWithContext builds an IR schema using a stable example occurrence context.

func (*Analyzer) ClaimExplicitName

func (a *Analyzer) ClaimExplicitName(name, fingerprint string) string

ClaimExplicitName reserves an explicit component name or panics if it conflicts.

func (*Analyzer) Components

func (a *Analyzer) Components() map[string]*Schema

Components returns the analyzed component schemas.

func (*Analyzer) Err added in v1.10.0

func (a *Analyzer) Err() error

Err returns the first unsupported schema projection encountered by this analyzer.

func (*Analyzer) FingerprintAttribute added in v1.8.0

func (a *Analyzer) FingerprintAttribute(att *expr.AttributeExpr) string

FingerprintAttribute computes the canonical schema fingerprint, including checked enum projections retained by prepared attribute declarations.

func (*Analyzer) SchemaFingerprints added in v1.8.0

func (a *Analyzer) SchemaFingerprints() map[string]string

SchemaFingerprints returns component fingerprints keyed by component name.

func (*Analyzer) Uniquify

func (a *Analyzer) Uniquify(name, fingerprint string) string

Uniquify returns a stable unique component name. A name reserved for a component still under analysis, such as the owner of a recursive variant, counts as taken.

type AnalyzerOption

type AnalyzerOption func(*Analyzer)

AnalyzerOption customizes analyzer behavior.

func WithExampleGenerator added in v1.8.0

func WithExampleGenerator(generator *expr.ExampleGenerator) AnalyzerOption

WithExampleGenerator overrides the generator used for synthesized examples.

func WithExampleSuppression

func WithExampleSuppression(fn func(*expr.AttributeExpr, bool) bool) AnalyzerOption

WithExampleSuppression controls whether examples should be omitted.

func WithExampleValue

func WithExampleValue(fn func(*expr.AttributeExpr, any) (any, bool)) AnalyzerOption

WithExampleValue selects a custom projector over the original attribute and raw example. A nil projector uses retained declared JSON-shaped values, preserving Bytes as []byte. Custom projector output is the caller's responsibility.

func WithServiceSemantics added in v1.10.0

func WithServiceSemantics(semantic *service.SemanticData) AnalyzerOption

WithServiceSemantics shares captured service occurrences with other backends.

type BodyTypes

type BodyTypes struct {
	// Err reports an unsupported schema projection; no output may be rendered when set.
	Err error

	Services   map[string]map[string]*EndpointBodies
	Components map[string]*Schema
	// DiscriminatorChildren maps a parent-hint component name to the
	// component names of its direct allOf children.
	DiscriminatorChildren map[string][]string
	// contains filtered or unexported fields
}

BodyTypes groups endpoint bodies and component schemas.

func BuildBodyTypes

func BuildBodyTypes(api *expr.APIExpr, types []expr.UserType, resultTypes []*expr.ResultTypeExpr, options ...AnalyzerOption) *BodyTypes

BuildBodyTypes analyzes endpoint request and response bodies plus referenced components.

type BoolOrSchema

type BoolOrSchema struct {
	Bool   *bool
	Schema *Schema
}

BoolOrSchema models JSON Schema bool-or-schema fields.

type ComponentIdentity added in v1.10.0

type ComponentIdentity struct {
	// Kind names the OpenAPI component collection, such as "mediaTypes".
	Kind string
	// Name is the explicit component key.
	Name string
	// Value is a deterministic representation of the complete component value.
	Value string
	// Source identifies the Loom value that contributed this claim.
	Source string
}

ComponentIdentity records an explicit reusable component name and the canonical value claimed for it.

type Components

type Components struct {
	// SecuritySchemes maps allocated names to distinct HTTP credential bindings.
	SecuritySchemes map[string]*expr.SchemeExpr
	Schemas         map[string]*Schema
	Parameters      map[string]*ParameterRef
	Headers         map[string]*HeaderRef
	RequestBodies   map[string]*RequestBodyRef
	Responses       map[string]*ResponseRef
	Examples        map[string]*ExampleRef
	// DiscriminatorChildren maps a parent-hint schema component name to
	// the schema component names of its direct allOf children. Publishing
	// the parent publishes these children: they are the implicit members of
	// its discriminator.
	DiscriminatorChildren map[string][]string
}

Components contains reusable IR components.

type Discriminator

type Discriminator struct {
	PropertyName   string
	Mapping        map[string]string
	DefaultMapping string
	Optional       bool
	// Untagged identifies a validation-neutral union hint.
	Untagged bool `json:",omitzero"`
	// Object identifies a parent-object hint.
	Object bool `json:",omitzero"`
	// Extensions retains Discriminator Object x-* properties.
	Extensions map[string]any `json:",omitzero"`
}

Discriminator describes union selection.

type Document

type Document struct {
	Paths      map[string]*PathItem
	Components *Components
	// Security contains API defaults with resolved component names.
	Security []map[string][]string
}

Document is the root OpenAPI-oriented IR document.

func BuildDocument

func BuildDocument(api *expr.APIExpr, types []expr.UserType, resultTypes []*expr.ResultTypeExpr, options ...AnalyzerOption) (*Document, error)

BuildDocument analyzes HTTP operations, schemas and security bindings. It returns an error when OpenAPI cannot represent a credential location or reconcile response metadata for alternatives sharing a status.

type EndpointBodies

type EndpointBodies struct {
	RequestBody    *Schema
	ResponseBodies map[string][]*Schema
	// contains filtered or unexported fields
}

EndpointBodies describes the request and response body schemas for one endpoint.

type Example

type Example struct {
	Summary         string
	Description     string
	ComponentName   string
	Value           any
	DataValue       any
	SerializedValue string
}

Example describes an IR example object.

type ExampleRef

type ExampleRef struct {
	Ref   string
	Value *Example
}

ExampleRef is an example reference or value.

type ExternalDocs

type ExternalDocs struct {
	Description string
	URL         string
}

ExternalDocs describes operation-level external documentation.

type Header struct {
	// Style and Explode retain the resolved response-header grammar.
	Style   string
	Explode *bool
	// ReferenceMetadata retains authored reusable-object edges until component allocation.
	ReferenceMetadata []string `json:"-"`

	Description   string
	Required      bool
	AllowReserved bool
	Schema        *Schema
	Example       any
	Examples      map[string]*ExampleRef
	Extensions    map[string]any
}

Header describes an IR header.

type HeaderRef

type HeaderRef struct {
	// Description overrides the target description, including an explicit empty string.
	Description *string `json:",omitzero"`
	// Summary overrides the target summary when supported by that object.
	Summary *string `json:",omitzero"`

	Ref   string
	Value *Header
}

HeaderRef is a header reference or value.

type MediaType

type MediaType struct {
	Schema        *Schema
	Example       any
	Examples      map[string]*ExampleRef
	ComponentName string
	Metadata      map[string][]string
	Extensions    map[string]any
}

MediaType describes an IR media type.

type NullExample added in v1.8.0

type NullExample struct{}

NullExample is a non-nil marker that marshals as an explicit JSON or YAML null while remaining distinguishable from an omitted example field.

func (NullExample) MarshalJSON added in v1.8.0

func (NullExample) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (NullExample) MarshalYAML added in v1.8.0

func (NullExample) MarshalYAML() (any, error)

MarshalYAML implements yaml.Marshaler.

type Operation

type Operation struct {
	Tags         []string
	Summary      string
	Description  string
	OperationID  string
	Parameters   []*ParameterRef
	RequestBody  *RequestBodyRef
	Responses    map[string]*ResponseRef
	Deprecated   bool
	Security     []map[string][]string
	ExternalDocs *ExternalDocs
	Extensions   map[string]any
}

Operation describes an IR operation.

func BuildRouteOperation

func BuildRouteOperation(route *expr.RouteExpr, path string, bodies *EndpointBodies, rand *expr.ExampleGenerator, apiMeta expr.MetaExpr, closeObjects bool) (*Operation, error)

BuildRouteOperation analyzes one route-scoped HTTP operation including parameters and OpenAPI metadata. It returns an error for a credential location or conflicting response metadata that OpenAPI cannot represent.

type OperationIdentity added in v1.10.0

type OperationIdentity struct {
	// Path is the normalized OpenAPI path key.
	Path string
	// Method is the HTTP method used by the operation.
	Method string
	// OperationID is the emitted operationId, if present.
	OperationID string
	// Source identifies the Loom operation that contributed this claim.
	Source string
}

OperationIdentity is the document-level identity that must remain unique after operations have been assembled from all generated sources.

type Parameter

type Parameter struct {
	// CookieFormEquivalent31 proves raw cookie bytes equal form bytes over the schema domain.
	CookieFormEquivalent31 bool `json:"-"`
	Name                   string
	In                     string
	ComponentName          string `json:"-"`
	Description            string
	Style                  string
	Explode                *bool
	AllowEmptyValue        bool
	AllowReserved          bool
	Deprecated             bool
	Required               bool
	Schema                 *Schema
	Example                any
	Examples               map[string]*ExampleRef
	Content                map[string]*MediaType
	WholeQueryString       bool
	Extensions             map[string]any
}

Parameter describes an IR parameter object.

type ParameterRef

type ParameterRef struct {
	Ref   string
	Value *Parameter
}

ParameterRef is a parameter reference or value.

type PathItem

type PathItem struct {
	Operations map[string]*Operation
}

PathItem groups operations by method.

type RenderedEndpointBodies

type RenderedEndpointBodies struct {
	RequestBody    *openapi.Schema
	ResponseBodies map[string][]*openapi.Schema
}

RenderedEndpointBodies is the rendered endpoint body set used by v3 adapters.

type RequestBody

type RequestBody struct {
	// ReferenceMetadata retains authored reusable-object edges until component allocation.
	ReferenceMetadata []string `json:"-"`

	Description   string
	Required      bool
	ComponentName string `json:"-"`
	Content       map[string]*MediaType
	Extensions    map[string]any
}

RequestBody describes an IR request body.

type RequestBodyRef

type RequestBodyRef struct {
	// Description overrides the target description, including an explicit empty string.
	Description *string `json:",omitzero"`
	// Summary overrides the target summary when supported by that object.
	Summary *string `json:",omitzero"`

	Ref   string
	Value *RequestBody
}

RequestBodyRef is a request body reference or value.

type Response

type Response struct {
	// ReferenceMetadata retains authored reusable-object edges until component allocation.
	ReferenceMetadata []string `json:"-"`

	Description     string
	Summary         string
	OmitDescription bool
	ComponentName   string `json:"-"`
	Headers         map[string]*HeaderRef
	Content         map[string]*MediaType
	Links           map[string]*ResponseLinkRef
	Extensions      map[string]any
}

Response describes an IR response.

type ResponseLink struct {
	OperationID  string
	OperationRef string
	Description  string
	Parameters   map[string]any
	RequestBody  any
	Extensions   map[string]any
}

ResponseLink describes an OpenAPI response link.

type ResponseLinkRef

type ResponseLinkRef struct {
	Ref   string
	Value *ResponseLink
}

ResponseLinkRef is a response link reference or value.

type ResponseRef

type ResponseRef struct {
	// Summary overrides the referenced summary, including an explicit empty string.
	Summary *string `json:",omitzero"`
	Ref     string
	// Description overrides the component description, including an explicit empty string.
	Description *string
	Value       *Response
}

ResponseRef is a response reference or value.

type Schema

type Schema struct {
	Ref          string
	Type         string
	Format       string
	Items        *Schema
	Properties   map[string]*Schema
	Defs         map[string]*Schema
	Title        string `json:",omitzero"`
	Description  string
	DefaultValue any
	Example      any
	// Examples retains multiple schema example values in declaration order.
	Examples []any `json:",omitzero,omitempty"`

	ReadOnly         bool
	WriteOnly        bool
	Deprecated       bool
	ContentEncoding  string
	ContentMediaType string
	ContentSchema    *Schema

	Enum             []any
	Pattern          string
	ExclusiveMinimum *expr.NumericBound
	Minimum          *expr.NumericBound
	ExclusiveMaximum *expr.NumericBound
	Maximum          *expr.NumericBound
	MinLength        *int
	MaxLength        *int
	MinItems         *int
	MaxItems         *int
	// MinProperties is the minimum object property count.
	MinProperties *int
	// MaxProperties is the maximum object property count.
	MaxProperties         *int
	Required              []string
	AdditionalProperties  *BoolOrSchema
	UnevaluatedProperties *BoolOrSchema

	// Not rejects values accepted by the child, preserving an empty child.
	Not           *Schema   `json:",omitzero"`
	AllOf         []*Schema `json:",omitzero,omitempty"`
	AnyOf         []*Schema
	OneOf         []*Schema
	Discriminator *Discriminator
	XML           *XML

	Extensions map[string]any
}

Schema represents a renderer-neutral schema node.

func (*Schema) MarshalJSON added in v1.9.0

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON preserves the v1 structural encoding used to derive reusable component names. Retired JSON Hyper-Schema slots remain zero-valued in the hash encoding so removing them from the active model does not rename existing OpenAPI components.

type XML added in v1.8.0

type XML struct {
	Name      string
	Namespace string
	Prefix    string
	NodeType  string
}

XML describes how a schema maps to XML nodes.

Jump to

Keyboard shortcuts

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