ir

package
v0.0.0-...-d1929c9 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AllOfUnion

type AllOfUnion struct {
	// FieldName is the field holding the union, named after its type.
	FieldName string `json:"fieldName,omitzero"`
	IsOneOf   bool   `json:"isOneOf,omitzero"`
	// Discriminator is the member the variants are told apart by, if one is; otherwise by the members present.
	Discriminator string         `json:"discriminator,omitzero"`
	Variants      []UnionVariant `json:"variants,omitempty"`
	// Choices are what decoding picks from, as for a union's Choices.
	Choices []UnionVariant `json:"choices,omitempty"`
}

AllOfUnion is the union part of an allOf.

type Auth

type Auth struct {
	Bearer Bearer `json:"bearer,omitzero"`
	Basic  Basic  `json:"basic,omitzero"`
	// Default is the scheme operations use unless they name their own, so the client requires its credential.
	Default AuthScheme `json:"default,omitzero"`
}

type AuthScheme

type AuthScheme string

AuthScheme names the credential an operation sends in its Authorization header.

const (
	AuthBearer AuthScheme = "bearer"
	AuthBasic  AuthScheme = "basic"
)

type Basic

type Basic struct {
	UsernameEnvName string `json:"usernameEnvName,omitzero"`
	PasswordEnvName string `json:"passwordEnvName,omitzero"`
}

type Bearer

type Bearer struct {
	Name string `json:"name,omitzero"`
}

type Document

type Document struct {
	// If enabled, debug mode will record responses that failed to unmarshal.
	Debug                  bool        `json:"debug,omitzero"`
	Title                  string      `json:"title,omitzero"`
	Production             bool        `json:"production,omitzero"`
	PackageName            string      `json:"packageName,omitzero"`
	BaseURL                URLParts    `json:"baseURL,omitzero"`
	UserAgent              string      `json:"userAgent,omitzero"`
	Operations             []Operation `json:"operations,omitempty"`
	GlobalParams           Params      `json:"globalParams,omitempty"`
	Schemas                []Schema    `json:"schemas,omitempty"`
	Auth                   Auth        `json:"security,omitzero"`
	HasURLFields           bool        `json:"hasURLFields,omitzero"`
	HasDurationFields      bool        `json:"hasDurationFields,omitzero"`
	HasDateFields          bool        `json:"hasDateFields,omitzero"`
	HasDateTimeOrIntFields bool        `json:"hasDateTimeOrIntFields,omitzero"`
	HasUnixTimeFields      bool        `json:"hasUnixTimeFields,omitzero"`

	// HasServerOverrides is true when any path item names a server of its own,
	// which is what the generated serverURL helper is for.
	HasServerOverrides bool `json:"hasServerOverrides,omitzero"`

	// InteractionCalls holds one entry per matched interaction.
	// Populated at code-gen time; not serialized to ir.json (too noisy).
	InteractionCalls InteractionCalls `json:"-"`
}

Document is the top-level IR type passed to templates.

func FromDocument

func FromDocument(doc *openapi.Document, packageName, userAgent string, production, debug bool) (*Document, error)

FromDocument converts a fully-loaded and flattened openapi.Document to an IR Document. cfg provides the package name and optional user-agent override. In debug mode, nothing the specification leaves open decodes into any: see narrowUnspecified.

func (Document) APIKey

func (doc Document) APIKey() *Param

func (Document) Client

func (doc Document) Client() *Param

func (Document) HasOptionalAuthCalls

func (d Document) HasOptionalAuthCalls() bool

HasOptionalAuthCalls reports whether an interaction calls an operation whose credentials are optional, whose recording may lack them.

func (Document) HasReadOnly

func (doc Document) HasReadOnly() bool

HasReadOnly reports whether a type has fields a request leaves out.

func (Document) HasTagged

func (doc Document) HasTagged() bool

HasTagged reports whether a generated type is a Tagged struct, needing the helpers that check one.

func (Document) HasWriteOnly

func (doc Document) HasWriteOnly() bool

HasWriteOnly reports whether a type has fields a response leaves out.

func (Document) MinimalLiteral

func (doc Document) MinimalLiteral(goType string) string

MinimalLiteral is a Go literal of goType that marshals: every union in it that a value requires, itself included, has its first variant set.

func (Document) NeedMustDecodeBody

func (d Document) NeedMustDecodeBody() bool

func (Document) NeedsJSONHelpers

func (doc Document) NeedsJSONHelpers() bool

NeedsJSONHelpers reports whether a generated type decodes its alternatives itself, needing the JSON helpers.

type EnumValue

type EnumValue struct {
	GoName string `json:"goName,omitzero"`
	// Value is the human-readable string form of the enum member, e.g. "active" or "3.14".
	Value string `json:"value,omitzero"`
	// Literal is the Go source literal to embed in the generated constant,
	// e.g. `"active"` (quoted) for a string enum or `3.14` for a number enum.
	Literal string `json:"literal,omitzero"`
}

EnumValue is one member of an enum type.

type Field

type Field struct {
	Name        string `json:"name,omitzero"`
	JSONName    string `json:"jsonName,omitzero"`
	Type        string `json:"type,omitzero"`
	JSONTag     string `json:"jsonTag,omitzero"`
	Description string `json:"description,omitzero"`
	Required    bool   `json:"required,omitzero"`
	Embedded    bool   `json:"embedded,omitzero"` // true for allOf $ref entries rendered as embedded structs
	// ReadOnly and WriteOnly mark a property only responses carry, or only requests: a request leaves the former out,
	// a response the latter, and neither requires it.
	ReadOnly  bool `json:"readOnly,omitzero"`
	WriteOnly bool `json:"writeOnly,omitzero"`

	// IsDateTimeOrInt is true when the property's schema is a oneOf of a
	// date-time string and an integer. The Go type is time.Time, but a custom
	// (un)marshaller is required to accept either form on the wire.
	IsDateTimeOrInt bool `json:"isDateTimeOrInt,omitzero"`

	// IsUnixTime is true when Type is time.Time but the property's schema
	// itself is an integer (format: date-time), not a date-time string --
	// see [integerGoType]. A custom (un)marshaller is required to encode and
	// decode it as a unix timestamp instead of RFC 3339.
	IsUnixTime bool `json:"isUnixTime,omitzero"`
}

Field is a named field within a struct schema.

type GlobalType

type GlobalType string
const (
	GlobalAPIKey    GlobalType = "APIKey"
	GlobalClient    GlobalType = "Client"
	GlobalUserAgent GlobalType = "User-Agent"
)

type GoType

type GoType struct {
	Name          string `json:"name,omitzero"`
	IsPointer     bool   `json:"isPointer,omitzero"`
	IsSlice       bool   `json:"isSlice,omitzero"`
	IsArrayOfSize int    `json:"isArrayOfSize,omitzero"`
	// IsNilable is true for a map, or a $ref to a named component schema
	// that is itself array- or map-kind (e.g. "type TimeEntries
	// []TimeEntry"): Name is already a nilable Go type on its own, so
	// Nilable returns it unchanged instead of adding a pointer.
	IsNilable bool `json:"isNilable,omitzero"`
}

GoType is a resolved Go type reference.

func SchemaGoType

func SchemaGoType(s *openapi.Schema) (*GoType, error)

SchemaGoType maps an openapi.Schema to its Go type string. After flattening, complex schemas are moved to components and referenced by $ref; a reference maps to the name of the component it points to.

func (GoType) NilByItself

func (t GoType) NilByItself() bool

NilByItself reports whether Nilable is the type itself, a slice or a nilable type, not a pointer to it.

func (GoType) Nilable

func (t GoType) Nilable() string

func (GoType) String

func (t GoType) String() string

String returns the Go type expression.

func (GoType) ZeroValue

func (t GoType) ZeroValue() string

ZeroValue returns the Go zero-value literal for the type.

type InteractionCall

type InteractionCall struct {
	Op         *Operation         // matched operation
	PathArgs   []string           // Go literal per path param, same order as Op.PathParams
	QueryArgs  []InteractionParam // set query params only (omitted = use nil params)
	HeaderArgs []InteractionParam // set query params only (omitted = use nil params)
	// IsSuccess is true when StatusCode matches one of Op's declared success responses.
	IsSuccess bool
	// ErrorType is the Go type name of the declared error response schema for
	// StatusCode, empty when the operation has no schema for that status (the
	// client falls back to a generic status-string error in that case).
	ErrorType string
	// BodyLiteral is a Go expression for the recorded request body, set
	// whenever Op.RequestBody is non-nil: a composite literal of the
	// request body's type when every field could be expressed that way,
	// falling back to a runtime JSON decode (mustDecodeBody) for values a
	// literal can't cleanly represent. Either way the replayed request
	// carries the same body the interaction was recorded with, instead of
	// a zero value.
	BodyLiteral string
}

InteractionCall is one operation call extracted from a recorded interaction.

func (InteractionCall) UsesMustDecodeBody

func (ic InteractionCall) UsesMustDecodeBody() bool

type InteractionCalls

type InteractionCalls []InteractionCall

func (InteractionCalls) UseMustDecodeBody

func (ics InteractionCalls) UseMustDecodeBody() bool

type InteractionParam

type InteractionParam struct {
	FieldName string // PascalCase field name on the params struct
	Literal   string // Go expression, e.g. `3` or `"abc"`
}

InteractionParam is one query param with its Go literal value.

type Operation

type Operation struct {
	// BaseURL is set when the path item names a server of its own, overriding
	// the document's for this operation only.
	BaseURL *URLParts `json:"baseURL,omitzero"`
	// Auth is the scheme whose credential the operation sends, if any.
	Auth AuthScheme `json:"auth,omitzero"`
	// AuthOptional is set if the operation may also be called without credentials, which it sends all the same.
	AuthOptional bool     `json:"authOptional,omitzero"`
	Name         string   `json:"name,omitzero"`
	Description  string   `json:"description,omitzero"`
	Summary      string   `json:"summary,omitzero"`
	Method       string   `json:"method,omitzero"`
	PathTemplate string   `json:"pathTemplate,omitzero"`
	JoinPathArgs []string `json:"joinPathArgs,omitempty"`
	PathParams   Params   `json:"pathParams,omitempty"`
	QueryParams  Params   `json:"queryParams,omitempty"`
	HeaderParams Params   `json:"headerParams,omitempty"`
	// FixedParams are the required parameters the specification pins to one value, which the client sends itself.
	FixedParams     Params    `json:"fixedParams,omitempty"`
	HasParams       bool      `json:"hasParams,omitzero"`
	ParamStructName string    `json:"paramStructName,omitzero"`
	RequestBody     *ReqBody  `json:"requestBody,omitempty"`
	Responses       Responses `json:"responses,omitempty"`
	SuccessReturn   *GoType   `json:"successReturn,omitempty"`
	Deprecated      bool      `json:"deprecated,omitzero"`
	// EmptySuccess is true when the operation's success body is an empty object: the client decodes it, so anything in
	// it is an error, and returns no value; the server writes {}.
	EmptySuccess bool `json:"emptySuccess,omitzero"`
	// RawBytesSuccess is true when the operation's success response has no
	// JSON media type, so SuccessReturn is a raw []byte read directly from
	// the response body rather than a JSON-decoded type. Such operations
	// are generated as a single concrete method, not a generic function.
	RawBytesSuccess bool `json:"rawBytesSuccess,omitzero"`
	// StreamSuccess is true when the operation's success response is not text (see Response.IsStream), so
	// SuccessReturn is io.ReadCloser and the method leaves the response body open for the caller.
	StreamSuccess bool `json:"streamSuccess,omitzero"`
}

Operation represents a single API operation.

func FromOperation

func FromOperation(
	rawPath openapi.Path,
	pathItemParams openapi.ParameterList,
	method string,
	op *openapi.Operation,
	globalParams paramMap,
) (*Operation, error)

FromOperation converts an openapi operation to its IR representation. pathItemParams are the parameters defined at the path item level and are merged with (and can be overridden by) operation-level parameters.

func (Operation) BaseURLExpr

func (op Operation) BaseURLExpr() string

BaseURLExpr returns the Go expression for the URL an operation builds its request path on: the client's, or serverURL with the server the path item named for itself. The latter stays overridable -- WithBaseURL has to reach every operation, or a caller cannot point the client at a test server.

func (Operation) FixedHeaders

func (op Operation) FixedHeaders() Params

FixedHeaders are the fixed parameters sent as headers.

func (Operation) FixedQuery

func (op Operation) FixedQuery() string

FixedQuery is the encoded query of the fixed parameters sent in it.

func (Operation) JSPath

func (op Operation) JSPath() string

JSPath is JSPathTemplate with the fixed query, for an operation that takes no query parameters.

func (Operation) JSPathTemplate

func (op Operation) JSPathTemplate() string

JSPathTemplate returns the path template with {jsonName} placeholders replaced by ${goName} JavaScript template-literal interpolations, and those of fixed parameters by their value.

func (Operation) NilParamsExpr

func (op Operation) NilParamsExpr() string

func (Operation) ParamsInStruct

func (op Operation) ParamsInStruct() Params

type Param

type Param struct {
	GlobalType   GlobalType `json:"globalType,omitzero"`
	VarName      string     `json:"varName,omitzero"`
	EnvName      string     `json:"envName,omitzero"`
	GoName       string     `json:"goName,omitzero"`
	FieldName    string     `json:"fieldName,omitzero"`
	JSONName     string     `json:"jsonName,omitzero"`
	Type         string     `json:"type,omitzero"`
	Required     bool       `json:"required,omitzero"`
	ParseExpr    string     `json:"parseExpr,omitzero"`
	ParseCast    string     `json:"parseCast,omitzero"`
	ParseErrFree bool       `json:"parseErrFree,omitzero"`
	IsEnum       bool       `json:"isEnum,omitzero"`
	// BaseType is the underlying Go type a generated Type was declared
	// from -- e.g. "string" for an enum's Type "Status", or for any other
	// named component built from a plain scalar. Set whenever Type came
	// from a $ref, since a generated name carries no zero-value or
	// formatting behavior of its own, unlike a builtin: NotZero and
	// FormatExpr switch on this instead, when set.
	BaseType string `json:"baseType,omitzero"`
	// IsUnixTime is true when Type is "time.Time" but the OpenAPI schema
	// itself is an integer (format: date-time), not a date-time string --
	// see [integerGoType]. FormatExpr needs this to know whether to encode
	// the param back into an integer instead of an RFC 3339 string.
	IsUnixTime  bool   `json:"isUnixTime,omitzero"`
	Description string `json:"description,omitzero"`
	// Item is one element of an array parameter, with v as its variable.
	Item    *Param `json:"item,omitzero"`
	Value   string `json:"value,omitzero"`   // the Go string literal of the one value the parameter can take
	In      string `json:"in,omitzero"`      // where a fixed parameter goes: path, query or header
	Example string `json:"example,omitzero"` // hardcoded example for tests
}

Param represents a path or query parameter.

func (Param) FormatExpr

func (p Param) FormatExpr() string

formatExpr returns the Go expression that converts the param to a string for URL encoding.

func (Param) NotZero

func (p Param) NotZero() string

NotZero returns the Go boolean expression that is true when param is not the zero value.

type Params

type Params []Param

func (Params) Required

func (ps Params) Required() bool

type PinnedMember

type PinnedMember struct {
	Name  string `json:"name,omitzero"`
	Value string `json:"value,omitzero"`
}

PinnedMember is a member an alternative allows one value for, written as JSON.

type ReqBody

type ReqBody struct {
	TypeName    string `json:"typeName,omitzero"`
	ContentType string `json:"contentType,omitzero"`
	Required    bool   `json:"required,omitzero"`
}

ReqBody is the IR representation of an operation request body.

type Response

type Response struct {
	StatusCode  string  `json:"statusCode,omitzero"`
	GoConstant  string  `json:"goConstant,omitzero"`
	Description string  `json:"description,omitzero"`
	ContentType string  `json:"contentType,omitzero"`
	GoType      *GoType `json:"goType,omitempty"`
	IsSuccess   bool    `json:"isSuccess,omitzero"`
	// IsRawBytes is true when ContentType has no JSON media type declared for
	// it, so GoType is a raw []byte read directly from the response body
	// rather than something to json.Unmarshal into.
	IsRawBytes bool `json:"isRawBytes,omitzero"`
	// IsStream is true for a success response whose media type is not text, such as a zip, a PDF or an image: GoType
	// is io.ReadCloser, the response body itself, which the caller reads and closes.
	IsStream bool `json:"isStream,omitzero"`
}

Response represents one expected HTTP response from an operation.

func (Response) IsJSON

func (r Response) IsJSON() bool

IsJSON reports whether the response's media type is a JSON one, whose body the client decodes.

type Responses

type Responses []Response

func (Responses) HasDefault

func (rs Responses) HasDefault() bool

type Schema

type Schema struct {
	Name        string      `json:"name,omitzero"`
	Description string      `json:"description,omitzero"`
	Kind        SchemaKind  `json:"kind,omitzero"`
	Type        string      `json:"type,omitzero"`
	Fields      []Field     `json:"fields,omitempty"`
	EnumValues  []EnumValue `json:"enumValues,omitempty"`
	MapKey      string      `json:"mapKey,omitzero"`
	MapValue    string      `json:"mapValue,omitzero"`

	// UnionVariants is set for SchemaKindUnion: one pointer field per
	// oneOf/anyOf variant. IsOneOf selects the cardinality rule enforced by
	// the generated UnmarshalJSONFrom: exactly one variant must match for
	// oneOf, at least one for anyOf.
	UnionVariants []UnionVariant `json:"unionVariants,omitempty"`
	// Choices are what decoding a union picks from: its variants, or, for a variant that is a union of its own,
	// each of that union's alternatives.
	Choices []UnionVariant `json:"choices,omitempty"`
	IsOneOf bool           `json:"isOneOf,omitzero"`
	// IsTypeAlias declares the type as an alias of Type rather than a new type.
	IsTypeAlias bool `json:"isTypeAlias,omitzero"`
	// Discriminator is the member a union's variants are told apart by, if one is: the generated decoder reads it and
	// decodes the one variant it names.
	Discriminator string `json:"discriminator,omitzero"`
	// AllOfUnion is the union among the parts of an allOf, held as a field of its own rather than embedded, since its
	// methods would otherwise encode the whole struct.
	AllOfUnion *AllOfUnion `json:"allOfUnion,omitzero"`
	// Members are the JSON members an allOf's fields and embedded parts declare, outside its union.
	Members []string `json:"members,omitempty"`
	// Unimplemented says why encoding this type is not supported yet; its methods return an error saying so.
	Unimplemented string `json:"unimplemented,omitzero"`
	// Streamed is set for a union, or an allOf with a union part, that decodes as it reads: its discriminator comes
	// first and picks the alternative, which then decodes each further member straight from the decoder.
	Streamed bool `json:"streamed,omitzero"`
	// MemberDecoder is set for a struct that decodes one member at a time, as an alternative of a streamed union.
	MemberDecoder bool `json:"memberDecoder,omitzero"`
	// Tagged is set for a struct made from a tagged union, whose methods check that only the member the tag names is set.
	Tagged *Tagged `json:"tagged,omitzero"`
	// ReadOnly and WriteOnly are the fields, as Go selectors through embedded parts, that a request leaves out and a
	// response leaves out.
	ReadOnly  []string `json:"readOnly,omitempty"`
	WriteOnly []string `json:"writeOnly,omitempty"`
}

Schema represents a named component schema.

func FromComponentSchemas

func FromComponentSchemas(schemas openapi.Schemas) ([]Schema, error)

FromComponentSchemas converts a set of named component schemas to IR schemas.

func (Schema) EncodesItself

func (s Schema) EncodesItself() bool

EncodesItself reports whether the type has a MarshalJSONTo method of its own.

type SchemaKind

type SchemaKind int

SchemaKind categorizes a schema into struct, enum, or array alias.

const (
	SchemaKindStruct SchemaKind = iota // object with properties
	SchemaKindEnum                     // string with enum values
	SchemaKindAlias                    // named type alias: array or plain scalar
	SchemaKindAllOf                    // allOf composition (struct with embedded types)
	SchemaKindMap
	SchemaKindUnion // untagged oneOf/anyOf composition (pointer-bag struct)
	SchemaKindTuple // fixed-length, positionally-typed array (prefixItems)
)

type Tagged

type Tagged struct {
	// Tag is the tag's JSON name, Field its Go field and Type that field's Go type.
	Tag   string `json:"tag,omitzero"`
	Field string `json:"field,omitzero"`
	Type  string `json:"type,omitzero"`
	// Optional is set if an alternative may leave the tag out, which decoding then infers from the members set.
	Optional bool `json:"optional,omitzero"`
	// Enum is set if Type is an enum type of the tag's values that the struct declares itself.
	Enum []EnumValue `json:"enum,omitempty"`
	// Values are the alternatives, one per value of the tag.
	Values []TaggedValue `json:"values,omitempty"`
	// Members are the fields of the alternatives' own members, each once.
	Members []TaggedMember `json:"members,omitempty"`
}

Tagged is set for a struct made from a tagged union whose alternatives differ in the value of their tag and in the members of their own, as Notion's blocks do: {"type": "paragraph", "paragraph": {...}}. The struct holds the members all alternatives share, the tag, and one field per member of an alternative's own; its methods check that only the members of the alternative the tag names are set.

type TaggedMember

type TaggedMember struct {
	// Name is the member's JSON name, Field its Go field, and Zero what the field holds while it is not set.
	Name  string `json:"name,omitzero"`
	Field string `json:"field,omitzero"`
	Zero  string `json:"zero,omitzero"`
}

TaggedMember is the field of a member of an alternative's own.

type TaggedOwn

type TaggedOwn struct {
	Name     string `json:"name,omitzero"`
	Required bool   `json:"required,omitzero"`
	Nullable bool   `json:"nullable,omitzero"`
}

TaggedOwn is a member of an alternative's own, by JSON name, whether the alternative requires it, and whether it may be null, which leaves its field as if it were left out.

func (TaggedOwn) Need

func (o TaggedOwn) Need() string

Need is how the alternative needs the member, by the name of the generated constant.

type TaggedValue

type TaggedValue struct {
	Value   string      `json:"value,omitzero"`
	Members []TaggedOwn `json:"members,omitempty"`
}

TaggedValue is one alternative of a Tagged struct: its value of the tag and the members of its own, by JSON name.

type URLParts

type URLParts struct {
	Scheme string `json:"scheme,omitzero"`
	Host   string `json:"host,omitzero"`
	Path   string `json:"path,omitzero"`
}

URLParts holds a decomposed server URL.

type UnionStep

type UnionStep struct {
	Field string `json:"field,omitzero"`
	Type  string `json:"type,omitzero"`
}

UnionStep is a field holding a nested union, on the way to one of its alternatives.

type UnionVariant

type UnionVariant struct {
	// FieldName is the exported Go field name, derived from the variant's
	// resolved type name (e.g. "Card" for a field of type *Card).
	FieldName string `json:"fieldName,omitzero"`
	// Type is the variant's own Go type, without the pointer the field may add.
	Type string `json:"type,omitzero"`
	// Zero is the value the field holds while the variant is not set, if Type has one no variant can take: nil for a
	// slice or a map, "" for a string. The field then is Type itself; otherwise it is a pointer to Type, nil until set.
	Zero string `json:"zero,omitzero"`
	// Value is the variant's value of the union's discriminator.
	Value string `json:"value,omitzero"`
	// Members and Required are the JSON members the variant declares and requires, if it is a plain Object.
	Members  []string `json:"members,omitempty"`
	Required []string `json:"required,omitempty"`
	Object   bool     `json:"object,omitzero"`
	// Pinned are the members the variant allows one value for, by its const or a one-value enum.
	Pinned []PinnedMember `json:"pinned,omitempty"`
	// Path is set for a choice that is an alternative of a union nested in this one, however deep: the fields of the
	// unions on the way to it, outermost first, each set to its union with the next one set.
	Path []UnionStep `json:"path,omitempty"`
}

UnionVariant is one member of a SchemaKindUnion's pointer bag.

func (UnionVariant) Assign

func (c UnionVariant) Assign(v string) string

func (UnionVariant) FieldType

func (c UnionVariant) FieldType() string

Assign returns the statement setting the union v holds to this choice, decoded into vv. FieldType is the Go type of the variant's field.

func (UnionVariant) IsSet

func (c UnionVariant) IsSet(field string) string

IsSet is the Go expression that reports whether field, the variant's field, is set.

Jump to

Keyboard shortcuts

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