codegen

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: 39 Imported by: 3 modules, 1 package

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

Overview

Package codegen generates HTTP servers, clients, and OpenAPI specifications from an evaluated Loom design.

Pipeline position

service.ServicesData              (codegen/service)
        |
        v
httpcodegen.NewServicesData(svc, API.HTTP)
        |
        +--> per service: analyze(HTTPServiceExpr) -> *ServiceData
        |       which embeds *service.Data and adds transport-specific
        |       endpoint data (routes, params, headers, bodies, errors).
        |
        v
Section renderers (server.go, client.go, server_types.go, client_types.go,
paths.go, cli_sections.go, openapi.go)
        |
        v
[]*codegen.File consumed by codegen/generator

What this package owns

  • HTTP-level endpoint shape: routes, path/query/header/cookie bindings, request/response bodies, status codes, error group mapping to status codes (EndpointData, RequestData, ResponseData, ErrorGroupData).
  • Body element types (ParamData, HeaderData, CookieData, TypeData, MultipartData) — see service_data_element_types.go.
  • Transport-facing init code generation (InitData builders in service_data_payload.go, service_data_response.go, service_data_response_errors.go, service_data_init_args.go).
  • Server/client encode/decode and validation emission.
  • OpenAPI v3 generation (openapi/ sub-package) plus the internal IR (openapi/internal/ir) that decouples the design from the spec shape.
  • WebSocket/SSE templating and fixture generation for streaming endpoints.

Intermediate representation

Endpoint wire shape flows through http/codegen/internal/transportir before the final ServiceData is produced. transportir decouples "what the endpoint looks like on the wire" (routes, parameters, bodies, responses) from the Go types emitted for it, which keeps the response/payload/body builders small.

File layout

  • service_data.go — ServicesData/ServiceData/EndpointData + entry points.
  • service_data_element_types.go — Route/Param/Header/Cookie/Type/Multipart types.
  • service_data_payload.go — payloadBuilder: request side.
  • service_data_response.go — resultBuilder: success responses.
  • service_data_response_errors.go — errorBuilder: error responses + Problem Details.
  • service_data_init_args.go — shared InitArg constructors.
  • service_data_analysis.go — analyze() entry point.
  • service_data_body_types.go — request/response body type emission.
  • service_data_multipart.go — multipart encode/decode data.
  • server.go / client.go / paths.go — section renderers.
  • server_types.go / client_types.go — type-file renderers.
  • cli_sections.go / example_*.go — client CLI + example emission.
  • openapi.go + openapi/ — OpenAPI spec emission.
  • template_sources*.go / funcs.go — string templates used by renderers.
  • websocket*.go / sse_client.go — streaming codegen.
  • internal/transportir — wire-shape IR.

Extension points

  • Add a new HTTP element kind (e.g., trailer): extend service_data_element_types.go and add a builder in service_data_payload.go or service_data_response.go.
  • Add a new response variant (e.g., a second Problem profile): extend errorBuilder in service_data_response_errors.go.
  • Add a new template section: drop a new file alongside server_sections.go or client_sections.go and register it in server.go / client.go.

Invariants

  • Transport types NEVER reach into service.Data's unexported fields; service-level state is accessed via its public methods or the already- populated embedded *service.Data.
  • Body element type names are registered through registerRequestBodyTypeNames and registerClientBodyType — do NOT mutate ServerTypeNames/ClientTypeNames directly from new call sites.
  • Views propagate through MethodData.ViewedResult; builders check viewed once and branch, they do not re-derive view selection.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClientCLIFiles

func ClientCLIFiles(genpkg string, data *ServicesData) []*codegen.File

ClientCLIFiles returns the client HTTP CLI support file.

func ClientCLIFilesForTransport added in v1.7.0

func ClientCLIFilesForTransport(
	genpkg string,
	data *ServicesData,
	transport ClientCLITransport,
) []*codegen.File

ClientCLIFilesForTransport returns client CLI support files configured for transport. It is used by transports that share the HTTP command model.

func ClientEncodeDecodeFile

func ClientEncodeDecodeFile(genpkg string, svc *expr.HTTPServiceExpr, services *ServicesData, extra ...*codegen.ImportSpec) *codegen.File

ClientEncodeDecodeFile returns the file containing the HTTP client encoding and decoding logic. The file also lists the imports extra.

func ClientFiles

func ClientFiles(genpkg string, data *ServicesData) []*codegen.File

ClientFiles returns the generated HTTP client files.

func ClientTypeFiles

func ClientTypeFiles(genpkg string, data *ServicesData) []*codegen.File

ClientTypeFiles returns the HTTP transport client types files.

func DiagnosticFiles added in v1.10.0

func DiagnosticFiles(services *ServicesData, transportName string) []*codegen.File

DiagnosticFiles returns immutable-policy construction metadata for credential- bearing services. The artifact is shared by application client/server wiring; transport names follow the existing HTTP or JSON-RPC generated directory.

func ExampleCLI

func ExampleCLI(genpkg string, svr *expr.ServerExpr, services *ServicesData) *codegen.File

ExampleCLI returns an example client tool HTTP implementation for the given server expression. It returns nil when the server hosts no HTTP service.

func ExampleCLIFiles

func ExampleCLIFiles(genpkg string, services *ServicesData) []*codegen.File

ExampleCLIFiles returns an example client tool HTTP implementation for each server expression that hosts an HTTP service.

func ExampleCLIForTransport added in v1.7.0

func ExampleCLIForTransport(
	genpkg string,
	svr *expr.ServerExpr,
	services *ServicesData,
	transport ExampleCLITransport,
) *codegen.File

ExampleCLIForTransport returns an example client configured for transport. It is used by transports that share the HTTP client runtime. It returns nil when the server hosts no service of services.

func ExampleServer

func ExampleServer(genpkg string, root *expr.RootExpr, svr *expr.ServerExpr, services *ServicesData) *codegen.File

ExampleServer returns an example HTTP server implementation for the given server expression, whether or not it hosts an HTTP service. Transports that share the HTTP server runtime use it as the base of their example server.

func ExampleServerFiles

func ExampleServerFiles(genpkg string, data *ServicesData) []*codegen.File

ExampleServerFiles returns an example HTTP server implementation for each server expression that hosts an HTTP service.

func HasWebSocket

func HasWebSocket(sd *ServiceData) bool

HasWebSocket returns true if at least one of the endpoints in the service defines a streaming payload or result.

func IsSSEEndpoint

func IsSSEEndpoint(ed *EndpointData) bool

IsSSEEndpoint returns true if the endpoint defines a streaming result with SSE.

func IsWebSocketEndpoint

func IsWebSocketEndpoint(ed *EndpointData) bool

IsWebSocketEndpoint returns true if the endpoint defines a streaming payload or result.

func OpenAPIFiles

func OpenAPIFiles(root *expr.RootExpr, options ...openapiv3.Option) ([]*codegen.File, error)

OpenAPIFiles returns the files for the OpenAPIFile spec of the given HTTP API.

func PathFiles

func PathFiles(genpkg string, data *ServicesData) []*codegen.File

PathFiles returns the service path files.

func ResponseContractTestFiles added in v1.8.0

func ResponseContractTestFiles(genpkg string, data *ServicesData) []*codegen.File

ResponseContractTestFiles returns consumer-owned HTTP response contract test scaffolds. Existing files are never overwritten.

func RunHTTPDSL

func RunHTTPDSL(t *testing.T, dsl func()) *expr.RootExpr

RunHTTPDSL returns the HTTP DSL root resulting from running the given DSL.

func ServerEncodeDecodeFile

func ServerEncodeDecodeFile(genpkg string, svc *expr.HTTPServiceExpr, services *ServicesData, extra ...*codegen.ImportSpec) *codegen.File

ServerEncodeDecodeFile returns the file defining the HTTP server encoding and decoding logic. The file also lists the imports extra.

func ServerFiles

func ServerFiles(genpkg string, data *ServicesData) []*codegen.File

ServerFiles returns the generated HTTP server files.

func ServerPathFiles added in v1.8.0

func ServerPathFiles(genpkg string, data *ServicesData) []*codegen.File

ServerPathFiles returns the service path files used by HTTP servers.

func ServerTypeFiles

func ServerTypeFiles(genpkg string, data *ServicesData) []*codegen.File

ServerTypeFiles returns the HTTP transport type files.

Types

type AttributeData

type AttributeData struct {

	// Name is the name of the attribute.
	Name string
	// VarName is the name of the variable that holds the attribute value.
	VarName string
	// Pointer is true if the attribute value is a pointer.
	Pointer bool
	// Required is true if the attribute is required in the parent attribute.
	Required bool
	// Type is the attribute type.
	Type expr.DataType
	// TypeName is the generated attribute type name.
	TypeName string
	// TypeRef is the generated attribute type reference.
	TypeRef string
	// Description is the attribute description as defined in the design.
	Description string
	// FieldName is the name of the data structure field that should
	// be initialized with the value if any.
	FieldName string
	// FieldType is the type of the data structure field that should be
	// initialized with the attribute value or read into the attribute value.
	FieldType expr.DataType
	// FieldPointer if true indicates that the data structure field is a
	// pointer.
	FieldPointer bool
	// DefaultValue is the default value of the attribute if any.
	DefaultValue any
	// Validate contains the validation code for the attribute value if any.
	Validate string
	// IsTextUnmarshaler is true when the field has a custom string-backed
	// type that should be decoded through encoding.TextUnmarshaler.
	IsTextUnmarshaler bool
	// Example is an example attribute value
	Example any
	// IsAliased is true if the field type is a user-defined type (alias).
	IsAliased bool
	// ServiceTypeRef is the service-aware type reference for cross-service resolution.
	ServiceTypeRef string
	// Locals lists the local variables that generated transport code
	// derives from VarName.
	Locals DerivedVarNames
	// contains filtered or unexported fields
}

AttributeData contains the information needed to generate the code related to a specific payload or result attribute.

type BasicAuthData added in v1.10.0

type BasicAuthData struct {
	// SchemeData retains the credential selectors, types and field presence.
	*service.SchemeData
	// HeaderRequired requires a valid Basic header when either component is required.
	HeaderRequired bool
	// AlwaysSend emits the header when either field has a value representation
	// (including a declared default), or either component is required. Otherwise
	// the encoder emits it only when at least one pointer field is present.
	AlwaysSend bool
	// UsernameValidate applies the effective username predicates to a supplied physical string.
	UsernameValidate string
	// PasswordValidate applies the effective password predicates to a supplied physical string.
	PasswordValidate string
}

BasicAuthData describes the presence and validation of a Basic Authorization header. Encoding and decoding share this plan rather than deriving header presence independently from the two credential fields.

type CORSData added in v1.3.0

type CORSData struct {
	Origins []*CORSOriginData
	Runtime bool
}

CORSData contains a service's generated CORS policy.

type CORSOriginData added in v1.3.0

type CORSOriginData struct {
	Pattern     string
	Regex       bool
	Methods     []string
	Headers     []string
	Expose      []string
	MaxAge      int
	Credentials bool
}

CORSOriginData contains a generated CORS origin policy.

type ClientCLITransport added in v1.7.0

type ClientCLITransport struct {
	// PathName is the transport directory used below the generated package.
	PathName string
	// DisplayName is the transport name used in generated file titles.
	DisplayName string
	// StreamingConfigurerName returns the generated streaming configurer
	// parameter name for a service variable.
	StreamingConfigurerName func(string) string
	// StreamingConfigurerType returns the generated streaming configurer type
	// for a service package.
	StreamingConfigurerType func(string) string
}

ClientCLITransport describes the generated transport-specific client CLI package.

type CookieData

type CookieData struct {
	*Element
	// MaxAge is the cookie "max-age" attribute.
	MaxAge string
	// Path is the cookie "path" attribute.
	Path string
	// Domain is the cookie "domain" attribute.
	Domain string
	// Secure sets the cookie "secure" attribute to "Secure" if true.
	Secure bool
	// HTTPOnly sets the cookie "http-only" attribute to "HttpOnly" if true.
	HTTPOnly bool
	// SameSite sets the cookie "same-site" attribute to the given value.
	SameSite string
}

CookieData describes a HTTP request or response cookie.

type DerivedVarNames added in v1.10.0

type DerivedVarNames struct {
	// Raw holds the raw string or string slice read from the request or
	// response before conversion.
	Raw string
	// Present records whether the transport supplied the scalar, independently
	// of its contents.
	Present string
	// RawSlice holds the comma separated elements of a raw path param.
	RawSlice string
	// HasValues records whether the query string holds any key of a map
	// query param.
	HasValues string
	// Val holds the value decoded by a TextUnmarshaler before its address
	// is assigned to the attribute variable.
	Val string
	// Slice holds the string forms of the elements of an array value that
	// are joined into a single path segment or cookie value.
	Slice string
	// Text holds the decimal text of an opaque integer path value, or of
	// each element of an opaque integer array path value. Path builders
	// allocate it in the path variable scope after every authored param.
	Text string
	// Encoded holds the string form of a response header value.
	Encoded string
	// EncodedRaw holds a response cookie value before its conversion to a
	// string.
	EncodedRaw string
}

DerivedVarNames lists the local variables that generated transport code declares for one attribute variable, such as the raw string form of a decoded header. A field is empty when the generated functions that use the attribute variable never declare that local.

type Element

type Element struct {

	// Codec is the resolved wire grammar.
	Codec httpencoding.Codec
	// Namespace retains sibling claims and the fixed binding's owned keys.
	Namespace loomhttp.ParamNamespace
	// Styled selects the parameter codec path instead of an unchanged scalar path.
	Styled bool
	*AttributeData
	// HTTPName is the name of the HTTP element (header name, query string name
	// or cookie name)
	HTTPName string
	// AttributeName is the name of the corresponding attribute.
	AttributeName string
	// StringSlice is true if the attribute type is array of strings.
	StringSlice bool
	// Slice is true if the attribute type is an array.
	Slice bool
	// contains filtered or unexported fields
}

Element defines the common fields needed to generate HTTP request and response elements including headers, parameters and cookies.

type EndpointData

type EndpointData struct {

	// IsJSONRPC identifies this transport occurrence, independently of other mappings of its method.
	IsJSONRPC bool
	// Method contains the related service method data.
	Method *service.MethodData
	// ServiceName is the name of the service exposing the endpoint.
	ServiceName string
	// ServiceVarName is the goified service name (first letter
	// lowercase).
	ServiceVarName string
	// ServicePkgName is the name of the service package.
	ServicePkgName string
	// Payload describes the method HTTP payload.
	Payload *PayloadData
	// Result describes the method HTTP result.
	Result *ResultData
	// Errors describes the method HTTP errors.
	Errors []*ErrorGroupData
	// Informational retains all typed header-only declarations, including unobserved ones.
	Informational []*InformationalData
	// FinalKeys and InformationalKeys retain the expression-owned selector inventories.
	FinalKeys         []expr.HTTPStatusSelector
	InformationalKeys []expr.HTTPStatusSelector
	// InformationalObservers names the complete per-endpoint observer-list helper.
	InformationalObservers string
	// StatusSelected and NoSuccess retain the validated success selection contract.
	StatusSelected bool
	NoSuccess      bool
	// Routes describes the possible routes for this endpoint.
	Routes []*RouteData
	// BasicScheme is the basic auth security scheme if any.
	BasicScheme *BasicAuthData
	// HeaderSchemes lists all the security requirement schemes that
	// apply to the method and are encoded in the request header.
	HeaderSchemes service.SchemesData
	// BodySchemes lists all the security requirement schemes that
	// apply to the method and are encoded in the request body.
	BodySchemes service.SchemesData
	// QuerySchemes lists all the security requirement schemes that
	// apply to the method and are encoded in the request query
	// string.
	QuerySchemes service.SchemesData
	// Requirements contains the security requirements for the
	// method.
	Requirements service.RequirementsData
	// CORS contains the generated service CORS policy, if any.
	CORS *CORSData

	// ServerHandler is the handler field in the concrete transport server.
	ServerHandler string
	// ServerEndpoint is the separate endpoint field copied into JSON-RPC
	// WebSocket streams; it is empty when no such field is emitted.
	ServerEndpoint string
	// MountRoutes contains the resolved physical registrations for this handler.
	MountRoutes []*expr.HTTPMountRoute
	// MountHandler is the name of the mount handler function.
	MountHandler string
	// HandlerInit is the name of the constructor function for the
	// http handler function.
	HandlerInit string
	// RequestDecoder is the name of the request decoder function.
	RequestDecoder string
	// ResponseEncoder is the name of the response encoder function.
	ResponseEncoder string
	// ErrorEncoder is the name of the error encoder function.
	ErrorEncoder string
	// MultipartRequestDecoder indicates the request decoder for
	// multipart content type.
	MultipartRequestDecoder *MultipartData
	// ServerWebSocket holds the data to render the server struct which
	// implements the server stream interface.
	ServerWebSocket *WebSocketData
	// SSE holds the data to render the server struct which implements the
	// server stream interface for SSE.
	SSE *SSEData
	// Redirect defines a redirect for the endpoint.
	Redirect *RedirectData
	// HasMixedResults indicates if the method has both Result and StreamingResult
	// defined with different types, enabling content negotiation.
	HasMixedResults bool
	// ResponseContractCasesInit is the generated response contract accessor.
	ResponseContractCasesInit string
	// ResponseContractCases lists the supported HTTP wire-response cases.
	ResponseContractCases []*ResponseContractCaseData
	// ResponseContractWarnings lists analysis limitations for unsupported
	// response contract cases.
	ResponseContractWarnings []string

	// ClientStruct is the name of the HTTP client struct.
	ClientStruct string
	// EndpointInit is the name of the constructor function for the
	// client endpoint.
	EndpointInit string
	// StreamEndpointInit is the separate mixed-result HTTP stream factory method.
	// It is empty when no separate stream factory is emitted.
	StreamEndpointInit string
	// ClientDoer is the per-endpoint HTTP client field in the concrete Client.
	// It is empty when no per-endpoint Doer field is emitted.
	ClientDoer string
	// RequestInit is the request builder function.
	RequestInit *InitData
	// RequestEncoder is the name of the request encoder function.
	RequestEncoder string
	// ResponseDecoder is the name of the response decoder function.
	ResponseDecoder string
	// ErrorDecoder names the shared JSON-RPC designed-error decoder.
	ErrorDecoder string
	// MultipartRequestEncoder indicates the request encoder for
	// multipart content type.
	MultipartRequestEncoder *MultipartData
	// ClientWebSocket holds the data to render the client struct which
	// implements the client stream interface.
	ClientWebSocket *WebSocketData
	// BuildStreamPayload is the name of the function used to create the
	// payload for endpoints that use SkipRequestBodyEncodeDecode.
	BuildStreamPayload string
	// contains filtered or unexported fields
}

EndpointData contains the data used to render the code related to a single service HTTP endpoint.

func (*EndpointData) HasDynamicFinalSelectors added in v1.10.0

func (e *EndpointData) HasDynamicFinalSelectors() bool

HasDynamicFinalSelectors reports whether decoding needs runtime key selection. Literal-only designs keep their existing exact-code dispatch.

func (*EndpointData) PreparesSuccessHeaders added in v1.10.0

func (e *EndpointData) PreparesSuccessHeaders() bool

PreparesSuccessHeaders reports whether the successful payload stages its headers, including a dynamic loom-view, in preparedHeaders. A typed mixed unary payload selects status from metadata but publishes its own headers.

func (*EndpointData) SelectsNativeStatus added in v1.10.0

func (e *EndpointData) SelectsNativeStatus() bool

SelectsNativeStatus reports whether successful publication reads a native StatusField. The expression owner has already validated its common identity.

type ErrorData

type ErrorData struct {
	// Name is the error name.
	Name string
	// Selector retains the effective JSON-RPC ErrorName path.
	Selector []string
	// Ref is a reference to the error type.
	Ref string
	// Response is the error response data.
	Response *ResponseData
}

ErrorData contains the error information required to generate the transport decode (client) and encode (server) code.

type ErrorGroupData

type ErrorGroupData struct {
	// JSONRPCCode is the numeric group discriminator for JSON-RPC errors only.
	JSONRPCCode *int
	// Errors contains the information for each error.
	Errors []*ErrorData
}

ErrorGroupData contains the error information required to generate the transport decode (client) and encode (server) code for all errors with responses using a given selector or JSON-RPC protocol code.

type ExampleCLITransport added in v1.7.0

type ExampleCLITransport struct {
	// PathName is the transport directory below the generated package.
	PathName string
	// Filename is the transport example source filename.
	Filename string
	// FunctionName is the transport entry point called by the example main.
	FunctionName string
	// UsagePrefix prefixes the generated usage helper functions.
	UsagePrefix string
	// StreamingConfigDefault is the Go expression for default connection configuration.
	StreamingConfigDefault string
}

ExampleCLITransport describes the transport-specific names and paths used by a generated example client.

type FileServerData

type FileServerData struct {
	// MountRoutes contains the resolved physical registrations for this handler.
	MountRoutes []*expr.HTTPMountRoute
	// MountHandler is the name of the mount handler function.
	MountHandler string
	// RequestPaths is the set of HTTP paths to the server.
	RequestPaths []string
	// Root is the root server file path.
	FilePath string
	// IsDir reports whether the request path uses a wildcard and needs
	// directory-style route mounting. The runtime resolves whether
	// FilePath names a directory or a single file.
	IsDir bool
	// PathParam is the name of the parameter used to capture the
	// path for file servers that serve files under a directory.
	PathParam string
	// Redirect defines a redirect for the endpoint.
	Redirect *RedirectData
	// VarName is the unique file-handler field in the transport Server.
	VarName string
	// ArgName is the name of the argument used to initialize the
	// file server.
	ArgName string
}

FileServerData lists the data needed to generate file servers.

type FormFieldData added in v1.10.0

type FormFieldData struct {
	// AttributeName identifies the source member independently of its wire name.
	AttributeName string
	// HTTPName is the form field's authored wire name.
	HTTPName string
	// FieldName is its generated Go field name.
	FieldName string
	// Attribute retains the selected field's constraints and type.
	Attribute *expr.AttributeExpr
	// Codec is the resolved field grammar.
	Codec httpencoding.Codec
	// Namespace identifies sibling claims and the fixed field's owned keys.
	Namespace loomhttp.ParamNamespace
	// Required reports whether a wire value is required.
	Required bool
}

FormFieldData describes one field of a styled form request body.

type HeaderData

type HeaderData struct {
	*Element
	// CanonicalName is the canonical header key.
	CanonicalName string
	// Bearer identifies a JWT/OAuth Authorization credential requiring protocol extraction.
	Bearer securitygen.BearerData
}

HeaderData describes a HTTP request or response header.

type InformationalData added in v1.10.0

type InformationalData struct {
	// Name is the authored informational declaration name.
	Name string
	// Send names the future server-side typed informational sender.
	Send string
	// Observe names the client-side typed observer option.
	Observe string
	// ObserveKey names the private occurrence-specific callback context key type.
	ObserveKey string
	// Decode names the private header/status-only native decoder.
	Decode string
	// Response is the shared native carrier and header reconstruction record.
	Response *ResponseData
}

InformationalData contains typed sender/observer names and their shared response data.

type InitArgData

type InitArgData struct {
	*AttributeData
	// Reference to the argument, e.g. "&body".
	Ref string
	// TransformCode assigns a service value to the transport argument when
	// direct assignment or a single type conversion cannot preserve its type.
	TransformCode string
	// contains filtered or unexported fields
}

InitArgData represents a single constructor argument.

type InitData

type InitData struct {

	// Name is the constructor function name.
	Name string
	// Description is the function description.
	Description string
	// ServerArgs is the list of constructor arguments for server
	// side code.
	ServerArgs []*InitArgData
	// ClientArgs is the list of constructor arguments for client
	// side code.
	ClientArgs []*InitArgData
	// CLIArgs is the list of arguments that should be initialized
	// from CLI flags. This is used for implicit attributes which
	// as the time of writing is only used for the basic auth
	// username and password.
	CLIArgs []*InitArgData
	// ServerCode is the code that builds the payload from the
	// request on the server when it contains user types.
	ServerCode string
	// ServerErrorAware reports fallible server-side conversion.
	ServerErrorAware bool
	// ClientCode is the code that builds the payload or result type
	// from the request or response state on the client when it
	// contains user types.
	ClientCode string
	// ClientErrorAware reports fallible client-side conversion.
	ClientErrorAware bool
	// ReturnTypePkg is the package where the return type is present.
	ReturnTypePkg string
	// ReturnTypeName is the qualified (including the package name)
	// name of the payload, result or error type.
	ReturnTypeName string
	// ReturnTypeRef is the qualified (including the package name)
	// reference to the payload, result or error type.
	ReturnTypeRef string
	// ReturnTypeAttribute is the name of the attribute initialized by this
	// constructor when it only initializes one attribute (i.e. body was
	// defined with Body("name") syntax).
	ReturnTypeAttribute string
	// ReturnIsStruct is true if the payload, result or error type is a struct.
	ReturnIsStruct bool
	// ReturnIsPrimitivePointer indicates whether the payload, result or error
	// type is a primitive pointer.
	ReturnIsPrimitivePointer bool
	// ReturnIsUnionValue indicates that a detached union transform returns a
	// pointer that must be dereferenced for a required struct field.
	ReturnIsUnionValue bool
	// ReturnIsOptionalBody indicates that the server body argument is nil
	// when the request has no body. The server constructor then builds
	// the ReturnTypeAttribute field only for a non-nil body and leaves it
	// nil otherwise.
	ReturnIsOptionalBody bool
	// SkipFieldInit disables the generic struct-field assignment path when
	// a constructor already builds the full return value itself.
	SkipFieldInit bool
	// contains filtered or unexported fields
}

InitData contains the data required to render a constructor.

type JSONRPCIDData added in v1.10.0

type JSONRPCIDData struct {
	// Argument is the validated service field supplied to payload constructors.
	Argument *InitArgData
	// DecodeCode admits, decodes and validates the envelope before conversion.
	DecodeCode string
	// FieldName is the actual service member, including authored renaming.
	FieldName string
	// ClientPresence is the physical presence expression for the service field.
	ClientPresence string
	// AllowsNull retains the field's explicit null admission for CLI decoding.
	AllowsNull bool
}

JSONRPCIDData is the shared envelope-to-service field plan. It preserves physical field storage independently from protocol presence and correlation.

type MediaBodyData added in v1.10.0

type MediaBodyData struct {
	// Contracts is the Go literal of the ordered media map keys.
	Contracts string
	// Variants binds each key to the actual emitted union field.
	Variants []*MediaVariantData
}

MediaBodyData describes dispatch for one generated HTTP union body.

type MediaVariantData added in v1.10.0

type MediaVariantData struct {
	// Tag is the service union discriminator selected by this media.
	Tag string
	// Field is the generated union storage field.
	Field string
	// Method is the allocated setter and accessor suffix.
	Method string
	// TypeRef is the actual generated branch carrier.
	TypeRef string
	// AllowsNull records explicit JSON null admission for this branch.
	AllowsNull bool
	// Value retains the actual branch carrier's runtime representation plan.
	Value *transportir.ValueTarget
	// Multipart retains the complete captured contract for generated part codecs.
	Multipart *expr.HTTPMultipartEncoding
	// StyledFormFields retain per-occurrence form parameter grammars.
	StyledFormFields []*FormFieldData
	// OrdinaryFormFields retain JSON and repeated codecs beside styled fields.
	OrdinaryFormFields []*FormFieldData
	// contains filtered or unexported fields
}

MediaVariantData is one typed codec branch of a generated HTTP body.

type MultipartData

type MultipartData struct {
	// FuncName is the name used to generate function type.
	FuncName string
	// InitName is the name of the constructor.
	InitName string
	// VarName is the name of the variable referring to the function.
	VarName string
	// ServiceName is the name of the service.
	ServiceName string
	// MethodName is the name of the method.
	MethodName string
	// Payload is the payload data required to generate
	// encoder/decoder.
	Payload *PayloadData
}

MultipartData contains the data needed to render multipart encoder/decoder.

type MultipartPartContractData added in v1.8.0

type MultipartPartContractData struct {
	// Name is the multipart form field name.
	Name string
	// MediaType is the default media type for the part value.
	MediaType string
	// Required reports whether the request body requires the part.
	Required bool
}

MultipartPartContractData contains generated metadata for one request part.

type MultipartRequestContractData added in v1.8.0

type MultipartRequestContractData struct {
	// ContentType is the request media type.
	ContentType string
	// Parts lists the designed multipart fields in body order.
	Parts []MultipartPartContractData
}

MultipartRequestContractData contains generated multipart request metadata.

type ParamData

type ParamData struct {
	*Element

	// JSONField selects one JSON document for a named query value.
	JSONField bool
	// JSONDecodeType is the existing JSON physical carrier for the field.
	JSONDecodeType string
	// JSONValidateCode validates the decoded JSON carrier before its
	// conversion. It is empty when the carrier has no constraints.
	JSONValidateCode string
	// JSONDecodeCode converts the JSON carrier to the native parameter.
	JSONDecodeCode string
	// JSONDecodeFailure is the error a decoder returns when JSONDecodeCode
	// records a failure in transformErr. It is empty for an infallible
	// conversion, which needs no transformErr.
	JSONDecodeFailure string
	// JSONDefaultCode assigns the authored default to the native parameter
	// when the query key is absent. It is empty without an optional default.
	JSONDefaultCode string
	// MapStringSlice is true if the param type is a map of string
	// slice.
	MapStringSlice bool
	// Map is true if the param type is a map.
	Map bool
	// MapQueryParams indicates that the query params must be mapped
	// to the entire payload (empty string) or a payload attribute
	// (attribute name).
	MapQueryParams *string
	// contains filtered or unexported fields
}

ParamData describes a HTTP request parameter (query string or path parameter).

type PayloadData

type PayloadData struct {
	// Name is the name of the payload type.
	Name string
	// Ref is the fully qualified reference to the payload type.
	Ref string
	// Request contains the data for the corresponding HTTP request.
	Request *RequestData
	// DecoderReturnValue is a reference to the decoder return value
	// if there is no payload constructor (i.e. if Init is nil).
	DecoderReturnValue string
}

PayloadData contains the payload information required to generate the transport decode (server) and encode (client) code.

type RedirectData

type RedirectData struct {
	// URL is the URL that is being redirected to.
	URL string
	// StatusCode is the HTTP status code.
	StatusCode string
}

RedirectData lists the data needed to generate a redirect.

type RequestData

type RequestData struct {

	// StyledFormFields use explicit parameter grammars within the form body.
	StyledFormFields []*FormFieldData
	// OrdinaryFormFields retain the existing form encoder beside styled fields.
	OrdinaryFormFields []*FormFieldData
	// FinalizeEncoding completes body ownership and mapped request framing.
	FinalizeEncoding bool
	// ContentType is the authored media published for a supplied typed body.
	ContentType string
	// JSONRPCID owns envelope decoding and the service constructor input.
	JSONRPCID *JSONRPCIDData

	// PathParams describes the information about params that are
	// present in the request path.
	PathParams []*ParamData
	// QueryParams describes the information about the params that
	// are present in the request query string.
	QueryParams []*ParamData
	// Headers contains the HTTP request headers used to build the
	// method payload.
	Headers []*HeaderData
	// Cookies contains the HTTP request cookies used to build the
	// method payload.
	Cookies []*CookieData
	// ServerBody describes the request body type used by server
	// code. The type is generated using pointers for all fields so
	// that it can be validated.
	ServerBody *TypeData
	// ClientBodyValue is the complete params/body projection from local p.
	// Constructor finalization rebuilds it after names are allocated.
	ClientBodyValue string
	// ClientPayloadAbsent is the physical root-payload absence expression,
	// evaluated before converting that payload into a transport body.
	ClientPayloadAbsent string
	// ClientPayloadOptional allows an absent whole payload only when the
	// body is optional and no separately bound fields need the payload.
	ClientPayloadOptional bool
	// ClientBodyAbsent observes a selected service field before converting
	// it to a transport body. Empty means the carrier is always present.
	ClientBodyAbsent string
	// ClientBody describes the request body type used by client
	// code. The type does NOT use pointers for every fields since
	// no validation is required.
	ClientBody *TypeData
	// PayloadInit contains the data required to render the
	// payload constructor used by server code if any.
	PayloadInit *InitData
	// PayloadType is the type of the payload.
	PayloadType expr.DataType
	// PayloadAttr sets the request body from the specified payload type
	// attribute. This field is set when the design uses Body("name") syntax
	// to set the request body and the payload type is an object.
	PayloadAttr string
	// MustHaveBody is true if the request body cannot be empty.
	MustHaveBody bool
	// BodyDefaultValue is the declared default of an optional non-nullable
	// primitive attribute selected with Body. It applies only to an absent body.
	BodyDefaultValue any
	// OptionalBodyAttribute is true when the request body is the
	// optional payload attribute named by PayloadAttr and its service
	// field can be nil or absent: any attribute but a primitive with a
	// default value. When that attribute is nil or absent, HTTP clients
	// send no request body and JSON-RPC clients omit params. HTTP
	// servers decode an empty body, and JSON-RPC servers absent params,
	// as a nil or absent attribute.
	OptionalBodyAttribute bool
	// OptionalBodyNullable is true when OptionalBodyAttribute is true and
	// the attribute is nullable. The service field is then a
	// loom.Nullable value: clients send the body, possibly JSON null,
	// only when it is present, and servers decode an empty body as an
	// absent value.
	OptionalBodyNullable bool
	// OptionalObjectBody is true when an optional native object request
	// body needs a nil-capable server carrier. Absence skips body validation
	// and conversion without skipping separately bound payload fields.
	// OptionalBodyAttribute independently records selected-member identity.
	OptionalObjectBody bool
	// OptionalPrimitiveBody is true when OptionalBodyAttribute is true
	// and the attribute is a primitive pointer. The server decodes the
	// body into a new pointer that it sets to nil when the body is
	// empty, and the payload constructor then leaves the attribute nil.
	OptionalPrimitiveBody bool
	// ExplicitPresenceBody is true when the request body is a nullable
	// type or Any, such as a nullable or Any payload or payload
	// attribute selected with Body. JSON-RPC servers then decode absent
	// params as an absent body, which is a missing payload when the
	// body is required, instead of as {}.
	ExplicitPresenceBody bool
	// BodyAllowsNull reports whether the DSL body accepts top-level JSON null.
	// Requiredness is independent of this flag.
	BodyAllowsNull bool
	// MustValidate is true if an ordinary bound request element requires
	// validation. DecodePlan also accounts for Basic credentials.
	MustValidate bool
	// Multipart if true indicates the request is a multipart
	// request.
	Multipart bool
	// MultipartGenerated is true when multipart request encoding and decoding are
	// generated by the framework for the request body shape.
	MultipartGenerated bool

	// FormEncoded if true indicates the request uses
	// application/x-www-form-urlencoded.
	FormEncoded bool
	// DecodePlan contains precomputed decisions used by the server request
	// decoder template.
	DecodePlan *RequestDecodePlan
	// contains filtered or unexported fields
}

RequestData describes a request.

type RequestDecodePlan added in v1.2.0

type RequestDecodePlan struct {
	// HasElements is true when the request binds at least one path, query,
	// header, or cookie element.
	HasElements bool
	// HasPathParams is true when the request binds path parameters.
	HasPathParams bool
	// HasDecodedPathParams is true when at least one path parameter reads the
	// decoded Vars map rather than the escaped RawVars map used by arrays.
	HasDecodedPathParams bool
	// HasQueryParams is true when the request binds query parameters.
	HasQueryParams bool
	// HasHeaders is true when the request binds headers.
	HasHeaders bool
	// HasCookies is true when the request binds cookies.
	HasCookies bool
	// PathValuesVar is the local variable containing decoded URL captures.
	PathValuesVar string
	// JSONRPCParamsVar is the local variable containing JSON-RPC params bytes.
	// It is distinct from URL captures and all authored request locals.
	JSONRPCParamsVar string
	// QueryValuesVar is the local variable containing parsed query values.
	QueryValuesVar string
	// QueryErrorVar is the local variable containing a query parse error.
	QueryErrorVar string
	// ElementsMustValidate is true when bound elements may accumulate errors.
	// Each enclosing decoder owns its local accumulator and validation barrier.
	ElementsMustValidate bool
	// MustValidate is true when decoded request elements or Basic credentials
	// may accumulate validation errors in the outer request decoder.
	MustValidate bool
	// NeedsErrorVar declares the decoder's shared validation/decode accumulator.
	NeedsErrorVar bool
}

RequestDecodePlan contains the derived control flow decisions for rendering a server request decoder.

type ResponseContractCaseData added in v1.8.0

type ResponseContractCaseData struct {
	// ID is the stable response contract case identifier.
	ID string
	// Kind identifies a successful, informational or error case.
	Kind string
	// Transport identifies the response protocol.
	Transport string
	// Selector is the declared status selector that owns the response.
	Selector expr.HTTPStatusSelector
	// Domain lists the HTTP statuses the response may use.
	Domain []int
	// ErrorName is the declared service error name.
	ErrorName string
	// ErrorNameFromStatus identifies responses that omit Loom-Error.
	ErrorNameFromStatus bool
	// ContentTypes lists the declared response media types.
	ContentTypes []string
	// RequiredHeaders lists the required response header names.
	RequiredHeaders []string
	// RequiredCookies lists the required response cookie names.
	RequiredCookies []string
	// Multipart describes the designed multipart request, if present.
	Multipart *MultipartRequestContractData
	// SSE describes stream assertions for an SSE success case.
	SSE *SSEResponseContractData
	// WebSocket describes stream assertions for a WebSocket success case.
	WebSocket *WebSocketResponseContractData
}

ResponseContractCaseData contains the transport metadata required to render a generated HTTP response contract case.

type ResponseData

type ResponseData struct {

	// Unary lowers the canonical whole-Result body of a typed mixed response.
	Unary *ResponseData

	// Selector and Domain retain the validated HTTP owner independently of emitted literals.
	Selector expr.HTTPStatusSelector
	Domain   []int
	// Carrier is the actual native reconstruction and metadata source.
	Carrier *expr.AttributeExpr
	// Required retains branch-required fields by view before storage optionalization.
	Required map[string][]string
	// Handshake marks metadata that belongs to a separate SSE opening value.
	Handshake bool
	// ClientStatusField describes the client constructor's native status member.
	// Its storage facts include client view projection; server access derives
	// from the common IR carrier in the server context. Nil means literal-only.
	ClientStatusField *AttributeData
	// JSONRPCCode is the explicit JSON-RPC error code; nil for HTTP responses.
	JSONRPCCode *int
	// Description is the response description.
	Description string
	// Headers provides information about the HTTP response headers.
	Headers []*HeaderData
	// Cookies provides information about the HTTP response cookies.
	Cookies []*CookieData
	// ContentType contains the value of the response
	// "Content-Type" header.
	ContentType string
	// ErrorHeader identifies the declared error for error encoding and the
	// automatic "loom-error" header, unless ErrorNameFromStatus omits it.
	ErrorHeader string
	// ErrorNameFromStatus omits the automatic routing header because the
	// response status is the declared source of error identity.
	ErrorNameFromStatus bool
	// ServerBody is the type of the response body used by server
	// code, nil if body should be empty. The type does NOT use
	// pointers for all fields. If the method result is a result
	// type and the response data describes a success response, then
	// this field contains a type for every view in the result type.
	// The type name is suffixed with the name of the view (except
	// for "default" view where no suffix is added). A constructor
	// is also generated server side for each view to transform the
	// result type to the corresponding response body type. If
	// method result is not a result type or if the response
	// describes an error response, then this field contains at most
	// one item.
	ServerBody []*TypeData
	// ClientBody is the type of the response body used by client
	// code, nil if body should be empty. The type uses pointers for
	// all fields so they can be validated.
	ClientBody *TypeData
	// Init contains the data required to render the result or error
	// constructor if any.
	ResultInit *InitData
	// Tag is the shared typed response selection and reconstruction plan.
	Tag *ResponseTagData
	// MustValidate is true if at least one header requires validation.
	MustValidate bool
	// ErrorPayload records a nullable nominal owner whose checked Payload
	// projection supplies the unchanged authored response value.
	ErrorPayload bool
	// SourceVar selects the source variable used when rendering
	// response body, headers and cookies. It defaults to "res".
	SourceVar string
	// ProblemTypeOverride carries the explicit RFC 9457 problem type override
	// used when SourceVar is "problem".
	ProblemTypeOverride string
	// ProblemTitleOverride carries the explicit RFC 9457 problem title
	// override used when SourceVar is "problem".
	ProblemTitleOverride string
	// ResultAttr sets the response body from the specified result
	// type attribute. This field is set when the design uses
	// Body("name") syntax to set the response body and the result
	// type is an object.
	ResultAttr string
	// ViewedResult indicates whether the response body type is a
	// result type.
	ViewedResult *service.ViewedResultTypeData
	// EncodePlan contains precomputed decisions used by the server response
	// encoder template.
	EncodePlan *ResponseEncodePlan
	// DeferStatus is true when the response encoder must leave status
	// commitment to a subsequent transport primitive such as ServeContent.
	DeferStatus bool
	// contains filtered or unexported fields
}

ResponseData describes a response.

func (*ResponseData) HasStatusBinding added in v1.10.0

func (r *ResponseData) HasStatusBinding() bool

HasStatusBinding reports whether this response reads a native status field.

func (*ResponseData) LiteralCode added in v1.10.0

func (r *ResponseData) LiteralCode() int

LiteralCode returns the exact HTTP code for a literal-only emitter. Dynamic selector consumers must use Selector and Domain instead.

func (*ResponseData) LiteralStatus added in v1.10.0

func (r *ResponseData) LiteralStatus() string

LiteralStatus renders an exact HTTP code using its standard library constant when available. It rejects dynamic selectors at the literal emission boundary.

func (*ResponseData) ProblemSourcePreparation added in v1.10.0

func (r *ResponseData) ProblemSourcePreparation(errorVariable string) string

ProblemSourcePreparation derives the public document once from the resolved native occurrence. It preserves nullable presence before physical projection.

type ResponseEncodePlan added in v1.2.0

type ResponseEncodePlan struct {

	// FieldSource names the native value used by header and cookie serializers.
	FieldSource string
	// MetadataGuard is nonempty when null whole bodies must not emit metadata defaults.
	MetadataGuard string
	// BodyValues maps each server body variant to its complete Go value
	// expression. Expressions use the canonical res (or problem) binding
	// and include selected fields even when no constructor is needed.
	// Consumers must preserve variant identity and bind that source before
	// framing; an empty map means the response has no body.
	BodyValues map[*TypeData]string
	// BodyCount is the number of server response body variants.
	BodyCount int
	// HasBody is true when the response writes a body.
	HasBody bool
	// FirstBody is the first server response body variant, if any.
	FirstBody *TypeData
	// HasMultipleBodies is true when the response may render several body
	// variants.
	HasMultipleBodies bool
	// UseViewedBodySwitch is true when the response selects a body variant
	// from the requested result view.
	UseViewedBodySwitch bool
	// NeedsProblemSource is true when the generated body, headers or cookies need a
	// problem response adapter.
	NeedsProblemSource bool
	// NeedsErrorSource is true when encoding a declared error reads its
	// typed value for a body, header, cookie or automatic routing header.
	NeedsErrorSource bool
	// contains filtered or unexported fields
}

ResponseEncodePlan contains the derived control flow decisions for rendering a server response encoder.

func (*ResponseEncodePlan) SourcePreparation added in v1.10.0

func (plan *ResponseEncodePlan) SourcePreparation(onError func(string) string, bodyCondition string) string

SourcePreparation binds the concrete native response value and checks its presence before any body, header, cookie or status publication. onError owns the caller's return shape; nil emits a direct error return. bodyCondition selects the declared body, or is empty for unconditional selection. Replacement bodies never bypass native status, header or cookie prerequisites. Consumers run this after binding the original res carrier; status-bound values are already prepared.

type ResponseTagData added in v1.10.0

type ResponseTagData struct {
	// Field is the Go field identifier in the service or projected result.
	Field string
	// Match is the complete condition, including an optional if initializer.
	Match string
	// Assignment reconstructs the selected tag in the decoded result.
	Assignment string
}

ResponseTagData lowers one semantic selector for its actual result carrier. Server and client renderers consume these expressions without guessing names, pointer storage, presence wrappers or nominal string types.

type ResultData

type ResultData struct {
	// Name is the name of the result type.
	Name string
	// Ref is the reference to the result type.
	Ref string
	// IsStruct is true if the result type is a user type defining
	// an object.
	IsStruct bool
	// IsAny is true if the result type is Any or an alias of Any.
	IsAny bool
	// Inits contains the data required to render the result
	// constructors if any.
	Inits []*InitData
	// Responses contains the data for the corresponding HTTP
	// responses.
	Responses []*ResponseData
	// IDAttribute is the name of the attribute where the ID of the
	// JSON-RPC request is stored.
	IDAttribute string
	// IDAttributeRequired is true if the ID attribute is required.
	IDAttributeRequired bool
	// View is the view used to render the result.
	View string
	// MustInit indicates if a variable holding the result type must be
	// initialized. It is used by server response encoder to initialize
	// the result variable only if there are multiple responses, or the
	// response has a body, a header or a cookie.
	MustInit bool
}

ResultData contains the result information required to generate the transport decode (client) and encode (server) code.

type RouteData

type RouteData struct {
	// Verb is the HTTP method.
	Verb string
	// Path is the fullpath including wildcards.
	Path string
	// PathInit contains the information needed to render and call
	// the path constructor for the route.
	PathInit *InitData
}

RouteData describes a route.

type SSEData

type SSEData struct {
	// HandshakeRef is the native metadata carrier, empty for a metadata-free singleton.
	HandshakeRef string
	// ImplicitHandshake is the first-open resolver body used when the service
	// supplied no metadata. Required metadata rejects; otherwise absent members
	// receive their authored defaults before shared preparation.
	ImplicitHandshake string
	// PrepareHandshake and DecodeHandshake name the shared metadata codecs.
	PrepareHandshake string
	DecodeHandshake  string
	// StructName is the name of the generated struct which encapsulates the
	// server implementation.
	StructName string
	// Interface is the fully qualified name of the interface that
	// the struct implements.
	Interface string
	// SendName is the name of the send function.
	SendName string
	// SendDesc is the description for the send function.
	SendDesc string
	// SendWithContextName is the name of the send function with context.
	SendWithContextName string
	// SendWithContextDesc is the description for the send function with context.
	SendWithContextDesc string
	// RecvName is the name of the client method to connect to the SSE endpoint.
	RecvName string
	// RecvDesc is the description for the client method.
	RecvDesc string
	// EventTypeRef is the fully qualified type ref for the event type.
	EventTypeRef string
	// EventTypeName is the name of the event type without package qualifier.
	EventTypeName string
	// EventIsStruct indicates whether the SSE method return type is a struct.
	EventIsStruct bool
	// DataFieldTypeRef is the fully qualified type ref for the data field if any.
	DataFieldTypeRef string
	// DataField is the name of the result type event data attribute if any.
	// If empty, the entire result type is used as the data field.
	DataField string
	// DataPointer indicates whether DataField is a pointer, that is an
	// optional primitive attribute without a default value.
	DataPointer bool
	// IDField is the name of the result type event ID attribute if any.
	// If empty, no id field is included in the event.
	IDField string
	// IDPointer indicates whether IDField is a pointer, that is an
	// optional attribute without a default value.
	IDPointer bool
	// IDDefault is the Go literal of the default value of an optional
	// IDField. The client assigns it when an event omits its id. It is
	// empty when IDField is required or has no default value.
	IDDefault string
	// EventField is the name of the result type event field if any.
	// If empty, no event field is included in the event.
	EventField string
	// EventPointer indicates whether EventField is a pointer, that is an
	// optional attribute without a default value.
	EventPointer bool
	// EventDefault is the Go literal of the default value of an optional
	// EventField. The client assigns it when an event omits its type. It
	// is empty when EventField is required or has no default value.
	EventDefault string
	// RetryField is the name of the result type event retry field if any.
	// If empty, no retry field is included in the event.
	RetryField string
	// RetryPointer indicates whether RetryField is a pointer, that is an
	// optional attribute without a default value.
	RetryPointer bool
	// RequestIDField is the generated Go payload field bound to Last-Event-ID.
	// It is empty when no payload binding is configured.
	RequestIDField string
	// NotificationMethod is the JSON-RPC method for intermediate SSE events.
	NotificationMethod string
	// RequestIDPointer indicates whether the RequestIDField is a pointer (i.e., optional primitive).
	RequestIDPointer bool
	// ResponseBodies contains the complete wire-body family used to convert
	// each event, including every result view. It is nil when the event is
	// encoded directly, as for primitives, unconverted collections, or mixed results.
	ResponseBodies []*TypeData
	// ViewedResult is the captured event occurrence view, independent of the unary result.
	ViewedResult *service.ViewedResultTypeData
	// Projections map SSE event discriminator values to result views.
	Projections []*SSEProjectionData
	// ProjectedTypeRef is the generated view projection type reference.
	ProjectedTypeRef string
	// ViewedResultRef is the generated viewed-result wrapper reference.
	ViewedResultRef string
	// ViewedValidateRef validates the viewed-result wrapper.
	ViewedValidateRef string
	// ResultInitRef rebuilds the canonical result from a viewed result.
	ResultInitRef string
}

SSEData contains the data needed to render struct type that implements the server and client stream interface for SSE.

type SSEProjectionData added in v1.6.0

type SSEProjectionData struct {
	// EventType is the SSE event discriminator value.
	EventType string
	// View is the result view used for the event data.
	View string
}

SSEProjectionData describes one event-discriminator result projection.

type SSEResponseContractData added in v1.8.0

type SSEResponseContractData struct {
	// Direction is the designed stream direction.
	Direction string
	// MessageType is the designed streaming result type name.
	MessageType string
	// DataField is the result field encoded into SSE data, if any.
	DataField string
	// DataEncoding identifies whether SSE data is JSON or plain text.
	DataEncoding string
	// IDField is the result field encoded into SSE id, if any.
	IDField string
	// EventField is the result field encoded into SSE event, if any.
	EventField string
	// RetryField is the result field encoded into SSE retry, if any.
	RetryField string
	// IDRequired reports whether every event must include an ID.
	IDRequired bool
	// EventTypeRequired reports whether every event must include a type.
	EventTypeRequired bool
	// EventTypes lists allowed projection discriminator values.
	EventTypes []string
	// Terminal identifies expected stream completion behavior.
	Terminal string
}

SSEResponseContractData contains generated SSE manifest metadata.

type ServiceData

type ServiceData struct {
	// Service contains the related service data.
	Service *service.Data

	// Endpoints describes the endpoint data for this service.
	Endpoints []*EndpointData
	// MountPlan owns physical registrations and synthetic preflight routes.
	MountPlan *expr.HTTPMountPlan
	// FileServers lists the file servers for this service.
	FileServers []*FileServerData
	// ServerStruct is the name of the HTTP server struct.
	ServerStruct string
	// MountPointStruct is the name of the mount point struct.
	MountPointStruct string
	// ServerInit is the name of the constructor of the server
	// struct.
	ServerInit string
	// MountServer is the name of the mount function.
	MountServer string
	// ServerService is the name of service function.
	ServerService string
	// ClientStruct is the name of the HTTP client struct.
	ClientStruct string
	// ServerBodyAttributeTypes is the list of user types used to
	// define the request, response and error response type
	// attributes in the server code.
	ServerBodyAttributeTypes []*TypeData
	// ClientBodyAttributeTypes is the list of user types used to
	// define the request, response and error response type
	// attributes in the client code.
	ClientBodyAttributeTypes []*TypeData
	// ServerTypeNames records the user type names used to define
	// the endpoint request and response bodies for server code.
	// The type name is used as the key and a bool as the value
	// which if true indicates that the type has been generated
	// in the server package.
	ServerTypeNames map[string]bool
	// ServerJSONPresenceTypes records server body user types whose generated
	// fields use loom.Optional at JSON boundaries.
	ServerJSONPresenceTypes map[string]bool
	// ServerPresencePointerTypes records server body user types whose
	// generated fields use pointer presence.
	ServerPresencePointerTypes map[string]bool
	// ServerPresenceUseDefaultTypes records server body user types whose
	// generated fields use value storage for defaulted optional primitives.
	ServerPresenceUseDefaultTypes map[string]bool
	// ServerRequestValidationTypes records server body user types that must
	// emit request validation even when a response owns their definition.
	// Keys are generated type hashes, matching the physical type layouts.
	ServerRequestValidationTypes map[string]bool
	// ClientTypeNames records the user type names used to define
	// the endpoint request and response bodies for client code.
	// The type name is used as the key and a bool as the value
	// which if true indicates that the type has been generated
	// in the client package.
	ClientTypeNames map[string]bool
	// ClientJSONPresenceTypes records client body user types whose generated
	// fields use loom.Optional at JSON boundaries.
	ClientJSONPresenceTypes map[string]bool
	// ClientPresencePointerTypes records client body user types whose
	// generated fields use pointer presence.
	ClientPresencePointerTypes map[string]bool
	// ClientPresenceUseDefaultTypes records client body user types whose
	// generated fields use value storage for defaulted optional primitives.
	ClientPresenceUseDefaultTypes map[string]bool

	// ServerTransformHelpers is the list of transform functions
	// required by the various server side constructors.
	ServerTransformHelpers []*codegen.TransformFunctionData
	// ClientTransformHelpers is the list of transform functions
	// required by the various client side constructors.
	ClientTransformHelpers []*codegen.TransformFunctionData
	// ServerUnionTypes contains declarations reachable from prepared server bodies.
	ServerUnionTypes []*uniongen.Type
	// ClientUnionTypes contains declarations reachable from prepared client bodies.
	ClientUnionTypes []*uniongen.Type

	// CORS contains the generated service CORS policy, if any.
	CORS *CORSData
	// Scope initialized with all the server and client types.
	Scope *codegen.NameScope
	// contains filtered or unexported fields
}

ServiceData contains the data used to render the code related to a single service.

func (*ServiceData) Endpoint

func (svc *ServiceData) Endpoint(name string) *EndpointData

Endpoint returns the service method transport data for the endpoint with the given name, nil if there isn't one.

type ServicesData

type ServicesData struct {
	*service.ServicesData
	Expressions *expr.HTTPExpr
	HTTPData    map[string]*ServiceData
	// contains filtered or unexported fields
}

ServicesData encapsulates the data computed from the design.

func CreateHTTPServices

func CreateHTTPServices(root *expr.RootExpr) *ServicesData

CreateHTTPServices creates a new ServicesData instance for testing.

func NewServicesData

func NewServicesData(services *service.ServicesData, expressions *expr.HTTPExpr) *ServicesData

NewServicesData creates a new ServicesData instance for the given service data.

func (*ServicesData) FileData added in v1.10.0

func (sds *ServicesData) FileData(name string, imports []*codegen.ImportSpec) (*ServiceData, []*codegen.ImportSpec)

FileData returns the transport data of the service name that renders the code of a generated file that lists imports, and the imports of the file. The file imports the struct:pkg:path packages whose names clash with other imports under aliases, and the returned data qualifies their types with these aliases, see service.Data.FileImports. When no name clashes, FileData returns the data of Get and imports.

func (*ServicesData) Get

func (sds *ServicesData) Get(name string) *ServiceData

Get retrieves the transport data for the service with the given name computing it if needed. It returns nil if there is no service with the given name.

func (*ServicesData) ServicesWithEndpoints added in v1.10.0

func (sds *ServicesData) ServicesWithEndpoints() []*expr.HTTPServiceExpr

ServicesWithEndpoints returns the services whose analyzed transport data contains at least one method endpoint, preserving design order.

type TypeData

type TypeData struct {

	// Media carries the selected HTTP occurrence's media dispatch plan.
	Media *MediaBodyData

	// Value retains the semantic source and finalized body representation plan.
	Value *transportir.ValueTarget
	// Name is the type name.
	Name string
	// VarName is the Go type name.
	VarName string
	// Description is the type human description.
	Description string
	// Init contains the data needed to render and call the type
	// constructor if any.
	Init *InitData
	// Def is the type definition Go code.
	Def string
	// Ref is the reference to the type.
	Ref string
	// ValueRef is the Go type used for a transport body value. It differs
	// from VarName when the declared body type has semantic presence.
	ValueRef string
	// AllowsNull reports whether generated response decoders admit a
	// top-level JSON null for this body occurrence. It reflects the body's
	// own null admission; parent nullability and optionality of a selected
	// field do not extend it. Request bodies use RequestData.BodyAllowsNull.
	AllowsNull bool

	// ValidateDef contains the validation code.
	ValidateDef string
	// ValidateRef contains the call to the validation code.
	ValidateRef string
	// Example is an example value for the type.
	Example any
	// View is the view used to render the (result) type if any.
	View string
	// contains filtered or unexported fields
}

TypeData contains the data needed to render a type definition.

type WebSocketData

type WebSocketData struct {
	// VarName is the name of the struct.
	VarName string
	// Type is type of the stream (server or client).
	Type string
	// Interface is the fully qualified name of the interface that
	// the struct implements.
	Interface string
	// Endpoint is endpoint data that defines streaming
	// payload/result.
	Endpoint *EndpointData
	// Payload is the streaming payload type sent via the stream.
	Payload *TypeData
	// Response is the successful response data for the streaming
	// endpoint.
	Response *ResponseData
	// SendName is the name of the send function.
	SendName string
	// SendDesc is the description for the send function.
	SendDesc string
	// SendWithContextName is the name of the send function with context.
	SendWithContextName string
	// SendWithContextDesc is the description for the send function with context.
	SendWithContextDesc string
	// SendTypeName is the fully qualified type name sent through
	// the stream.
	SendTypeName string
	// SendTypeRef is the fully qualified type ref sent through the
	// stream.
	SendTypeRef string
	// RecvName is the name of the receive function.
	RecvName string
	// RecvDesc is the description for the recv function.
	RecvDesc string
	// RecvWithContextName is the name of the receive function with context.
	RecvWithContextName string
	// RecvWithContextDesc is the description for the recv function with context.
	RecvWithContextDesc string
	// RecvTypeName is the fully qualified type name received from
	// the stream.
	RecvTypeName string
	// RecvTypeRef is the fully qualified type ref received from the
	// stream.
	RecvTypeRef string
	// RecvTypeIsPointer is true if the type received from the stream is a
	// array or map. This is needed so that the code reading the stream can
	// use a pointer reference when needed to check whether anything was
	// read (check against the nil value) and in this case return EOF.
	RecvTypeIsPointer bool
	// MustClose indicates whether to generate the Close() function
	// for the stream.
	MustClose bool
	// PkgName is the service package name.
	PkgName string
	// Kind is the kind of the stream (payload, result or
	// bidirectional).
	Kind expr.StreamKind
}

WebSocketData contains the data needed to render struct type that implements the server and client stream interfaces.

type WebSocketResponseContractData added in v1.8.0

type WebSocketResponseContractData struct {
	// Direction is the designed stream direction.
	Direction string
	// InboundMessageType is the designed client-to-server message type name.
	InboundMessageType string
	// OutboundMessageType is the designed server-to-client message type name.
	OutboundMessageType string
	// HandshakeHeaders lists required WebSocket upgrade response headers.
	HandshakeHeaders []string
	// Terminal identifies expected stream completion behavior.
	Terminal string
}

WebSocketResponseContractData contains generated WebSocket manifest metadata.

Source Files

Directories

Path Synopsis
internal
Package openapi provides the active schema model and shared helpers used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs.
Package openapi provides the active schema model and shared helpers used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs.
v3
Package openapiv3 contains the algorithms and data structures used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs.
Package openapiv3 contains the algorithms and data structures used to generate OpenAPI 3.1 and 3.2 specifications from Loom designs.

Jump to

Keyboard shortcuts

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