gomodel

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package gomodel turns the spec IR into a typed Go model: named declarations, fields, pointers, enums, maps and merged allOf schemas. No Go type is text until rendering.

Index

Constants

View Source
const (
	PartTypes     = "models.types"
	PartEnums     = "models.enums"
	PartUnions    = "models.unions"
	PartParams    = "models.params"
	PartBodies    = "models.bodies"
	PartResponses = "models.responses"
)

Parts a declaration goes to. Layout places each part in one file.

View Source
const (
	RuntimePath    = "github.com/mockzilla/mockzilla-codegen/pkg/runtime"
	ValidationPath = RuntimePath + "/validation"
	MaskPath       = RuntimePath + "/mask"
	MCPToolPath    = RuntimePath + "/mcptool"
	HTTPServerPath = RuntimePath + "/httpserver"
	HTTPClientPath = RuntimePath + "/httpclient"
)

The import paths of the helpers that generated code uses: the runtime and its packages.

Variables

This section is empty.

Functions

func Dump

func Dump(m *Model) string

Dump writes a model as plain text for tests and debugging. It is not Go source.

func FitsFloat64

func FitsFloat64(t Type) bool

FitsFloat64 reports whether a value of type t keeps every digit when its JSON is read through float64 first. An integer wider than 53 bits does not, nor does raw JSON or a type the model cannot see into: one of another package, or one x-go-type writes out.

func Validates

func Validates(t Type) bool

Validates reports whether a value of type t, or of the type t points to, has a Validate method.

func ZeroLiteral

func ZeroLiteral(t Type) string

ZeroLiteral is the zero value of t as a Go literal: "", 0 or false, empty for other types.

Types

type BodyValue

type BodyValue struct {
	IsNullable bool
	Object     *Decl
	Items      *BodyValue
	Values     *BodyValue
}

BodyValue is what the server checks of one value of a request body; unions are not looked into.

type Builtin

type Builtin struct {
	Name string
}

Builtin is a predeclared type such as string, int64, byte or any.

type Check

type Check struct {
	Field          string
	Path           string
	IsVariant      bool
	Member         int
	IsPointer      bool
	IsWrapped      bool
	IsGuarded      bool
	IsZeroAbsent   bool
	Zero           string
	IsRequired     bool
	IsNullRejected bool
	Side           Side
	Rules          []Rule
	IsNested       bool
	Nested         *Decl
	Items          *Check
	Values         *Check
	Keys           []Rule
}

Check is what Validate checks of one value. Field is the Go field it lives in, empty for the value itself, and Path its JSON name in error paths. IsGuarded skips the checks of a nil value, which is absent; IsRequired reports it. Nested is the declaration whose Validate is called, nil with IsNested for runtime.Email. IsWrapped marks a Nullable; IsNullRejected reports it set to null. IsVariant marks the check of a union variant, Member which of its members it checks. IsZeroAbsent skips a plain optional field at its zero value: Zero, or validation.IsZero if empty.

type Content

type Content struct {
	MediaType string
	Type      Type
	Item      Type
	Body      *BodyValue
	Encoding  map[string]Encoding
}

Content is one media type; Type is nil when it has no schema. Item is the type of one frame of a sequential media type such as text/event-stream: its itemSchema, else its schema, which describes one event in specs before 3.2; nil for a media type with neither. Body is what the server checks of a request body. Encoding is how a form writes each property, by name.

type Count

type Count struct {
	Func     string
	Variants []*Variant
	Fields   [][]*Field
	Names    string
}

Count is the runtime check of how many Variants are set, or how many lists of Fields are all set.

type Decl

type Decl struct {
	ID               string
	Name             string
	Part             string
	Kind             DeclKind
	Doc              string
	Deprecated       bool
	DeprecatedReason string
	IsForm           bool
	Struct           *Struct
	Union            *Union
	Enum             *Enum
	Target           Type
	Validation       *Validation
	Error            *ErrorMessage
	Masks            []*Mask
	Origin           diag.Origin
	// contains filtered or unexported fields
}

Decl is one package-level type. ID is the JSON pointer it comes from. Struct is set for KindStruct and KindUnion, Union for KindUnion, Enum for KindEnum, Target for the other kinds. Validation is nil for aliases and when validation is off; Error is set for error types; Masks is set for types that hold sensitive values. IsForm marks the unions and objects a form body holds.

func ErrorDecl

func ErrorDecl(t Type) *Decl

ErrorDecl is the error type a value of type t is, through pointers and aliases, or nil.

func FormDecl

func FormDecl(t Type) *Decl

FormDecl is the struct or the union with UnmarshalForm that a value of type t is, or nil.

func StructDecl

func StructDecl(t Type) *Decl

StructDecl is the struct declaration a value of type t is, through pointers and aliases, or nil.

type DeclKind

type DeclKind int
const (
	KindStruct DeclKind = iota
	// KindAlias is type X = Y.
	KindAlias
	// KindDefined is type X Y.
	KindDefined
	KindEnum
	// KindUnion is a struct with a field per variant, next to the fields its variants share.
	KindUnion
)

type DeclRef

type DeclRef struct {
	Decl *Decl
}

DeclRef is a type this model declares.

type Encoding

type Encoding struct {
	ContentType string
	Style       string
	IsExplode   bool
	IsReserved  bool
}

Encoding is a form property written in ContentType, or as a query parameter of Style when set.

type Enum

type Enum struct {
	Base       Type
	Values     []EnumValue
	ValuesFunc string
}

Enum is a named type over Base with one constant per value, in spec order.

func (*Enum) Const

func (e *Enum) Const(v spec.Value) (string, bool)

Const returns the name of the constant that holds v.

type EnumValue

type EnumValue struct {
	Name  string
	Value spec.Value
}

type ErrorMessage

type ErrorMessage struct {
	Path           string
	HasConstructor bool
	Unset          []string
}

ErrorMessage is where an error type keeps its message. HasConstructor adds a NewT function; Unset lists, by JSON path, the required properties it leaves empty.

type Field

type Field struct {
	Name             string
	JSONName         string
	Type             Type
	Required         bool
	Nullable         bool
	OmitEmpty        bool
	OmitZero         bool
	ReadOnly         bool
	WriteOnly        bool
	Deprecated       bool
	DeprecatedReason string
	IsJSONIgnored    bool
	Doc              string
	Tags             []Tag
	Sensitive        *extension.Mask
	Value            *BodyValue
	Default          string
	Getter           *Getter
	Origin           diag.Origin
	// contains filtered or unexported fields
}

Field is one struct field. Required, Nullable, ReadOnly and WriteOnly repeat the spec. IsJSONIgnored writes the field with the JSON tag "-". Sensitive is how Masked masks it, nil for a value that is not sensitive. Value and Default are what the server checks and sets in a body. Getter returns the field or its default, nil when the field has none. OmitZero tags it omitzero.

func (*Field) IsZeroAbsent

func (f *Field) IsZeroAbsent() bool

IsZeroAbsent reports an optional field held as a plain value, which is absent at its zero value.

type Getter

type Getter struct {
	Name    string
	Default spec.Value
}

Getter is the method that returns a field, or Default when the field is nil.

type Group

type Group struct {
	IsAnyOf       bool
	IsNullable    bool
	IsLiteral     bool
	Discriminator string
	Variants      []*Variant
	Members       []Member
}

Group is one union: one variant set for oneOf, one or more for anyOf, or none if nullable.

type Import

type Import struct {
	Path  string
	Alias string
}

Import is a package path and the alias to import it under, empty for none.

type JSONKind

type JSONKind uint8

JSONKind is a set of JSON value kinds, as runtime.Kind has them.

const (
	JSONNull JSONKind = 1 << iota
	JSONBool
	JSONInteger
	JSONNumber
	JSONString
	JSONArray
	JSONObject

	JSONAny    = JSONNull | JSONBool | JSONInteger | JSONNumber | JSONString | JSONArray | JSONObject
	JSONScalar = JSONBool | JSONInteger | JSONNumber | JSONString
)

func JSONKinds

func JSONKinds(t Type) JSONKind

JSONKinds is what JSON a value of type t is written as. A union takes what its variants take.

type Map

type Map struct {
	Key  Type
	Elem Type
}

type Mask

type Mask struct {
	Field      string
	Kind       MaskKind
	IsPointer  bool
	IsWrapped  bool
	Pattern    *Pattern
	KeepPrefix int
	KeepSuffix int
}

Mask is one change Masked makes to a copy. Field is the Go field, empty for the value itself. Pattern is the expression of MaskRegex; KeepPrefix and KeepSuffix the characters MaskPartial leaves visible.

type MaskKind

type MaskKind int

MaskKind is what Masked does to one value.

const (
	MaskFull MaskKind = iota
	MaskRegex
	MaskHash
	MaskPartial
	// MaskZero clears a sensitive value that is no string.
	MaskZero
	// MaskNested calls Masked of the value's own type.
	MaskNested
	// MaskItems masks each item of a slice.
	MaskItems
	// MaskValues masks each value of a map.
	MaskValues
)

type Member

type Member struct {
	Variant *Variant
	Index   int
}

Member is one member of a group: the variant it sets, and which of the variant's schemas it is.

type Methods

type Methods struct {
	Client        []string
	Stream        []string
	Tool          []string
	IsToolSkipped bool
}

Methods are the suffixes of the methods the generator declares next to the one named after an operation. Every operation but a webhook gets Client; one that answers a 2xx in a sequential media type also gets Stream, and one the MCP tools keep gets Tool, where x-mcp decides over IsToolSkipped.

type Model

type Model struct {
	Decls      []*Decl
	Patterns   []*Pattern
	Operations []*Operation
}

Model is the Go side of a spec. Decls come in walk order: components first, each followed by the types inside it, then what operations declare.

func Build

func Build(doc *spec.Document, opts Options) (*Model, []diag.Diagnostic)

Build turns a parsed spec into the Go model. Problems in the spec come back as diagnostics.

type Nullable

type Nullable struct {
	Elem Type
}

Nullable is runtime.Nullable of Elem: a value that may be absent or null.

type Operation

type Operation struct {
	Name        string
	Spec        *spec.Operation
	Params      []ParamGroup
	QueryString *QueryString
	Bodies      []Content
	Responses   []Response
}

Operation is an operation or webhook with its Go name and the types it uses.

type Options

type Options struct {
	IntType            string
	Descriptions       bool
	ExtraTags          []string
	EnumPrefix         bool
	Namer              *naming.Namer
	Reserved           []string
	ReservedOperations []string
	Methods            Methods
	OperationSuffixes  []string
	IsValidated        bool
	ValidateResponse   bool
	IsServer           bool
	HasResponseHeaders bool
	ErrorMapping       map[string]string
	Imports            []config.Import
	FormatTypes        map[string]Type
	Nullable           bool
}

Options are the settings Build uses. Reserved names are declared by the generator elsewhere in the package; each operation also declares its name plus every OperationSuffixes entry, and no operation takes a ReservedOperations name, which the generator declares as a method next to the operations, or the name of one of the Methods of another operation. IsValidated adds Validate methods, ValidateResponse where responses differ. ErrorMapping maps error type names to the path of their message. IsServer reserves the names of the response constructors of the service contract; HasResponseHeaders declares a struct of the typed headers of every response that has some, which the server and the client envelopes use. Imports are the packages an x-go-type may name without an x-go-type-import. Nullable makes every value that may hold no value a Nullable.

func OptionsFrom

func OptionsFrom(cfg *config.Config) Options

OptionsFrom reads Options from a config. Blocks left out get their defaults.

type ParamGroup

type ParamGroup struct {
	In       string
	Decl     *Decl
	Params   []*spec.Parameter
	Defaults map[string]string
}

ParamGroup is the struct that holds the parameters of one location; Params are the parameters in the order of the struct's fields.

type Pattern

type Pattern struct {
	Name   string
	Text   string
	Source string
	Part   string
	Origin diag.Origin
}

Pattern is the Text of a spec pattern, compiled once from its Go Source into a variable of Part.

type Pointer

type Pointer struct {
	Elem Type
}

type Qualified

type Qualified struct {
	Import Import
	Name   string
}

Qualified is a type from another package, such as time.Time.

type QueryString

type QueryString struct {
	Param   *spec.Parameter
	Content Content
	Default string
}

QueryString is a querystring parameter: the whole query in one media type.

type Response

type Response struct {
	Status   string
	Contents []Content
	Headers  *Decl
}

Response is one status of an operation. Headers is the struct of its typed headers, nil when it declares none or no server is generated.

type Rule

type Rule struct {
	Kind        RuleKind
	Number      string
	IsExclusive bool
	IsBase64    bool
	Format      string
	Pattern     *Pattern
	Const       spec.Value
	Values      []spec.Value
}

Rule is one keyword check. Number is a bound, length, count or factor as the spec writes it.

type RuleKind

type RuleKind int

RuleKind picks the runtime check a rule calls.

const (
	RuleMinLength RuleKind = iota
	RuleMaxLength
	RulePattern
	RuleFormat
	RuleMinimum
	RuleMaximum
	RuleMultipleOf
	RuleMinItems
	RuleMaxItems
	RuleUnique
	RuleUniqueJSON
	RuleMinProperties
	RuleMaxProperties
	RuleConst
	RuleEnum
	RuleEnumJSON
)

type Shape

type Shape struct {
	Required []string
	Known    []string
	IsClosed bool
}

Shape is one object a union variant can be.

type Side

type Side int

Side is who carries a value: readOnly values only come in responses, writeOnly ones only in requests.

const (
	SideBoth Side = iota
	SideResponse
	SideRequest
)

type Slice

type Slice struct {
	Elem Type
}

type Struct

type Struct struct {
	Fields               []*Field
	AdditionalProperties *Field
	IsClosed             bool
}

Struct lists its fields in spec order. AdditionalProperties, when set, holds the keys that are not properties: its type is a map and its JSON name is "-". IsClosed is additionalProperties: false.

type Tag

type Tag struct {
	Key   string
	Value string
}

Tag is a struct tag written next to json, such as yaml:"name,omitempty".

type Type

type Type interface {
	// contains filtered or unexported methods
}

Type is a Go type expression. It stays a value until rendering turns it into text.

func Elem

func Elem(t Type) Type

Elem is the type a pointer points to or a Nullable holds, or t itself.

func Held

func Held(t Type) Type

Held is how a struct field holds a value of type t that may be absent: a pointer, unless t can be nil already.

func Underlying

func Underlying(t Type) Type

Underlying is the type under t, through aliases and defined types.

type Union

type Union struct {
	IsText   bool
	Variants []*Variant
	Groups   []*Group
	// contains filtered or unexported fields
}

Union holds one field per variant. Groups are the unions a value is at once. IsText is a union of scalars with no shared properties, which a parameter writes as text.

type Validation

type Validation struct {
	Counts          []Count
	IsDiscriminated bool
	Checks          []*Check
	HasResponse     bool
}

Validation is what the Validate methods of a declaration check. Counts check how many variants each union group has set. HasResponse adds ValidateResponse, whose checks differ from those of Validate.

type Variant

type Variant struct {
	Name      string
	Type      Type
	FieldType Type
	Values    []string
	IsDefault bool
	IsAbsent  bool
	Kinds     JSONKind
	Required  []string
	Known     []string
	IsClosed  bool
	Shapes    []Shape
	Origin    diag.Origin
	// contains filtered or unexported fields
}

Variant is one member of a union. FieldType is a pointer to Type unless Type can be nil. The other fields tell decoding which JSON picks it; Known is nil when any key fits. Shapes are the objects a variant that is itself a union can be, at any depth. Members of one Go type share it.

Jump to

Keyboard shortcuts

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