ir

package
v1.19.0 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 24 Imported by: 4

Documentation

Overview

Package ir contains definitions for the intermediate representation of OpenAPI objects and generated Go types.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PrintGoValue

func PrintGoValue(v any) string

PrintGoValue prints given value as Go value.

Types

type Const added in v1.19.0

type Const struct {
	Value any
	Set   bool
}

Const represents const value.

type ContentType

type ContentType string

ContentType is a Content-Type header value.

func (ContentType) Mask added in v0.35.0

func (t ContentType) Mask() bool

func (ContentType) String

func (t ContentType) String() string

type Default

type Default struct {
	Value any
	Set   bool
}

Default represents default value.

func (Default) IsNil

func (d Default) IsNil() bool

IsNil whether value is set, but null.

type Encoding added in v0.44.0

type Encoding string

Encoding of body.

const (
	// EncodingJSON is Encoding for json.
	EncodingJSON        Encoding = "application/json"
	EncodingProblemJSON Encoding = "application/problem+json"
	// EncodingFormURLEncoded is Encoding for URL-encoded form.
	EncodingFormURLEncoded Encoding = "application/x-www-form-urlencoded"
	// EncodingMultipart is Encoding for multipart form.
	EncodingMultipart Encoding = "multipart/form-data"
	// EncodingOctetStream is Encoding for binary.
	EncodingOctetStream Encoding = "application/octet-stream"
	// EncodingTextPlain is Encoding for text.
	EncodingTextPlain Encoding = "text/plain"
)

func (Encoding) FormURLEncoded added in v0.44.0

func (t Encoding) FormURLEncoded() bool

func (Encoding) JSON added in v0.44.0

func (t Encoding) JSON() bool

func (Encoding) MultipartForm added in v0.44.0

func (t Encoding) MultipartForm() bool

func (Encoding) OctetStream added in v0.44.0

func (t Encoding) OctetStream() bool

func (Encoding) ProblemJSON added in v1.15.0

func (t Encoding) ProblemJSON() bool

func (Encoding) String added in v0.44.0

func (t Encoding) String() string

func (Encoding) TextPlain added in v0.44.0

func (t Encoding) TextPlain() bool

type EnumVariant

type EnumVariant struct {
	Name  string
	Value any
}

func (*EnumVariant) ValueGo

func (v *EnumVariant) ValueGo() string

type EqualityMethodSpec added in v1.17.0

type EqualityMethodSpec struct {
	// TypeName is the Go type name (e.g., "WorkflowStatus")
	TypeName string

	// Fields describes each field's equality comparison logic
	Fields []FieldEqualitySpec

	// NeedsDepthTracking indicates if this type contains nested objects
	// requiring depth limit enforcement
	NeedsDepthTracking bool

	// MaxDepth is the configured maximum nesting depth (default: 10)
	MaxDepth int
}

EqualityMethodSpec describes how to generate an Equal method for a type.

type ExternalEncoding added in v1.15.0

type ExternalEncoding int

ExternalEncoding is a kind of external type.

const (
	// ExternalNative indicates that the type implements ogen's json.Marshaler or json.Unmarshaler.
	ExternalNative ExternalEncoding = 1 << iota
	// ExternalJSON indicates that the type implements stdlib json.Marshaler or json.Unmarshaler.
	ExternalJSON
	// ExternalText indicates that the type implements stdlib encoding.TextMarshaler or encoding.TextUnmarshaler.
	ExternalText
	// ExternalBinary indicates that the type implements stdlib encoding.BinaryMarshaler or encoding.BinaryUnmarshaler.
	ExternalBinary
)

func (ExternalEncoding) Has added in v1.15.0

Has checks if the encoding kind is present in the ExternalEncoding.

func (ExternalEncoding) String added in v1.15.0

func (e ExternalEncoding) String() string

String returns the string representation of the ExternalEncoding.

type ExternalType added in v0.56.0

type ExternalType struct {
	PackagePath string
	PackageName string
	ImportAlias string
	TypeName    string
	Encode      ExternalEncoding
	Decode      ExternalEncoding
	IsPointer   bool
}

ExternalType represents an external type.

func (ExternalType) Primitive added in v1.15.0

func (e ExternalType) Primitive() PrimitiveType

String returns the string representation of the ExternalType.

type Field

type Field struct {
	// Go Name of field.
	Name string
	// Type of field.
	Type *Type
	// JSON tag. May be empty.
	Tag Tag
	// Whether field is inlined map (i.e. additionalProperties, patternProperties).
	Inline InlineField
	// Spec is property schema. May be nil.
	Spec *jsonschema.Property
}

Field of structure.

func (Field) Const added in v1.19.0

func (f Field) Const() Const

Const returns const value of this field, if it is set.

func (Field) Default

func (f Field) Default() Default

Default returns default value of this field, if it is set.

func (Field) GoDoc

func (f Field) GoDoc() []string

GoDoc returns field godoc.

func (Field) ValidationName

func (f Field) ValidationName() string

ValidationName returns name for FieldError.

type FieldEqualitySpec added in v1.17.0

type FieldEqualitySpec struct {
	// FieldName is the struct field name (e.g., "ID", "Description")
	FieldName string

	// FieldType categorizes the field for comparison logic selection
	FieldType FieldTypeCategory

	// GoType is the full Go type (e.g., "string", "OptString", "*NestedObject")
	GoType string

	// IsNested indicates if this field is a nested object requiring recursive Equal() call
	IsNested bool

	// IsMap indicates if the field (or wrapped value for Optional/Nullable) is a map type
	IsMap bool

	// IsArray indicates if the field (or wrapped value for Optional/Nullable) is an array type
	IsArray bool

	// IsArrayOfStructs indicates if this is an array field where elements are structs
	IsArrayOfStructs bool

	// IsArrayOfNullable indicates if this is an array field where elements are nullable wrappers (NilT)
	IsArrayOfNullable bool

	// IsByteSlice indicates if this field is a byte slice ([]byte / jx.Raw)
	IsByteSlice bool
}

FieldEqualitySpec describes how to compare a single field.

type FieldHashSpec added in v1.17.0

type FieldHashSpec struct {
	// FieldName is the struct field name
	FieldName string

	// FieldType categorizes the field for hashing logic selection
	FieldType FieldTypeCategory

	// GoType is the full Go type
	GoType string

	// IsNested indicates if this field has a Hash() method
	IsNested bool
}

FieldHashSpec describes how to hash a single field.

type FieldTypeCategory added in v1.17.0

type FieldTypeCategory int

FieldTypeCategory classifies fields for equality comparison.

const (
	FieldTypePrimitive    FieldTypeCategory = iota // string, int, bool, etc.
	FieldTypeOptional                              // OptT, OptNilT
	FieldTypeNullable                              // NilT
	FieldTypePointer                               // *T
	FieldTypeNestedObject                          // struct with generated Equal()
	FieldTypeArray                                 // []T
	FieldTypeMap                                   // map[K]V
)

type GenericVariant

type GenericVariant struct {
	Nullable bool
	Optional bool
}

func (GenericVariant) Any

func (v GenericVariant) Any() bool

func (GenericVariant) Name

func (v GenericVariant) Name() string

func (GenericVariant) NullableOptional

func (v GenericVariant) NullableOptional() bool

func (GenericVariant) OnlyNullable

func (v GenericVariant) OnlyNullable() bool

func (GenericVariant) OnlyOptional

func (v GenericVariant) OnlyOptional() bool

type HashMethodSpec added in v1.17.0

type HashMethodSpec struct {
	// TypeName is the Go type name
	TypeName string

	// Fields describes each field's hashing logic
	Fields []FieldHashSpec

	// UsesNestedHash indicates if this type contains nested objects
	// that provide their own Hash() methods
	UsesNestedHash bool
}

HashMethodSpec describes how to generate a Hash method for a type.

type InlineField

type InlineField int

InlineField defines how to inline field.

const (
	InlineNone InlineField = iota
	InlineAdditional
	InlinePattern
	InlineSum
)

type JSON

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

JSON specifies json encoding and decoding for Type.

func (JSON) AdditionalProps

func (j JSON) AdditionalProps() *Field

AdditionalProps return field of Type that should be encoded as inlined map.

func (JSON) AnyFields added in v1.1.1

func (j JSON) AnyFields() bool

AnyFields whether if type has any fields to encode.

func (JSON) Decode

func (j JSON) Decode() string

func (JSON) Decoder added in v1.15.0

func (j JSON) Decoder() string

Decoder returns format name for handling json decoding.

Mostly used for decoding of string formats, like `json.DecodeUUID`, where UUID is Decoder.

func (JSON) Encoder added in v1.15.0

func (j JSON) Encoder() string

Encoder returns format name for handling json encoding.

Mostly used for encoding of string formats, like `json.EncodeUUID`, where UUID is Encoder.

func (JSON) Except added in v1.1.1

func (j JSON) Except(set ...string) JSON

Except return JSON with filter by given properties.

func (JSON) Fields

func (j JSON) Fields() (fields JSONFields)

Fields return all fields of Type that should be encoded via json.

func (JSON) Fn

func (j JSON) Fn() string

Fn returns jx.Encoder or jx.Decoder method name.

If blank, value cannot be encoded with single method call.

func (JSON) Format

func (j JSON) Format() string

Format returns format name for handling json encoding or decoding.

Mostly used for encoding or decoding of string formats, like `json.EncodeUUID`, where UUID is Format.

func (JSON) IsBase64

func (j JSON) IsBase64() bool

IsBase64 whether field has base64 encoding.

func (JSON) PatternProps

func (j JSON) PatternProps() (fields []*Field)

PatternProps return field of Type that should be encoded as inlined map with pattern.

func (JSON) Sum

func (j JSON) Sum() SumJSON

Sum returns specification for parsing value as sum type.

func (JSON) SumProps added in v0.72.0

func (j JSON) SumProps() (fields []*Field)

SumProps return field of Type that should be encoded as inlined sum.

func (JSON) SumTypes added in v0.27.0

func (j JSON) SumTypes() string

SumTypes returns jx.Type list for this sum type.

func (JSON) TimeFormat added in v1.6.0

func (j JSON) TimeFormat() string

TimeFormat returns time format for json encoding and decoding.

func (JSON) Type

func (j JSON) Type() string

Type returns json value type that can represent Type.

E.g. string primitive can be represented by StringValue which is commonly returned from `i.WhatIsNext()` method. Blank string is returned if there is no appropriate json type.

type JSONFields

type JSONFields []*Field

func (JSONFields) FirstRequiredIndex

func (j JSONFields) FirstRequiredIndex() int

FirstRequiredIndex returns first required field index.

Or -1 if there is no required fields.

func (JSONFields) HasRequired

func (j JSONFields) HasRequired() bool

HasRequired whether object has required fields

func (JSONFields) RequiredMask

func (j JSONFields) RequiredMask() []uint8

RequiredMask returns array of 64-bit bitmasks for required fields.

type Kind

type Kind string
const (
	KindPrimitive Kind = "primitive"
	KindArray     Kind = "array"
	KindMap       Kind = "map"
	KindAlias     Kind = "alias"
	KindConst     Kind = "const"
	KindEnum      Kind = "enum"
	KindStruct    Kind = "struct"
	KindPointer   Kind = "pointer"
	KindInterface Kind = "interface"
	KindGeneric   Kind = "generic"
	KindSum       Kind = "sum"
	KindAny       Kind = "any"
	KindStream    Kind = "stream"
)

type Media added in v0.42.0

type Media struct {
	// Encoding is the parsed content type used for encoding, but not for header value.
	Encoding Encoding
	// Type is response or request type.
	Type *Type

	// JSONStreaming indicates that the JSON media should be streamed.
	JSONStreaming bool
	// RawResponse indicates that the raw HTTP response should be returned.
	RawResponse bool
}

type NilSemantic

type NilSemantic string

NilSemantic specifies nil value semantics.

const (
	NilInvalid  NilSemantic = "invalid"  // nil is invalid
	NilOptional NilSemantic = "optional" // nil is "no value"
	NilNull     NilSemantic = "null"     // nil is null
)

Possible nil value semantics.

func (NilSemantic) Invalid

func (n NilSemantic) Invalid() bool

func (NilSemantic) Null

func (n NilSemantic) Null() bool

func (NilSemantic) Optional

func (n NilSemantic) Optional() bool

type OTELAttribute added in v0.53.0

type OTELAttribute struct {
	// Key is a name of the attribute constructor in otelogen package.
	Key string
	// Value is a value of the attribute.
	Value string
}

OTELAttribute represents OpenTelemetry attribute defined by otelogen package.

func (OTELAttribute) String added in v0.53.0

func (a OTELAttribute) String() string

String returns call to the constructor of this attribute.

type Operation

type Operation struct {
	Name           string
	Summary        string
	Description    string
	Deprecated     bool
	WebhookInfo    *WebhookInfo
	PathParts      []*PathPart
	Params         []*Parameter
	Request        *Request
	Responses      *Responses
	Security       SecurityRequirements
	Spec           *openapi.Operation
	OperationGroup string
}

func (*Operation) CookieParams

func (op *Operation) CookieParams() []*Parameter

func (Operation) GoDoc

func (op Operation) GoDoc() []string

func (Operation) HasCookieParams added in v0.59.0

func (op Operation) HasCookieParams() bool

func (Operation) HasHeaderParams added in v0.33.0

func (op Operation) HasHeaderParams() bool

func (Operation) HasQueryParams

func (op Operation) HasQueryParams() bool

func (Operation) HasRawResponse added in v1.15.0

func (op Operation) HasRawResponse() bool

HasRawResponse returns true if the operation has any response content types marked with x-ogen-raw-response: true.

func (*Operation) HeaderParams

func (op *Operation) HeaderParams() []*Parameter

func (*Operation) ListResponseTypes

func (op *Operation) ListResponseTypes(otel bool) []ResponseInfo

func (Operation) OTELAttributes added in v0.53.0

func (op Operation) OTELAttributes() (r []OTELAttribute)

OTELAttributes returns OpenTelemetry attributes for this operation.

func (Operation) PathParamIndex

func (op Operation) PathParamIndex(name string) int

func (*Operation) PathParams

func (op *Operation) PathParams() []*Parameter

func (Operation) PathParamsCount

func (op Operation) PathParamsCount() (r int)

func (Operation) PrettyOperationID added in v0.37.0

func (op Operation) PrettyOperationID() string

func (*Operation) QueryParams

func (op *Operation) QueryParams() []*Parameter

type OperationGroup added in v1.1.0

type OperationGroup struct {
	Name       string
	Operations []*Operation
}

type Parameter

type Parameter struct {
	Name string
	Type *Type
	Spec *openapi.Parameter
	Tag  Tag
}

func (Parameter) Default

func (op Parameter) Default() Default

Default returns default value of this field, if it is set.

func (Parameter) GoDoc

func (op Parameter) GoDoc() []string

type PathPart

type PathPart struct {
	Raw   string
	Param *Parameter
}

func (PathPart) String

func (p PathPart) String() string

type PickedMappingEntries added in v1.14.0

type PickedMappingEntries []*ResolvedSumSpecMap

func (PickedMappingEntries) JoinConstNames added in v1.14.0

func (e PickedMappingEntries) JoinConstNames() string

type PrimitiveType

type PrimitiveType string

PrimitiveType represents a primitive type in Go.

const (
	None      PrimitiveType = ""
	String    PrimitiveType = "string"
	ByteSlice PrimitiveType = "[]byte"
	Int       PrimitiveType = "int"
	Int8      PrimitiveType = "int8"
	Int16     PrimitiveType = "int16"
	Int32     PrimitiveType = "int32"
	Int64     PrimitiveType = "int64"
	Uint      PrimitiveType = "uint"
	Uint8     PrimitiveType = "uint8"
	Uint16    PrimitiveType = "uint16"
	Uint32    PrimitiveType = "uint32"
	Uint64    PrimitiveType = "uint64"
	Float32   PrimitiveType = "float32"
	Float64   PrimitiveType = "float64"
	Bool      PrimitiveType = "bool"
	Null      PrimitiveType = "struct{}"
	Time      PrimitiveType = "time.Time"
	Duration  PrimitiveType = "time.Duration"
	UUID      PrimitiveType = "uuid.UUID"
	MAC       PrimitiveType = "net.HardwareAddr"
	IP        PrimitiveType = "netip.Addr"
	URL       PrimitiveType = "url.URL"
	File      PrimitiveType = "ht.MultipartFile"
	Decimal   PrimitiveType = "decimal.Decimal"
	Custom    PrimitiveType = "<custom>"
)

Primitive types.

func (PrimitiveType) IsString

func (p PrimitiveType) IsString() bool

IsString whether this type is string.

func (PrimitiveType) String

func (p PrimitiveType) String() string

type Request

type Request struct {
	Type      *Type
	EmptyBody *Type
	Contents  map[ContentType]Media
	Spec      *openapi.RequestBody
}

func (*Request) DoTakePtr added in v0.56.0

func (r *Request) DoTakePtr() bool

DoTakePtr returns true if type should be taken by pointer.

func (*Request) GoType added in v0.56.0

func (r *Request) GoType() string

GoType returns Go type of this response.

type ResolvedSumSpecMap added in v1.14.0

type ResolvedSumSpecMap struct {
	Name              string
	Key               string
	DiscriminatorType *Type
}

type Response

type Response struct {
	NoContent *Type
	Contents  map[ContentType]Media
	Spec      *openapi.Response
	Headers   map[string]*Parameter

	// Indicates that all response types
	// are wrappers with StatusCode field.
	WithStatusCode bool

	// Indicates that all response types
	// are wrappers with response header fields.
	WithHeaders bool
}

func (Response) ResponseInfo added in v0.33.0

func (s Response) ResponseInfo(otel bool) []ResponseInfo

type ResponseInfo

type ResponseInfo struct {
	Type           *Type
	Encoding       Encoding
	ContentType    ContentType
	StatusCode     int
	NoContent      bool
	WithStatusCode bool
	WithHeaders    bool
	JSONStreaming  bool
	RawResponse    bool
	OpenTelemetry  bool
	Headers        map[string]*Parameter
}

func (ResponseInfo) ContentTypeHeader added in v0.78.0

func (r ResponseInfo) ContentTypeHeader() string

func (ResponseInfo) ExposeHeadersHeader added in v1.19.0

func (r ResponseInfo) ExposeHeadersHeader() string

type Responses added in v0.33.0

type Responses struct {
	Type       *Type
	Pattern    [5]*Response
	StatusCode map[int]*Response
	Default    *Response
}

func (*Responses) DoPass added in v0.56.0

func (r *Responses) DoPass() bool

DoPass whether response type should be present in result tuple.

func (*Responses) DoTakePtr added in v0.56.0

func (r *Responses) DoTakePtr() bool

DoTakePtr returns true if type should be taken by pointer.

func (*Responses) GoType added in v0.56.0

func (r *Responses) GoType() string

GoType returns Go type of this response.

func (*Responses) HasPattern added in v0.44.0

func (r *Responses) HasPattern() bool

func (*Responses) ResultTuple added in v0.56.0

func (r *Responses) ResultTuple(a, b string) string

ResultTuple returns result tuple for this response.

type Security

type Security struct {
	Kind          SecurityKind
	Format        SecurityFormat
	ParameterName string
	Description   string
	Type          *Type
	Scopes        map[string][]string
}

func (*Security) GoDoc

func (s *Security) GoDoc() []string

type SecurityFormat

type SecurityFormat string

SecurityFormat defines security parameter format.

const (
	// APIKeySecurityFormat is plain value format.
	APIKeySecurityFormat SecurityFormat = "apiKey"
	// BearerSecurityFormat is Bearer authentication (RFC 6750) format.
	//
	// Unsupported yet.
	BearerSecurityFormat SecurityFormat = "bearer"
	// BasicHTTPSecurityFormat is Basic HTTP authentication (RFC 7617) format.
	BasicHTTPSecurityFormat SecurityFormat = "basic"
	// DigestHTTPSecurityFormat is Digest HTTP authentication (RFC 7616) format.
	//
	// Unsupported yet.
	DigestHTTPSecurityFormat SecurityFormat = "digest"

	// Oauth2SecurityFormat is Oauth2 security format.
	Oauth2SecurityFormat SecurityFormat = "oauth2"

	// CustomSecurityFormat is a user-defined security format.
	CustomSecurityFormat = "x-ogen-custom-security"
)

func (SecurityFormat) IsAPIKeySecurity

func (s SecurityFormat) IsAPIKeySecurity() bool

IsAPIKeySecurity whether s is APIKeySecurityFormat.

func (SecurityFormat) IsBasicHTTPSecurity

func (s SecurityFormat) IsBasicHTTPSecurity() bool

IsBasicHTTPSecurity whether s is BasicHTTPSecurityFormat.

func (SecurityFormat) IsBearerSecurity

func (s SecurityFormat) IsBearerSecurity() bool

IsBearerSecurity whether s is BearerSecurityFormat.

func (SecurityFormat) IsCustomSecurity added in v0.76.0

func (s SecurityFormat) IsCustomSecurity() bool

IsCustomSecurity whether s is CustomSecurityFormat.

func (SecurityFormat) IsDigestHTTPSecurity

func (s SecurityFormat) IsDigestHTTPSecurity() bool

IsDigestHTTPSecurity whether s is DigestHTTPSecurityFormat.

func (SecurityFormat) IsOAuth2Security added in v0.74.0

func (s SecurityFormat) IsOAuth2Security() bool

IsOAuth2Security whether s is Oauth2SecurityFormat.

type SecurityKind

type SecurityKind string

SecurityKind defines security kind.

const (
	// QuerySecurity is URL query security parameter. Matches "apiKey" type with "in" = "query".
	QuerySecurity SecurityKind = "query"
	// HeaderSecurity is HTTP header security parameter. Matches some "http" schemes and "apiKey" with "in" = "header".
	HeaderSecurity SecurityKind = "header"
	// CookieSecurity is HTTP cookie security parameter. Matches some "http" schemes and "apiKey" with "in" = "cookie".
	CookieSecurity SecurityKind = "cookie"
	// OAuth2Security is special type for OAuth2-based authentication. Matches "oauth2" and "openIdConnect".
	OAuth2Security SecurityKind = "oauth2"
)

func (SecurityKind) IsCookie added in v0.59.0

func (s SecurityKind) IsCookie() bool

IsCookie whether s is CookieSecurity.

func (SecurityKind) IsHeader

func (s SecurityKind) IsHeader() bool

IsHeader whether s is HeaderSecurity.

func (SecurityKind) IsOAuth2

func (s SecurityKind) IsOAuth2() bool

IsOAuth2 whether s is OAuth2Security.

func (SecurityKind) IsQuery

func (s SecurityKind) IsQuery() bool

IsQuery whether s is QuerySecurity.

type SecurityRequirements added in v0.57.0

type SecurityRequirements struct {
	Securities   []*Security
	Requirements []bitset.Bitset
}

func (SecurityRequirements) BitArrayLen added in v0.57.0

func (s SecurityRequirements) BitArrayLen() (r int)

BitArrayLen returns the length for bitset's underlying array.

type Server added in v0.52.0

type Server struct {
	Name   string
	Params []ServerParam
	Spec   openapi.Server
}

Server describes a OpenAPI server.

func (Server) FormatString added in v0.52.0

func (s Server) FormatString() string

FormatString returns a format string (fmt.Sprintf) for the server.

If the server has no variables, returns plain string.

func (Server) GoDoc added in v0.52.0

func (s Server) GoDoc() []string

GoDoc returns GoDoc comment for the server.

func (Server) IsTemplate added in v0.52.0

func (s Server) IsTemplate() bool

IsTemplate returns true if server URL has variables.

type ServerParam added in v0.52.0

type ServerParam struct {
	// Name is a Go name of the parameter.
	Name string
	Spec openapi.ServerVariable
}

ServerParam describes a server template parameter.

type Servers added in v0.52.0

type Servers []Server

Servers is a list of servers.

func (Servers) Const added in v0.52.0

func (s Servers) Const() []Server

Const return a list of constant server URLs.

func (Servers) Templates added in v0.52.0

func (s Servers) Templates() []Server

Templates returns a list of server URL templates.

type SumJSON

type SumJSON struct {
	Type SumJSONType
}

SumJSON specifies rules for parsing sum types in json.

func (SumJSON) Discriminator

func (s SumJSON) Discriminator() bool

func (SumJSON) Fields

func (s SumJSON) Fields() bool

func (SumJSON) Primitive

func (s SumJSON) Primitive() bool

func (SumJSON) String

func (s SumJSON) String() string

func (SumJSON) TypeDiscriminator

func (s SumJSON) TypeDiscriminator() bool

type SumJSONType

type SumJSONType byte
const (
	SumJSONPrimitive SumJSONType = iota
	SumJSONFields
	SumJSONDiscriminator
	SumJSONTypeDiscriminator
)

type SumSpec

type SumSpec struct {
	Unique []*Field
	// DefaultMapping is name of default mapping.
	//
	// Used for variant which has no unique fields.
	DefaultMapping string

	// Discriminator is field name of sum type discriminator.
	Discriminator string
	// Mapping is discriminator value -> variant mapping.
	Mapping []SumSpecMap

	// TypeDiscriminator denotes to distinguish variants by type.
	TypeDiscriminator bool

	// UniqueFieldTypes maps field JSON names to their expected jx.Type for type-based discrimination.
	// Key: field JSON name, Value: jx.Type constant name (e.g., "jx.String", "jx.Number")
	// Only populated for fields that require runtime type checking.
	UniqueFieldTypes map[string]string

	// UniqueFields maps field names to variants that have that field as unique.
	// Used for generating field-based discrimination in oneOf/anyOf.
	// Key: field JSON name, Value: list of variants with that unique field
	UniqueFields map[string][]UniqueFieldVariant

	// ValueDiscriminators maps field names to value-based discriminators.
	// Used when variants have the same field name and JSON type but different enum values.
	// Key: field JSON name, Value: ValueDiscriminator with enum value mappings
	ValueDiscriminators map[string]ValueDiscriminator
}

SumSpec for KindSum.

func (SumSpec) PickMappingEntriesFor added in v1.14.0

func (s SumSpec) PickMappingEntriesFor(t, sumOf *Type) PickedMappingEntries

PickMappingEntriesFor returns all mapping entries for given type they exists.

func (SumSpec) PickMappingEntryFor deprecated added in v0.71.0

func (s SumSpec) PickMappingEntryFor(t *Type) *SumSpecMap

Deprecated: use PickMappingEntriesFor instead.

PickMappingEntryFor returns the first mapping entry for given type if exists.

type SumSpecMap

type SumSpecMap struct {
	Key               string
	Type              *Type
	DiscriminatorType *Type
	Name              string
}

type Tag

type Tag struct {
	JSON      string             // json tag, empty for none
	Form      *openapi.Parameter // query form parameter
	ExtraTags map[string]string  // a map of extra struct field tags
}

Tag of Field or Parameter.

func (Tag) EscapedJSON

func (t Tag) EscapedJSON() string

EscapedJSON returns quoted and escaped JSON tag.

func (Tag) GetTags added in v0.59.0

func (t Tag) GetTags() string

GetTags returns a formatted list of struct tags, which must be quoted by '`'

type Type

type Type struct {
	Doc                 string              // ogen documentation
	Kind                Kind                // kind
	Name                string              // only for struct, alias, interface, enum, stream, generic, map, sum
	Primitive           PrimitiveType       // only for primitive, enum
	AliasTo             *Type               // only for alias
	PointerTo           *Type               // only for pointer
	SumOf               []*Type             // only for sum
	SumSpec             SumSpec             // only for sum
	Item                *Type               // only for array, map
	EnumVariants        []*EnumVariant      // only for enum
	Fields              []*Field            // only for struct
	Implements          map[*Type]struct{}  // only for struct, alias, enum
	Implementations     map[*Type]struct{}  // only for interface
	InterfaceMethods    map[string]struct{} // only for interface
	Schema              *jsonschema.Schema  // for all kinds except pointer, interface. Can be nil.
	NilSemantic         NilSemantic         // only for pointer
	GenericOf           *Type               // only for generic
	GenericVariant      GenericVariant      // only for generic
	MapPattern          ogenregex.Regexp    // only for map
	DenyAdditionalProps bool                // only for map and struct
	AllowedProps        map[string]struct{} // only for map and struct
	External            ExternalType        // only for custom type
	Validators          Validators
	Tuple               bool // only for struct
	// Features contains a set of features the type must implement.
	// Available features: 'json', 'uri'.
	//
	// If some of these features are set, generator
	// generates additional encoding methods if needed.
	Features []string
}

func Alias

func Alias(name string, to *Type) *Type

func Any

func Any(schema *jsonschema.Schema) *Type

func Array

func Array(item *Type, sem NilSemantic, schema *jsonschema.Schema) *Type

func External added in v1.15.0

func External(schema *jsonschema.Schema) (*Type, error)

func Generic

func Generic(name string, of *Type, v GenericVariant) *Type

func Interface

func Interface(name string) *Type

func Pointer

func Pointer(to *Type, sem NilSemantic) *Type

func Primitive

func Primitive(typ PrimitiveType, schema *jsonschema.Schema) *Type

func Stream

func Stream(name string, schema *jsonschema.Schema) *Type

func (*Type) AddFeature

func (t *Type) AddFeature(feature string)

func (*Type) AddMethod

func (t *Type) AddMethod(name string)

func (Type) CanGeneric

func (t Type) CanGeneric() bool

CanGeneric reports whether Type can be boxed to KindGeneric.

func (*Type) CanHaveMethods

func (t *Type) CanHaveMethods() bool

func (*Type) CloneFeatures

func (t *Type) CloneFeatures() []string

func (Type) Default

func (t Type) Default() Default

Default returns default value of this type, if it is set.

func (Type) DefaultFields

func (t Type) DefaultFields() (r []*Field)

DefaultFields returns fields with default values.

func (*Type) DoPassByPointer added in v0.56.0

func (t *Type) DoPassByPointer() bool

DoPassByPointer returns true if type should be passed by pointer.

func (*Type) EncodeFn

func (t *Type) EncodeFn() string

func (*Type) Equal

func (t *Type) Equal(target *Type) bool

Equal reports whether two types are equal.

func (*Type) Examples

func (t *Type) Examples() (r []string)

func (Type) FakeFields

func (t Type) FakeFields() (r []*Field)

func (*Type) FakeValue

func (t *Type) FakeValue() string

func (Type) FileParameters added in v0.41.0

func (t Type) FileParameters() (params []Parameter)

func (Type) FormParameters added in v0.41.0

func (t Type) FormParameters() (params []Parameter)

func (*Type) Format

func (t *Type) Format() bool

Format denotes whether custom formatting for Type is required while encoding or decoding.

TODO(ernado): can we use t.JSON here?

func (Type) FromString

func (t Type) FromString() string

func (*Type) Go

func (t *Type) Go() string

Go returns valid Go type for this Type.

func (Type) GoDoc

func (t Type) GoDoc() []string

GoDoc returns type godoc.

func (Type) HasDefaultFields

func (t Type) HasDefaultFields() bool

HasDefaultFields whether type has fields with default values.

func (*Type) HasFeature

func (t *Type) HasFeature(feature string) bool

func (*Type) Implement

func (t *Type) Implement(i *Type)

func (*Type) Is

func (t *Type) Is(vs ...Kind) bool

func (*Type) IsAlias

func (t *Type) IsAlias() bool

func (*Type) IsAny

func (t *Type) IsAny() bool

func (*Type) IsArray

func (t *Type) IsArray() bool

func (*Type) IsBase64Stream added in v0.55.0

func (t *Type) IsBase64Stream() bool

func (*Type) IsDecimal added in v1.16.0

func (t *Type) IsDecimal() bool

func (*Type) IsEnum

func (t *Type) IsEnum() bool

func (*Type) IsExternal added in v1.15.0

func (t *Type) IsExternal() bool

func (*Type) IsFloat

func (t *Type) IsFloat() bool

func (*Type) IsGeneric

func (t *Type) IsGeneric() bool

func (*Type) IsInteger

func (t *Type) IsInteger() bool

func (*Type) IsInterface

func (t *Type) IsInterface() bool

func (*Type) IsMap

func (t *Type) IsMap() bool

func (*Type) IsNull

func (t *Type) IsNull() bool

func (*Type) IsNumeric

func (t *Type) IsNumeric() bool

func (*Type) IsPointer

func (t *Type) IsPointer() bool

func (*Type) IsPrimitive

func (t *Type) IsPrimitive() bool

func (*Type) IsStream

func (t *Type) IsStream() bool

func (*Type) IsStringifiedFloat added in v0.70.0

func (t *Type) IsStringifiedFloat() bool

func (*Type) IsStruct

func (t *Type) IsStruct() bool

func (*Type) IsSum

func (t *Type) IsSum() bool

func (*Type) JSON

func (t *Type) JSON() JSON

JSON returns json encoding/decoding rules for t.

func (*Type) ListImplementations

func (t *Type) ListImplementations() []*Type

func (*Type) Methods

func (t *Type) Methods() []string

func (*Type) MustField

func (t *Type) MustField(name string) *Field

func (*Type) NamePostfix

func (t *Type) NamePostfix() string

NamePostfix returns name postfix for optional wrapper.

func (*Type) NeedValidation

func (t *Type) NeedValidation() bool

func (*Type) Pointer

func (t *Type) Pointer(sem NilSemantic) *Type

func (*Type) ReadOnlyReceiver added in v0.56.0

func (t *Type) ReadOnlyReceiver() string

ReadOnlyReceiver returns the receiver type for read-only methods.

func (*Type) RecursiveTo

func (t *Type) RecursiveTo(target *Type) bool

func (*Type) SetFieldType

func (t *Type) SetFieldType(name string, newT *Type)

func (Type) String

func (t Type) String() string

func (Type) ToString

func (t Type) ToString() string

func (*Type) TypeDiscriminator added in v0.56.0

func (t *Type) TypeDiscriminator() (r []TypeDiscriminatorCase)

func (*Type) Unimplement

func (t *Type) Unimplement(i *Type)

type TypeDiscriminatorCase added in v0.56.0

type TypeDiscriminatorCase struct {
	// JXTypes is jx.Type values list.
	JXTypes string
	// Type is the type to be used for this case.
	Type *Type
	// IntType is the type to be used for this case when the type discriminator should distinguish
	// between integer and float types.
	IntType *Type
}

TypeDiscriminatorCase is a helper struct for describing type discriminator case.

type UniqueFieldVariant added in v1.18.0

type UniqueFieldVariant struct {
	VariantName string // e.g., "SystemEvent"
	VariantType string // e.g., "SystemEventEvent"
	FieldType   string // jx.Type constant, e.g., "jx.String"
	Nullable    bool   // true if field is nullable (accepts both base type and jx.Null)

	// ArrayElementType is the jx.Type of array elements for array element discrimination.
	// Only set when FieldType is "jx.Array" and element type can distinguish variants.
	// e.g., "jx.String" for array[string], "jx.Number" for array[integer], "jx.Object" for array[object]
	ArrayElementType string

	// ArrayElementTypeID is the full type ID for array elements (e.g., "string", "integer", "object").
	// Used for more detailed discrimination like distinguishing integer vs number.
	ArrayElementTypeID string
}

UniqueFieldVariant represents a variant that has a specific unique field.

type Validators

type Validators struct {
	String  validate.String
	Int     validate.Int
	Float   validate.Float
	Decimal validate.Decimal
	Array   validate.Array
	Object  validate.Object
	// Ogen contains parameters for custom validation.
	Ogen map[string]any
}

func (*Validators) SetArray

func (v *Validators) SetArray(schema *jsonschema.Schema)

func (*Validators) SetDecimal added in v1.16.0

func (v *Validators) SetDecimal(schema *jsonschema.Schema) error

func (*Validators) SetFloat

func (v *Validators) SetFloat(schema *jsonschema.Schema) error

func (*Validators) SetInt

func (v *Validators) SetInt(schema *jsonschema.Schema) error

func (*Validators) SetObject

func (v *Validators) SetObject(schema *jsonschema.Schema)

func (*Validators) SetOgenValidate added in v1.15.0

func (v *Validators) SetOgenValidate(schema *jsonschema.Schema)

func (*Validators) SetString

func (v *Validators) SetString(schema *jsonschema.Schema) (err error)

type ValueDiscriminator added in v1.18.0

type ValueDiscriminator struct {
	// FieldName is the JSON field name used for discrimination
	FieldName string
	// ValueToVariant maps enum values to variant type constants
	// Key: enum value (e.g., "active"), Value: variant type constant (e.g., "ActiveStatusResponse")
	ValueToVariant map[string]string
}

ValueDiscriminator represents a field that discriminates variants by enum value.

type WebhookInfo added in v0.53.0

type WebhookInfo struct {
	// Name is the name of the webhook.
	Name string
}

WebhookInfo contains information about webhook.

Jump to

Keyboard shortcuts

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