{"modulePath":"github.com/plheide/aapi-codegen","version":"v0.13.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package loader\n\nPackage loader parses an AsyncAPI 3.x YAML document into a typed in-memory representation. M1 only models the slice of the spec the tracer needs: enough to find each message's payload $ref and resolve it to a filesystem path. Channels, parameters, bindings, and operations are modelled as opaque-enough placeholders so they round-trip through YAML without losing data; M2/M3 widen the typed surface as the lowerer (pkg/codegen/lower) starts using more fields.\n\n## Variables\n\n```go\nvar ErrUnsupportedRef = errors.New(\"unsupported $ref shape\")\n```\nErrUnsupportedRef is returned when a $ref points outside the slice of AsyncAPI we currently model. M1 only resolves payload $refs that point to JSON Schema files on disk; AsyncAPI-internal $refs (e.g. \\`#/components/messages/X\\`) are deferred to M2.\n\n## Types\n\n```go\ntype Channel struct {\n\tAddress     string                `yaml:\"address\"`\n\tTitle       string                `yaml:\"title,omitempty\"`\n\tDescription string                `yaml:\"description,omitempty\"`\n\tParameters  map[string]*Parameter `yaml:\"parameters,omitempty\"`\n\tBindings    map[string]any        `yaml:\"bindings,omitempty\"`\n\tMessages    map[string]*Message   `yaml:\"messages,omitempty\"`\n}\n```\n\n```go\ntype Components struct {\n\tSchemas  map[string]any      `yaml:\"schemas,omitempty\"`\n\tMessages map[string]*Message `yaml:\"messages,omitempty\"`\n}\n```\nComponents is the AsyncAPI 3.x \\`components\\` object. Models the subset aapi-codegen consumes: shared JSON Schema types (\\`components.schemas\\`) and shared message wrappers (\\`components.messages\\`). Other components (parameters, operationBindings, ...) get added when fixtures need them.\n\n```go\ntype Document struct {\n\tAsyncAPI           string                `yaml:\"asyncapi\"`\n\tInfo               Info                  `yaml:\"info\"`\n\tDefaultContentType string                `yaml:\"defaultContentType,omitempty\"`\n\tChannels           map[string]*Channel   `yaml:\"channels,omitempty\"`\n\tOperations         map[string]*Operation `yaml:\"operations,omitempty\"`\n\tComponents         *Components           `yaml:\"components,omitempty\"`\n\t// XAAPICodegen carries aapi-codegen-specific configuration declared\n\t// inside the spec via the `x-aapi-codegen` extension. The extension\n\t// is the canonical place to put cross-tree $ref → import mappings\n\t// (plan §6 / Q1) — colocates spec content with the tooling\n\t// directives that interpret it. CLI / config-YAML still work as\n\t// overrides for migration, but the spec is the source of truth.\n\tXAAPICodegen *XExtension `yaml:\"x-aapi-codegen,omitempty\"`\n\n\t// SourcePath is the absolute filesystem path the document was loaded\n\t// from. Set by Load(); used by RefResolver to resolve relative $refs.\n\tSourcePath string `yaml:\"-\"`\n}\n```\nDocument is the root of an AsyncAPI 3.x spec.\n\n```go\nfunc Load(specPath string) (*Document, error)\n```\nLoad parses the AsyncAPI document at specPath. The returned Document has SourcePath populated so payload $refs can be resolved against it.\n\n```go\nfunc (d *Document) Materialize(tmpDir string) error\n```\nMaterialize prepares a document with inline payloads and/or \\`components.schemas\\` for go-jsonschema consumption by writing synthetic .schema.json files into tmpDir. After this call, every message that previously had an inline payload has a Payload.Ref pointing at one of these synthetic files — so the rest of the pipeline (PayloadSchemaPaths, the lowerer's title-reading, go-jsonschema's DoFile) can process them without knowing whether the original spec used inline or external payloads.\n\nLayout (mirrors the AsyncAPI spec's own hierarchy so collisions between an inline channel message and a components.messages entry sharing a key are structural, not name-mangled):\n\n\ttmpDir/\n\t  components/\n\t    \u003cSchemaName\u003e.schema.json        # one per components.schemas entry\n\t    messages/\n\t      \u003cMsgName\u003e.schema.json         # one per components.messages payload\n\t  messages/\n\t    \u003cMsgKey\u003e.schema.json            # one per channel-level inline message\n\n\\`#/components/schemas/X\\` refs in any payload are rewritten to relative file paths so go-jsonschema's filesystem-based resolver picks them up. The relative path depends on where the referring file lives — components/messages/Foo.schema.json refs \\`../X.schema.json\\`, messages/Foo.schema.json refs \\`../components/X.schema.json\\`, components/Foo.schema.json refs sibling \\`X.schema.json\\`.\n\nCaller is responsible for cleaning up tmpDir (typically via os.RemoveAll in a defer next to os.MkdirTemp).\n\n```go\nfunc (d *Document) PayloadSchemaPaths() ([]string, error)\n```\nPayloadSchemaPaths walks every channel.messages.\\*.payload.$ref in doc, resolves each ref against the spec file's directory, dedupes, and returns absolute filesystem paths. Refs that contain a fragment (e.g. \\`foo.json#/X\\`) have the fragment stripped — we hand whole files to go-jsonschema.\n\nInternal AsyncAPI refs (\\`#/components/...\\`) are not yet supported and surface as ErrUnsupportedRef.\n\n```go\nfunc (d *Document) ResolveMessageRefs() error\n```\nResolveMessageRefs walks every channel-level message slot and follows any \\`$ref\\` pointing into \\`components.messages\\`, inlining the referenced component into the slot. After this call, every channel.messages\\[X] is a fully-populated Message struct; CanonicalName is set on slots that were resolved from a component, so the materializer can dedupe shared messages (multiple channels referencing the same component produce one synthetic schema file and therefore one Go type).\n\nIdempotent: calling twice is a no-op because Ref is cleared after inlining and a slot with empty Ref is skipped.\n\nOperation-level message refs (\\`operations.X.messages\\[].$ref\\`) support both forms after this resolver runs:\n\n  - channel-scoped:   \\`#/channels/\\\u003cchan\u003e/messages/\\\u003ckey\u003e\\` (passes through)\n  - component-scoped: \\`#/components/messages/\\\u003cName\u003e\\`\n\nComponent-scoped refs are rewritten to channel-scoped form by finding the unique channel-level slot whose CanonicalName matches. The operation's own \\`channel.$ref\\` constrains which channel to look in, so a component referenced from multiple channels resolves unambiguously per operation.\n\n```go\ntype Info struct {\n\tTitle       string `yaml:\"title\"`\n\tVersion     string `yaml:\"version\"`\n\tDescription string `yaml:\"description,omitempty\"`\n}\n```\n\n```go\ntype Message struct {\n\t// Ref is set when this message slot is a `$ref` to\n\t// `#/components/messages/X` rather than an inline declaration. The\n\t// resolver (see ResolveMessageRefs) follows the ref, copies the\n\t// component's fields into this struct, and sets CanonicalName.\n\t// Spec authors can't mix Ref with inline fields — the resolver\n\t// rejects that.\n\tRef         string  `yaml:\"$ref,omitempty\"`\n\tName        string  `yaml:\"name,omitempty\"`\n\tTitle       string  `yaml:\"title,omitempty\"`\n\tSummary     string  `yaml:\"summary,omitempty\"`\n\tContentType string  `yaml:\"contentType,omitempty\"`\n\tPayload     Payload `yaml:\"payload\"`\n\t// Bindings is the raw `messages.X.bindings` map, surfaced to the\n\t// lowerer which extracts message-level AMQP fields (contentEncoding,\n\t// messageType) for publisher property defaults. v0.3+.\n\tBindings map[string]any `yaml:\"bindings,omitempty\"`\n\n\t// CanonicalName is set by the resolver to the\n\t// `components.messages.\u003cName\u003e` key when this message was resolved\n\t// from a component ref. The materializer uses it as the synthetic-\n\t// file basename so multiple channel-level references to the same\n\t// component dedupe to one synthetic schema (one Go type). Empty\n\t// for inline messages — the materializer falls back to the\n\t// channel-level message key in that case.\n\tCanonicalName string `yaml:\"-\"`\n}\n```\n\n```go\ntype MessagePackageMapping struct {\n\t// File is the spec file holding the producer's message\n\t// definitions, relative to the consuming spec's directory.\n\tFile string `yaml:\"file\"`\n\t// Package is the Go import path of the producer's already-generated\n\t// package (e.g. \"example.com/orders/clients/async/orderevent/v1\").\n\tPackage string `yaml:\"package\"`\n\t// Alias is the Go import alias the generated code uses for the\n\t// imported package. Mandatory — analogous to SchemaPackageMapping.Alias,\n\t// for the same Go import-collision reason (multiple `/v1` paths).\n\tAlias string `yaml:\"alias\"`\n}\n```\nMessagePackageMapping ties a referenced AsyncAPI spec file (consumed via cross-file message $ref) to the Go package the producer's already-generated message types live in. Lets a consumer-view spec say \"this message comes from over there\" without aapi-codegen having to open the other file: the message-name segment of the $ref becomes the Go type name in the mapped package, and the worker's generated Subscriber takes a handler that operates on the imported type.\n\nMapping is by \\*file path\\* (the part of the $ref before \\`#\\`), resolved relative to the consuming spec's directory at codegen time — same resolution rule the materializer uses for cross-tree payload $refs. Two file paths that resolve to the same on-disk file collapse to one mapping; conflicting mappings on the same file raise a clear error at lower time. v0.5+.\n\n```go\ntype Operation struct {\n\tAction   string                `yaml:\"action\"` // \"send\" | \"receive\"\n\tChannel  OperationChannelRef   `yaml:\"channel\"`\n\tTitle    string                `yaml:\"title,omitempty\"`\n\tSummary  string                `yaml:\"summary,omitempty\"`\n\tMessages []OperationMessageRef `yaml:\"messages,omitempty\"`\n\t// Bindings is the raw `operations.X.bindings` map, surfaced to the\n\t// lowerer which extracts operation-level AMQP fields (priority,\n\t// expiration) for publisher property defaults. v0.3+.\n\tBindings map[string]any `yaml:\"bindings,omitempty\"`\n}\n```\n\n```go\ntype OperationChannelRef struct {\n\tRef string `yaml:\"$ref\"`\n}\n```\nOperationChannelRef is the typed shape of \\`operations.X.channel.$ref\\`.\n\n```go\ntype OperationMessageRef struct {\n\tRef string `yaml:\"$ref\"`\n}\n```\nOperationMessageRef is the typed shape of items in \\`operations.X.messages\\`.\n\n```go\ntype Parameter struct {\n\tDescription string `yaml:\"description,omitempty\"`\n\t// Enum lists the values the parameter may take. A list of strings\n\t// makes the parameter a Go enum type in the Publisher and Subscriber\n\t// signatures.\n\tEnum []any `yaml:\"enum,omitempty\"`\n\t// XAAPICodegen is the parameter's `x-aapi-codegen` extension.\n\tXAAPICodegen *ParameterExtension `yaml:\"x-aapi-codegen,omitempty\"`\n\t// Schema is `channels.X.parameters.Y.schema`, the AsyncAPI 2.x\n\t// shape, which a 3.x Parameter Object doesn't have: `asyncapi\n\t// validate` rejects it. It is still read for specs written that\n\t// way: a `type: string` with an `enum` or a `pattern` types the\n\t// parameter, unless the parameter declares its own Enum or\n\t// XAAPICodegen pattern (see HasOwnType), which wins.\n\tSchema map[string]any `yaml:\"schema,omitempty\"`\n}\n```\nParameter is an AsyncAPI 3.x Parameter Object, \\`channels.X.parameters.Y\\`.\n\n```go\nfunc (p *Parameter) HasOwnType() bool\n```\nHasOwnType reports whether the parameter declares an enum or an x-aapi-codegen pattern of its own, the AsyncAPI 3.x way. Its Schema is then ignored.\n\n```go\ntype ParameterExtension struct {\n\t// Pattern is a regular expression (RE2) the parameter's values must\n\t// match. Unless validation is omitted, it makes the parameter a Go\n\t// type with constructors that check it.\n\tPattern string `yaml:\"pattern,omitempty\"`\n}\n```\nParameterExtension is \\`channels.X.parameters.Y.x-aapi-codegen\\`.\n\n```go\ntype Payload struct {\n\tRef string `yaml:\"$ref,omitempty\"`\n\t// Inline schema fields (type/properties/etc.) get parsed into this map\n\t// for now. Promoted to typed fields when M2 needs them.\n\tInline map[string]any `yaml:\",inline\"`\n}\n```\nPayload is either an inline schema or a $ref to an external one. M1 only handles the $ref form (every reference spec uses it). When Ref is empty the lowerer can fall back to interpreting the rest of the YAML as an inline schema; M1 doesn't need that path.\n\n```go\ntype SchemaPackageMapping struct {\n\tID      string `yaml:\"id\"`\n\tPackage string `yaml:\"package\"`\n\tAlias   string `yaml:\"alias\"`\n}\n```\nSchemaPackageMapping ties a JSON-Schema $id to the Go package its types live in. Declared either in the spec's x-aapi-codegen extension (canonical) or in the optional aapi-codegen.config.yaml (legacy / migration override). Aliasing is mandatory because two canonical schemas commonly share a last path segment (\\`v1\\`/\\`v1\\`) and Go's import-alias derivation would otherwise collide.\n\nThis type duplicates the codegen.SchemaPackageMapping shape on purpose — the loader can't import codegen without a dependency cycle. Generate() converts loader.SchemaPackageMapping → codegen.SchemaPackageMapping at the boundary.\n\n```go\ntype XExtension struct {\n\tSchemaPackages  []SchemaPackageMapping  `yaml:\"schema-packages,omitempty\"`\n\tMessagePackages []MessagePackageMapping `yaml:\"message-packages,omitempty\"`\n\t// OmitValidation opts out of generated UnmarshalJSON methods for\n\t// this spec. Useful when consumers hand-write their own\n\t// UnmarshalJSON (e.g. wire-compat shims for legacy PascalCase\n\t// publishers). Either source — spec extension or config — can opt\n\t// out; the merge is OR semantics (Generate's mergeOmitValidation).\n\tOmitValidation bool `yaml:\"omit-validation,omitempty\"`\n\t// OmitPublishers suppresses the Publisher struct + Send\u003cMsg\u003e methods\n\t// even when the spec has `action: send` operations. Use when a spec\n\t// is consumer-facing only (the producer lives elsewhere; this spec is\n\t// a reference copy). v0.2+.\n\tOmitPublishers bool `yaml:\"omit-publishers,omitempty\"`\n\t// OmitSubscribers suppresses the Subscriber struct + Subscribe\u003cMsg\u003e\n\t// methods + \u003cMsg\u003eHandler interfaces even when the spec has\n\t// `action: receive` operations. Symmetric to OmitPublishers. v0.2+.\n\tOmitSubscribers bool `yaml:\"omit-subscribers,omitempty\"`\n}\n```\nXExtension is the typed shape of the spec-level \\`x-aapi-codegen\\` extension. Add fields as new declarations move into the spec.\n\n","path":"github.com/plheide/aapi-codegen/pkg/codegen/loader","name":"loader","synopsis":"Package loader parses an AsyncAPI 3.x YAML document into a typed in-memory representation.","isRedistributable":true}
