Deluan Quintão 0e5b9e3263
feat(plugins): share plugin DTOs via a types package (#5655)
* refactor(plugins): remove Python PDK generation from ndpgen

* feat(plugins): parse Go type aliases distinctly in ndpgen

* feat(plugins): resolve shared-type aliases against a registry in ndpgen

* fix(plugins): resolve host-service shared aliases package-wide

Mirror the capability approach in ParseDirectoryWithShared: do a first
pass over all package files to build a package-wide alias map, then pass
it into parseServiceFile so that a shared-type alias declared in a sibling
file is visible when resolving types in the service interface file.

Add a focused test that writes the alias in one file and the hostservice
in another, confirming RED before the fix and GREEN after. Also
strengthens the existing Task 3 test with an ArtistRef.Target assertion.

* feat(plugins): add ndpgen -shared-types mode for the Go types package

* feat(plugins): generate the nd-pdk-types Rust crate from -shared-types

* feat(plugins): inject types import and emit deprecated aliases in Go output

* feat(plugins): emit deprecated Rust aliases to the shared types crate

* feat(plugins): inline shared-type shapes into XTP schemas

* feat(plugins): add nd-pdk-types crate and wire dependents

* feat(plugins): move shared capability types to plugins/types with deprecated aliases

* fix(plugins): point Rust deprecated-alias note at the replacement type

* fix(plugins): include shared aliases in KnownStructs so Rust fields keep their type

Capability.KnownStructs() and Service.KnownStructs() previously only
registered names from .Structs. After the shared-types migration, types
like ArtistRef/TrackInfo/SongRef live in .SharedAliases instead, so
ToRustTypeWithStructs could not find them and fell back to serde_json::Value
for every struct field referencing a shared type.

Add the shared-alias names to the knownStructs map in both methods.
Regenerate the Rust capability files; track/song/artist fields now render
as their named types (TrackInfo, SongRef, ArtistRef, etc.).

Add a regression test that verifies a struct field whose type is only in
SharedAliases renders as the named type and not serde_json::Value.

* docs(plugins): remove stale Python references from ndpgen and plugins READMEs

ndpgen no longer has a -python flag; remove it from the usage synopsis,
flags table, and defaults note in ndpgen/README.md. Delete the "Python
Client Library" section that described its output.

plugins/README.md referenced plugins/pdk/python/host/ (deleted) as the
source for Python host-service stubs. Remove that paragraph; Python plugins
still work via the XTP-schema / extism-py path (see examples/*-py).

* refactor(plugins): dedupe ndpgen helpers and tidy shared-type codegen

* docs(plugins): restore Python as a supported XTP schema target

The ndpgen-generated Python PDK was removed, but the XTP YAML schemas are
language-neutral and the XTP CLI still generates Python bindings from them
(as the extism-py examples demonstrate). Only the ndpgen Python output was
dropped, not Python support itself.

* test(plugins): use the shared types package in test plugins

The test fixtures referenced the now-deprecated capability aliases
(sonicsimilarity.SongRef, metadata.ArtistRef/SongRef). Point them at the
canonical types package so our own fixtures don't depend on symbols slated
for removal.

* refactor(plugins): use the shared types package in host adapters

Replace deprecated capabilities.TrackInfo, capabilities.ArtistRef, and
capabilities.SongRef aliases with the canonical types.TrackInfo,
types.ArtistRef, and types.SongRef from plugins/types.

* fix(plugins): reference shared types by canonical path in generated Rust

Previously the generator emitted `pub field: SongRef` (the local deprecated
alias) for struct fields whose type came from SharedAliases. Refactored
ToRustTypeWithStructs into a private toRustType that accepts a shared map,
and added ToRustTypeWithShared which resolves shared-alias names to their
canonical nd_pdk_types::X path before falling through to the knownStructs
check. Both rustCapabilityFuncMap and rustFuncMap now build the shared map
from SharedAliases and use it for fieldRustType, so the generated capability
files reference nd_pdk_types::SongRef / nd_pdk_types::TrackInfo directly.
The deprecated pub type aliases remain in place as the external back-compat
surface. Deprecation warning count from cargo build drops to 0.

* fix(examples): implement missing Scrobbler.playback_report in Rust examples

The Scrobbler trait gained a playback_report method but the two Rust example
plugins (webhook-rs and discord-rich-presence-rs) were not updated, causing
E0046 compile errors. Added the missing fn playback_report to both: webhook-rs
logs and returns Ok(()) mirroring its now_playing handler; discord-rich-presence-rs
is a no-op since Discord presence does not need playback reports. make all-rust
now exits 0.

* refactor(plugins): point Rust deprecation notes at the nd_pdk::types umbrella path

Plugin authors depend on the nd-pdk umbrella crate, which re-exports
nd_pdk_types as 'types', so the migration target they should type is
nd_pdk::types::X. The alias target stays nd_pdk_types::X (the real path
inside nd-pdk-capabilities).

* fix(plugins): error when a shared-type alias can't be resolved against the registry

* refactor(plugins): parse each Go source file once in ndpgen

* fix(plugins): correct ndpgen review nits (flag name, unused dep, docs)

* refactor(plugins): drop the now-unused path param from parseServiceFile

* refactor(plugins): use shared types directly, rename TrackInfo to Track

Capability interfaces now reference the shared `types` package by qualified
name (types.Track, types.SongRef, types.ArtistRef) instead of the package-local
deprecated aliases, and the shared TrackInfo type is renamed to Track to match
its role as the plugin-facing projection of a library media file.

The deprecated bare aliases (scrobbler.TrackInfo, metadata.ArtistRef,
sonicsimilarity.SongRef, etc.) are kept as re-exports so existing plugins keep
compiling, with a deprecation warning steering them to the canonical types.

To support this, ndpgen now resolves qualified types.X references: it collects
them during type discovery, maps each used canonical type back to its declared
deprecated alias for re-export, emits nd_pdk_types::X paths in Rust, and names
the XTP schema components by their canonical type. Regenerated the Go and Rust
PDK and the XTP schemas, and added generator tests covering the qualified-ref
path. Also adds clarifying doc comments to the shared types.

* refactor(plugins): extract shared types selector into a named const

Replace the "types." string literal that detects and strips the shared types
package selector with a single sharedTypesPrefix constant across the ndpgen
generator (parser, types, generator, xtp_schema), giving the package one source
of truth for the selector.

Also restore the single reused scratch map (cleared each iteration) in the
resolveSharedAliases BFS instead of allocating a fresh map per shared-struct
field, matching the prior implementation.

Pure cleanup from a /simplify pass: regeneration produces byte-for-byte
identical Go, Rust, and XTP output.

* refactor(plugins): keep TrackInfo in the capability package for now

Move the track type back out of the shared plugins/types package: it is again
defined inline as TrackInfo in plugins/capabilities/scrobbler.go and referenced
directly by the scrobbler and lyrics capabilities, reverting the rename to
types.Track. The host helper is renamed back to mediaFileToTrackInfo and now
returns capabilities.TrackInfo. SongRef and ArtistRef stay in the shared types
package; TrackInfo keeps using types.ArtistRef for its artist lists.

This type is expected to be reshaped in upcoming work, so leaving it in the
capability package avoids churning the shared types twice. Regenerated the Go
and Rust PDK and the XTP schemas accordingly.

* fix(plugins): emit the Go types import for direct shared-type refs

ndpgen's Capability/Service.ImportsSharedTypes only reported a shared-types
dependency when a deprecated re-export alias (type X = types.X) was declared. A
struct field referencing the canonical form directly (e.g. types.SongRef) with
no such alias produced an empty SharedAliases slice, so the Go templates skipped
the import while still emitting fields/signatures using types.SongRef — leaving
generated PDK code for new shared DTOs uncompilable unless an otherwise
unnecessary alias was added.

ImportsSharedTypes now also returns true when any struct field references the
types. package by qualified name, via a new structsReferenceSharedTypes helper
that reuses collectReferencedTypes (so []types.X and map[...]types.X are covered
too).

* fix(plugins): preserve base64 encoding for shared byte fields in Rust

The Rust shared-types crate template rendered a []byte field as a plain Vec<u8>
without the base64_bytes serde override used by the capability/client templates.
Go's encoding/json serializes []byte as a base64 string, so a Rust plugin using
nd_pdk::types would have serialized an array of numbers instead of the wire
format the Go/server side expects.

GenerateSharedTypesRust now registers the base64_bytes partial and passes a
HasByteFields flag (new anyFieldIsByteSlice helper); types.rs.tmpl emits the
base64_bytes module and a #[serde(with = "base64_bytes")] attribute on []byte
fields, mirroring the capability template.

* fix(plugins): include directly-referenced shared types in XTP schemas

buildSchemas registered shared types into the schema components only by iterating
cap.SharedAliases, which records deprecated re-export aliases. A capability that
referenced a shared DTO solely as types.Foo (no declared alias) therefore never
got Foo into the component set, so the self-contained XTP schema rendered the
field as a generic object (or emitted a dangling $ref), breaking the direct
shared-type use case enabled by -shared.

resolveSharedAliases now also returns the resolved shapes of every used shared
type (alias or not); these are carried on the new Capability.SharedTypes field
and registered by buildSchemas alongside SharedAliases. Validated end-to-end with
the xtp CLI: a direct types.Foo reference now produces a proper component plus a
$ref, so xtp generates a typed struct instead of an untyped serde_json::Map.

* fix(plugins): resolve renamed shared aliases to canonical schema refs

When a deprecated alias renames its canonical type (e.g. type TrackInfo =
types.Track) and a capability field is typed with the alias name (TrackInfo),
buildProperty emitted a $ref to #/components/schemas/TrackInfo. Components are
keyed by the canonical name (Track), so no TrackInfo component was emitted,
leaving a dangling reference that crashes the xtp code generator.

buildSchemas now builds an alias->canonical map; buildProperty (and the slice
item path) resolves $ref targets through it, and a used alias name marks its
canonical component used so it is emitted. Validated with the xtp CLI: the
renamed-alias schema previously crashed xtp and now generates cleanly.

* fix(plugins): detect shared types used directly in method signatures

ImportsSharedTypes only inspected struct fields, so a capability method using a
shared type directly in its signature (e.g. types.SongRef as input/output rather
than inside a local struct) was not detected. The generated Go templates still
rendered the provider/export signatures with types.SongRef, so the capability
package omitted the types import and failed to compile; the same gap applied to
service params/returns.

ImportsSharedTypes now also scans capability method input/output types and
service method params/returns, via a typeReferencesSharedTypes helper that reuses
collectReferencedTypes (covering pointer/slice/map wrappers).

* fix(plugins): add base64 dependency to the shared Rust types crate

When a shared DTO has a []byte field, ndpgen emits the base64_bytes serde helper
and use base64::... imports into nd-pdk-types/src/lib.rs, but the crate manifest
declared only serde. In that case make gen produced a crate that failed to
compile with 'unresolved module base64'.

Add base64 = "0.22" (matching nd-pdk-capabilities) so the generated shared types
crate compiles whenever a []byte field is present. Verified by generating a
shared crate with a []byte field and confirming cargo check fails before and
passes after.

* fix(plugins): translate shared method types in generated Rust

A capability method using a shared DTO directly as input/output (e.g.
types.SongRef) was passed through rustOutputType unchanged, so the Rust template
emitted invalid trait and extism_pdk::Json<$crate::pkg::types.SongRef> signatures
that do not compile.

Method input/output types now resolve through the shared registry: trait
signatures use rustTraitType (shared -> nd_pdk_types::X, locals stay bare) and the
export macros use rustMethodType (fully qualified: shared -> nd_pdk_types::X,
primitives -> Rust, locals -> $crate::<pkg>::X). Verified end-to-end by compiling
a generated capability that takes types.SongRef directly against the real
nd-pdk-types crate.

* fix(plugins): canonicalize XTP export refs for renamed shared aliases

buildSchemas canonicalized alias-to-canonical references for struct-field $ref
targets, but buildExport built export input/output $refs straight from
fieldBaseType. A capability whose export used a renamed deprecated alias
directly (e.g. type TrackInfo = types.Track with NowPlaying(TrackInfo)) emitted
$ref: #/components/schemas/TrackInfo, while the component is emitted under the
canonical name Track — a dangling export reference.

Lift the alias-to-canonical map into GenerateSchema (buildAliasToCanonical) and
apply it to export refs via canonicalRefName, the same resolution already used
for field properties.

* fix(plugins): route shared macro types through $crate for plugin builds

When a capability method used a shared type directly, the generated export macro
named the type as nd_pdk_types::SongRef. The macro expands in the downstream
plugin crate, which depends on the umbrella nd-pdk crate and not on nd-pdk-types
directly, so that path is unresolvable there and the plugin fails to build.

rustMethodType (macro-facing) now emits $crate::types::X, and the generated
nd-pdk-capabilities lib.rs re-exports nd_pdk_types as types so $crate resolves
it. Trait signatures keep nd_pdk_types::X since they live in nd-pdk-capabilities,
which has the direct dependency. Verified end-to-end: a plugin crate depending
only on the umbrella that uses a capability with a direct types.X method now
compiles via the macro.

* fix(plugins): add nd-pdk-types dependency to the Rust host crate

When a host service uses a shared type, ndpgen emits nd_pdk_types::X into the
generated nd-pdk-host client wrappers, but the host crate's manifest did not
depend on nd-pdk-types, so the crate failed to compile with 'unresolved module
nd_pdk_types'. Host client wrappers are plain functions resolved in the host
crate's own context (not macros expanded downstream), so a direct dependency is
the right fix.

Add nd-pdk-types = { path = "../nd-pdk-types" } to nd-pdk-host, mirroring
nd-pdk-capabilities. Found while auditing all Rust paths against the realistic
crate topology after the capability-side $crate fix; verified by generating a
host service with a shared-type return and confirming cargo check fails before
and passes after.

* fix(plugins): resolve shared aliases in Rust host signatures

The Rust host client rendered method params and returns through
RustTypeWithStructs, which only consults KnownStructs. A host service using a
shared alias in a signature (e.g. type Track = types.Track plus
MatchSongs(...) ([]Track, error)) therefore emitted a bare Vec<Track>, but the
client template emits no Track alias or import, so the generated nd-pdk-host
crate did not compile. Only struct fields went through the shared map.

rustType/rustParamType now use the shared map too (RustTypeWithShared /
RustParamTypeWithShared), so an aliased param/return resolves to its canonical
nd_pdk_types::X path, matching field handling. Verified by generating a host
service returning a shared alias and confirming cargo check fails before and
passes after.
2026-06-29 21:20:33 -04:00

796 lines
24 KiB
Go

package internal
import (
"os"
"path/filepath"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Parser", func() {
var tmpDir string
BeforeEach(func() {
var err error
tmpDir, err = os.MkdirTemp("", "ndpgen-test-*")
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
os.RemoveAll(tmpDir)
})
Describe("ParseDirectory", func() {
It("should parse a simple host service interface", func() {
src := `package host
import "context"
// SubsonicAPIService provides access to Navidrome's Subsonic API.
//nd:hostservice name=SubsonicAPI permission=subsonicapi
type SubsonicAPIService interface {
// Call executes a Subsonic API request.
//nd:hostfunc
Call(ctx context.Context, uri string) (response string, err error)
}
`
err := os.WriteFile(filepath.Join(tmpDir, "service.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(HaveLen(1))
svc := services[0]
Expect(svc.Name).To(Equal("SubsonicAPI"))
Expect(svc.Permission).To(Equal("subsonicapi"))
Expect(svc.Interface).To(Equal("SubsonicAPIService"))
Expect(svc.Methods).To(HaveLen(1))
m := svc.Methods[0]
Expect(m.Name).To(Equal("Call"))
Expect(m.HasError).To(BeTrue())
Expect(m.Params).To(HaveLen(1))
Expect(m.Params[0].Name).To(Equal("uri"))
Expect(m.Params[0].Type).To(Equal("string"))
Expect(m.Returns).To(HaveLen(1))
Expect(m.Returns[0].Name).To(Equal("response"))
Expect(m.Returns[0].Type).To(Equal("string"))
})
It("should parse multiple methods", func() {
src := `package host
import "context"
// SchedulerService provides scheduling capabilities.
//nd:hostservice name=Scheduler permission=scheduler
type SchedulerService interface {
//nd:hostfunc
ScheduleRecurring(ctx context.Context, cronExpression string) (scheduleID string, err error)
//nd:hostfunc
ScheduleOneTime(ctx context.Context, delaySeconds int32) (scheduleID string, err error)
//nd:hostfunc
CancelSchedule(ctx context.Context, scheduleID string) (canceled bool, err error)
}
`
err := os.WriteFile(filepath.Join(tmpDir, "scheduler.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(HaveLen(1))
svc := services[0]
Expect(svc.Name).To(Equal("Scheduler"))
Expect(svc.Methods).To(HaveLen(3))
Expect(svc.Methods[0].Name).To(Equal("ScheduleRecurring"))
Expect(svc.Methods[0].Params[0].Type).To(Equal("string"))
Expect(svc.Methods[1].Name).To(Equal("ScheduleOneTime"))
Expect(svc.Methods[1].Params[0].Type).To(Equal("int32"))
Expect(svc.Methods[2].Name).To(Equal("CancelSchedule"))
Expect(svc.Methods[2].Returns[0].Type).To(Equal("bool"))
})
It("should skip methods without hostfunc annotation", func() {
src := `package host
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc
Exported(ctx context.Context) error
// This method is not exported
NotExported(ctx context.Context) error
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(HaveLen(1))
Expect(services[0].Methods).To(HaveLen(1))
Expect(services[0].Methods[0].Name).To(Equal("Exported"))
})
It("should handle custom export name", func() {
src := `package host
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc name=custom_export_name
MyMethod(ctx context.Context) error
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services[0].Methods[0].ExportName).To(Equal("custom_export_name"))
Expect(services[0].Methods[0].FunctionName("test")).To(Equal("custom_export_name"))
})
It("should skip generated files", func() {
regularSrc := `package host
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc
Method(ctx context.Context) error
}
`
genSrc := `// Code generated. DO NOT EDIT.
package host
//nd:hostservice name=Generated permission=gen
type GeneratedService interface {
//nd:hostfunc
Method() error
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(regularSrc), 0600)
Expect(err).NotTo(HaveOccurred())
err = os.WriteFile(filepath.Join(tmpDir, "test_gen.go"), []byte(genSrc), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(HaveLen(1))
Expect(services[0].Name).To(Equal("Test"))
})
It("should skip interfaces without hostservice annotation", func() {
src := `package host
import "context"
// Regular interface without annotation
type RegularInterface interface {
Method(ctx context.Context) error
}
//nd:hostservice name=Annotated permission=annotated
type AnnotatedService interface {
//nd:hostfunc
Method(ctx context.Context) error
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(HaveLen(1))
Expect(services[0].Name).To(Equal("Annotated"))
})
It("should return empty slice for directory with no host services", func() {
src := `package host
type RegularInterface interface {
Method() error
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(BeEmpty())
})
It("returns an error when a shared-type alias cannot be resolved (no registry)", func() {
fileA := `package host
import "github.com/navidrome/navidrome/plugins/types"
type TrackInfo = types.TrackInfo
`
fileB := `package host
import "context"
//nd:hostservice name=Matcher permission=matcher
type MatcherService interface {
//nd:hostfunc
Match(ctx context.Context, t TrackInfo) (bool, error)
}
`
Expect(os.WriteFile(filepath.Join(tmpDir, "aliases.go"), []byte(fileA), 0600)).To(Succeed())
Expect(os.WriteFile(filepath.Join(tmpDir, "matcher.go"), []byte(fileB), 0600)).To(Succeed())
_, err := ParseDirectoryWithShared(tmpDir, nil)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("TrackInfo"))
Expect(err.Error()).To(ContainSubstring("-shared"))
})
It("resolves shared-type aliases declared in a sibling file (package-wide alias map)", func() {
// File A: declares the shared-type alias in the same package
fileA := `package host
import "github.com/navidrome/navidrome/plugins/types"
// Deprecated: use types.Track.
type Track = types.Track
`
// File B: declares the host service that references Track from file A
fileB := `package host
import "context"
//nd:hostservice name=Matcher permission=matcher
type MatcherService interface {
//nd:hostfunc
MatchSongs(ctx context.Context, query string) (results []Track, err error)
}
`
Expect(os.WriteFile(filepath.Join(tmpDir, "aliases.go"), []byte(fileA), 0600)).To(Succeed())
Expect(os.WriteFile(filepath.Join(tmpDir, "matcher.go"), []byte(fileB), 0600)).To(Succeed())
shared := map[string]StructDef{
"Track": {
Name: "Track",
Fields: []FieldDef{
{Name: "Title", Type: "string", JSONTag: "title"},
{Name: "Artist", Type: "string", JSONTag: "artist"},
},
},
}
services, err := ParseDirectoryWithShared(tmpDir, shared)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(HaveLen(1))
byName := map[string]SharedAlias{}
for _, a := range services[0].SharedAliases {
byName[a.Name] = a
}
// Track alias is in a sibling file — must be resolved package-wide
Expect(byName).To(HaveKey("Track"))
Expect(byName["Track"].Target).To(Equal("types.Track"))
})
})
Describe("parseKeyValuePairs", func() {
It("should parse key=value pairs", func() {
result := parseKeyValuePairs("name=Test permission=test")
Expect(result).To(HaveKeyWithValue("name", "Test"))
Expect(result).To(HaveKeyWithValue("permission", "test"))
})
It("should return nil for empty input", func() {
result := parseKeyValuePairs("")
Expect(result).To(BeNil())
})
})
Describe("typeToString", func() {
It("should handle basic types", func() {
src := `package test
type T interface {
Method(s string, i int, b bool) ([]byte, error)
}
`
err := os.WriteFile(filepath.Join(tmpDir, "types.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
// Parse and verify type conversion works
// This is implicitly tested through ParseDirectory
})
It("should convert interface{} to any", func() {
src := `package test
import "context"
//nd:hostservice name=Test permission=test
type TestService interface {
//nd:hostfunc
GetMetadata(ctx context.Context) (data map[string]interface{}, err error)
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
services, err := ParseDirectory(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(services).To(HaveLen(1))
Expect(services[0].Methods[0].Returns[0].Type).To(Equal("map[string]any"))
})
})
Describe("Method helpers", func() {
It("should generate correct function names", func() {
m := Method{Name: "Call"}
Expect(m.FunctionName("subsonicapi")).To(Equal("subsonicapi_call"))
m.ExportName = "custom_name"
Expect(m.FunctionName("subsonicapi")).To(Equal("custom_name"))
})
It("should generate correct type names", func() {
m := Method{Name: "Call"}
// Host-side types are public
Expect(m.RequestTypeName("SubsonicAPI")).To(Equal("SubsonicAPICallRequest"))
Expect(m.ResponseTypeName("SubsonicAPI")).To(Equal("SubsonicAPICallResponse"))
// Client/PDK types are private
Expect(m.ClientRequestTypeName("SubsonicAPI")).To(Equal("subsonicAPICallRequest"))
Expect(m.ClientResponseTypeName("SubsonicAPI")).To(Equal("subsonicAPICallResponse"))
})
})
Describe("Service helpers", func() {
It("should generate correct output file name", func() {
s := Service{Name: "SubsonicAPI"}
Expect(s.OutputFileName()).To(Equal("subsonicapi_gen.go"))
})
It("should generate correct export prefix", func() {
s := Service{Name: "SubsonicAPI"}
Expect(s.ExportPrefix()).To(Equal("subsonicapi"))
})
})
Describe("ParseCapabilities", func() {
It("should parse a simple capability interface", func() {
src := `package capabilities
// MetadataAgent provides metadata retrieval.
//nd:capability name=metadata
type MetadataAgent interface {
// GetArtistBiography returns artist biography.
//nd:export name=nd_get_artist_biography
GetArtistBiography(ArtistInput) (ArtistBiographyOutput, error)
}
// ArtistInput is the input for artist-related functions.
type ArtistInput struct {
// ID is the artist ID.
ID string ` + "`json:\"id\"`" + `
// Name is the artist name.
Name string ` + "`json:\"name\"`" + `
}
// ArtistBiographyOutput is the output for GetArtistBiography.
type ArtistBiographyOutput struct {
// Biography is the biography text.
Biography string ` + "`json:\"biography\"`" + `
}
`
err := os.WriteFile(filepath.Join(tmpDir, "metadata.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
capabilities, err := ParseCapabilities(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(capabilities).To(HaveLen(1))
cap := capabilities[0]
Expect(cap.Name).To(Equal("metadata"))
Expect(cap.Interface).To(Equal("MetadataAgent"))
Expect(cap.Required).To(BeFalse())
Expect(cap.Doc).To(ContainSubstring("MetadataAgent provides metadata retrieval"))
Expect(cap.Methods).To(HaveLen(1))
m := cap.Methods[0]
Expect(m.Name).To(Equal("GetArtistBiography"))
Expect(m.ExportName).To(Equal("nd_get_artist_biography"))
Expect(m.Input.Type).To(Equal("ArtistInput"))
Expect(m.Output.Type).To(Equal("ArtistBiographyOutput"))
// Check structs were collected
Expect(cap.Structs).To(HaveLen(2))
})
It("should parse a required capability", func() {
src := `package capabilities
// Scrobbler requires all methods to be implemented.
//nd:capability name=scrobbler required=true
type Scrobbler interface {
//nd:export name=nd_scrobbler_is_authorized
IsAuthorized(AuthInput) (AuthOutput, error)
//nd:export name=nd_scrobbler_scrobble
Scrobble(ScrobbleInput) (ScrobblerOutput, error)
}
type AuthInput struct {
UserID string ` + "`json:\"userId\"`" + `
}
type AuthOutput struct {
Authorized bool ` + "`json:\"authorized\"`" + `
}
type ScrobbleInput struct {
UserID string ` + "`json:\"userId\"`" + `
}
type ScrobblerOutput struct {
Error *string ` + "`json:\"error,omitempty\"`" + `
}
`
err := os.WriteFile(filepath.Join(tmpDir, "scrobbler.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
capabilities, err := ParseCapabilities(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(capabilities).To(HaveLen(1))
cap := capabilities[0]
Expect(cap.Name).To(Equal("scrobbler"))
Expect(cap.Required).To(BeTrue())
Expect(cap.Methods).To(HaveLen(2))
})
It("should parse type aliases and consts", func() {
src := `package capabilities
//nd:capability name=scrobbler required=true
type Scrobbler interface {
//nd:export name=nd_scrobble
Scrobble(ScrobbleInput) (ScrobblerOutput, error)
}
type ScrobbleInput struct {
UserID string ` + "`json:\"userId\"`" + `
}
// ScrobblerErrorType indicates error handling behavior.
type ScrobblerErrorType string
const (
// ScrobblerErrorNone indicates no error.
ScrobblerErrorNone ScrobblerErrorType = "none"
// ScrobblerErrorRetry indicates retry later.
ScrobblerErrorRetry ScrobblerErrorType = "retry"
)
type ScrobblerOutput struct {
ErrorType *ScrobblerErrorType ` + "`json:\"errorType,omitempty\"`" + `
}
`
err := os.WriteFile(filepath.Join(tmpDir, "scrobbler.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
capabilities, err := ParseCapabilities(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(capabilities).To(HaveLen(1))
cap := capabilities[0]
// Type alias should be collected
Expect(cap.TypeAliases).To(HaveLen(1))
Expect(cap.TypeAliases[0].Name).To(Equal("ScrobblerErrorType"))
Expect(cap.TypeAliases[0].Type).To(Equal("string"))
// Consts should be collected
Expect(cap.Consts).To(HaveLen(1))
Expect(cap.Consts[0].Type).To(Equal("ScrobblerErrorType"))
Expect(cap.Consts[0].Values).To(HaveLen(2))
Expect(cap.Consts[0].Values[0].Name).To(Equal("ScrobblerErrorNone"))
Expect(cap.Consts[0].Values[0].Value).To(Equal(`"none"`))
})
It("should collect nested struct dependencies", func() {
src := `package capabilities
//nd:capability name=metadata
type MetadataAgent interface {
//nd:export name=nd_get_images
GetImages(ArtistInput) (ImagesOutput, error)
}
type ArtistInput struct {
ID string ` + "`json:\"id\"`" + `
}
type ImagesOutput struct {
Images []ImageInfo ` + "`json:\"images\"`" + `
}
type ImageInfo struct {
URL string ` + "`json:\"url\"`" + `
Size int32 ` + "`json:\"size\"`" + `
}
`
err := os.WriteFile(filepath.Join(tmpDir, "metadata.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
capabilities, err := ParseCapabilities(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(capabilities).To(HaveLen(1))
cap := capabilities[0]
// Should collect all 3 structs: ArtistInput, ImagesOutput, and ImageInfo
Expect(cap.Structs).To(HaveLen(3))
structNames := make([]string, len(cap.Structs))
for i, s := range cap.Structs {
structNames[i] = s.Name
}
Expect(structNames).To(ContainElements("ArtistInput", "ImagesOutput", "ImageInfo"))
})
It("should return empty slice for directory with no capabilities", func() {
src := `package capabilities
type RegularInterface interface {
Method() error
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
capabilities, err := ParseCapabilities(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(capabilities).To(BeEmpty())
})
It("should ignore methods without export annotation", func() {
src := `package capabilities
//nd:capability name=test
type TestCapability interface {
//nd:export name=nd_exported
ExportedMethod(Input) (Output, error)
// This method has no export annotation
NotExportedMethod(Input) (Output, error)
}
type Input struct {
Value string ` + "`json:\"value\"`" + `
}
type Output struct {
Result string ` + "`json:\"result\"`" + `
}
`
err := os.WriteFile(filepath.Join(tmpDir, "test.go"), []byte(src), 0600)
Expect(err).NotTo(HaveOccurred())
capabilities, err := ParseCapabilities(tmpDir)
Expect(err).NotTo(HaveOccurred())
Expect(capabilities).To(HaveLen(1))
// Only the exported method should be captured
Expect(capabilities[0].Methods).To(HaveLen(1))
Expect(capabilities[0].Methods[0].Name).To(Equal("ExportedMethod"))
})
It("distinguishes Go type aliases from defined types", func() {
src := `package capabilities
import "github.com/navidrome/navidrome/plugins/types"
// Deprecated: use types.ArtistRef.
type ArtistRef = types.ArtistRef
// ScrobblerError is a sentinel error string.
type ScrobblerError string
//nd:capability name=scrobbler required=true
type Scrobbler interface {
//nd:export name=nd_scrobbler_check
Check(ArtistRef) (bool, error)
}
`
Expect(os.WriteFile(filepath.Join(tmpDir, "scrobbler.go"), []byte(src), 0600)).To(Succeed())
shared := map[string]StructDef{
"ArtistRef": {Name: "ArtistRef", Fields: []FieldDef{{Name: "Name", Type: "string", JSONTag: "name"}}},
}
caps, err := ParseCapabilitiesWithShared(tmpDir, shared)
Expect(err).NotTo(HaveOccurred())
Expect(caps).To(HaveLen(1))
// ArtistRef is a shared-type alias (types.*): it lands in SharedAliases, not TypeAliases.
sharedByName := map[string]SharedAlias{}
for _, a := range caps[0].SharedAliases {
sharedByName[a.Name] = a
}
Expect(sharedByName).To(HaveKey("ArtistRef"))
Expect(sharedByName["ArtistRef"].Target).To(Equal("types.ArtistRef"))
// ScrobblerError is a plain defined type: it stays in TypeAliases.
typeByName := map[string]TypeAlias{}
for _, a := range caps[0].TypeAliases {
typeByName[a.Name] = a
}
Expect(typeByName).To(HaveKey("ScrobblerError"))
Expect(typeByName["ScrobblerError"].IsAlias).To(BeFalse())
})
})
Describe("ParseCapabilitiesWithShared", func() {
It("returns an error when a shared-type alias cannot be resolved (no registry)", func() {
src := `package capabilities
import "github.com/navidrome/navidrome/plugins/types"
// TrackInfo is an alias for the shared type.
type TrackInfo = types.TrackInfo
//nd:capability name=nowplaying required=true
type NowPlaying interface {
//nd:export name=nd_now_playing
NowPlaying(TrackInfo) error
}
`
Expect(os.WriteFile(filepath.Join(tmpDir, "nowplaying.go"), []byte(src), 0600)).To(Succeed())
_, err := ParseCapabilitiesWithShared(tmpDir, nil)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("TrackInfo"))
Expect(err.Error()).To(ContainSubstring("-shared"))
})
It("resolves shared-type aliases against the registry", func() {
shared := map[string]StructDef{
"ArtistRef": {Name: "ArtistRef", Fields: []FieldDef{{Name: "Name", Type: "string", JSONTag: "name"}}},
"TrackInfo": {Name: "TrackInfo", Fields: []FieldDef{
{Name: "Title", Type: "string", JSONTag: "title"},
{Name: "Artists", Type: "[]ArtistRef", JSONTag: "artists"},
}},
}
src := `package capabilities
import "github.com/navidrome/navidrome/plugins/types"
// Deprecated: use types.TrackInfo.
type TrackInfo = types.TrackInfo
// Deprecated: use types.ArtistRef.
type ArtistRef = types.ArtistRef
// NowPlayingRequest carries a track.
type NowPlayingRequest struct {
Track TrackInfo ` + "`json:\"track\"`" + `
}
//nd:capability name=scrobbler required=true
type Scrobbler interface {
//nd:export name=nd_scrobbler_now_playing
NowPlaying(NowPlayingRequest) error
}
`
Expect(os.WriteFile(filepath.Join(tmpDir, "scrobbler.go"), []byte(src), 0600)).To(Succeed())
caps, err := ParseCapabilitiesWithShared(tmpDir, shared)
Expect(err).NotTo(HaveOccurred())
Expect(caps).To(HaveLen(1))
names := []string{}
for _, a := range caps[0].SharedAliases {
names = append(names, a.Name)
}
// TrackInfo is referenced directly; ArtistRef is pulled in transitively via TrackInfo.Artists.
Expect(names).To(ContainElements("TrackInfo", "ArtistRef"))
byName := map[string]SharedAlias{}
for _, a := range caps[0].SharedAliases {
byName[a.Name] = a
}
Expect(byName["TrackInfo"].Target).To(Equal("types.TrackInfo"))
Expect(byName["TrackInfo"].Def.Fields).To(HaveLen(2)) // for schema inlining
Expect(byName["ArtistRef"].Target).To(Equal("types.ArtistRef"))
})
It("resolves shared types from qualified types.X references with a renamed alias", func() {
shared := map[string]StructDef{
"ArtistRef": {Name: "ArtistRef", Fields: []FieldDef{{Name: "Name", Type: "string", JSONTag: "name"}}},
"Track": {Name: "Track", Fields: []FieldDef{
{Name: "Title", Type: "string", JSONTag: "title"},
{Name: "Artists", Type: "[]ArtistRef", JSONTag: "artists"},
}},
}
src := `package capabilities
import "github.com/navidrome/navidrome/plugins/types"
// Deprecated: use types.Track.
type TrackInfo = types.Track
// Deprecated: use types.ArtistRef.
type ArtistRef = types.ArtistRef
// NowPlayingRequest carries a track.
type NowPlayingRequest struct {
Track types.Track ` + "`json:\"track\"`" + `
}
//nd:capability name=scrobbler required=true
type Scrobbler interface {
//nd:export name=nd_scrobbler_now_playing
NowPlaying(NowPlayingRequest) error
}
`
Expect(os.WriteFile(filepath.Join(tmpDir, "scrobbler.go"), []byte(src), 0600)).To(Succeed())
caps, err := ParseCapabilitiesWithShared(tmpDir, shared)
Expect(err).NotTo(HaveOccurred())
Expect(caps).To(HaveLen(1))
byName := map[string]SharedAlias{}
for _, a := range caps[0].SharedAliases {
byName[a.Name] = a
}
// The deprecated alias keeps its name (TrackInfo) but now targets types.Track.
// ArtistRef is pulled in transitively via Track.Artists.
Expect(byName).To(HaveKey("TrackInfo"))
Expect(byName).To(HaveKey("ArtistRef"))
Expect(byName["TrackInfo"].Target).To(Equal("types.Track"))
Expect(byName["TrackInfo"].Def.Fields).To(HaveLen(2)) // for schema inlining
Expect(byName["ArtistRef"].Target).To(Equal("types.ArtistRef"))
// The capability struct field keeps the canonical qualified reference.
var nowPlaying StructDef
for _, st := range caps[0].Structs {
if st.Name == "NowPlayingRequest" {
nowPlaying = st
}
}
Expect(nowPlaying.Fields).To(HaveLen(1))
Expect(nowPlaying.Fields[0].Type).To(Equal("types.Track"))
})
})
Describe("Export helpers", func() {
It("should generate correct provider interface name", func() {
e := Export{Name: "GetArtistBiography"}
Expect(e.ProviderInterfaceName()).To(Equal("ArtistBiographyProvider"))
e = Export{Name: "OnInit"}
Expect(e.ProviderInterfaceName()).To(Equal("InitProvider"))
})
It("should generate correct impl variable name", func() {
e := Export{Name: "GetArtistBiography"}
Expect(e.ImplVarName()).To(Equal("artistBiographyImpl"))
e = Export{Name: "OnInit"}
Expect(e.ImplVarName()).To(Equal("initImpl"))
})
It("should generate correct export function name", func() {
e := Export{Name: "GetArtistBiography", ExportName: "nd_get_artist_biography"}
Expect(e.ExportFuncName()).To(Equal("_NdGetArtistBiography"))
})
})
})